From 152b9251a95e1136793e469b1e782003281324ff Mon Sep 17 00:00:00 2001 From: soul Date: Thu, 29 Oct 2026 23:00:49 +0100 Subject: [PATCH 001/190] Research: release pipeline prior art (Unity CI, Personal licensing, Forgejo runners and releases, versioning tools) Co-Authored-By: Claude Opus 5.5 --- .../2026-10-29-release-pipeline-prior-art.md | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 docs/research/2026-10-29-release-pipeline-prior-art.md diff --git a/docs/research/2026-10-29-release-pipeline-prior-art.md b/docs/research/2026-10-29-release-pipeline-prior-art.md new file mode 100644 index 000000000..8faf9ed21 --- /dev/null +++ b/docs/research/2026-10-29-release-pipeline-prior-art.md @@ -0,0 +1,53 @@ +# Release pipeline prior art (Eyes, 2026-10-29) + +Serves: the Aetheria release pipeline forks (where Starfire builds run, how versions bump), raised 2026-10-29 by the operator's "we should have an auto release pipeline with semantic versioning and change logs". Eyes pass, session self-2026-10-28-ag9. +Facts with pointers. No recommendations. "unverified" = not opened/confirmed. + +## 1. Headless Unity CI builds (GameCI) +- Docker Hub `unityci/editor` (built by github.com/game-ci/docker, MIT, "not affiliated with Unity"). Tags checked via https://hub.docker.com/v2/repositories/unityci/editor/tags?name=6000.3 (1,881 tags total at fetch): + - 6000.3.24f1 (the project's version) EXISTS, pushed 2026-09-10: `ubuntu-6000.3.24f1-{base,linux-il2cpp,windows-mono,mac-mono,webgl,ios,android}-3.2.2` (also `-3`, `-3.2`, unprefixed). Sizes (compressed): base 5.21 GB, linux-il2cpp 5.68 GB, windows-mono 5.95 GB. No `linux-mono` tag (Linux Mono player support is in the base editor; unverified wording). `windows-6000.3.24f1-base` tags marked inactive. + - Newer: 6000.3.26f1 (2026-10-08), 6000.3.27f1 (2026-10-21), same module set. Windows-container images (`windows--base/windows-il2cpp/...`, 9-13 GB) also exist. +- GameCI docs: https://game.ci/docs/github/builder — "Many Mono targets can be cross-compiled, so a Linux runner can produce a Windows Mono player"; IL2CPP needs matching OS for some platforms (https://game.ci/docs/docker/docker-images: "Some platforms require their respective operating systems in order to generate IL2CPP builds"). Windows and macOS targets each consume an extra license seat, all Linux targets together one. +- unityVersion needs full string e.g. `6000.0.23f1`; `dockerMemoryLimit` defaults 95% of system memory on Linux; 6.6+ needs 1 GiB shm (`dockerShmSize`). +- Known failure reports (not this exact setup): Unity issuetracker 24511 — `windows-mono` module install on Linux fails ERROR_CHECKSUM_MISMATCH for 6000.5.9f1 (stale md5 in release manifest; applies to Hub/module install, not prebuilt GameCI images). Old game-ci issue: Windows IL2CPP from Linux not possible/failed (2021.2 era); Mono worked. +- Memory/disk: no authoritative figure found. Unity issue UUM-90456: Linux IL2CPP "Linking GameAssembly.so" high memory, OOM-killed on low-RAM machines; forum: "LLVM ERROR: out of memory" on 32 GB, Master->Release C++ config fixed it. Unity docs (6000.3 linux-il2cpp-crosscompiler): toolchain package 462 MB (Linux), 2 GB each Win/mac host. Image pulls are 5-6 GB compressed each (above); a single image holds one module set (no combined image unless built with `game-ci build-unity-image`). +- gVisor/rootless: ZERO reports found of Unity Editor under gVisor/runsc (searches 2x). Yggdrasil runner facts from the runbook (F:\Projects\gamecult-ops\runbooks\forgejo-eureka-yggdrasil.md lines 29-45, 85-105): runsc with `--ignore-cgroups`, ENFORCED cap MemoryMax=4G via unit (no swap), CPUQuota 200%; "A 6 GB allocation was OOM-killed (exit 137) at the 4G cap"; gVisor reports host 16 CPUs/62 GB; capacity 1. +- No reports found of unity-builder on Forgejo/Gitea Actions (searched). + +## 2. Unity licensing for CI +- Unity 6000.3 manual (https://docs.unity.com/en-us/engine/6000.3/manual/get-started/install-and-upgrade/licenses-and-activation/managing-your-unity-license): command-line `-serial/-username/-password` (and `-returnlicense`) procedures "don't apply to Unity Personal. To activate a license for Unity Personal, log in to the Unity Hub." Headless/automated builds named as a use case for the Pro procedure. Named-user variant: `-serial -username -password` with serial omitted. +- Unity Build Server terms (https://unity.com/legal/terms-of-service/build-server, "Last updated: June 30, 2026"): §2.5 "You may not use Unity Build Server with the Unity Personal tier of the Unity Software." §1.1: if Total Finances exceed $200,000 USD, Personal may not be used at all. Build Server = floating licence server product. Unity Licensing Server docs (https://docs.unity.com/en-us/licensing-server) don't state eligible tiers on fetched page (Requirements page not read). +- GameCI Personal path (https://game.ci/docs/github/activation): activate in Unity Hub locally, copy the `.ulf` to secret `UNITY_LICENSE` + `UNITY_EMAIL`/`UNITY_PASSWORD`; Pro: `UNITY_SERIAL`+email+password; floating: `unityLicensingServer`. Docs say licences are not tied to a Unity version/platform; .ulf can be generated on one OS and used on another. Page does not mention Unity 6. +- Status of alf->ulf web activation (game-ci/documentation#408, open, updated 2026-10-04): https://license.unity3d.com/manual flow for Personal intermittently works (hidden "option-personal" element trick; "less than $100k" option); reports 2025-06..2025-11 "works", 2026-03-30 "web method expired with error", 2026-10-04 "workaround doesn't work anymore" vs another user succeeded same day. Alternative in thread (2025-08-21 GabLeRoux): create the .ulf via Unity Hub (not the website). A 2026-04-23 comment describes extracting a serial from the Hub-made .ulf and passing it with -username/-password (unverified). Also game-ci/unity-test-runner#235 (closed dup; 2026-04-29 comment "Confirmed the workaround above still works today"). +- Unity forum (Aug 2023) "Unity no longer supports manual activation of Personal licenses": no Unity staff reply. Codemagic help (updated Jun 2026, secondary) says Plus/Pro needed for CI. +- I did not find the current Unity Terms of Service text on Personal + automated builds beyond the Build Server terms above. + +## 3. Forgejo Actions / releases +- forgejo-runner Windows: official releases are linux-amd64/arm64 only (https://code.forgejo.org/api/v1/repos/forgejo/runner/releases, v13.2.1 2026-10-29). README: "supported and tested on amd64 and arm64" on Linux-kernel OSes. Windows: community builds only (github.com/Crown0815/Forgejo-runner-windows-builder; runner issues #263, #976, #1032 fixed compile via PR 987, #1441 open "How to keep the Windows built stable"; maintainers (earl-warren, #263) decline to test/support Windows). Host label syntax `self-hosted:host` documented at https://forgejo.org/docs/latest/admin/actions/configuration/ ("no isolation at all"); docs don't mention Windows. A third-party fork (forge.yumechi.jp yume-runner) ships a pwsh host-mode sample (unverified). +- Release API: `/repos/{owner}/{repo}/releases` and `/releases/{id}/assets` (https://forgejo.org/docs/latest/user/repository/releases/). Official action `actions/forgejo-release` (https://code.forgejo.org/actions/forgejo-release): inputs url, repo, tag, title, sha, token (needs write:repository), release-dir, release-notes(-file), prerelease, override, direction upload/download, gpg signing. +- Limits on THIS forge (https://eureka.gamecult.org/forge/api/v1/settings/attachment, version 16.0.3+gitea-1.22.0): release/attachment max_size 2048 MB per file, max_files 5 per upload, allowed_types default list incl .zip .gz .tgz .json .log .md .pdf .png ... (no .exe, .tar.xz, .7z, .AppImage, .msi). Config cheat sheet confirms `[repository.release]` ALLOWED_TYPES default list, MAX_SIZE 2048, MAX_FILES 5 (https://forgejo.org/docs/latest/admin/config-cheat-sheet/). Release-asset ALLOWED_TYPES is overridable by admin. +- Push mirror: docs say it mirrors "branches, tags, and commits" (`git push --mirror`); releases not mentioned (https://forgejo.org/docs/latest/user/repo-mirror/). A third-party project (gitea.com/FrankenBit/release-toolkit) states releases are API objects that do not cross a push mirror; tags do. So releases do not propagate (consistent, not officially stated). +- State of GameCult/Aetheria on the forge now: exists (id 60), `empty: true`, `mirror: false`, has_actions true, has_releases true, no releases/tags, default branch master. + +## 4. SemVer + changelog tooling +| Tool | What decides bump | Forgejo/Gitea | Non-conventional history | +|---|---|---|---| +| release-please (googleapis) | Conventional Commit prefixes (feat=minor, fix=patch, !=major); `Release-As:` footer overrides. | GitHub-only; issue googleapis/release-please#2870 (opened 2026-08-06, open) asks for Forgejo/Gitea provider. | README: "assumes you are using Conventional Commit messages"; non-releasable commits produce no release PR; squash-merge `BEGIN_COMMIT_OVERRIDE` in PR body rewrites changelog lines. | +| semantic-release 25.0.9 | commit-analyzer (angular preset default). | Default plugin is @semantic-release/github; Gitea publishers are third-party npm: @markwylde/semantic-release-gitea 2.2.0 (2025-12), @forge-for-gitea/semantic-release-gitea 1.2.0 (2025-09), @saithodev/... 2.1.0 (2021). Node tool. | Non-matching commits yield no release (standard behaviour; not verified from docs fetched). | +| changesets | Hand-written changeset files declaring bump per package; no commit parsing. | CLI host-agnostic (git + files); changesets/action is GitHub-only (unverified); designed for npm/monorepos ("conceptually beneficial for single package repos"). | Unaffected by commit style. | +| git-cliff | `--bump`/`--bumped-version` from commits: fix=patch, feat=minor, !=major; custom_major/minor_increment_regex; `[bump] features_always_bump_minor`, `breaking_always_bump_major`, `initial_tag`; `--bump major|minor|patch` explicit; tag_pattern. | Remote integrations: GitHub, GitLab, Gitea/Forgejo, Bitbucket, Azure DevOps (docs: website/docs/integration/gitea.md; configuration/remote.md). Rust single binary. Changelog only (does not publish releases). | `conventional_commits=false, filter_unconventional=false` includes any commit unparsed; `commit_parsers` regex on message groups arbitrary prose (e.g. `{message=".*", group="Other"}`); for unconventional commits only the subject line is used when bumping (docs usage/bump-version.md). | +| knope 0.23.2 (2026-10-22) | Conventional commits and/or changeset files (`.changeset/*.md` style); can disable conventional commits via PrepareRelease. | Native Gitea support: `[gitea] owner/repo/host` (example host codeberg.org), `GITEA_TOKEN`, Gitea CreateRelease step, release assets test (crates/knope/tests/gitea_release/release_assets). | "Any commit without a first line structured like [type(scope)!: summary] isn't a conventional commit" (ignored for bump). | +| cocogitto (cog) | `cog bump --auto` from Conventional Commits; hooks; `cog changelog` (tera templates). | README mentions only GitHub integration (action/bot); changelog `remote` templates (remote = "github.com" in example); Gitea unverified. | `cog check`/`cog commit` enforce convention; non-conforming handling not read. | +| Release Drafter v7 | Pull-request labels/title via `version-resolver` (major/minor/patch labels) and autolabeler; drafts release notes from merged PRs. | README: package `release-drafter` has CLI/API "for other CI systems... supports GitHub, GitHub Enterprise Server, Gitea, Forgejo, and GitLab." Main use is GitHub Action. | Independent of commit style; depends on PRs/labels existing (Aetheria history is direct commits; PR usage unverified). | +- Aetheria facts given: prose subjects, no Conventional Commits, v0.1 tag from 2020. + +### Game projects in practice (checked via release APIs) +- Mindustry (Anuken/Mindustry): GitHub tags `v160.7`, `v160.6` (build-number versions, 2026-09/10), 4 assets per release (Mindustry.jar, server-release.jar, assets.jar, dependencies.jar), notes hand-written bullets. +- OpenTTD: tags `16.0-beta5` (2026-10-24, prerelease, 0 attached assets on the GitHub release); release.yml workflow triggered by `release: published` / workflow_dispatch builds source, docs, Linux, etc. +- Veloren (GitLab veloren/veloren): releases v0.18.0 (2026-01-23), v0.17.0 (2024-12-27), v0.16.0 (2024-03-31); plus moving tags `weekly` and `nightly` (updated 2026-10-27). FreeBSD ports track weekly as `s20260128`. CI file not read. +- Godot: tags `4.7.2-stable`, `4.7-stable`; ~34 assets per release; hand-managed. +- Unitystation (Unity, open source): GitHub releases stopped 2017; "Get latest release by using our launcher" (latest-release body). +- None of these showed Conventional-Commit-driven bumps in what I read; not verified beyond release listings. + +## Unread / not done +- Unity Licensing Server Requirements page; unity-builder issue tracker for 6000.3; Forgejo `release` event / GITHUB_TOKEN permissions in 16.0 Actions; cocogitto non-conventional behaviour; semantic-release/changesets docs on non-conventional input (stated from knowledge, marked unverified above). From a4be037a4294efaa5d3d5267ecdc71c4375a9c80 Mon Sep 17 00:00:00 2001 From: soul Date: Fri, 30 Oct 2026 03:12:31 +0100 Subject: [PATCH 002/190] LFS lives on the Eureka forge: .lfsconfig points every clone at it Co-Authored-By: Claude Opus 5.5 --- .lfsconfig | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .lfsconfig diff --git a/.lfsconfig b/.lfsconfig new file mode 100644 index 000000000..d9ce439fc --- /dev/null +++ b/.lfsconfig @@ -0,0 +1,2 @@ +[lfs] + url = https://eureka.gamecult.org/forge/GameCult/Aetheria.git/info/lfs From 17c19521f5804fb59280aa2b38305d0b7b779cc4 Mon Sep 17 00:00:00 2001 From: Nibu Date: Thu, 5 Nov 2026 11:39:11 +0000 Subject: [PATCH 003/190] ship-authoring stats --top-speed adds the VelocityLimit a hull made without --like lacks validate refuses a ship hull with no top speed, and stats --top-speed refused a hull with none, so a package made without --like could not be made valid by any command (follow-up package-hull-top-speed). The flag now adds exactly one VelocityLimit and edits it on a later run; two stay refused. Co-Authored-By: Claude Sonnet 5.5 --- tests/Aetheria.Shared.Tests/ShipProductTests.cs | 11 +++++++++-- tools/AetherDb/ShipAuthoringCommands.cs | 16 ++++++++++++++-- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/ShipProductTests.cs b/tests/Aetheria.Shared.Tests/ShipProductTests.cs index bb358c4df..343f35082 100644 --- a/tests/Aetheria.Shared.Tests/ShipProductTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipProductTests.cs @@ -353,8 +353,6 @@ public sealed class ShipProductTests : IDisposable RefusedAndUntouched(path, "--mass", "5", "--mass", "6"); // A valid flag beside a bad one writes nothing. RefusedAndUntouched(path, "--mass", "5", "--durability", "-2"); - RefusedAndUntouched(bare, "--top-speed", "50"); - RefusedAndUntouched(bare, "--mass", "5", "--top-speed", "50"); // Two VelocityLimits leave no one top speed to set. RefusedAndUntouched(twin, "--top-speed", "50"); @@ -385,6 +383,15 @@ public sealed class ShipProductTests : IDisposable Assert.Equal((1f, 0f, 8000f), (ShipAuthoringStore.Load(path).Hull.Mass, ShipAuthoringStore.Load(path).Hull.Drag, ShipAuthoringStore.Load(path).Hull.Durability)); Assert.Equal(0, Run("stats", bare, "--armor", "12").Code); Assert.Equal(12f, ShipAuthoringStore.Load(bare).Hull.Armor); + + // A hull with no VelocityLimit gets exactly one from --top-speed, the only way a hull made without --like can + // satisfy validate; a second run edits that one rather than adding another. + Assert.Empty(ShipAuthoringStore.Load(bare).Hull.Behaviors.OfType()); + Assert.Equal(0, Run("stats", bare, "--mass", "5", "--top-speed", "50").Code); + Assert.Equal(0, Run("stats", bare, "--top-speed", "60").Code); + var added = Assert.Single(ShipAuthoringStore.Load(bare).Hull.Behaviors.OfType()).TopSpeed; + Assert.Equal((60f, 60f), (added.Min, added.Max)); + Assert.Equal(5f, ShipAuthoringStore.Load(bare).Hull.Mass); } [Fact] diff --git a/tools/AetherDb/ShipAuthoringCommands.cs b/tools/AetherDb/ShipAuthoringCommands.cs index bce7eda08..841da957e 100644 --- a/tools/AetherDb/ShipAuthoringCommands.cs +++ b/tools/AetherDb/ShipAuthoringCommands.cs @@ -8,7 +8,7 @@ using System.Linq; // Uses the existing database executable; mod authoring does not earn another binary target. public static class ShipAuthoringCommands { - private const string Usage = "ship-authoring create [--like ] | inspect | centre | validate | product (--name [--description ] [--not-offered] | --remove) | price | stats [--mass m] [--durability d] [--armor a] [--drag x] [--top-speed v] | compose "; + private const string Usage = "ship-authoring create [--like ] | starter --like | inspect | centre | validate | product (--name [--description ] [--not-offered] | --remove) | price | stats [--mass m] [--durability d] [--armor a] [--drag x] [--top-speed v] | compose "; private static readonly string[] StatFlags = { "--mass", "--durability", "--armor", "--drag", "--top-speed" }; @@ -78,6 +78,12 @@ public static class ShipAuthoringCommands Console.WriteLine($"Created draft {path}; fill its model bindings and schematic in Blender."); return 0; } + if (args[0] == "starter" && args.Length == 6 && args[4] == "--like") + { + var path = ShipStarterCommand.Write(args[1], args[2], args[3], ShippedShipHull(args[5])); + Console.WriteLine($"Wrote a flyable starter package {path}; replace its stand-in model through Blender and Package, then set price and product."); + return 0; + } if (args[0] == "price" && args.Length == 3) { // Judged before the file is touched: a refusal leaves it byte-identical. @@ -111,7 +117,13 @@ public static class ShipAuthoringCommands if (stats.TryGetValue("--top-speed", out var topSpeed)) { var limits = (hull.Behaviors ?? new List()).OfType().ToArray(); - if (limits.Length != 1) throw new InvalidOperationException($"{ship.Id}: --top-speed needs exactly one VelocityLimit on the hull; it has {limits.Length}."); + if (limits.Length > 1) throw new InvalidOperationException($"{ship.Id}: --top-speed needs at most one VelocityLimit on the hull; it has {limits.Length}."); + // A hull made without --like has none, and this is its only way to get one: validate refuses a ship without a top speed. + if (limits.Length == 0) + { + limits = new[] { new VelocityLimitData() }; + (hull.Behaviors ??= new List()).Add(limits[0]); + } // A fixed top speed, as every shipped hull authors one (Min equal to Max); its terms are kept. limits[0].TopSpeed.Min = limits[0].TopSpeed.Max = topSpeed; } From 5b4665dfbbd637d65ee25617c83d97bd2eaf6fc1 Mon Sep 17 00:00:00 2001 From: Nibu Date: Thu, 5 Nov 2026 11:39:11 +0000 Subject: [PATCH 004/190] ship-authoring starter: a complete flyable package for authors with no Blender Writes //ship.cc and ship.glb: a shipped hull's stats, a 4x6 grid with two drives, a radiator, two energy guns and the internal modules, and a boxed model carrying every anchor. The package is read back through ShipModCatalog.ReadPackage, so the GLB's node ids and mesh roles are judged by the reader the game boots with. Refuses to overwrite a package. Co-Authored-By: Claude Sonnet 5.5 --- docs/moddable-ship-authoring.md | 5 + .../ShipModCatalogTests.cs | 22 ++ tools/AetherDb/ShipStarterCommand.cs | 213 ++++++++++++++++++ 3 files changed, 240 insertions(+) create mode 100644 tools/AetherDb/ShipStarterCommand.cs diff --git a/docs/moddable-ship-authoring.md b/docs/moddable-ship-authoring.md index 446bb6d89..6a9e5c5c0 100644 --- a/docs/moddable-ship-authoring.md +++ b/docs/moddable-ship-authoring.md @@ -63,6 +63,11 @@ be empties. Package exports the collection, Grease Pencil excluded, to collection holds exactly one Grease Pencil object, and shows AetherDb's verdict in the panel. It runs the AetherDb in the game folder's `ModTools` (see Tools below). +A package made with `create` and no `--like` has no top speed, which `validate` refuses; `ship-authoring stats --top-speed ` +adds the one `VelocityLimit` it needs (and edits it on a later run). +Without Blender, `ship-authoring starter --like ` writes a complete flyable package: the +shipped hull's stats, a 4×6 grid carrying two thrusters, a radiator, two energy guns and the internal modules, and a boxed +`ship.glb` with every anchor. The model is a stand-in to replace through Blender and **Package**. `ship-authoring inspect ` reads drafts; `validate` requires complete hull, model, and anchor authoring, and judges `ship.glb` once it exists. diff --git a/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs b/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs index 717108d8d..3def3e6dd 100644 --- a/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs @@ -501,6 +501,28 @@ public sealed class ShipModCatalogTests : IDisposable Assert.True(File.Exists(target), error); } + // starter: a complete package from nothing but a hull to take stats from. The package must pass the reader the game boots + // with (GLB node ids and mesh roles included) and plan a rig, and a second run must not touch the first package. + [Fact] + public void StarterWritesAPackageTheGameLoadsAndPlansARigFrom() + { + var like = new HullData { Name = "Like", HullType = HullType.Ship, Mass = 1234, Behaviors = { new VelocityLimitData() } }; + var mods = Path.Combine(_directory.Path, "GameData", "Mods"); + var path = ShipStarterCommand.Write(mods, "probe.starter", "Probe Starter", like); + + var package = ShipModCatalog.ReadPackage(path); + Assert.Equal(("Probe Starter", 1234f), (package.Hull.Name, package.Hull.Mass)); + var plan = ShipModPlan.Build(package.Hull, package.Visual); + Assert.Equal(2, plan.Thrusters.Length); + Assert.Single(plan.Radiators); + Assert.Equal(new[] { 1, 1 }, plan.Weapons.Select(weapon => weapon.Muzzles.Length)); + Assert.Equal(package.Hull.Shape.Width * package.Hull.Shape.Height, package.Hull.Shape.Cells.Cast().Count(cell => cell)); + + var before = File.ReadAllBytes(path); + Assert.Throws(() => ShipStarterCommand.Write(mods, "probe.starter", "Other", like)); + Assert.Equal(before, File.ReadAllBytes(path)); + } + [Fact] public void CentreCommandPrintsShapeCenterOfMass() { diff --git a/tools/AetherDb/ShipStarterCommand.cs b/tools/AetherDb/ShipStarterCommand.cs new file mode 100644 index 000000000..2a502a1f5 --- /dev/null +++ b/tools/AetherDb/ShipStarterCommand.cs @@ -0,0 +1,213 @@ +using GameCult.Caching; +using CultMath; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; + +// `ship-authoring starter`: a complete, flyable mod package for authors with no Blender at hand. It writes the package +// (//ship.cc and ship.glb) with the stats of a shipped hull, a small hull grid, a working rig (two thrusters, +// a radiator, two energy guns, the internal modules) and a boxed model that carries every anchor the rig needs. The +// model is a stand-in an author replaces through Blender and Package; the records are judged by the same validator and +// reader the game boots with, so a starter that is written is a starter the game loads. +public static class ShipStarterCommand +{ + // Hull grid, x across, y from the stern (0) to the bow. The mount rows below say what sits in each cell. + private const int Width = 4, Height = 6; + + private sealed class Part + { + public string Id, Role, Parent; + public HardpointType? Mount; + public int2 Cell, Size = new int2(1, 1); + public float3 Position; + // Box half-extents; null for an empty node. Scale is the node scale, used by the shield envelope. + public float3? Half; + public float3? Scale; + } + + public static string Write(string modsRoot, string id, string name, HullData like) + { + ShipAuthoringStore.RequireShipId(id); + var directory = Path.Combine(Path.GetFullPath(modsRoot), id); + var path = Path.Combine(directory, "ship.cc"); + if (File.Exists(path) || File.Exists(Path.Combine(directory, "ship.glb"))) + throw new InvalidOperationException($"Refusing to replace the package in {directory}"); + + // Metres, nose toward -Y, up +Z, as the Blender add-on's kit frame has it; the GLB writer converts to glTF's Y-up. + var parts = new[] + { + new Part { Id = "map", Role = "map-icon", Half = new float3(3f, 5f, .05f) }, + new Part { Id = "collider", Role = "hull-collider", Half = new float3(3f, 5f, 1f) }, + new Part { Id = "shield", Role = "shield", Scale = new float3(4f, 6f, 2.5f) }, + new Part { Id = "tractor", Role = "tractor", Position = new float3(0f, -5f, 0f) }, + new Part { Id = "thruster.port", Role = "thruster-emitter", Mount = HardpointType.Thruster, Cell = new int2(0, 0), Size = new int2(2, 1), Position = new float3(2.2f, 5.4f, 0f), Half = new float3(.4f, .6f, .4f) }, + new Part { Id = "thruster.starboard", Role = "thruster-emitter", Mount = HardpointType.Thruster, Cell = new int2(2, 0), Size = new int2(2, 1), Position = new float3(-2.2f, 5.4f, 0f), Half = new float3(.4f, .6f, .4f) }, + new Part { Id = "radiator", Role = "radiator-mesh", Mount = HardpointType.Radiator, Cell = new int2(1, 1), Size = new int2(2, 1), Position = new float3(0f, 2f, 1.1f), Half = new float3(1.5f, .8f, .08f) }, + new Part { Id = "gun.port", Role = "weapon-mount", Mount = HardpointType.Energy, Cell = new int2(0, 5), Position = new float3(1.8f, -3f, 1.1f) }, + new Part { Id = "gun.port.muzzle", Role = "weapon-muzzle", Parent = "gun.port", Position = new float3(1.8f, -4f, 1.1f) }, + new Part { Id = "gun.starboard", Role = "weapon-mount", Mount = HardpointType.Energy, Cell = new int2(3, 5), Position = new float3(-1.8f, -3f, 1.1f) }, + new Part { Id = "gun.starboard.muzzle", Role = "weapon-muzzle", Parent = "gun.starboard", Position = new float3(-1.8f, -4f, 1.1f) }, + }; + // Internal modules show on no model, so they have a cell and no anchor. + var internals = new[] + { + ("reactor", HardpointType.Reactor, new int2(1, 2), new int2(2, 2)), ("shield", HardpointType.Shield, new int2(3, 4), new int2(1, 1)), + ("control", HardpointType.ControlModule, new int2(1, 4), new int2(2, 2)), ("sensors", HardpointType.Sensors, new int2(0, 4), new int2(1, 1)), + }; + + var ship = new ShipAuthoring + { + Id = id, + ModelAsset = "ship.glb", + Anchors = parts.Select(part => new ShipAnchor { Id = part.Id, Role = part.Role, ModelNodeId = part.Id, ParentId = part.Parent }).ToList() + }; + var hull = ShipAuthoringStore.HullLike(like, name, id); + hull.Shape = new Shape(Width, Height); + for (var x = 0; x < Width; x++) + for (var y = 0; y < Height; y++) + hull.Shape.Cells[x, y] = true; + hull.Hardpoints = parts.Where(part => part.Mount != null) + .Select(part => (part.Id, part.Mount.Value, part.Cell, part.Size)) + .Concat(internals.Select(row => (Id: "internal." + row.Item1, Mount: row.Item2, Cell: row.Item3, Size: row.Item4))) + .Select(row => new HardpointData + { + Type = row.Item2, Position = row.Item3, Shape = Block(row.Item4), Transform = row.Item1, + // The grid's stern is y = 0 and its bow the far row: a drive there pushes the ship toward the bow, which the + // authoring grid spells Reversed (as Djinni's stern drives are). + Rotation = row.Item2 == HardpointType.Thruster ? ItemRotation.Reversed : ItemRotation.None + }).ToList(); + ShipAuthoringStore.Validate(hull, ship); + + Directory.CreateDirectory(directory); + File.WriteAllBytes(Path.Combine(directory, ship.ModelAsset), Glb(parts)); + using (var cache = ShipAuthoringStore.Open(path, writable: true)) + { + ShipAuthoringStore.Write(cache, hull, ship); + cache.FlushAsync().Wait(); + } + // The reader the game boots with, over the written package: the GLB's node ids and mesh roles are judged too. + ShipModCatalog.ReadPackage(path); + return path; + } + + private static Shape Block(int2 size) + { + var shape = new Shape(size.x, size.y); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + return shape; + } + + // One GLB holding every part as a root-level node, each box with its own vertices (a convex collider cooks from it + // as it is), and each muzzle a child of its mount. Node ids travel in extras.aetheria.id, as Package writes them. + private static byte[] Glb(Part[] parts) + { + var bin = new List(); + var views = new List(); + var accessors = new List(); + var meshes = new List(); + var meshOf = new Dictionary(); + + int View(byte[] bytes, int target) + { + while (bin.Count % 4 != 0) bin.Add(0); + views.Add($@"{{""buffer"":0,""byteOffset"":{bin.Count},""byteLength"":{bytes.Length},""target"":{target}}}"); + bin.AddRange(bytes); + return views.Count - 1; + } + string F(float value) => value.ToString("R", CultureInfo.InvariantCulture); + + foreach (var part in parts.Where(part => part.Half != null)) + { + var (hx, hy, hz) = (part.Half.Value.x, part.Half.Value.y, part.Half.Value.z); + var positions = new List(); + var normals = new List(); + var indices = new List(); + // Six faces, outward normals, in the Blender frame; Gltf() turns each into glTF's. + foreach (var (axis, sign) in new[] { (0, 1), (0, -1), (1, 1), (1, -1), (2, 1), (2, -1) }) + { + var u = (axis + 1) % 3; + var v = (axis + 2) % 3; + var half = new[] { hx, hy, hz }; + var first = (ushort)(positions.Count / 3); + foreach (var (a, b) in new[] { (-1, -1), (1, -1), (1, 1), (-1, 1) }) + { + var corner = new float[3]; + corner[axis] = sign * half[axis]; + corner[u] = a * half[u]; + corner[v] = b * half[v]; + positions.AddRange(Gltf(corner[0], corner[1], corner[2])); + var normal = new float[3]; + normal[axis] = sign; + normals.AddRange(Gltf(normal[0], normal[1], normal[2])); + } + // The (axis, u, v) frame is right-handed, so the corner order above winds counter-clockwise seen from +axis. + var order = sign > 0 ? new[] { 0, 1, 2, 0, 2, 3 } : new[] { 0, 2, 1, 0, 3, 2 }; + indices.AddRange(order.Select(i => (ushort)(first + i))); + } + var positionView = View(positions.SelectMany(BitConverter.GetBytes).ToArray(), 34962); + var normalView = View(normals.SelectMany(BitConverter.GetBytes).ToArray(), 34962); + var indexView = View(indices.SelectMany(BitConverter.GetBytes).ToArray(), 34963); + var low = Gltf(-hx, -hy, -hz); + var high = Gltf(hx, hy, hz); + var box = new[] { Math.Min(low[0], high[0]), Math.Min(low[1], high[1]), Math.Min(low[2], high[2]), Math.Max(low[0], high[0]), Math.Max(low[1], high[1]), Math.Max(low[2], high[2]) }; + accessors.Add($@"{{""bufferView"":{positionView},""componentType"":5126,""count"":{positions.Count / 3},""type"":""VEC3"",""min"":[{F(box[0])},{F(box[1])},{F(box[2])}],""max"":[{F(box[3])},{F(box[4])},{F(box[5])}]}}"); + accessors.Add($@"{{""bufferView"":{normalView},""componentType"":5126,""count"":{normals.Count / 3},""type"":""VEC3""}}"); + accessors.Add($@"{{""bufferView"":{indexView},""componentType"":5123,""count"":{indices.Count},""type"":""SCALAR""}}"); + meshOf[part] = meshes.Count; + meshes.Add($@"{{""primitives"":[{{""attributes"":{{""POSITION"":{accessors.Count - 3},""NORMAL"":{accessors.Count - 2}}},""indices"":{accessors.Count - 1}}}]}}"); + } + + // A muzzle is a child of its mount, so its translation is relative to the mount's. + var byId = parts.ToDictionary(part => part.Id, StringComparer.Ordinal); + var nodeIndex = parts.Select((part, index) => (part.Id, index)).ToDictionary(pair => pair.Id, pair => pair.index, StringComparer.Ordinal); + string Node(Part part) + { + var translation = part.Parent == null ? part.Position : part.Position - byId[part.Parent].Position; + var g = Gltf(translation.x, translation.y, translation.z); + var json = new StringBuilder($@"{{""name"":""{part.Id}"""); + if (meshOf.TryGetValue(part, out var mesh)) json.Append($@",""mesh"":{mesh}"); + if (part.Scale != null) { var s = Gltf(part.Scale.Value.x, part.Scale.Value.y, part.Scale.Value.z); json.Append($@",""scale"":[{F(Math.Abs(s[0]))},{F(Math.Abs(s[1]))},{F(Math.Abs(s[2]))}]"); } + json.Append($@",""translation"":[{F(g[0])},{F(g[1])},{F(g[2])}]"); + var children = parts.Where(child => child.Parent == part.Id).Select(child => nodeIndex[child.Id]).ToArray(); + if (children.Length > 0) json.Append($@",""children"":[{string.Join(",", children)}]"); + json.Append($@",""extras"":{{""aetheria.id"":""{part.Id}""}}}}"); + return json.ToString(); + } + var roots = parts.Where(part => part.Parent == null).Select(part => nodeIndex[part.Id]); + var document = $@"{{""asset"":{{""version"":""2.0"",""generator"":""AetherDb ship-authoring starter""}},""scene"":0,""scenes"":[{{""nodes"":[{string.Join(",", roots)}]}}]," + + $@"""nodes"":[{string.Join(",", parts.Select(Node))}],""meshes"":[{string.Join(",", meshes)}],""accessors"":[{string.Join(",", accessors)}]," + + $@"""bufferViews"":[{string.Join(",", views)}],""buffers"":[{{""byteLength"":{bin.Count + (4 - bin.Count % 4) % 4}}}]}}"; + return Container(document, bin.ToArray()); + } + + // Blender (x right, y back, z up) to glTF (x right, y up, z toward the viewer): the exporter's +Y-up conversion. + private static float[] Gltf(float x, float y, float z) => new[] { x, z, -y }; + + private static byte[] Container(string json, byte[] bin) + { + byte[] Pad(byte[] bytes, byte fill) + { + var padded = new byte[(bytes.Length + 3) / 4 * 4]; + Array.Fill(padded, fill); + bytes.CopyTo(padded, 0); + return padded; + } + var body = Pad(Encoding.UTF8.GetBytes(json), (byte)' '); + var data = Pad(bin, 0); + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + writer.Write(0x46546C67u); + writer.Write(2u); + writer.Write((uint)(28 + body.Length + data.Length)); + writer.Write((uint)body.Length); + writer.Write(0x4E4F534Au); + writer.Write(body); + writer.Write((uint)data.Length); + writer.Write(0x004E4942u); + writer.Write(data); + return stream.ToArray(); + } +} From a892b5463bac008e95518eca322a6e074e39a0d9 Mon Sep 17 00:00:00 2001 From: Nibu Date: Thu, 5 Nov 2026 11:39:11 +0000 Subject: [PATCH 005/190] Wren: the starter's first package, a stand-in light courier in GameData/Mods Written by ship-authoring starter --like Djinni, priced, with an unoffered Aeronautics Unlimited product (so the census counts it sold and no faction fields a box). Tests: it composes into the catalog, its mounts take catalog gear, and the fitted ship moves under thrust. Drop the directory to remove it; replace the model through Blender and Package to make it a real hull. Co-Authored-By: Claude Sonnet 5.5 --- GameData/Mods/aetheria.wren/ship.cc | 3 + GameData/Mods/aetheria.wren/ship.glb | 3 + .../Aetheria.Shared.Tests/WrenPackageTests.cs | 68 +++++++++++++++++++ 3 files changed, 74 insertions(+) create mode 100644 GameData/Mods/aetheria.wren/ship.cc create mode 100644 GameData/Mods/aetheria.wren/ship.glb create mode 100644 tests/Aetheria.Shared.Tests/WrenPackageTests.cs diff --git a/GameData/Mods/aetheria.wren/ship.cc b/GameData/Mods/aetheria.wren/ship.cc new file mode 100644 index 000000000..0b5e70964 --- /dev/null +++ b/GameData/Mods/aetheria.wren/ship.cc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b66dab2993fc365eacaf900ef1405f40b8ac2301977793c61d1c96475743017a +size 10506 diff --git a/GameData/Mods/aetheria.wren/ship.glb b/GameData/Mods/aetheria.wren/ship.glb new file mode 100644 index 000000000..03b70b729 --- /dev/null +++ b/GameData/Mods/aetheria.wren/ship.glb @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:98bf1b4a0e19e67568930ca79b9d61529c21c63dd74ee8df3d3f1d419d3a81cc +size 6964 diff --git a/tests/Aetheria.Shared.Tests/WrenPackageTests.cs b/tests/Aetheria.Shared.Tests/WrenPackageTests.cs new file mode 100644 index 000000000..bb95cbb55 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/WrenPackageTests.cs @@ -0,0 +1,68 @@ +using System.Linq; +using CultMath; +using GameCult.Caching; +using Xunit; +using static CultMath.math; +using Random = CultMath.Random; + +// GameData/Mods/aetheria.wren: a first-party package written by `ship-authoring starter --like Djinni`, then priced and given +// an unoffered Aeronautics Unlimited product by `ship-authoring price` and `product`; its model is the starter's boxed +// stand-in. It is the pipeline's proof from a hull package on disk to a ship that flies in the headless simulation: the +// package composes into the catalog, its mounts take catalog gear, and the fitted ship moves under thrust. `fly` cannot +// reach it (an unoffered product is never drawn), so these tests are the flight check until a pinned Loadout exists. +public sealed class WrenPackageTests +{ + private const string Id = "aetheria.wren"; + + private static HullData Wren(CultCache cache) => cache.Get(new CultRecordRef(ShipModCatalog.HullKey(Id))); + + [Fact] + public void TheStarterPackageIsInTheComposedCatalogWithTheStatsOfItsLike() + { + using var cache = RestoredHullsTests.OpenCatalog(); + var hull = Wren(cache); + var like = cache.GetByName("Djinni"); + Assert.NotNull(hull); + Assert.Equal(("Wren", HullType.Ship, like.Mass, like.Durability), (hull.Name, hull.HullType, hull.Mass, hull.Durability)); + Assert.Equal(ShipModCatalog.AuthoringKey(Id), hull.Visual.Key); + Assert.Equal(2, hull.Hardpoints.Count(h => h.Type == HardpointType.Thruster)); + Assert.Equal(2, hull.Hardpoints.Count(h => h.Type == HardpointType.Energy)); + } + + // The starter's product is its maker's but off the market (rulings package-carries-product, off-market-is-unoffered-product): + // the census wants every design sold or placed, and no faction fields a stand-in box. + [Fact] + public void TheStarterIsMadeButNeverOffered() + { + using var cache = RestoredHullsTests.OpenCatalog(); + var hull = Wren(cache); + var product = Assert.Single(cache.GetAll(), p => p.Design.Key.Equals(ShipModCatalog.HullKey(Id))); + Assert.Equal("Aeronautics Unlimited", cache.Get(product.Manufacturer).Name); + Assert.True(product.NotOffered); + Assert.True(hull.Price > 0); + Assert.DoesNotContain(hull, LoadoutGenerator.SoldHulls(cache)); + } + + // Every mount takes a catalog design: the starter's footprints are sized to gear that exists, so it can be fitted out. + [Fact] + public void EveryMountTakesACatalogDesign() + { + using var cache = RestoredHullsTests.OpenCatalog(); + var designs = cache.GetAll().ToArray(); + var bare = Wren(cache).Hardpoints.Where(hardpoint => !designs.Any(hardpoint.Takes)).Select(hardpoint => $"{hardpoint.Transform} ({hardpoint.Type})").ToArray(); + // No shield design fits a 1x1 yet (hardpoint-fit lists Djinni's 4-cell shield with none either); every other mount does. + Assert.Equal(new[] { "internal.shield (Shield)" }, bare); + } + + [Fact] + public void TheStarterFliesUnderThrust() + { + using var cache = RestoredHullsTests.OpenCatalog(); + var ship = RestoredHullsTests.BuildThrustedShip(cache, "Wren"); + var start = ship.Velocity; + ship.MovementDirection = float2(0, 1); + for (var i = 0; i < 10; i++) ship.Zone.Update(1f / 60f); + Assert.NotEqual(start, ship.Velocity); + Assert.True(ship.GetBehavior().Limit > 0f); + } +} From 8c5a904cb7d1da930489c04680c871ffa0295d2b Mon Sep 17 00:00:00 2001 From: Nibu Date: Thu, 5 Nov 2026 11:39:11 +0000 Subject: [PATCH 006/190] Tests that pin a thruster's authored push read it at ThrustScale 1 e0c1daa4e made thrust a tenth of authored by default (GameplaySettings.ThrustScale = .1), which broke twelve tests that pin what a thruster, a hull or a brain does (Brownout, ConditionRatio, Longinus top speed, the evasion, approach and envelope tests, SimRateEquivalence). Their fixtures now state ThrustScale 1: they pin mechanics, and a retune of the global knob does not move them. Co-Authored-By: Claude Sonnet 5.5 --- tests/Aetheria.Shared.Tests/BrownoutTests.cs | 3 ++- tests/Aetheria.Shared.Tests/ConditionRatioTests.cs | 3 ++- tests/Aetheria.Shared.Tests/RestoredHullsTests.cs | 10 +++++++++- tests/Aetheria.Shared.Tests/RunStartTests.cs | 2 +- 4 files changed, 14 insertions(+), 4 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/BrownoutTests.cs b/tests/Aetheria.Shared.Tests/BrownoutTests.cs index 95958170c..3ac400c56 100644 --- a/tests/Aetheria.Shared.Tests/BrownoutTests.cs +++ b/tests/Aetheria.Shared.Tests/BrownoutTests.cs @@ -53,7 +53,8 @@ public sealed class BrownoutTests : IDisposable { DefaultEntitySettings = new EntitySettings(), Tiers = new[] { new RarityTier { Name = "Common", Quality = .5f, Color = new float3(1, 1, 1) } }, - QualityPriceModifier = new ExponentialLerp() + QualityPriceModifier = new ExponentialLerp(), + ThrustScale = 1f // these pin a thruster's authored push, not the global flight tuning }; private static PerformanceStat Constant(float v) => new PerformanceStat { Min = v, Max = v }; diff --git a/tests/Aetheria.Shared.Tests/ConditionRatioTests.cs b/tests/Aetheria.Shared.Tests/ConditionRatioTests.cs index 00d446384..3e02965db 100644 --- a/tests/Aetheria.Shared.Tests/ConditionRatioTests.cs +++ b/tests/Aetheria.Shared.Tests/ConditionRatioTests.cs @@ -28,7 +28,8 @@ public sealed class ConditionRatioTests : IDisposable { DefaultEntitySettings = new EntitySettings(), Tiers = new[] { new RarityTier { Name = "Common", Quality = .5f, Color = new float3(1, 1, 1) } }, - QualityPriceModifier = new ExponentialLerp() + QualityPriceModifier = new ExponentialLerp(), + ThrustScale = 1f // these pin a thruster's authored push, not the global flight tuning }; private static PerformanceStat Constant(float v) => new PerformanceStat { Min = v, Max = v }; diff --git a/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs b/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs index 6dd235551..121d468b3 100644 --- a/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs +++ b/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs @@ -31,7 +31,15 @@ public sealed class RestoredHullsTests // (tools/AetherDb/AuthoredSettings.cs) is the same headless YAML reader tools/AetherDb already uses to // inspect Settings.asset outside Unity; this loads the real GameplaySettings the same way instead of // hand-copying its fields a second time. - internal static GameplaySettings Settings() => AuthoredSettings.Load(FindRepoRoot()).Read("GameplaySettings"); + internal static GameplaySettings Settings() => PinnedFlight(AuthoredSettings.Load(FindRepoRoot()).Read("GameplaySettings")); + + // The authored settings with the global thrust tuning at 1 (GameplaySettings.ThrustScale, 0.1 in play): tests that pin + // what a thruster, a hull or a brain does read the gear's own thrust, so a retune of the knob does not move them. + internal static GameplaySettings PinnedFlight(GameplaySettings settings) + { + settings.ThrustScale = 1f; + return settings; + } // Same composition FireControlCut7Tests.OpenReadOnlyRealCatalog uses: a registry scoped to the shipped // assembly's own [CultDocument] types, so this test's own process-wide type registration never pollutes the diff --git a/tests/Aetheria.Shared.Tests/RunStartTests.cs b/tests/Aetheria.Shared.Tests/RunStartTests.cs index 69b040d4e..efd17eb71 100644 --- a/tests/Aetheria.Shared.Tests/RunStartTests.cs +++ b/tests/Aetheria.Shared.Tests/RunStartTests.cs @@ -53,7 +53,7 @@ public sealed partial class RunStartTests : IDisposable _galaxy = new Galaxy(tutorial, authored.Read("TutorialBackgroundSettings"), _cache, new PlayerSettings(), Directory.CreateDirectory(Path.Combine(_root, "Narrative")), _ => { }, null, GalaxySeed); - _items = new ItemManager(1u, _cache, new ProvenanceLedger(), authored.Read("GameplaySettings"), _ => { }); + _items = new ItemManager(1u, _cache, new ProvenanceLedger(), RestoredHullsTests.PinnedFlight(authored.Read("GameplaySettings")), _ => { }); _protagonist = _galaxy.ResolveFaction(tutorial.ProtagonistFaction); // GameSettings.StartingHullName is a plain field of the Unity settings object, not a ServerShared subtree From a0c760f5cf46c798012ac2ece37dc7113dbd46c3 Mon Sep 17 00:00:00 2001 From: Nibu Date: Thu, 5 Nov 2026 11:39:59 +0000 Subject: [PATCH 007/190] Wren: product renamed Wren Courier; 'Wren' collided with a shipped product and compose excluded the package Co-Authored-By: Claude Sonnet 5.5 --- GameData/Mods/aetheria.wren/ship.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GameData/Mods/aetheria.wren/ship.cc b/GameData/Mods/aetheria.wren/ship.cc index 0b5e70964..d81f9bba5 100644 --- a/GameData/Mods/aetheria.wren/ship.cc +++ b/GameData/Mods/aetheria.wren/ship.cc @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:b66dab2993fc365eacaf900ef1405f40b8ac2301977793c61d1c96475743017a -size 10506 +oid sha256:6b1744dfa7dd6c5325ca3bd04fba941408cdc1255c06d1fc0d52fa67c97dc100 +size 10514 From 2b0fb3c22ded74ab25513c122d74014aadffa086 Mon Sep 17 00:00:00 2001 From: Nibu Date: Fri, 6 Nov 2026 00:15:56 +0000 Subject: [PATCH 008/190] fly reaches unoffered hulls through their Loadout; authoring doc no longer says console-only A hull no maker offers is drawn by no generator, so fly now falls back to a catalog Loadout of the named ship hull (Loadouts.Materialize with the game's chooser). The authoring doc claimed a product-less package is console-only; it is unreachable unless a Loadout fits it. Co-Authored-By: Claude Sonnet 5.5 --- Assets/Scripts/Gameplay/ActionGameManager.cs | 20 ++++++++++++++++---- docs/moddable-ship-authoring.md | 5 +++-- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/Assets/Scripts/Gameplay/ActionGameManager.cs b/Assets/Scripts/Gameplay/ActionGameManager.cs index 62105a711..a0cf3a4c1 100644 --- a/Assets/Scripts/Gameplay/ActionGameManager.cs +++ b/Assets/Scripts/Gameplay/ActionGameManager.cs @@ -590,12 +590,24 @@ public class ActionGameManager : MonoBehaviour } var generator = new LoadoutGenerator(ref ItemManager.Random, ItemManager, CurrentGalaxy, Zone.GalaxyZone, null, 2); var pack = generator.GenerateShipLoadout(data => string.Equals(data.Name, hullName, StringComparison.InvariantCultureIgnoreCase)); - if (pack == null) + Ship ship; + if (pack != null) ship = (Ship) EntitySerializer.Unpack(ItemManager, Zone, pack); + else { - ConsoleController.Instance.AppendLogLine($"No ship hull named \"{hullName}\""); - return; + // An unoffered hull is drawn by nobody; it reaches a ship only through a Loadout (ruling off-market-is-general). + var failures = new List(); + var loadout = ItemManager.ItemData.GetAll().FirstOrDefault(l => + ItemManager.ItemData.Get(l.Hull) is { HullType: HullType.Ship } hull && + string.Equals(hull.Name, hullName, StringComparison.InvariantCultureIgnoreCase)); + ship = loadout == null ? null : Loadouts.Materialize(ItemManager, Zone, loadout, generator.ChooseProduct, failures) as Ship; + if (ship == null) + { + ConsoleController.Instance.AppendLogLine(failures.Count > 0 + ? $"Cannot build \"{hullName}\": {string.Join("; ", failures)}" + : $"No ship hull named \"{hullName}\" that a maker offers or a Loadout fits"); + return; + } } - var ship = (Ship) EntitySerializer.Unpack(ItemManager, Zone, pack); ship.IsPlayerShip = true; ship.Direction = _currentEntity.Direction; ship.Position.xz = _currentEntity.Position.xz + _currentEntity.Direction.Rotate(ItemRotation.Clockwise) * 30; diff --git a/docs/moddable-ship-authoring.md b/docs/moddable-ship-authoring.md index 6a9e5c5c0..81871b2dc 100644 --- a/docs/moddable-ship-authoring.md +++ b/docs/moddable-ship-authoring.md @@ -245,8 +245,9 @@ catalog. Continue refuses a run naming a design the catalog no longer holds price and `ship-authoring product --name [--description ]` writes the package's product by that maker (`--remove` deletes it). A package with a product needs a price above 0, - because generation skips price 0; a package with none stays valid and is - console-only. Compose follows. + because generation skips price 0; a package with none stays valid but no + maker offers it, so generation never draws it. Console `fly ` reaches such a hull only + through a catalog Loadout of it. Compose follows. 3. A command-line validator rejects malformed cells, overlapping or dangling hardpoints, missing model nodes, and unresolved asset references with precise errors. It changes no live catalog or scene on failure. The From 65a6297aee247c603141850eaf0be2dc7048f989 Mon Sep 17 00:00:00 2001 From: Nibu Date: Sat, 7 Nov 2026 11:55:50 +0000 Subject: [PATCH 009/190] Save standings by faction, not by list position RunSave.Capture wrote Factions in HomeZones key order and Relationships in galaxy.Factions order; Galaxy's save constructor paired them by index, so a galaxy whose two orders differed resumed with standings on the wrong factions. SavedGame.Standings (Key 16) now carries each standing with its faction ref. A save without it still reads Relationships by index, the only record it holds. Co-Authored-By: Claude Sonnet 5.5 --- Assets/Scripts/ServerShared/Galaxy.cs | 12 +++-- Assets/Scripts/ServerShared/SavedGame.cs | 20 +++++++- tests/Aetheria.Shared.Tests/RunSaveTests.cs | 53 +++++++++++++++++++-- 3 files changed, 76 insertions(+), 9 deletions(-) diff --git a/Assets/Scripts/ServerShared/Galaxy.cs b/Assets/Scripts/ServerShared/Galaxy.cs index 08512f8af..797e77764 100644 --- a/Assets/Scripts/ServerShared/Galaxy.cs +++ b/Assets/Scripts/ServerShared/Galaxy.cs @@ -58,10 +58,14 @@ public class Galaxy Seed = savedGame.Seed; Factions = savedGame.Factions.Select(faction => cultCache.Get(faction)).ToArray(); - for (var i = 0; i < Factions.Length; i++) - { - FactionRelationships[Factions[i]] = savedGame.Relationships[i]; - } + if (savedGame.Standings != null) + foreach (var standing in savedGame.Standings) + FactionRelationships[cultCache.Get(standing.Faction)] = standing.Relationship; + else + // A save before Standings wrote Relationships in an order it did not record; it is right only for a + // galaxy that never reordered, and is all that save holds. + for (var i = 0; i < Factions.Length; i++) + FactionRelationships[Factions[i]] = savedGame.Relationships[i]; var savedZones = savedGame.Zones.Select(zone => cultCache.Get(zone)).ToArray(); Zones = savedZones.Select(zone => diff --git a/Assets/Scripts/ServerShared/SavedGame.cs b/Assets/Scripts/ServerShared/SavedGame.cs index 90ef03566..ff4de6e9b 100644 --- a/Assets/Scripts/ServerShared/SavedGame.cs +++ b/Assets/Scripts/ServerShared/SavedGame.cs @@ -45,6 +45,8 @@ public class SavedGame [Key(11)] public bool IsTutorial; + // Read only by a save written before Standings: its entries follow galaxy.Factions order, not Factions order, so + // Galaxy trusts it only when the two orders cannot differ (see Galaxy's save constructor). [Key(12)] public FactionRelationship[] Relationships; @@ -61,6 +63,21 @@ public class SavedGame // gets Regions, Partition and Deal from its saved graph, boss zones, Exit and seed. [Key(15)] public List Provinces; + + // Each faction's standing, keyed by the faction itself so no list order can misplace it. Written by RunSave.Capture; + // null in a save written before it, which then reads Relationships. + [Key(16)] + public List Standings; +} + +[MessagePackObject] +public class SavedStanding +{ + [Key(0)] + public CultRecordRef Faction; + + [Key(1)] + public FactionRelationship Relationship; } [MessagePackObject] @@ -87,7 +104,8 @@ public static class RunSave DiscoveredZones = galaxy.DiscoveredZones.Select(dz => Array.IndexOf(galaxy.Zones, dz)).ToArray(), Background = galaxy.Background, Factions = factions.Select(f => cache.RefOf(f)).ToArray(), - Relationships = galaxy.Factions.Select(f => galaxy.FactionRelationships[f]).ToArray(), + Standings = galaxy.Factions.Select(f => new SavedStanding + {Faction = cache.RefOf(f), Relationship = galaxy.FactionRelationships[f]}).ToList(), HomeZones = galaxy.HomeZones.ToDictionary( x => Array.IndexOf(factions, x.Key), x => Array.IndexOf(galaxy.Zones, x.Value)), diff --git a/tests/Aetheria.Shared.Tests/RunSaveTests.cs b/tests/Aetheria.Shared.Tests/RunSaveTests.cs index 00a6baa75..05c0a86ac 100644 --- a/tests/Aetheria.Shared.Tests/RunSaveTests.cs +++ b/tests/Aetheria.Shared.Tests/RunSaveTests.cs @@ -150,6 +150,48 @@ public sealed class RunSaveTests : IDisposable } } + // Galaxy.Factions and Galaxy.HomeZones.Keys are two orders of the same factions. A saved standing belongs to its + // faction, whichever order the galaxy lists them in. + [Fact] + public void StandingsSurviveSaveAndContinueWhenFactionOrderDiffersFromHomeZoneOrder() + { + using (var cache = AetheriaStores.Open(Catalog, catalogWritable: true)) + { + cache.Upsert(new Faction { Name = "Borealis", ShortName = "BOR" }); + cache.Upsert(new Faction { Name = "Corvid", ShortName = "COR" }); + cache.FlushAsync().Wait(); + } + + using (var cache = Open()) + { + var factions = cache.GetAll().OrderBy(f => f.Name, StringComparer.Ordinal).ToArray(); + var game = Game(cache, factions); + RunSave.Commit(cache, game, Zones(2, null, -1), new ProvenanceLedger()); + } + + var expected = new Dictionary + { + { "Adrasteia", FactionRelationship.Hated }, { "Borealis", FactionRelationship.Friendly }, { "Corvid", FactionRelationship.Beloved } + }; + + using (var cache = Open()) + { + var galaxy = new Galaxy(cache, cache.GetGlobal(), _ => { }); + Assert.NotEqual(galaxy.Factions, galaxy.HomeZones.Keys); + foreach (var faction in galaxy.Factions) galaxy.FactionRelationships[faction] = expected[faction.Name]; + var itemManager = new ItemManager(1u, cache, new ProvenanceLedger(), TestSettings(), _ => { }); + galaxy.Zones[0].Contents = new Zone(itemManager, new PlanetSettings(), new ZonePack(), galaxy.Zones[0], galaxy); + var (game, zones) = RunSave.Capture(cache, galaxy, galaxy.Zones[0].Contents, null, new SavedActionBarBinding[0], 0); + RunSave.Commit(cache, game, zones, RunSave.Lots(cache)); + } + + using (var cache = Open()) + { + var galaxy = new Galaxy(cache, cache.GetGlobal(), _ => { }); + Assert.Equal(expected, galaxy.Factions.ToDictionary(f => f.Name, f => galaxy.FactionRelationships[f])); + } + } + // The run's credits ride the save: what Capture is given is what a later Continue reads from the run store. [Fact] public void CreditsSurviveContinue() @@ -753,11 +795,14 @@ public sealed class RunSaveTests : IDisposable return new ZonePack { Orbits = { root, moon }, Planets = { body } }; } - private static SavedGame Game(CultCache cache) => new SavedGame + private static SavedGame Game(CultCache cache) => Game(cache, cache.GetAll().Single()); + + // HomeZones lists the factions in reverse of their saved order. + private static SavedGame Game(CultCache cache, params Faction[] factions) => new SavedGame { - Factions = new[] { cache.RefOf(cache.GetAll().Single()) }, - Relationships = new[] { FactionRelationship.Neutral }, - HomeZones = new Dictionary { { 0, 0 } }, + Factions = factions.Select(f => cache.RefOf(f)).ToArray(), + Relationships = factions.Select(_ => FactionRelationship.Neutral).ToArray(), + HomeZones = factions.Select((_, i) => factions.Length - 1 - i).ToDictionary(i => i, _ => 0), BossZones = new Dictionary(), DiscoveredZones = new[] { 0 }, ActionBarBindings = new SavedActionBarBinding[0], From b571555e2a2ac2637366e200924f769d9168dd70 Mon Sep 17 00:00:00 2001 From: Nibu Date: Sat, 7 Nov 2026 15:00:22 +0000 Subject: [PATCH 010/190] ship-authoring stats --top-speed adds the VelocityLimit a bare hull lacks create without --like makes a hull with no behaviors, Validate refuses a ship hull without a VelocityLimit, and stats --top-speed refused any hull without exactly one: no command could give such a hull a top speed. The first --top-speed now adds the one limit; two or more are still refused. Co-Authored-By: Claude Sonnet 5.5 --- tests/Aetheria.Shared.Tests/ShipProductTests.cs | 6 ++++-- tools/AetherDb/ShipAuthoringCommands.cs | 7 +++++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/ShipProductTests.cs b/tests/Aetheria.Shared.Tests/ShipProductTests.cs index bb358c4df..f2326ed82 100644 --- a/tests/Aetheria.Shared.Tests/ShipProductTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipProductTests.cs @@ -353,8 +353,6 @@ public sealed class ShipProductTests : IDisposable RefusedAndUntouched(path, "--mass", "5", "--mass", "6"); // A valid flag beside a bad one writes nothing. RefusedAndUntouched(path, "--mass", "5", "--durability", "-2"); - RefusedAndUntouched(bare, "--top-speed", "50"); - RefusedAndUntouched(bare, "--mass", "5", "--top-speed", "50"); // Two VelocityLimits leave no one top speed to set. RefusedAndUntouched(twin, "--top-speed", "50"); @@ -385,6 +383,10 @@ public sealed class ShipProductTests : IDisposable Assert.Equal((1f, 0f, 8000f), (ShipAuthoringStore.Load(path).Hull.Mass, ShipAuthoringStore.Load(path).Hull.Drag, ShipAuthoringStore.Load(path).Hull.Durability)); Assert.Equal(0, Run("stats", bare, "--armor", "12").Code); Assert.Equal(12f, ShipAuthoringStore.Load(bare).Hull.Armor); + // A hull with no top speed (create without --like) gets its one VelocityLimit from the first --top-speed. + Assert.Equal(0, Run("stats", bare, "--top-speed", "50").Code); + var added = ShipAuthoringStore.Load(bare).Hull.Behaviors.OfType().Single().TopSpeed; + Assert.Equal((50f, 50f), (added.Min, added.Max)); } [Fact] diff --git a/tools/AetherDb/ShipAuthoringCommands.cs b/tools/AetherDb/ShipAuthoringCommands.cs index bce7eda08..9f8f1c41c 100644 --- a/tools/AetherDb/ShipAuthoringCommands.cs +++ b/tools/AetherDb/ShipAuthoringCommands.cs @@ -110,8 +110,11 @@ public static class ShipAuthoringCommands var (hull, ship, _) = ShipAuthoringStore.Load(args[1]); if (stats.TryGetValue("--top-speed", out var topSpeed)) { - var limits = (hull.Behaviors ?? new List()).OfType().ToArray(); - if (limits.Length != 1) throw new InvalidOperationException($"{ship.Id}: --top-speed needs exactly one VelocityLimit on the hull; it has {limits.Length}."); + hull.Behaviors ??= new List(); + var limits = hull.Behaviors.OfType().ToList(); + // A hull made without --like has none, and Validate refuses a ship hull without one: the first --top-speed adds it. + if (limits.Count == 0) { limits.Add(new VelocityLimitData()); hull.Behaviors.Add(limits[0]); } + if (limits.Count != 1) throw new InvalidOperationException($"{ship.Id}: --top-speed needs at most one VelocityLimit on the hull; it has {limits.Count}."); // A fixed top speed, as every shipped hull authors one (Min equal to Max); its terms are kept. limits[0].TopSpeed.Min = limits[0].TopSpeed.Max = topSpeed; } From d97e2714cd529dd5590cbb0c9ddef9a489428d74 Mon Sep 17 00:00:00 2001 From: Nibu Date: Tue, 10 Nov 2026 05:50:28 +0000 Subject: [PATCH 011/190] Retire the Wwise catalog fields: SoundBank, AudioStats (AudioStat) and Faction music Nothing reads or writes them (audio is native Unity plus AquaSynth). Keys 21, 22 and 13 to 15 stay reserved as never-reuse comments, as with the earlier retirements. The shipped catalog still holds old values; the reader skips unknown keys. Co-Authored-By: Claude Sonnet 5.5 --- Assets/Scripts/ServerShared/Corporations.cs | 9 +-------- Assets/Scripts/ServerShared/ItemData.cs | 16 +--------------- docs/aetheria-release-map.md | 8 +++++--- 3 files changed, 7 insertions(+), 26 deletions(-) diff --git a/Assets/Scripts/ServerShared/Corporations.cs b/Assets/Scripts/ServerShared/Corporations.cs index 3b676aef4..e527606d9 100644 --- a/Assets/Scripts/ServerShared/Corporations.cs +++ b/Assets/Scripts/ServerShared/Corporations.cs @@ -47,14 +47,7 @@ public class Faction [Inspectable, CultReference(typeof(Faction), many: true), CultInspectorRange(0, 1), JsonProperty("allegiance"), Key(12)] public Dictionary, float> Allegiance = new Dictionary, float>(); - [Inspectable, JsonProperty("overworldMusic"), Key(13)] - public uint OverworldMusic; - - [Inspectable, JsonProperty("combatMusic"), Key(14)] - public uint CombatMusic; - - [Inspectable, JsonProperty("bossMusic"), Key(15)] - public uint BossMusic; + // Keys 13 to 15 (overworldMusic, combatMusic, bossMusic) held Wwise ids; retired, never reuse them. // Key 16 is reserved for Relations (operator ruling faction-relations-field). diff --git a/Assets/Scripts/ServerShared/ItemData.cs b/Assets/Scripts/ServerShared/ItemData.cs index fe705b4f6..72c07fc9a 100644 --- a/Assets/Scripts/ServerShared/ItemData.cs +++ b/Assets/Scripts/ServerShared/ItemData.cs @@ -417,11 +417,7 @@ public abstract class EquippableItemData : CraftedItemData [Inspectable, CultInspectorAssetGuid, JsonProperty("actionIcon"), Key(20)] public string ActionBarIcon; - [Inspectable, JsonProperty("soundBank"), Key(21)] - public uint SoundBank; - - [Inspectable, JsonProperty("audioStats"), Key(22)] - public List AudioStats = new List(); + // Keys 21 (soundBank) and 22 (audioStats) held Wwise ids; audio is native Unity plus AquaSynth now. Retired; never reuse them. [IgnoreMember] public abstract HardpointType HardpointType { get; } @@ -455,16 +451,6 @@ public abstract class EquippableItemData : CraftedItemData } } -[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)] -public class AudioStat -{ - [Inspectable, JsonProperty("parameter"), Key(0)] - public uint Parameter; - - [Inspectable, JsonProperty("stat"), Key(1)] - public PerformanceStat Stat = new PerformanceStat(); -} - [CultDocument("aetheria.geardata", "1"), Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)] public class GearData : EquippableItemData { diff --git a/docs/aetheria-release-map.md b/docs/aetheria-release-map.md index 3176c3163..87e5beb8c 100644 --- a/docs/aetheria-release-map.md +++ b/docs/aetheria-release-map.md @@ -224,9 +224,11 @@ at the same commit. stat); `SoundBank` is catalog key 21 (`:403-404`). - Gone since B5: the `AetherDrive` audio calls and its `RpmAudioParameter` and `TorqueRatioAudioParameter` fields (grep 0), and the `EntityInstance` block that read - `item.Data.SoundBank` (grep 0). Follow-up `wwise-catalog-fields` still names both; its live - set is `SoundBank` (key 21), `AudioStats` (key 22) and `Faction.OverworldMusic`, - `CombatMusic`, `BossMusic` (`Corporations.cs:52-59`, keys 13 to 15). + `item.Data.SoundBank` (grep 0). Follow-up `wwise-catalog-fields` retired the rest: `SoundBank` + (key 21), `AudioStats` (key 22, with `AudioStat`) and `Faction.OverworldMusic`, `CombatMusic`, + `BossMusic` (keys 13 to 15) are deleted, their keys left as never-reuse comments. The shipped + `GameData/Aetheria.cc` still carries the old values (29 equippables with a `SoundBank`, 2 factions + with music); the reader skips unknown keys and the next catalog write drops them. - `WwiseMetadata.cs` (91 lines) and `WwiseSoundBinding.cs` (21 lines) are used only by that surface; both have `.meta` files. A repo-wide grep outside `docs` finds the Wwise symbols in exactly these files: `ChargedWeapon.cs`, `InstantWeapon.cs`, `Reactor.cs`, `Thruster.cs`, From db6bda1655d78a6c804da60e05a7cd87ab07cb29 Mon Sep 17 00:00:00 2001 From: Nibu Date: Tue, 10 Nov 2026 20:54:42 +0000 Subject: [PATCH 012/190] docs: ship concept batch brief (#5) --- docs/ship-concept-batch.md | 182 +++++++++++++++++++++++++++++++++++++ 1 file changed, 182 insertions(+) create mode 100644 docs/ship-concept-batch.md diff --git a/docs/ship-concept-batch.md b/docs/ship-concept-batch.md new file mode 100644 index 000000000..efef39dd7 --- /dev/null +++ b/docs/ship-concept-batch.md @@ -0,0 +1,182 @@ +# Ship concept batch: brief + +**Value:** a reproducible way to turn the lore's faction looks and the hull data's size limits into a few dozen Klein concept images, sifted by human votes. +**Entry points:** the mill's file contract (section 1), the Raven call (section 2), the prompt template (section 4), batch 1 (section 6), the sift plan (section 7). +**Status:** a plan. No image has been generated, Raven was not called, and `raven-image` was not yet installed on Yggdrasil when this was written (root install pending, `gamecult-ops` 3fdcf02). + +All images this batch makes are **concept art only until a human has reviewed them** (section 8). Nothing here is canon: the lore pages it draws on are labelled brainstorming (`AetheriaLore` `Brainstorming/Ship Design Language.md`). + +Sources: AetheriaLore `main` 14d827ca (`scripts/concept-mill/`, `Aetheria/media/concept-mill/`, `Aetheria/Brainstorming/`), Aetheria `master` c33feebde (`docs/content-batch-one.md`, `Assets/Scripts/ServerShared/Enums.cs`), gamecult-ops `tools/raven-image/README.md` (3fdcf02). + +## 1. What the existing Concept Mill emits + +The mill is in AetheriaLore, not Aetheria. It is a build script plus a hand-edited data file; it never calls an image model. Renders come from outside (so far the BFL `flux-3-image` API, operated by hand) and are ingested. + +**Input, per render** (not in the repo; default root `Aetheria/Brainstorming/Renders/`, `--renders ` overrides): `.png` and `.md`. The `.md` is the render record: + +``` +# +## Hypothesis what this render tests +## What changed delta from the previous round +## Agent verdict (rounds 4-5 call it "Agent observation") +## Render record Model, Parameters, Request id, Date, Composition (bullets) +## Prompt the full composed prompt, blocks separated by blank lines +``` + +**Source of truth:** `scripts/concept-mill/ships.yaml`, hand-edited. `build.mjs` validates it and fails on a duplicate ship id, a duplicate variant id inside a ship, an unknown `status.kind`, a ship with no variants, more than one `pick`/`default` per ship, or a missing derivative file. + +Per **ship** (the unit the page and the vote use): + +| Field | Meaning | +|---|---| +| `id` | slug, unique; the URL hash `#<ship>/<variant>` and the vote key | +| `name`, `code`, `faction`, `role`, `desig` | display; `desig` is e.g. `Bench 1 · entry B · safe bet` | +| `crew`, `mass` | strings (`mass` is `Small (per prompt)` or `TBD`) | +| `hardpoints` | rows `[qty, size, mount-text]` (size: `Small`, `Medium`, `Utility`, `Sensor`, `Built-in`) | +| `loadout` | list of strings | +| `concept`, `notes`, `beaten` | readout prose: what it is for, design note, what counters it | +| `status` | `{kind: pass\|new\|scrap, stamp, verdict}`; `stamp`/`verdict` carry only the operator's word, or say she has not given one. `kind` places the ship in the menu: Kept / Unreviewed / Scrap bin | + +Per **variant** (one render): `id`, `round` (display label), `image` (derivative basename), `prompt` (record basename, defaults to `image`), optional `source` (render basename to ingest from), `hypothesis`, `verdict`, `operator` (verbatim operator verdict), `pick: true` or `default: true` (at most one per ship). Hypothesis and verdict default to the record's `## Hypothesis` and `## Agent verdict` sections. + +**Output, per variant** (committed, in `Aetheria/media/concept-mill/`): + +- `<image>.webp`: PNG resized to 1600 px wide, quality 82 +- `<image>-thumb.webp`: 720 px wide, quality 72 +- `prompts/<prompt>.txt`: a byte copy of the render's `.md` record + +**Output, manifest:** `site/quartz/components/data/conceptMill.json`: `{sections: [{kind, title}], votes: {enabled, endpoint, bifrostUrl}, ships: [...]}`. Each ship is its `ships.yaml` row with `crew` stringified, `hardpoints` as `{qty, size, mount}` objects, and `variants: [{id, round, image, thumb, prompt, hypothesis, verdict, operator, pick}]` where the three paths are URLs under `/media/concept-mill/`; plus `defaultVariant` (the pick/default variant, else the last). Ships are ordered by section, then faction in first-seen order, then file order. Today: 27 ships, 48 variants. + +**Provenance the mill keeps today:** whatever the `.md` record holds, shown as a downloadable text file. It has no machine-readable provenance fields, no seed, no hash, no licence or review state; the BFL endpoint offered no seed. Section 5 adds them. + +**Vote slot (what Heimdall's Bifrost page meets):** hidden until `votes.enabled` and `votes.endpoint` are set in `ships.yaml`. The page does `GET <endpoint>` (no credentials) and expects JSON `{ "<ship id>": {up, down, members?: {up, down}} }`, and links `<bifrostUrl>/<ship id>` ("Vote on Bifrost"). **Votes are per ship, not per variant.** A sift that must rank several seeds of one concept needs either one ship row per seed or a variant-keyed tally; the second is a change to `aetheriaConceptMill.inline.ts`. This batch uses the first (section 5), so no mill change is needed. + +## 2. What the Raven client needs + +`raven-image` (gamecult-ops `tools/raven-image`, one stdlib Python file plus `graphs/flux3-klein.json`): + +- **Where it runs:** Yggdrasil only. The service is `http://10.77.0.4:8190` (`RAVEN_URL` overrides). Install is root's (`/opt/commons/opt/raven-image/`, symlink in `/opt/commons/bin/`); until then a caller can run the file from a checkout of 3fdcf02. +- **Call:** `raven-image "<prompt>" --size 1536x1024 --seed <n> [--no-enhance] -o <path>.png`. Prints one line per image: `path seed size seconds`. `-n` makes several images (`out-1.png`, ...); this batch passes explicit seeds, so one call per image. +- **Exit codes:** 0 ok; **75** Raven busy or off (no retry; the caller decides when to ask again); 1 for a rejected graph, failed render or timeout (900 s wait per image). +- **Cost:** about 45 s warm, 81 s cold, per 1536x1024 image (README check run). Raven is Deru's desktop: small batches, one client at a time. +- **What it leaves to the caller:** it prints the seed and, per the brief, the prompt; it writes only the PNG. It writes **no sidecar**, so the batch driver must write the record (section 5). The upsampler (on by default) rewrites the prompt; the record must keep both what we sent and what the printed prompt says Klein received, or use `--no-enhance`. +- **Driver needs:** a list of `(concept id, seed, size, prompt file)`; skip-if-PNG-exists so exit 75 resumes cleanly; stop the whole run on the first 75. + +## 3. Proposal constraints from lore and hull data + +**Hull classes.** `HullType` has only `Ship`, `Station`, `Turret` (`Enums.cs:139`). Lore and code define no size class for ships. The labels Light, Medium and Heavy below are **this batch's**, from the shipped hulls' schematic grids (cells, 2.0 m per cell, `hull_grid.py:11`; maximum 32 cells a side): + +| Batch class | Grid (cells, width x length) | Hull precedent | Approx. size | +|---|---|---|---| +| Light | up to 8 x 18 | Longinus 6x17, Turret 8x8 | 12-16 m wide, up to ~36 m long | +| Medium | 10-12 x 12-19 | Smoke Test Hull 10x19, Zenith 12x12 | 20-24 m wide | +| Heavy | 7 x 16 at 4200 mass, or 14+ wide | Noka MKI spec 7x16 (`content-batch-one.md` section 2), Djinni 14x17 | 28 m+ | + +The shipped hull grids are from `GameData/Aetheria.cc` as decoded in `/opt/commons/handoff/aetheria-ship-brief-for-brokkr-20261110.md`. No metre size, crew count or calibre is canon; prompts must not state metres. + +**Hardpoints.** Types: Energy, Ballistic, Launcher, Sensors, Thruster, Radiator, Shield, Reactor, ControlModule (+Hull, Tool, Thermal, WarpDrive). Only weapons (Energy, Ballistic, Launcher), Thruster and Radiator have a visible mount on the model; Reactor, Shield, Sensors, ControlModule are internal (`ShipAuthoring.cs`). Spec precedent for a heavy: 2 Ballistic 2x2, 1 Launcher 1x3, 1 Sensors 1x1 visible-ish, 2 Thruster, 2 Radiator, 2 Shield. For concept prompts: **at most four counted features, each with a location** (Faction Ship Concept Prompts guideline 4). Thrusters and radiators are left out of prompts: the operator places them (Ship Design Language). + +**Silhouettes** are the faction blocks in `Ship Design Language.md` (twelve are used here) and, where later rounds shortened them to livery and register, the `r8` records in `Aetheria/media/concept-mill/prompts/`. Rules the prompts keep: one analogy that places the parts; thick, closed, mirror-symmetric; matte; no wings, fins, wheels or tracks (vacuum hull); no real people, no political symbols. + +## 4. Prompt templates + +Composition follows the mill's latest practice (records `oboz-r8f`, global block **G3**): blocks separated by a blank line, in this order: + +1. **Ship prompt** (below), most specific, first. +2. **Faction livery block**: the faction's block from `Ship Design Language.md`, cut to palette, finish and markings (the r8 Zhestokost block is the model). +3. **Global block G3**: the text in `prompts/oboz-r8f.txt` (third paragraph), copied unchanged. It is not restated here; copying it into this doc would make a second copy. +4. **Frame clause**, verbatim: *One complete ship, centered with clear margin around it, three-quarter front view from slightly above showing the dorsal surface and one side; moderate lens; plain seamless light gray background; soft key light with gentle form shadows; matte finishes throughout.* + +**Ship prompt template:** + +> Design the {name}, a {crew}-crew {faction} {role}. Its whole body follows {analogy}: one {mass-adjective} cast body, mirror-symmetric along its long axis. {feature 1 with location}. {feature 2 with location}. {feature 3 with location}. The cockpit is {cockpit form and location}. {class cue: proportion only, never metres}. + +Slots are filled from the batch table (section 6): `analogy` is the "hook" column, features come from the "visible" column, class cue is one of: *light: long and narrow, about three times as long as wide*; *medium: compact and square-shouldered, about one and a half times as long as wide*; *heavy: broad and low, a little over twice as long as wide* (7x16 is 2.3:1). Names are working titles; the mill's `name` is set when a concept is kept. + +**Variation axes** (one varied per sibling, never several): analogy (safe bet vs moonshot, as the Ship Prompt Bench labels them); feature placement; class cue. Mirror the bench's `Safe bet` / `Moonshot` label in `desig`. + +## 5. Seed policy and record + +- **Seeds are derived, not picked:** `seed(concept, k) = first 4 bytes (big-endian) of sha256("<concept-id>:<k>")`, for `k = 0..3`. Nobody chooses a lucky seed; anyone can regenerate. Raven's random default is never used. +- **One mill ship row per rendered seed:** ship id `<concept-id>-s<k>`, so Bifrost's per-ship tally ranks seeds with no mill change. (A later page change can fold them into variants of one ship.) +- **A seed does not carry across sizes.** The same seed at a different resolution makes a different image. So a hi-res re-render of a sifted winner is a **new image** with `parent: <low-res id>`, not a larger copy of it. +- **Upsampler off for the sift** (`--no-enhance`): the composed prompts are already full captions (about 450-550 words), and with it off the image is a function of (prompt, seed, size, graph). Not yet probed: whether Klein's text encoder truncates a prompt this long; the first render pair must answer it before the batch runs (cost: two images). +- **Record per image** (one `.md` sidecar in the mill's existing record format, so `build.mjs` ingests it unchanged), with the **Render record** bullets: + +``` +- Model: FLUX.3 Klein distilled (ComfyUI graph flux3-klein.json, sha256 <hash>), via raven-image <gamecult-ops commit> +- Parameters: size 1536x1024 | 768x512, seed <n>, steps/cfg/sampler as in the graph (16, 1, euler/simple), upsampler off|on +- Seed derivation: sha256("<concept-id>:<k>") +- Date: <UTC>; made by <Mind> run <run id> +- Parent: <image id or none> +- Composition: ship prompt, faction livery block (<source file@commit>), global block G3 (<source>), frame clause +- Upsampled prompt as printed by the client: <text, only when the upsampler was on> +- Review: UNREVIEWED concept-only; reviewer and date when a human has looked +- Licence: FLUX Kommunity License v.1.0; outputs are concept art until the legal root rules (gamecult-ops tools/raven-image/README.md); no training on outputs +``` + + `status.stamp` in `ships.yaml` stays `UNREVIEWED` and `verdict` says the operator has not given one, per the file header. + +## 6. Batch 1: 36 concepts + +Twelve factions (Zhestokost, Alakrita, Aeronautics Unlimited, Finch Cybernetics, Rossum & Douglas, NiteLife Energy, Lightsail Express, Cetacean Navigators, Cryonix, Sol Dominion, Adrasteia, Death Monkey Explosives), three classes each. Chosen because each has a full block in `Ship Design Language.md`. Roles are **proposals** drawn from the mill's existing roster and the faction blocks, not from Faction Play (not read for this pass); the Noka MKI row is the content-batch spec's hull. `id` is `<slug>-<class letter>`; the ship id of a render is `<id>-s<k>`. + +| id | Faction | Class | Role | Anatomy hook | Visible features (location) | +|---|---|---|---|---|---| +| zh-l | Zhestokost | L | column picket | cast-iron stove, narrowed | 1 short gun in a box turret (bow); 1 sensor block (dorsal); magazine hatch (flank) | +| zh-m | Zhestokost | M | line gunship | forklift | 2 box turrets (shoulders); magazine hatches (dorsal rows); tow lug (stern) | +| zh-h | Zhestokost | H | Noka MKI heavy | armored fist, one centerline cannon | 1 centerline cannon (bow); 2 smaller guns (shoulders); 1 launcher bank (dorsal) | +| alk-l | Alakrita | L | duel interceptor | racing scull | 2 lasers (hood edges); crease lines (full length) | +| alk-m | Alakrita | M | raid cutter | closed folding fan | 2 forward guns; fin stack (stern); gold inlay | +| alk-h | Alakrita | H | patron's heavy escort | folded fan, broadened | 3 guns (prow row); laurel plaque (cockpit) | +| au-l | Aeronautics Unlimited | L | swarm skirmisher | bison hump | rocket pod (hump face); gun (forward); sensor dome (dorsal) | +| au-m | Aeronautics Unlimited | M | tool gunboat | compact excavator | tool socket (bow); 2 guns (shoulders); module bays (flank) | +| au-h | Aeronautics Unlimited | H | frontier monitor | pack mule | 2 module bays; launcher (dorsal); survey mast | +| fin-l | Finch Cybernetics | L | tracker | bird skull | ear dish (flank); lens row (brow); 1 gun (chin) | +| fin-m | Finch Cybernetics | M | relay picket | diving bird, folded | 2 dishes (flanks); 2 guns (shoulders) | +| fin-h | Finch Cybernetics | H | sensor cruiser | prosthetic joint | 3 dishes; 1 gun battery (bow) | +| rd-l | Rossum & Douglas | L | wedge interceptor | flying wedge | 2 guns (nose); flush hatches (dorsal) | +| rd-m | Rossum & Douglas | M | MIRV picket | wedge, thickened | missile hatches (dorsal plane x4); sensor (nose) | +| rd-h | Rossum & Douglas | H | missile barge | wedge, widest | missile hatches (x4); 2 guns (shoulders) | +| nl-l | NiteLife Energy | L | station guard | espresso machine | cartridge (flank); 1 gun (bow); release catch (cartridge) | +| nl-m | NiteLife Energy | M | cartridge gunship | smart speaker | cartridge (dorsal); 2 guns (flanks) | +| nl-h | NiteLife Energy | H | station monitor | appliance, scaled | cartridge (rear); 3 guns (forward) | +| ls-l | Lightsail Express | L | courier | long-haul cab | cab; 1 clamp rail (spine); 1 gun (cab roof) | +| ls-m | Lightsail Express | M | armed hauler | truck and trailer, fused | 2 containers; 2 guns (cab); clamps (spine) | +| ls-h | Lightsail Express | H | convoy tug | road train, fused | 3 containers; docking collar (stern); 2 guns | +| cet-l | Cetacean Navigators | L | corridor escort | dolphin flanks | 2 lobes; 1 gun (boom); amber locks | +| cet-m | Cetacean Navigators | M | recovery tug | beluga back | 2 lobes; tow points (stern); 1 gun | +| cet-h | Cetacean Navigators | H | rescue carrier | whale decks | 2 lobes; transfer locks (ridge); 2 guns | +| cry-l | Cryonix | L | cold sniper | spruce cone | folded emitters (flank); 1 long gun (bow) | +| cry-m | Cryonix | M | heat-sink skirmisher | vacuum flask | folded emitters; 2 guns (waist) | +| cry-h | Cryonix | H | long-range heavy | closed cone, large | folded emitter scales; 1 long gun (bow) | +| sol-l | Sol Dominion | L | interdiction cutter | cast-iron flatiron | sensor plane (dorsal); 2 disablers (shoulders) | +| sol-m | Sol Dominion | M | patrol cutter | hammerhead | hammer sensor plane; 2 disablers (tips) | +| sol-h | Sol Dominion | H | registry cruiser | stamp handle | module bands; 3 disablers (bow) | +| adr-l | Adrasteia | L | deniable courier | flatfish | 1 gun, recessed (nose); 1 cut facet (camera side) | +| adr-m | Adrasteia | M | cold smuggler | cut gemstone, flat | 1 sensor (recessed); cargo collar (belly) | +| adr-h | Adrasteia | H | quiet gunship | stingray | 2 guns (recessed); asymmetric facet | +| dme-l | Death Monkey Explosives | L | charge runner | toolbox | charge feed (dorsal); 1 spike (bow) | +| dme-m | Death Monkey Explosives | M | infrastructure breaker | demolition frame | 2 spikes; detachable charge section (belly) | +| dme-h | Death Monkey Explosives | H | demolition barge | amp stack | 4 charge bays; 2 braces | + +Hooks are drawn from the faction blocks and the bench where they exist (Zhestokost, Alakrita, AU, Finch, R&D, NiteLife, Lightsail, Cetacean, Cryonix, Sol Dominion, Adrasteia, DME entries) and are otherwise this brief's suggestions; the first batch is where they get tested. The guideline "one analogy per prompt" is kept: the hook column is the one analogy; the features are placements. + +**Count:** 36 concepts x 4 seeds = 144 low-res images. + +## 7. Sift plan + +1. **Probe (2 images, before anything else):** one concept at 768x512 with the upsampler off, one at 1536x1024, same prompt, to check that the long composed prompt is not truncated and that 768x512 is legible. If the low-res image is unreadable, sift at 1152x768 and update the cost. +2. **Stage 1, low-res:** 144 images at 768x512, upsampler off, seeds from section 5. Cost is not measured; if time scales with pixels it is about a quarter of 45 s, so about 12-15 s each and roughly 35 minutes in all. Run in chunks of 12 so exit 75 loses little, one client at a time, driver stops at the first 75. +3. **Ingest** as `<concept>-s<k>` ships (status `new`, `UNREVIEWED`), through `build.mjs` from a renders root of PNG plus record. Votes: `up`/`down` per ship on Bifrost. +4. **Cull by vote:** per concept, keep the seed with the most net up votes; a concept with no net-positive seed is dropped. A human looks at the kept images before anything is re-rendered; a Mind's reading of a thumbnail is not a review. +5. **Stage 2, hi-res:** re-render each kept concept at 1536x1024, same prompt, 2 new seeds (`k = 4, 5`), `parent` set to the winning low-res image. About 36 x 2 x 45 s = 54 minutes at most. +6. **Review:** an operator verdict moves a ship out of `new`; only her word sets `pass` or `scrap` (ships.yaml header). + +## 8. Rules for these images + +- **Concept-only until human-reviewed.** Klein outputs are not shipped assets; the licence question (revenue line, affiliates, what concept art feeding a shipped product counts as) is open with whoever holds the legal root (`tools/raven-image/README.md`, "Licence: concept art only until ruled"). +- **How each image was made is recorded** per section 5, one record per image, committed with the image. +- **No training on outputs**, nor on anything derived from them (FLUX licence 4.b). +- No likenesses of real people (licence 4.a); no political symbols (lore). +- Nothing in this batch calls Raven until the driver, the probe in section 7 and the install are done. From c6a3bee879f1b572f4df582d5bcff09add21af5f Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Tue, 10 Nov 2026 22:10:49 +0000 Subject: [PATCH 013/190] Continue refuses a run whose equipment no longer fits its hull's edited layout A mod package edited in place keeps its hull key, so RequireDesigns passed while saved gear could sit outside the new hardpoints or interior cells and be dropped on load. RequireLayouts applies the equip rules (HardpointData.TakesAt, interior cells for tools) to each saved entity and names the changed hulls. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/SavedGame.cs | 31 +++++++++++++++- tests/Aetheria.Shared.Tests/RunSaveTests.cs | 41 +++++++++++++++++++++ 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/Assets/Scripts/ServerShared/SavedGame.cs b/Assets/Scripts/ServerShared/SavedGame.cs index ff4de6e9b..88ff8c9bf 100644 --- a/Assets/Scripts/ServerShared/SavedGame.cs +++ b/Assets/Scripts/ServerShared/SavedGame.cs @@ -158,7 +158,7 @@ public static class RunSave var named = designs.Where(key => key.IsSet()).Distinct() .Where(key => cache.Get<ItemData>(key) == null) .Select(key => key.Value).OrderBy(key => key, StringComparer.Ordinal).ToArray(); - if (named.Length == 0) return; + if (named.Length == 0) { RequireLayouts(cache, game); return; } const string modHull = "mod-hull:"; var mods = named.Where(key => key.StartsWith(modHull, StringComparison.Ordinal)).Select(key => key.Substring(modHull.Length)).ToArray(); var others = named.Where(key => !key.StartsWith(modHull, StringComparison.Ordinal)).ToArray(); @@ -168,6 +168,35 @@ public static class RunSave ". Reinstall them, or start a new game."); } + // Continue's second gate: a hull's cells or hardpoints edited under a saved run must still hold what the run + // equipped on it (a package edited in place keeps its key, so the design check above passes). Each saved piece of + // gear must sit where equipping would accept it on the hull as the catalog holds it now, by the same rules + // (HardpointData.TakesAt for hardpoint gear, interior cells for tools); occupancy is not rechecked, the save + // carries only what equipping admitted. + private static void RequireLayouts(CultCache cache, SavedGame game) + { + var moved = new SortedSet<string>(StringComparer.Ordinal); + void Check(EntityPack pack) + { + if (pack.Hull.Data.Key.IsSet() && cache.Get<ItemData>(pack.Hull.Data.Key) is HullData hull) + foreach (var (position, item) in pack.Equipment.Concat(pack.CargoBays).Concat(pack.DockingBays)) + { + if (!item.Data.Key.IsSet() || !(cache.Get<ItemData>(item.Data.Key) is EquippableItemData design)) continue; + var fits = design.HardpointType == HardpointType.Tool + ? design.Shape.Coordinates.All(cell => hull.InteriorCells[position + design.Shape.Rotate(cell, item.Rotation)]) + : hull.Hardpoints.Any(hardpoint => hardpoint.TakesAt(design, position - hardpoint.Position)); + if (!fits) moved.Add(hull.Name); + } + foreach (var child in pack.Children) Check(child); + } + foreach (var zoneRef in game.Zones ?? Array.Empty<CultRecordRef<SavedZone>>()) + foreach (var pack in cache.Get(zoneRef).Contents?.Entities ?? new List<EntityPack>()) + Check(pack); + if (moved.Count > 0) + throw new InvalidOperationException("This run's equipment no longer fits its hulls' layouts; changed hulls: " + + string.Join(", ", moved) + ". Restore the earlier version of the mod, or start a new game."); + } + private static InvalidOperationException MalformedSave(string where) => new InvalidOperationException($"This run's save is malformed: {where}. Start a new game."); diff --git a/tests/Aetheria.Shared.Tests/RunSaveTests.cs b/tests/Aetheria.Shared.Tests/RunSaveTests.cs index 05c0a86ac..545c1681a 100644 --- a/tests/Aetheria.Shared.Tests/RunSaveTests.cs +++ b/tests/Aetheria.Shared.Tests/RunSaveTests.cs @@ -592,6 +592,47 @@ public sealed class RunSaveTests : IDisposable Assert.Equal(before, File.ReadAllBytes(Run)); } + // Continue from a hull's edited layout: a mod package edited in place keeps its key, so the design check passes, but + // gear saved against the old hardpoints must not be loaded onto the new ones (equipping would silently drop it). + [Fact] + public void RunWhoseHullHardpointMovedRefusesContinueNamingTheHull() + { + var hullKey = new CultRecordKey("mod-hull:mod.skiff"); + HullData Skiff(int2 hardpointAt) => new HullData + { + Name = "Skiff", + Shape = new Shape(4, 4), + Hardpoints = new List<HardpointData> { new HardpointData { Type = HardpointType.Sensors, Position = hardpointAt, Shape = new Shape() } } + }; + CultRecordRef<ItemData> lamp; + using (var cache = AetheriaStores.Open(Catalog, catalogWritable: true)) + { + cache.UpsertAsync(typeof(HullData), Skiff(new int2(1, 1)), hullKey).GetAwaiter().GetResult(); + lamp = new CultRecordRef<ItemData>(cache.Upsert(new GearData { Name = "Lamp", Hardpoint = HardpointType.Sensors, Shape = new Shape() }).Key); + cache.FlushAsync().Wait(); + } + using (var cache = Open()) + { + var pack = BarePack(new EquippableItem { Data = new CultRecordRef<ItemData>(hullKey), Lot = 1 }); + pack.Equipment = new[] { (new int2(1, 1), new EquippableItem { Data = lamp, Lot = 1 }) }; + var lots = new ProvenanceLedger { NextLot = 2 }; + lots.Lots[1] = new Lot { Origin = new Attributed() }; + RunSave.Commit(cache, Game(cache), new[] { ZoneOf(pack) }, lots); + } + using (var cache = Open()) RunSave.RequireDesigns(cache, cache.GetGlobal<SavedGame>()); + + using (var cache = AetheriaStores.Open(Catalog, catalogWritable: true)) + { + cache.UpsertAsync(typeof(HullData), Skiff(new int2(3, 3)), hullKey).GetAwaiter().GetResult(); + cache.FlushAsync().Wait(); + } + using (var cache = Open()) + { + var refusal = Assert.Throws<InvalidOperationException>(() => RunSave.RequireDesigns(cache, cache.GetGlobal<SavedGame>())); + Assert.Contains("changed hulls: Skiff", refusal.Message); + } + } + // --- RequireDesigns: what it walks, what it lists --------------------------------------------------------------- // Commits a run whose zones the caller builds, then returns RequireDesigns' refusal message, or null when it passes. From b3f3c9a0c80719db5474d17fe66bbe8ef656da35 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Tue, 10 Nov 2026 22:11:56 +0000 Subject: [PATCH 014/190] docs: record the Continue hull-layout gate in the release map Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- docs/aetheria-release-map.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/aetheria-release-map.md b/docs/aetheria-release-map.md index 87e5beb8c..18f9b6941 100644 --- a/docs/aetheria-release-map.md +++ b/docs/aetheria-release-map.md @@ -514,7 +514,7 @@ record. | follow-up | `belt-render-reads-index` | full game | Belt rendering through the index. | | follow-up | `c4-ship-element-ids` | full game | Variants campaign. | | follow-up | `variants-python-raw-push` | full game | Variants campaign. | -| follow-up | `mod-hull-changed-under-run` | full game | Mod edits under a run; demo hulls are first-party. | +| follow-up | `mod-hull-changed-under-run` | full game | Mod edits under a run; demo hulls are first-party. Done 2026-11-10 (#6): `RunSave.RequireLayouts` makes Continue refuse a run whose gear no longer fits its hull's edited cells or hardpoints, naming the hull. | | follow-up | `ship-lods` | full game | Only if a profile shows cost. | | follow-up | `hull-decals` | full game | Insignia and damage decals. | | follow-up | `hull-player-paint` | full game | Player liveries. | From 9135360bebfafece21cac04d6b7a6da2bcf9977d Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 01:58:59 +0000 Subject: [PATCH 015/190] AetherDb: weapon-ammo lists every weapon's energy, magazine, reload and ammunition type Read-only audit command, so ammunition rulings are checked against the catalog and not against names. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- tools/AetherDb/Program.cs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tools/AetherDb/Program.cs b/tools/AetherDb/Program.cs index 99963e8dd..50f97c019 100644 --- a/tools/AetherDb/Program.cs +++ b/tools/AetherDb/Program.cs @@ -36,6 +36,7 @@ public static class Program case "brownout-migrate": return BrownoutMigrate(args.Contains("apply")); case "roles-migrate": return RolesMigrate(args.Contains("apply")); case "firing-arc-migrate": return FiringArcMigrate(args.Contains("apply")); + case "weapon-ammo": return WeaponAmmo(); case "range-falloff": return RangeFalloff(args.Skip(1).ToArray()); case "targeting-catalog": return TargetingCatalog(args.Contains("apply")); case "targeting-catalog-6c": return TargetingCatalog6c(args.Contains("apply")); @@ -1109,6 +1110,19 @@ public static class Program // and a damage multiplier at maximum range. Guided weapons, lock weapons and mine layers keep the unauthored // defaults (no falloff). The command upserts every weapon design, which is also what drops the retired damage curve // (key 7) from the stored records. Idempotent: the values are functions of Range alone. Dry run unless "apply". + // Read-only: what every weapon design draws per shot (reactor energy, magazine, rounds), so ammunition rulings are audited + // against the catalog and not against names. + private static int WeaponAmmo() + { + var db = AetherDb.Open(); + Console.WriteLine($"{"weapon",-28} {"behaviour",-20} {"energy",-11} {"mag",5} {"reload",6} ammo"); + foreach (var item in db.Cache.GetAll<WeaponItemData>().OrderBy(i => i.Name, StringComparer.Ordinal)) + foreach (var w in item.Behaviors.OfType<WeaponData>()) + Console.WriteLine($"{item.Name,-28} {w.GetType().Name,-20} {w.Energy.Min}-{w.Energy.Max,-6} {w.MagazineSize,5} {w.ReloadTime,6} " + + (w.AmmoType.IsSet() ? db.Cache.Get<SimpleCommodityData>(w.AmmoType.Key)?.Name ?? w.AmmoType.Key.Value : "-")); + return 0; + } + private static int RangeFalloff(string[] args) { var apply = args.Contains("apply"); From 8f77000844c38d457f131109451ae1cceb62a8c5 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 01:58:59 +0000 Subject: [PATCH 016/190] Launchers draw real rounds: Missiles commodity and recipe, a reload that pays its crate, a reserve readout Rulings ballistics-real-ammo and ballistics-cycle-power, follow-up launcher-ammunition. The Munitions batch adds the Missiles commodity (a high-explosive warhead and a rocket motor at the munitions works; guidance waits on the electronics chain) and sets AmmoType=Missiles on the five launcher designs; reactor energy per shot stays as authored. InstantWeapon: the reload used to refill the magazine on its timer and never reach the cargo branch in UseAmmo, so no ammunition-fed weapon ever paid a round. The refill now takes one unit of AmmoType from cargo (TakeReloadRound) and, with none, the magazine stays empty; UseAmmo only starts a reload when a unit is there. Weapon.Reserve exposes the cargo count and the HUD shows rounds/reserve for magazine weapons. Tests: shipped launchers all name Missiles and Missiles has a recipe; a fed weapon fires its magazine and no more without crates, reloads once per crate; Reserve equals the cargo count and falls per reload. The commodity count pin goes 22 to 23. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../ServerShared/Behaviors/InstantWeapon.cs | 27 +++--- .../Scripts/ServerShared/Behaviors/Weapon.cs | 2 + Assets/Scripts/UI/HUD/SchematicDisplay.cs | 2 +- .../CommodityRecordsTests.cs | 2 +- .../FireControlPerWeaponTests.cs | 88 ++++++++++++++++++- .../LauncherAmmunitionCatalogTests.cs | 28 ++++++ tools/AetherDb/Economy/Munitions.cs | 16 ++++ 7 files changed, 149 insertions(+), 16 deletions(-) create mode 100644 tests/Aetheria.Shared.Tests/LauncherAmmunitionCatalogTests.cs diff --git a/Assets/Scripts/ServerShared/Behaviors/InstantWeapon.cs b/Assets/Scripts/ServerShared/Behaviors/InstantWeapon.cs index da23bc107..c8587f72d 100644 --- a/Assets/Scripts/ServerShared/Behaviors/InstantWeapon.cs +++ b/Assets/Scripts/ServerShared/Behaviors/InstantWeapon.cs @@ -229,7 +229,7 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerCo if (!_coolingDown || !(_cooldown < 0)) return false; _overshoot = min(-_cooldown * CountdownSpan, dt); _coolingDown = false; - if (_data.MagazineSize > 0 && _ammo == 0) + if (_data.MagazineSize > 0 && _ammo == 0 && TakeReloadRound()) { _ammo = _data.MagazineSize; OnReloadComplete?.Invoke(); @@ -239,6 +239,17 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerCo return true; } + // A reload pays a round (ruling ballistics-real-ammo): one unit of the weapon's AmmoType leaves the cargo as the magazine refills, + // and with none to take the magazine stays empty. A weapon with no AmmoType reloads free. + private bool TakeReloadRound() + { + if (!_data.AmmoType.IsSet()) return true; + var cargo = Entity.FindItemInCargo(_data.AmmoType.Key); + if (cargo == null) return false; + if (cargo.ItemsOfType[_data.AmmoType.Key][0] is SimpleCommodity simpleCommodity) cargo.Remove(simpleCommodity, 1); + return true; + } + private float CountdownSpan => max(ShortestCycle, _data.MagazineSize > 0 && _ammo == 0 ? _data.ReloadTime : Cooldown); // A countdown that starts outside a round (a charge failing) carries the last one's overshoot like every restart. @@ -265,18 +276,8 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerCo return true; } - var hasAmmo = true; - if (_data.AmmoType.IsSet()) - { - var cargo = Entity.FindItemInCargo(_data.AmmoType.Key); - if (cargo != null) - { - var item = cargo.ItemsOfType[_data.AmmoType.Key][0]; - if (item is SimpleCommodity simpleCommodity) - cargo.Remove(simpleCommodity, 1); - } - else hasAmmo = false; - } + // The reload starts only if a round is there to load; FinishCountdown takes it. + var hasAmmo = !_data.AmmoType.IsSet() || Entity.CountItemsInCargo(_data.AmmoType.Key) > 0; if(hasAmmo) { OnReloadBegin?.Invoke(); diff --git a/Assets/Scripts/ServerShared/Behaviors/Weapon.cs b/Assets/Scripts/ServerShared/Behaviors/Weapon.cs index cb42d6bd4..62e4f4b14 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Weapon.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Weapon.cs @@ -102,6 +102,8 @@ public abstract class Weapon : ActivatedBehavior public abstract float DamagePerSecond { get; } public abstract float RangeDamagePerSecond(float range); public abstract int Ammo { get; } + // Rounds in the ship's cargo that reload this weapon's magazine: crates of AmmoType, 0 when the weapon draws none. + public int Reserve => _data.AmmoType.IsSet() ? Entity.CountItemsInCargo(_data.AmmoType.Key) : 0; public WeaponData WeaponData => _data; public float RangeFactor(float at) => WeaponData.RangeFactor(MinRange, EffectiveRange, Range, _data.DamageAtMaxRange, at); diff --git a/Assets/Scripts/UI/HUD/SchematicDisplay.cs b/Assets/Scripts/UI/HUD/SchematicDisplay.cs index 57f545960..f5d6d8af3 100644 --- a/Assets/Scripts/UI/HUD/SchematicDisplay.cs +++ b/Assets/Scripts/UI/HUD/SchematicDisplay.cs @@ -236,7 +236,7 @@ public class SchematicDisplay : MonoBehaviour if (x.Weapon.WeaponData.AmmoType.IsSet()) { if(x.Weapon.WeaponData.MagazineSize > 1) - x.ListElement.AmmoLabel.text = x.Weapon.Ammo.ToString(); + x.ListElement.AmmoLabel.text = $"{x.Weapon.Ammo}/{x.Weapon.Reserve}"; else x.ListElement.AmmoLabel.text = _entity.CountItemsInCargo(x.Weapon.WeaponData.AmmoType.Key).ToString(); } diff --git a/tests/Aetheria.Shared.Tests/CommodityRecordsTests.cs b/tests/Aetheria.Shared.Tests/CommodityRecordsTests.cs index 2b2acfaa0..91bce1993 100644 --- a/tests/Aetheria.Shared.Tests/CommodityRecordsTests.cs +++ b/tests/Aetheria.Shared.Tests/CommodityRecordsTests.cs @@ -13,7 +13,7 @@ public sealed class CommodityRecordsTests public void ShippedCatalogOpensWithTheRetiredKeysGone() { using var cache = RestoredHullsTests.OpenCatalog(); - Assert.Equal(22, cache.GetAll<SimpleCommodityData>().Count()); + Assert.Equal(23, cache.GetAll<SimpleCommodityData>().Count()); Assert.Equal(63, cache.GetAll<CompoundCommodityData>().Count()); Assert.Contains(cache.GetAll<SimpleCommodityData>(), c => c.Name == "Ammo"); Assert.All(cache.GetAll<CompoundCommodityData>(), c => Assert.False(string.IsNullOrEmpty(c.Name))); diff --git a/tests/Aetheria.Shared.Tests/FireControlPerWeaponTests.cs b/tests/Aetheria.Shared.Tests/FireControlPerWeaponTests.cs index f2fc94777..0b5faa343 100644 --- a/tests/Aetheria.Shared.Tests/FireControlPerWeaponTests.cs +++ b/tests/Aetheria.Shared.Tests/FireControlPerWeaponTests.cs @@ -85,7 +85,7 @@ public sealed class FireControlPerWeaponTests : IDisposable (ItemRotation Rotation, float Arc)[] mounts = null, bool beam = false, WeaponFuse? fuse = null, float blast = 0f, float range = 100f, float targetRange = 60f, float accuracy = 1f, float minHit = .2f, bool lockWeapon = false, bool turret = false, float energy = 0f, float heat = 0f, float visibility = 0f, int magazine = 0, bool singleAmmoBurst = false, bool decoy = false, bool charged = false, bool auto = false, float damage = 100f, - float effective = float.PositiveInfinity, float damageAtMax = 0f, float velocity = 0f, float targetLayerHeight = 0f) + float effective = float.PositiveInfinity, float damageAtMax = 0f, float velocity = 0f, float targetLayerHeight = 0f, int? crates = null, float reload = 1f) { mounts ??= new[] { (ItemRotation.None, 0f) }; var hullData = new HullData @@ -144,10 +144,20 @@ public sealed class FireControlPerWeaponTests : IDisposable behavior.Heat = Constant(heat); behavior.Visibility = Constant(visibility); behavior.MagazineSize = magazine; + behavior.ReloadTime = reload; var cache = AetheriaStores.Open(Catalog + Guid.NewGuid().ToString("N"), catalogWritable: true); _openCaches.Add(cache); cache.Upsert(new VerseGrammar { Revision = 1 }); + // An ammunition-fed weapon: it names the Missiles commodity, and the shooter carries `crates` of it in a bay. + if (crates.HasValue) + { + var bayShape = new Shape(4, 4); + foreach (var cell in bayShape.AllCoordinates) bayShape[cell] = true; + cache.Upsert(new CargoBayData { Name = "Bay", Shape = new Shape(), InteriorShape = bayShape, Price = 20, Durability = 4 }); + cache.Upsert(new SimpleCommodityData { Name = "Missiles", Shape = new Shape(), Price = 1, MaxStack = 100 }); + behavior.AmmoType = new CultRecordRef<SimpleCommodityData>(cache.RefOf<ItemData>(cache.GetByName<SimpleCommodityData>("Missiles")).Key); + } cache.Upsert(hullData); cache.Upsert(shooterHullData); cache.Upsert(new WeaponItemData @@ -220,6 +230,13 @@ public sealed class FireControlPerWeaponTests : IDisposable var item = shooter.Equipment.Single(x => x.EquippableItem == d); rig.Decoy = new Gun { Item = item, Weapon = (Weapon) item.Behaviors.Single(b => b is Weapon) }; } + if (crates.HasValue) + { + var bay = new EquippedCargoBay(items, Make("Bay", lot++, 4), new int2(1, 1), shooter, "bay"); + shooter.CargoBays.Add(bay); + if (crates.Value > 0) + Assert.True(bay.TryStore(new SimpleCommodity { Data = items.ItemData.RefOf<ItemData>(items.ItemData.GetByName<SimpleCommodityData>("Missiles")), Quantity = crates.Value })); + } var targeting = Make("Targeting", lot++, 1); Assert.True(shooter.TryFindSpace(targeting, out var tpos)); Assert.True(shooter.TryEquip(targeting, tpos)); @@ -1306,4 +1323,73 @@ public sealed class FireControlPerWeaponTests : IDisposable Assert.False(weapon.CanFire); } + + // ==== Ruling ballistics-real-ammo: an ammunition-fed weapon pays a round per magazine reload, no free reload ==== + + // One launcher-shaped weapon (magazine 2, reload 3 s, Missiles) held on its trigger at no target, `crates` of Missiles in the + // hold. Returns the rig and a counter of committed shots. + private (Rig Rig, Func<int> Shots) AmmoRig(int crates) + { + var r = Build(fuse: WeaponFuse.Proximity, blast: 30f, range: 40f, magazine: 2, auto: true, crates: crates, reload: 3f); + r.Shooter.SetTarget(TargetRef.None); + Aim(r, float2(0, 1)); + var shots = 0; + r.Zone.ShotCommitted.Subscribe(_ => shots++); + r.Gun.Weapon.Activate(); + return (r, () => shots); + } + + private static void Run(Rig r, float seconds) + { + for (var t = 0f; t < seconds; t += .25f) { r.Gun.Weapon.Activate(); r.Zone.Update(.25f); } + } + + // With no crate in the hold the magazine is fired once and the gun then stays empty, however long the trigger is held. Kills: + // a reload that refills the magazine without taking a crate (UseAmmo or FinishCountdown refilling on the timer alone). + [Fact] + public void AnAmmunitionFedWeaponWithNoCratesFiresItsMagazineAndNoMore() + { + var (r, shots) = AmmoRig(crates: 0); + Run(r, 30f); + Assert.Equal(2, shots()); + Assert.Equal(0, r.Gun.Weapon.Ammo); + } + + // One crate is one reload: after ReloadTime the full magazine fires again, the crate is gone, and then the gun is empty. Kills: + // a reload that consumes no crate, or more than one, or refills a partial magazine. + [Fact] + public void OneCrateReloadsTheWholeMagazineOnceAfterTheReloadTime() + { + var (r, shots) = AmmoRig(crates: 1); + Run(r, 2f); + Assert.Equal(2, shots()); + Assert.Equal(1, r.Gun.Weapon.Reserve); + Run(r, 30f); + Assert.Equal(4, shots()); + Assert.Equal(0, r.Gun.Weapon.Reserve); + Assert.Equal(0, r.Gun.Weapon.Ammo); + } + + // The reserve a HUD shows is the cargo count of the weapon's ammunition, and it falls by one when the magazine reloads. Kills: a + // Reserve that reads a constant, the wrong commodity, or a count that ignores the stack quantity. + [Fact] + public void TheReserveIsTheCargoCountOfTheAmmunitionAndFallsByOnePerReload() + { + var (r, shots) = AmmoRig(crates: 3); + Assert.Equal(3, r.Gun.Weapon.Reserve); + Assert.Equal(3, r.Shooter.CountItemsInCargo(r.Gun.Weapon.WeaponData.AmmoType.Key)); + Run(r, 2f); + Assert.Equal(2, shots()); + Assert.Equal(3, r.Gun.Weapon.Reserve); + Run(r, 3.5f); + Assert.Equal(2, r.Gun.Weapon.Reserve); + } + + // A weapon with no ammunition type has no reserve. + [Fact] + public void AWeaponThatDrawsNoAmmunitionHasNoReserve() + { + var r = Build(magazine: 2); + Assert.Equal(0, r.Gun.Weapon.Reserve); + } } diff --git a/tests/Aetheria.Shared.Tests/LauncherAmmunitionCatalogTests.cs b/tests/Aetheria.Shared.Tests/LauncherAmmunitionCatalogTests.cs new file mode 100644 index 000000000..209a0caa9 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/LauncherAmmunitionCatalogTests.cs @@ -0,0 +1,28 @@ +using System.Linq; +using GameCult.Caching; +using Xunit; + +// Ruling ballistics-real-ammo, follow-up launcher-ammunition: a launcher is not a free gun. Read from the shipped catalog through +// AetherDb's own open, so what is checked is what ships. +public sealed class LauncherAmmunitionCatalogTests +{ + private static bool IsLauncher(WeaponData data) => data is LauncherData || data is GuidedWeaponData || data is LockWeaponData; + + // Every launcher design reloads from the Missiles commodity, and Missiles can be made. Kills: a launcher authored (or a new one + // added) with AmmoType unset, which reloads for free forever; Missiles without a recipe, which no station would ever supply. + [Fact] + public void EveryShippedLauncherReloadsFromMissilesAndMissilesCanBeMade() + { + using var db = AetherDb.Open(); + var missiles = db.Cache.GetAll<SimpleCommodityData>().Single(c => c.Name == "Missiles"); + var key = db.Cache.RefOf(missiles).Key; + var launchers = db.Cache.GetAll<WeaponItemData>().SelectMany(i => i.Behaviors.OfType<WeaponData>().Where(IsLauncher).Select(d => (i.Name, d))).ToArray(); + Assert.True(launchers.Length >= 5, $"fixture: the catalog holds its launchers ({launchers.Length})"); + foreach (var (name, data) in launchers) + { + Assert.True(data.AmmoType.IsSet(), $"{name} draws no ammunition"); + Assert.Equal(key, data.AmmoType.Key); + } + Assert.Contains(db.Cache.GetAll<RecipeData>(), r => r.Output.Key.Equals(key) && r.Inputs.Count > 0); + } +} diff --git a/tools/AetherDb/Economy/Munitions.cs b/tools/AetherDb/Economy/Munitions.cs index 9f0dfd075..2630c2dac 100644 --- a/tools/AetherDb/Economy/Munitions.cs +++ b/tools/AetherDb/Economy/Munitions.cs @@ -141,6 +141,14 @@ public sealed class Munitions : EconomyBatch "The same powder as a gun charge, shaped to burn for seconds instead of milliseconds: missile stocks and gun stocks compete for one powder train.", new[] { "thruster" }, (powder, 2), (steel, 1)); + // Missiles: the crate a launcher design reloads from. One crate is one magazine reload (UseAmmo removes one unit of the weapon's + // AmmoType at an empty magazine), the same convention as Ammo for guns. A crate is a warhead and a motor per two missiles' worth + // of magazine; the guidance package (seeker and fin actuators) waits on the electronics chain, so the recipe does not yet draw it. + var missiles = Simple("missiles", "Missiles", "Crated guided munitions: a high-explosive warhead mated to a rocket motor on a launch rail. The crate a launcher reloads from; the rounds are real, only the reactor energy of the launch is not.", 8f, 1800); + Recipe(missiles, "munitions-works", 1200, 24, 2, + "A missile crate is a warhead, a motor and a seeker in one box, and the box is the arsenal's most counted object: Zhestokost ties each launcher crew's allowance to a serial range, so a cache of loose crates is either a deserter's or a quartermaster's crime.", + new string[0], (warhead, 1), (motor, 1)); + var dispenser = Compound("mine-dispenser", "Mine Dispenser", "A rack and ejector that lays mines in a pattern.", 20f, 1600); Recipe(dispenser, "fabrication", 900, 20, 1, "Little more than steel and actuators, which is why every convoy navy can build one and every blockade starts with one.", @@ -151,6 +159,14 @@ public sealed class Munitions : EconomyBatch foreach (var gun in new[] { "Light Machine Gun", "Autocannon", "Long Slug Rifle", "Charged Scattergun", "Slug Rifle", "Flak Gun", "Cluster Cannon", "Point Defense Gun" }) Design(gun, 1800, 30, "A ballistic gun is a barrel and a feed; the round brings the energy."); Design("Mine Launcher", 1800, 24, "A dispenser and the warheads it lays."); + + // Launchers draw real rounds (ruling ballistics-real-ammo): the reactor energy per shot stays as authored, and each magazine + // reload consumes one Missiles crate. + foreach (var launcher in new[] { "Guided Missile Launcher", "Long-Range Missile Rack", "Short-Range Missile Rack", "Incendiary Rocket Pod", "Swarm Rocket Pod" }) + _a.Edit<WeaponItemData>(launcher, w => + { + foreach (var data in w.Behaviors.OfType<WeaponData>()) data.AmmoType = new CultRecordRef<SimpleCommodityData>(missiles.Key); + }); } private CultRecordRef<Faction> FactionRef(string name) From fdbf0b6851b8e52e1e581f74a416b91ca89caa09 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 01:58:59 +0000 Subject: [PATCH 017/190] GameData/Aetheria.cc: Munitions apply (Missiles commodity and recipe, AmmoType on five launchers) economy author Munitions apply on the latest origin/master catalog; rerun reports 0 added, 0 changed. sha256 d1c96c6ed8530a4e17246604580eca3a45666b3846d56d557f8869ce7c2cc2b3 Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- GameData/Aetheria.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GameData/Aetheria.cc b/GameData/Aetheria.cc index 7a7b99f5c..5b9332c1f 100644 --- a/GameData/Aetheria.cc +++ b/GameData/Aetheria.cc @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:68b37cb55c012c9d1df97bbf0de5c0a56d1804ce5f16f498738cd4de51c88e4b -size 214588 +oid sha256:d1c96c6ed8530a4e17246604580eca3a45666b3846d56d557f8869ce7c2cc2b3 +size 213302 From 386f29bf0d9c78f520402352357353380bb8b758 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 02:55:39 +0000 Subject: [PATCH 018/190] Generated ships carry the crates their weapons reload from; Missiles gets a cargo shape; comment and lore fixes LoadoutGenerator.GenerateShipLoadout, the one owner of NPC and generated-scenario fitting, now stocks AmmunitionCrates (3) of every distinct AmmoType the ship's weapons draw, after the consumable roll and without touching the random stream; it logs and goes on if no hold takes them. Missiles is authored with Ammo's 1x1 shape and a stack of 5 (a shapeless commodity cannot be stored at all). Tests: generated ships hold exactly the crates they draw and none of an ammunition they do not; a magazine weapon with no AmmoType still reloads free. weapon-ammo moves so RangeFalloff keeps its doc comment; the Munitions comment and lore now match the recipe (warhead and motor, magazines 2 to 288). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../Scripts/ServerShared/LoadoutGenerator.cs | 17 +++++++++ .../AmmunitionStockingTests.cs | 38 +++++++++++++++++++ .../FireControlPerWeaponTests.cs | 14 +++++++ tools/AetherDb/Economy/Munitions.cs | 18 +++++---- tools/AetherDb/Program.cs | 10 ++--- 5 files changed, 85 insertions(+), 12 deletions(-) create mode 100644 tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs diff --git a/Assets/Scripts/ServerShared/LoadoutGenerator.cs b/Assets/Scripts/ServerShared/LoadoutGenerator.cs index 9f4829eee..c82ec1300 100644 --- a/Assets/Scripts/ServerShared/LoadoutGenerator.cs +++ b/Assets/Scripts/ServerShared/LoadoutGenerator.cs @@ -24,6 +24,10 @@ public class LoadoutGenerator public const float ShipConsumableChance = .1f; public const int ShipConsumableUnits = 1; + // Ammunition-fed weapons reload from cargo (ruling ballistics-real-ammo), so a generated ship carries this many crates of every + // distinct AmmoType its weapons draw: enough to fight on past the first magazine, few enough to leave the rest of the hold. + public const int AmmunitionCrates = 3; + public LoadoutGenerator( ref Random random, ItemManager itemManager, @@ -56,6 +60,7 @@ public class LoadoutGenerator OutfitEntity(entity); EquipPickup(entity); StockConsumables(entity, ShipConsumableChance, ShipConsumableUnits); + StockAmmunition(entity); return EntitySerializer.Pack(entity); } @@ -162,6 +167,18 @@ public class LoadoutGenerator } } + // The crates the ship's weapons reload from: AmmunitionCrates of each distinct AmmoType, stopping when no hold takes another. + // Draws nothing from the random stream, so adding it moves no other roll. + private void StockAmmunition(Entity entity) + { + foreach (var key in entity.Weapons.Select(weapon => weapon.WeaponData.AmmoType).Where(type => type.IsSet()).Select(type => type.Key).Distinct()) + { + var crates = new SimpleCommodity { Data = new CultRecordRef<ItemData>(key), Quantity = AmmunitionCrates }; + if (!entity.CargoBays.Any(bay => bay.TryStore(crates))) + ItemManager.Log($"{entity.Name}: no room for {AmmunitionCrates} crates of {key.Value}."); + } + } + private static bool IsHeater(GearData item) => item.HardpointType == HardpointType.Tool && item.Behaviors.Any(b => b is ThermotoggleData { HighPass: false }) && diff --git a/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs b/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs new file mode 100644 index 000000000..1fd278bfe --- /dev/null +++ b/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs @@ -0,0 +1,38 @@ +using System.Linq; +using Xunit; + +// Ruling ballistics-real-ammo: generation stocks combatants with rounds, because a magazine weapon reloads from cargo and a ship with +// no crates fires one magazine and goes quiet. Measured on ships the production generator returns, over the shipped catalog. +public sealed partial class RunStartTests +{ + // Every generated ship whose weapons draw an ammunition type carries crates of each such type; a ship whose weapons draw none + // carries none of an ammunition commodity it does not draw. Kills: generation that stocks nothing (every NPC gun dies after one magazine), + // that stocks only one of several types, or that stocks ships with no use for them. + [Fact] + public void GeneratedShipsCarryTheAmmunitionTheirWeaponsDraw() + { + var generator = new LoadoutGenerator(ref _items.Random, _items, _galaxy, _galaxy.Entrance, _protagonist, .5f); + var shipHulls = LoadoutGenerator.SoldHulls(_cache).Where(h => h.HullType == HullType.Ship).Select(h => h.Name).ToList(); + var ammunition = _cache.GetAll<WeaponItemData>().SelectMany(i => i.Behaviors.OfType<WeaponData>()).Where(w => w.AmmoType.IsSet()) + .Select(w => w.AmmoType.Key).Distinct().ToArray(); + Assert.NotEmpty(ammunition); + var fed = 0; + foreach (var name in shipHulls) + for (var i = 0; i < 12; i++) + { + var pack = generator.GenerateShipLoadout(h => h.Name == name); + if (pack == null) continue; + var ship = EntitySerializer.Unpack(_items, null, pack); + var drawn = ship.Weapons.Select(w => w.WeaponData.AmmoType).Where(t => t.IsSet()).Select(t => t.Key).Distinct().ToArray(); + foreach (var key in drawn) + { + Assert.True(ship.CountItemsInCargo(key) > 0, $"{name}: a weapon draws {key.Value} and the hold has none"); + Assert.Equal(LoadoutGenerator.AmmunitionCrates, ship.CountItemsInCargo(key)); + } + foreach (var key in ammunition.Except(drawn)) + Assert.True(ship.CountItemsInCargo(key) == 0, $"{name}: no weapon draws {key.Value} and the hold carries it"); + if (drawn.Length > 0) fed++; + } + Assert.True(fed > 0, "fixture: some generated ship carries an ammunition-fed weapon"); + } +} diff --git a/tests/Aetheria.Shared.Tests/FireControlPerWeaponTests.cs b/tests/Aetheria.Shared.Tests/FireControlPerWeaponTests.cs index 0b5faa343..690bd27d3 100644 --- a/tests/Aetheria.Shared.Tests/FireControlPerWeaponTests.cs +++ b/tests/Aetheria.Shared.Tests/FireControlPerWeaponTests.cs @@ -1392,4 +1392,18 @@ public sealed class FireControlPerWeaponTests : IDisposable var r = Build(magazine: 2); Assert.Equal(0, r.Gun.Weapon.Reserve); } + + // A magazine weapon that names no ammunition still reloads free and keeps firing: only an AmmoType makes a reload cost a crate. + // Kills: TakeReloadRound refusing when AmmoType is unset, which would silence every unfed magazine gun after one magazine. + [Fact] + public void AMagazineWeaponWithNoAmmunitionTypeStillReloadsFree() + { + var r = Build(fuse: WeaponFuse.Proximity, blast: 30f, range: 40f, magazine: 2, auto: true, reload: 3f); + r.Shooter.SetTarget(TargetRef.None); + Aim(r, float2(0, 1)); + var shots = 0; + r.Zone.ShotCommitted.Subscribe(_ => shots++); + Run(r, 30f); + Assert.True(shots > 4, $"an unfed magazine weapon fires past its first magazine, fired {shots}"); + } } diff --git a/tools/AetherDb/Economy/Munitions.cs b/tools/AetherDb/Economy/Munitions.cs index 2630c2dac..83cbee2f2 100644 --- a/tools/AetherDb/Economy/Munitions.cs +++ b/tools/AetherDb/Economy/Munitions.cs @@ -141,12 +141,16 @@ public sealed class Munitions : EconomyBatch "The same powder as a gun charge, shaped to burn for seconds instead of milliseconds: missile stocks and gun stocks compete for one powder train.", new[] { "thruster" }, (powder, 2), (steel, 1)); - // Missiles: the crate a launcher design reloads from. One crate is one magazine reload (UseAmmo removes one unit of the weapon's - // AmmoType at an empty magazine), the same convention as Ammo for guns. A crate is a warhead and a motor per two missiles' worth - // of magazine; the guidance package (seeker and fin actuators) waits on the electronics chain, so the recipe does not yet draw it. - var missiles = Simple("missiles", "Missiles", "Crated guided munitions: a high-explosive warhead mated to a rocket motor on a launch rail. The crate a launcher reloads from; the rounds are real, only the reactor energy of the launch is not.", 8f, 1800); - Recipe(missiles, "munitions-works", 1200, 24, 2, - "A missile crate is a warhead, a motor and a seeker in one box, and the box is the arsenal's most counted object: Zhestokost ties each launcher crew's allowance to a serial range, so a cache of loose crates is either a deserter's or a quartermaster's crime.", + // Missiles: the crate a launcher design reloads from. One crate is one magazine reload (the reload takes one unit of the weapon's + // AmmoType), the same convention as Ammo for guns, whatever the magazine holds (2 to 288 rounds across the five designs). A crate is + // a warhead and a motor; the guidance package (seeker and fin actuators) waits on the electronics chain, so the recipe does not + // yet draw it. Shape and stack match Ammo's, so a hold takes crates cell for cell. + var missiles = new SimpleCommodityData { Name = "Missiles", Shape = new Shape(), MaxStack = 5, Mass = 8f, Price = 1800, + Description = "Crated guided munitions: a high-explosive warhead mated to a rocket motor on a launch rail. The crate a launcher reloads from; the rounds are real, only the reactor energy of the launch is not." }; + _a.Put(missiles, CommodityKey("missiles")); + var missilesRef = new CultRecordRef<ItemData>(CommodityKey("missiles")); + Recipe(missilesRef, "munitions-works", 1200, 24, 2, + "A missile crate is a warhead and a motor in one box, and the box is the arsenal's most counted object: Zhestokost ties each launcher crew's allowance to a serial range, so a cache of loose crates is either a deserter's or a quartermaster's crime.", new string[0], (warhead, 1), (motor, 1)); var dispenser = Compound("mine-dispenser", "Mine Dispenser", "A rack and ejector that lays mines in a pattern.", 20f, 1600); @@ -165,7 +169,7 @@ public sealed class Munitions : EconomyBatch foreach (var launcher in new[] { "Guided Missile Launcher", "Long-Range Missile Rack", "Short-Range Missile Rack", "Incendiary Rocket Pod", "Swarm Rocket Pod" }) _a.Edit<WeaponItemData>(launcher, w => { - foreach (var data in w.Behaviors.OfType<WeaponData>()) data.AmmoType = new CultRecordRef<SimpleCommodityData>(missiles.Key); + foreach (var data in w.Behaviors.OfType<WeaponData>()) data.AmmoType = new CultRecordRef<SimpleCommodityData>(CommodityKey("missiles")); }); } diff --git a/tools/AetherDb/Program.cs b/tools/AetherDb/Program.cs index 50f97c019..5d3d18e93 100644 --- a/tools/AetherDb/Program.cs +++ b/tools/AetherDb/Program.cs @@ -1105,11 +1105,6 @@ public static class Program return 0; } - // Damage falloff (aetheria-release, damage-curve-fate-ruled): every gun and beam authors an effective range at a - // fraction of its Range (Min and Max scaled, Terms copied so the effective range wears and heats as the range does) - // and a damage multiplier at maximum range. Guided weapons, lock weapons and mine layers keep the unauthored - // defaults (no falloff). The command upserts every weapon design, which is also what drops the retired damage curve - // (key 7) from the stored records. Idempotent: the values are functions of Range alone. Dry run unless "apply". // Read-only: what every weapon design draws per shot (reactor energy, magazine, rounds), so ammunition rulings are audited // against the catalog and not against names. private static int WeaponAmmo() @@ -1123,6 +1118,11 @@ public static class Program return 0; } + // Damage falloff (aetheria-release, damage-curve-fate-ruled): every gun and beam authors an effective range at a + // fraction of its Range (Min and Max scaled, Terms copied so the effective range wears and heats as the range does) + // and a damage multiplier at maximum range. Guided weapons, lock weapons and mine layers keep the unauthored + // defaults (no falloff). The command upserts every weapon design, which is also what drops the retired damage curve + // (key 7) from the stored records. Idempotent: the values are functions of Range alone. Dry run unless "apply". private static int RangeFalloff(string[] args) { var apply = args.Contains("apply"); From 5ec368c11ed1e006a93fc6821f4678efeb6325b4 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 02:55:39 +0000 Subject: [PATCH 019/190] GameData/Aetheria.cc: Munitions re-apply (Missiles shape and stack, recipe lore) economy author Munitions apply; rerun reports 0 changed. sha256 b737d1c74f48c3c0a2e911efd2824345c8491cd8a0c0d3754d78b85d3ea29c40 Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- GameData/Aetheria.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GameData/Aetheria.cc b/GameData/Aetheria.cc index 5b9332c1f..e46487c5f 100644 --- a/GameData/Aetheria.cc +++ b/GameData/Aetheria.cc @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:d1c96c6ed8530a4e17246604580eca3a45666b3846d56d557f8869ce7c2cc2b3 -size 213302 +oid sha256:b737d1c74f48c3c0a2e911efd2824345c8491cd8a0c0d3754d78b85d3ea29c40 +size 213296 From 35fa50f2561aef083dc9817ecbba772ebe9a1b6a Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 03:12:36 +0000 Subject: [PATCH 020/190] Generated turrets are stocked with the crates their weapons reload from GenerateTurretLoadout calls the same StockAmmunition as ships; an ammo-fed turret otherwise went quiet after one magazine. Test: generated turrets hold exactly the crates for each ammunition type they draw. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../Scripts/ServerShared/LoadoutGenerator.cs | 1 + .../AmmunitionStockingTests.cs | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/Assets/Scripts/ServerShared/LoadoutGenerator.cs b/Assets/Scripts/ServerShared/LoadoutGenerator.cs index c82ec1300..93c00aff9 100644 --- a/Assets/Scripts/ServerShared/LoadoutGenerator.cs +++ b/Assets/Scripts/ServerShared/LoadoutGenerator.cs @@ -76,6 +76,7 @@ public class LoadoutGenerator var entity = new OrbitalEntity(ItemManager, null, hull, default, ItemManager.GameplaySettings.DefaultEntitySettings); entity.Faction = Faction; OutfitEntity(entity); + StockAmmunition(entity); return EntitySerializer.Pack(entity) as OrbitalEntityPack; } diff --git a/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs b/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs index 1fd278bfe..d1d0f1317 100644 --- a/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs +++ b/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs @@ -35,4 +35,23 @@ public sealed partial class RunStartTests } Assert.True(fed > 0, "fixture: some generated ship carries an ammunition-fed weapon"); } + + // A generated turret reloads from its own hold like a ship: every ammunition type its weapons draw has crates in it. Kills: a turret + // path that skips StockAmmunition, which leaves an ammo-fed turret quiet after one magazine. + [Fact] + public void GeneratedTurretsCarryTheAmmunitionTheirWeaponsDraw() + { + var generator = new LoadoutGenerator(ref _items.Random, _items, _galaxy, _galaxy.Entrance, _protagonist, .5f); + var fed = 0; + for (var i = 0; i < 60; i++) + { + var turret = EntitySerializer.Unpack(_items, null, generator.GenerateTurretLoadout()); + foreach (var key in turret.Weapons.Select(w => w.WeaponData.AmmoType).Where(t => t.IsSet()).Select(t => t.Key).Distinct()) + { + fed++; + Assert.Equal(LoadoutGenerator.AmmunitionCrates, turret.CountItemsInCargo(key)); + } + } + Assert.True(fed > 0, "fixture: some generated turret carries an ammunition-fed weapon"); + } } From 1f93e22239b05524fea1d82089004de89ecfdc61 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 03:19:46 +0000 Subject: [PATCH 021/190] AetherDb: MunitionsFeed gives the munitions chain real sources; Mines; every round-firing gun names its round MunitionsFeed (run after Munitions) authors the chain's leaf recipes: extraction at mining (Rock, New Metals, Gold, Potassium, Diamond) and volatiles (Water, Methane, Ammonia), Algae at agriculture, Oxygen/Steel/Cellulose Pulp at processing, Circuit Board/Actuator at fabrication. Munitions adds the Mines commodity and recipe, AmmoType=Ammo on Slug Rifle, Long Slug Rifle and Light Machine Gun, AmmoType=Mines on the Mine Launcher, a real Light Machine Gun magazine (0 -> 100 rounds, reload 3 s), and Zhestokost depot stand-ins for mining, volatiles and agriculture so the new recipes' station kinds are placed. Tests read the shipped catalog (pending the blob commit). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../MunitionsSourcingCatalogTests.cs | 79 +++++++++++++++++ tools/AetherDb/Economy/Munitions.cs | 29 ++++++- tools/AetherDb/Economy/MunitionsFeed.cs | 84 +++++++++++++++++++ 3 files changed, 191 insertions(+), 1 deletion(-) create mode 100644 tests/Aetheria.Shared.Tests/MunitionsSourcingCatalogTests.cs create mode 100644 tools/AetherDb/Economy/MunitionsFeed.cs diff --git a/tests/Aetheria.Shared.Tests/MunitionsSourcingCatalogTests.cs b/tests/Aetheria.Shared.Tests/MunitionsSourcingCatalogTests.cs new file mode 100644 index 000000000..45c8db147 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/MunitionsSourcingCatalogTests.cs @@ -0,0 +1,79 @@ +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; +using Xunit; + +// Ruling ballistics-real-ammo, read from the shipped catalog: every gun that fires a round names the commodity it draws, and every +// such commodity (and the chain behind it) is produced from extraction, not from nothing. A round with no source is a magazine +// nobody can ever refill. +public sealed class MunitionsSourcingCatalogTests +{ + // The guns that fire real rounds: ballistic and launcher hardpoints, and the mine layer (a launcher in all but hardpoint). + private static bool FiresRounds(WeaponItemData item, WeaponData data) => + item.HardpointType == HardpointType.Ballistic || item.HardpointType == HardpointType.Launcher || data is MineLayerData; + + // Kills: a ballistic gun (or the Light Machine Gun's free hose) authored with AmmoType unset, which reloads for nothing; a + // drawn commodity that is not a commodity record; a magazine too small for a reload to mean anything. + [Fact] + public void EveryRoundFiringGunNamesAnAmmunitionCommodityAndHoldsARealMagazine() + { + using var db = AetherDb.Open(); + var guns = db.Cache.GetAll<WeaponItemData>() + .SelectMany(i => i.Behaviors.OfType<WeaponData>().Where(d => FiresRounds(i, d)).Select(d => (i.Name, d))).ToArray(); + Assert.True(guns.Length >= 14, $"fixture: the catalog holds its round-firing guns ({guns.Length})"); + foreach (var (name, data) in guns) + { + Assert.True(data.AmmoType.IsSet(), $"{name} draws no ammunition"); + Assert.NotNull(db.Cache.Get<SimpleCommodityData>(data.AmmoType.Key)); + Assert.True(data.MagazineSize >= 1, $"{name} has no magazine"); + } + Assert.Equal(new[] { "Ammo", "Mines", "Missiles" }, guns.Select(g => db.Cache.Get<SimpleCommodityData>(g.d.AmmoType.Key).Name).Distinct().OrderBy(n => n).ToArray()); + } + + // Kills: an ammunition commodity no chain of recipes reaches raw goods for (the Ammo, Missiles and Mines leaves had no recipe at all). + [Fact] + public void EveryDrawnAmmunitionHasAFiniteProductionDepth() + { + using var db = AetherDb.Open(); + var depth = EconomyChecks.Deep(db.Cache); + var drawn = db.Cache.GetAll<WeaponItemData>().SelectMany(i => i.Behaviors.OfType<WeaponData>()).Where(d => d.AmmoType.IsSet()) + .Select(d => d.AmmoType.Key.Value).Distinct().ToArray(); + Assert.Equal(3, drawn.Length); + foreach (var key in drawn) + Assert.True(depth[key] != null, $"{db.Cache.Get<ItemData>(new CultRecordKey(key)).Name} has no finite production depth"); + } + + // Kills: a leaf of the munitions chain left without a source or a sink (the 19 L-source-sink faults this chain shipped with). + [Fact] + public void TheMunitionsChainHasNoSourceSinkFault() + { + using var db = AetherDb.Open(); + var chain = new HashSet<string>(ChainOf(db.Cache), System.StringComparer.Ordinal); + Assert.True(chain.Count >= 25, $"fixture: the chain is walked ({chain.Count} goods)"); + var faults = EconomyChecks.SourceSink(db.Cache).Where(f => chain.Contains(KeyOfRecipe(f.Record))).ToArray(); + Assert.True(faults.Length == 0, string.Join("\n", faults.Select(f => f.Message))); + } + + private static string KeyOfRecipe(string recipeKey) => recipeKey.StartsWith("recipe:") ? recipeKey.Substring("recipe:".Length) : recipeKey; + + // Every good that feeds a drawn round, or fills a role of a round-firing gun, through the recipe graph; the rounds included. + private static IEnumerable<string> ChainOf(CultCache catalog) + { + var recipes = catalog.GetAll<RecipeData>().ToDictionary(r => r.Output.Key.Value); + var open = new Stack<string>(catalog.GetAll<WeaponItemData>().SelectMany(i => i.Behaviors.OfType<WeaponData>()) + .Where(d => d.AmmoType.IsSet()).Select(d => d.AmmoType.Key.Value).Distinct()); + foreach (var item in catalog.GetAll<WeaponItemData>().Where(i => i.Behaviors.OfType<WeaponData>().Any(d => FiresRounds(i, d)))) + { + var recipe = Recipes.RecipeOf(catalog, item); + if (recipe == null) continue; + foreach (var role in Recipes.RoleInputsOf(catalog, recipe)) + foreach (var filler in Recipes.Fillers(catalog, role.Name)) open.Push(filler.Value); + } + var seen = new HashSet<string>(open); + while (open.Count > 0) + if (recipes.TryGetValue(open.Pop(), out var recipe)) + foreach (var input in recipe.Inputs.Select(c => c.Commodity.Key.Value)) + if (seen.Add(input)) open.Push(input); + return seen; + } +} diff --git a/tools/AetherDb/Economy/Munitions.cs b/tools/AetherDb/Economy/Munitions.cs index 83cbee2f2..c20165253 100644 --- a/tools/AetherDb/Economy/Munitions.cs +++ b/tools/AetherDb/Economy/Munitions.cs @@ -32,7 +32,9 @@ public sealed class Munitions : EconomyBatch // Zhestokost has no station model of any kind yet. Its first planned model is the supply depot (ruling faction-station-models), // so its industrial kinds stand in on the depot until their own models land. One hop: depot itself has no Zhestokost stand-in. var zhestokost = FactionRef("Zhestokost"); - foreach (var kind in new[] { "processing", "fabrication", "munitions-works" }) + // The feed stock for the chain (MunitionsFeed) is extracted and grown where the arsenal's planners can reach it, so the mining, + // volatiles and agriculture kinds stand in on the depot too until the factions that own those industries place them. + foreach (var kind in new[] { "processing", "fabrication", "munitions-works", "mining", "volatiles", "agriculture" }) StandIn(kind, zhestokost, "depot"); // Interface goods: named by this chain, owned by another. @@ -153,6 +155,15 @@ public sealed class Munitions : EconomyBatch "A missile crate is a warhead and a motor in one box, and the box is the arsenal's most counted object: Zhestokost ties each launcher crew's allowance to a serial range, so a cache of loose crates is either a deserter's or a quartermaster's crime.", new string[0], (warhead, 1), (motor, 1)); + // Mines: the crate the mine launcher reloads from, a warhead per mine laid. Shape and stack as Missiles. + var mines = new SimpleCommodityData { Name = "Mines", Shape = new Shape(), MaxStack = 5, Mass = 7f, Price = 1400, + Description = "Crated proximity mines: a high-explosive warhead in a steel drum with a fuzed trigger. The crate a mine launcher reloads from." }; + _a.Put(mines, CommodityKey("mines")); + var minesRef = new CultRecordRef<ItemData>(CommodityKey("mines")); + Recipe(minesRef, "munitions-works", 900, 20, 2, + "A mine is a warhead with patience. Every blockade that holds a lane for a season is paid for in crates of these, and a convoy captain who finds a lane suddenly quiet counts the hours since the last tender came through.", + new string[0], (warhead, 1), (steel, 2)); + var dispenser = Compound("mine-dispenser", "Mine Dispenser", "A rack and ejector that lays mines in a pattern.", 20f, 1600); Recipe(dispenser, "fabrication", 900, 20, 1, "Little more than steel and actuators, which is why every convoy navy can build one and every blockade starts with one.", @@ -171,6 +182,22 @@ public sealed class Munitions : EconomyBatch { foreach (var data in w.Behaviors.OfType<WeaponData>()) data.AmmoType = new CultRecordRef<SimpleCommodityData>(CommodityKey("missiles")); }); + + // Every ballistic gun draws a round (ruling ballistics-real-ammo). The Light Machine Gun had no magazine, a free hose; it gets a + // real one so a single Ammo crate reloads it like the other guns. The mine launcher draws a Mines crate. + foreach (var gun in new[] { "Slug Rifle", "Long Slug Rifle", "Light Machine Gun" }) + _a.Edit<WeaponItemData>(gun, w => + { + foreach (var data in w.Behaviors.OfType<WeaponData>()) + { + data.AmmoType = new CultRecordRef<SimpleCommodityData>(ammo.Key); + if (gun == "Light Machine Gun") { data.MagazineSize = 100; data.ReloadTime = 3f; } + } + }); + _a.Edit<WeaponItemData>("Mine Launcher", w => + { + foreach (var data in w.Behaviors.OfType<WeaponData>()) data.AmmoType = new CultRecordRef<SimpleCommodityData>(CommodityKey("mines")); + }); } private CultRecordRef<Faction> FactionRef(string name) diff --git a/tools/AetherDb/Economy/MunitionsFeed.cs b/tools/AetherDb/Economy/MunitionsFeed.cs new file mode 100644 index 000000000..eab9c16cc --- /dev/null +++ b/tools/AetherDb/Economy/MunitionsFeed.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; + +// Economy content, batch 1b: where the munitions chain's raw materials come from. Munitions writes the chain and names its leaves +// (Water, Methane, Ammonia, Oxygen, Potassium, Diamond, Steel, Cellulose Pulp, Actuator, Circuit Board) without recipes; this batch +// gives each a source at a station kind whose description already says it does that work: input-free extraction at mining (ore, +// Gold, Potassium, Diamond) and volatiles (Water, Methane, Ammonia), and processing or fabrication from those goods for the rest. +// Run after Munitions: it edits nothing the other batch writes and every output it names must exist. +public sealed class MunitionsFeed : EconomyBatch +{ + private EconomyAuthor _a; + + public override void Author(EconomyAuthor author) + { + _a = author; + + // Extraction: no inputs, so these are the chain's raw goods. + var rock = Make("Rock", "mining", 300, 10, 8, + "Nobody on a mining station calls it rock; it is the overburden, the slag, the thing the real cargo was buried in. It is also what every smelter, board shop and cement yard starts from, so the cheapest hold in the verse is the one that decides who can build."); + var metals = Make("New Metals", "mining", 300, 12, 6, + "The ore that built the cities: whoever holds the claim feeds every foundry downstream, which is why mining rights are the one commodity the garrisons will not leave unguarded."); + var gold = Make("Gold", "mining", 600, 8, 2, + "Gold has a use besides vanity: it does not corrode in a contact. Boards bound for a hull in a cold or wet corridor are gold-plated, and a prospector who finds a seam sells it to the board shops before the jewellers."); + var potassium = Make("Potassium", "mining", 300, 8, 4, + "Potash and saltpetre salts turn up in the same evaporite beds that mark old water. Farms want it for fertiliser and the arsenal wants it for powder; the survey crews tag the beds by which buyer reached them first."); + var diamond = Make("Diamond", "mining", 1200, 12, 1, + "Industrial stones from the deep kimberlite cores: grit for lining barrels and cutting tools rather than jewellery. A miner who sells one for a ring has wasted a barrel."); + var water = Make("Water", "volatiles", 300, 8, 6, + "Every station buys water first and everything else second. The ice haulers run on the knowledge that a station's water reserve is the one stock it cannot be talked out of counting."); + var methane = Make("Methane", "volatiles", 300, 8, 4, + "Skimmed from the cold ice where it keeps for ever. Hauled home it is cooking gas, a feedstock for the formaldehyde plants, and the first thing that burns when a tank is struck."); + var ammonia = Make("Ammonia", "volatiles", 300, 8, 4, + "Ammonia ice is the nitrogen the whole verse eats and shoots: the farms spread it and the arsenals nitrate it. The skimmers who work cold bodies know exactly which of the two their hold is bound for by the hauler waiting at the dock."); + + // Processing from those goods. + var oxygen = Make("Oxygen", "processing", 240, 10, 3, + "Cracking water ice pays twice: the oxygen goes to lungs and acid towers, and the hydrogen is fuel. A station that sells its oxygen cheap is either swimming in ice or hiding a shortage.", + (water, 3)); + + var steel = Make("Steel", "processing", 600, 20, 4, + "Foundries on the ore belts pour bar, sheet and billet from alloy ore and slag flux. A pour is cheap; the rolling mills that finish it are the part a blockade starves, and every gun, hull plate and nail in the verse is waiting behind them.", + (metals, 3), (rock, 1)); + + // Algae is a catalog commodity the agriculture station description says grows from Water and Potassium. + var algae = Make("Algae", "agriculture", 600, 12, 6, + "Vats of green water under lamp-light: the first thing a new habitat grows, because it eats ash and sunlight and gives back food, fibre and air. A farm that loses its algae loses its station within the season.", + (water, 2), (potassium, 1)); + + var pulp = Make("Cellulose Pulp", "processing", 300, 10, 2, + "Algae from the farm vats is washed, digested and pressed into pulp. The same vats make paper for a Zhestokost order book and guncotton stock for its arsenal, and the split is seen in how many hands the washing hall hires.", + (algae, 3)); + + var board = Make("Circuit Board", "fabrication", 600, 14, 2, + "Gold-plated contacts on a silicate board: the oldest reliable electronics. A region that cannot make its own boards imports a shortage in every device that has a fuze, a sensor or a lock.", + (gold, 1), (rock, 2)); + + Make("Actuator", "fabrication", 600, 16, 1, + "A steel housing, a motor and a controller board. It opens hatches and feeds guns, and a repair crew keeps a drawer of them because everything on a ship eventually needs to move on command.", + (steel, 2), (board, 1)); + } + + private CultRecordRef<ItemData> Make(string name, string kind, float cycle, int workforce, int count, string lore, + params (CultRecordRef<ItemData> Commodity, int Count)[] inputs) + { + var named = _a.Catalog.GetAll<ItemData>().Where(i => i.Name == name).ToArray(); + if (named.Length != 1) throw new InvalidOperationException($"{named.Length} items are named '{name}'; the munitions feed needs exactly one."); + var output = new CultRecordRef<ItemData>(_a.Catalog.RefOf(named[0]).Key); + _a.Put(new RecipeData + { + Output = output, + OutputCount = count, + Inputs = inputs.Select(i => new CommodityCount { Commodity = i.Commodity, Count = i.Count }).ToList(), + Cycle = cycle, + Workforce = workforce, + Upkeep = new List<CommodityCount>(), + StationKind = new CultRecordRef<StationKindData>(StationKindData.KeyOf(kind)), + LoreHook = lore, + Fills = new List<string>() + }, RecipeData.KeyOf(output.Key)); + return output; + } +} From 54632d4eb92604e0934b32b67b48143e36b2dadc Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 03:32:45 +0000 Subject: [PATCH 022/190] Tests: pin Mines in the commodity count; the stand-in fixture uses salvage, since Zhestokost now stands in for mining Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../Aetheria.Shared.Tests/CommodityRecordsTests.cs | 2 +- tests/Aetheria.Shared.Tests/StationKindTests.cs | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/CommodityRecordsTests.cs b/tests/Aetheria.Shared.Tests/CommodityRecordsTests.cs index 91bce1993..b59885c26 100644 --- a/tests/Aetheria.Shared.Tests/CommodityRecordsTests.cs +++ b/tests/Aetheria.Shared.Tests/CommodityRecordsTests.cs @@ -13,7 +13,7 @@ public sealed class CommodityRecordsTests public void ShippedCatalogOpensWithTheRetiredKeysGone() { using var cache = RestoredHullsTests.OpenCatalog(); - Assert.Equal(23, cache.GetAll<SimpleCommodityData>().Count()); + Assert.Equal(24, cache.GetAll<SimpleCommodityData>().Count()); Assert.Equal(63, cache.GetAll<CompoundCommodityData>().Count()); Assert.Contains(cache.GetAll<SimpleCommodityData>(), c => c.Name == "Ammo"); Assert.All(cache.GetAll<CompoundCommodityData>(), c => Assert.False(string.IsNullOrEmpty(c.Name))); diff --git a/tests/Aetheria.Shared.Tests/StationKindTests.cs b/tests/Aetheria.Shared.Tests/StationKindTests.cs index 2082a3719..02db0c081 100644 --- a/tests/Aetheria.Shared.Tests/StationKindTests.cs +++ b/tests/Aetheria.Shared.Tests/StationKindTests.cs @@ -248,17 +248,17 @@ public sealed class StationKindTests : IDisposable { var world = World.Make(this, zenithOffered: false); var hub = world.Sell(world.Zh, "trade-hub", "Zh Hub"); - world.StandIn("mining", world.Zh, "trade-hub"); - var mining = world.Cache.Get(Kind("mining")); + world.StandIn("salvage", world.Zh, "trade-hub"); + var salvage = world.Cache.Get(Kind("salvage")); - Assert.Contains(Kind("mining").Key.Value, StationKinds.KindsOf(world.Cache, world.Zh).Select(kind => kind.Key.Value)); - Assert.Equal(Kind("trade-hub").Key, StationKinds.HullKindFor(world.Cache, world.Zh, Kind("mining")).Key); + Assert.Contains(Kind("salvage").Key.Value, StationKinds.KindsOf(world.Cache, world.Zh).Select(kind => kind.Key.Value)); + Assert.Equal(Kind("trade-hub").Key, StationKinds.HullKindFor(world.Cache, world.Zh, Kind("salvage")).Key); for (uint seed = 1; seed <= 10; seed++) { - var pack = world.Generator(world.Zh, seed).GenerateStationLoadout(Kind("mining")); + var pack = world.Generator(world.Zh, seed).GenerateStationLoadout(Kind("salvage")); Assert.Equal("Zh Hub", world.HullName(pack)); - Assert.Equal(Kind("mining").Key, pack.Kind.Key); - Assert.Equal(mining.Name, pack.Name); + Assert.Equal(Kind("salvage").Key, pack.Kind.Key); + Assert.Equal(salvage.Name, pack.Name); } var own = world.Generator(world.Zh).GenerateStationLoadout(Kind("trade-hub")); Assert.Equal(hub.Name, own.Name); From 8948b99e5964045c7559b9e382cc8d13ff81d7e2 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 03:32:54 +0000 Subject: [PATCH 023/190] GameData/Aetheria.cc: Munitions + MunitionsFeed apply (chain sources, Mines, gun ammo) sha256 0f81d35d4cec8f57178220f20bca98ffaa6709783349efe3cc28aa64ea1f02b1 economy author Munitions MunitionsFeed apply: 14 extraction/processing recipes (Rock, New Metals, Gold, Potassium, Diamond, Water, Methane, Ammonia, Algae, Oxygen, Steel, Cellulose Pulp, Circuit Board, Actuator), Mines commodity and recipe, Zhestokost depot stand-ins for mining, volatiles and agriculture. AmmoType=Ammo on Slug Rifle, Long Slug Rifle, Light Machine Gun; AmmoType=Mines on the Mine Launcher. Stat change: Light Machine Gun MagazineSize 0 -> 100, ReloadTime 1 -> 3 s. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- GameData/Aetheria.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GameData/Aetheria.cc b/GameData/Aetheria.cc index e46487c5f..553e6bcce 100644 --- a/GameData/Aetheria.cc +++ b/GameData/Aetheria.cc @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:b737d1c74f48c3c0a2e911efd2824345c8491cd8a0c0d3754d78b85d3ea29c40 -size 213296 +oid sha256:0f81d35d4cec8f57178220f20bca98ffaa6709783349efe3cc28aa64ea1f02b1 +size 220607 From c21fad28f566447b2c2769a87cf456b6d706ff11 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 03:36:58 +0000 Subject: [PATCH 024/190] Ammunition stock has one owner; a named AmmoType makes a one-round magazine Loadouts.StockAmmunition is the single owner of crate stocking. The generator calls it for generated ships and turrets, and Loadouts.Materialize calls it at the end, which covers every Loadout-built entity: scenario stage.Fit/Preset, the boss in ZoneGenerator, and the console-built ship. Paths left alone: Unpack of a pack or save (an entity's cargo is its own and a saved game's cargo is never touched on load), scenario stage.Cargo (adds on top of the stock), the LoadoutCommit validation build (discarded). The new-run player ship is stage.Generated and so already stocked by the generator. A hull with no bay gets no crates and a log line. InstantWeapon: a weapon that names an AmmoType is magazine-fed with an effective magazine of max(1, MagazineSize): every round leaves the magazine and the reload takes a crate. A weapon with no AmmoType and a magazine of 0 or 1 stays free. HUD shows rounds/reserve for every AmmoType weapon. ConstantWeapon keeps its own per-interval crate draw. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../ServerShared/Behaviors/InstantWeapon.cs | 16 ++-- Assets/Scripts/ServerShared/Loadout.cs | 15 ++++ .../Scripts/ServerShared/LoadoutGenerator.cs | 16 +--- Assets/Scripts/UI/HUD/SchematicDisplay.cs | 7 +- .../AmmunitionStockingTests.cs | 74 +++++++++++++++++++ .../FireControlPerWeaponTests.cs | 48 +++++++++++- 6 files changed, 148 insertions(+), 28 deletions(-) diff --git a/Assets/Scripts/ServerShared/Behaviors/InstantWeapon.cs b/Assets/Scripts/ServerShared/Behaviors/InstantWeapon.cs index c8587f72d..96cdc330e 100644 --- a/Assets/Scripts/ServerShared/Behaviors/InstantWeapon.cs +++ b/Assets/Scripts/ServerShared/Behaviors/InstantWeapon.cs @@ -133,13 +133,13 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerCo public InstantWeapon(InstantWeaponData data, EquippedItem item) : base(data, item) { _data = data; - _ammo = data.MagazineSize; + _ammo = Magazine; } public InstantWeapon(InstantWeaponData data, ConsumableItemEffect item) : base(data, item) { _data = data; - _ammo = data.MagazineSize; + _ammo = Magazine; } protected void Trigger() @@ -229,9 +229,9 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerCo if (!_coolingDown || !(_cooldown < 0)) return false; _overshoot = min(-_cooldown * CountdownSpan, dt); _coolingDown = false; - if (_data.MagazineSize > 0 && _ammo == 0 && TakeReloadRound()) + if (Magazine > 0 && _ammo == 0 && TakeReloadRound()) { - _ammo = _data.MagazineSize; + _ammo = Magazine; OnReloadComplete?.Invoke(); } else @@ -250,7 +250,7 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerCo return true; } - private float CountdownSpan => max(ShortestCycle, _data.MagazineSize > 0 && _ammo == 0 ? _data.ReloadTime : Cooldown); + private float CountdownSpan => max(ShortestCycle, Magazine > 0 && _ammo == 0 ? _data.ReloadTime : Cooldown); // A countdown that starts outside a round (a charge failing) carries the last one's overshoot like every restart. protected void StartCountdown() @@ -266,9 +266,13 @@ public class InstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerCo return overshoot; } + // A weapon that names an AmmoType is magazine-fed whatever MagazineSize says: its magazine is at least one round, every round + // leaves it and the reload takes a crate. A weapon with no AmmoType and a magazine of one or none fires free. + private int Magazine => _data.AmmoType.IsSet() ? max(1, _data.MagazineSize) : _data.MagazineSize; + private bool UseAmmo(float dt) { - if (_data.MagazineSize <= 1) return true; + if (!_data.AmmoType.IsSet() && _data.MagazineSize <= 1) return true; if (_ammo > 0) { diff --git a/Assets/Scripts/ServerShared/Loadout.cs b/Assets/Scripts/ServerShared/Loadout.cs index b8b73a0ab..f327837e2 100644 --- a/Assets/Scripts/ServerShared/Loadout.cs +++ b/Assets/Scripts/ServerShared/Loadout.cs @@ -202,9 +202,24 @@ public static class Loadouts built[g] = (items.Select(item => item.GetBehavior<Weapon>()).ToList(), items); } entity.WeaponGroups = built; + StockAmmunition(itemManager, entity); return entity; } + // The crates an entity's weapons reload from: LoadoutGenerator.AmmunitionCrates of each distinct AmmoType, stopping when no hold takes + // another. The one owner of ammunition stock: every path that fits weapons onto a new entity (the generator, a Loadout's Materialize, + // so a scenario's Fit, a boss, a console-built ship) ends here. A saved or packed entity is never stocked: its cargo is its own. + // Draws nothing from the random stream, so adding it moves no other roll. + public static void StockAmmunition(ItemManager itemManager, Entity entity) + { + foreach (var key in entity.Weapons.Select(weapon => weapon.WeaponData.AmmoType).Where(type => type.IsSet()).Select(type => type.Key).Distinct()) + { + var crates = new SimpleCommodity { Data = new CultRecordRef<ItemData>(key), Quantity = LoadoutGenerator.AmmunitionCrates }; + if (!entity.CargoBays.Any(bay => bay.TryStore(crates))) + itemManager.Log($"{entity.Name}: no room for {LoadoutGenerator.AmmunitionCrates} crates of {key.Value}."); + } + } + // The hull, then each slot's gear, made by the given builders and equipped to the loadout's cells: the one placement of // a loadout, run once on the throwaway manager to decide the fit and once on the live one to build. Null with every // misfit listed when any cell does not take its gear. diff --git a/Assets/Scripts/ServerShared/LoadoutGenerator.cs b/Assets/Scripts/ServerShared/LoadoutGenerator.cs index 93c00aff9..fcd554efd 100644 --- a/Assets/Scripts/ServerShared/LoadoutGenerator.cs +++ b/Assets/Scripts/ServerShared/LoadoutGenerator.cs @@ -60,7 +60,7 @@ public class LoadoutGenerator OutfitEntity(entity); EquipPickup(entity); StockConsumables(entity, ShipConsumableChance, ShipConsumableUnits); - StockAmmunition(entity); + Loadouts.StockAmmunition(ItemManager, entity); return EntitySerializer.Pack(entity); } @@ -76,7 +76,7 @@ public class LoadoutGenerator var entity = new OrbitalEntity(ItemManager, null, hull, default, ItemManager.GameplaySettings.DefaultEntitySettings); entity.Faction = Faction; OutfitEntity(entity); - StockAmmunition(entity); + Loadouts.StockAmmunition(ItemManager, entity); return EntitySerializer.Pack(entity) as OrbitalEntityPack; } @@ -168,18 +168,6 @@ public class LoadoutGenerator } } - // The crates the ship's weapons reload from: AmmunitionCrates of each distinct AmmoType, stopping when no hold takes another. - // Draws nothing from the random stream, so adding it moves no other roll. - private void StockAmmunition(Entity entity) - { - foreach (var key in entity.Weapons.Select(weapon => weapon.WeaponData.AmmoType).Where(type => type.IsSet()).Select(type => type.Key).Distinct()) - { - var crates = new SimpleCommodity { Data = new CultRecordRef<ItemData>(key), Quantity = AmmunitionCrates }; - if (!entity.CargoBays.Any(bay => bay.TryStore(crates))) - ItemManager.Log($"{entity.Name}: no room for {AmmunitionCrates} crates of {key.Value}."); - } - } - private static bool IsHeater(GearData item) => item.HardpointType == HardpointType.Tool && item.Behaviors.Any(b => b is ThermotoggleData { HighPass: false }) && diff --git a/Assets/Scripts/UI/HUD/SchematicDisplay.cs b/Assets/Scripts/UI/HUD/SchematicDisplay.cs index f5d6d8af3..526a83c80 100644 --- a/Assets/Scripts/UI/HUD/SchematicDisplay.cs +++ b/Assets/Scripts/UI/HUD/SchematicDisplay.cs @@ -234,12 +234,7 @@ public class SchematicDisplay : MonoBehaviour x.ListElement.CooldownFill.anchorMax = new Vector2(x.Cooldown.Progress, 1); x.ListElement.DurabilityLabel.text = $"{(int)(x.Row.Item.EquippableItem.Durability / itemData.Durability * 100)}%"; if (x.Weapon.WeaponData.AmmoType.IsSet()) - { - if(x.Weapon.WeaponData.MagazineSize > 1) - x.ListElement.AmmoLabel.text = $"{x.Weapon.Ammo}/{x.Weapon.Reserve}"; - else - x.ListElement.AmmoLabel.text = _entity.CountItemsInCargo(x.Weapon.WeaponData.AmmoType.Key).ToString(); - } + x.ListElement.AmmoLabel.text = $"{x.Weapon.Ammo}/{x.Weapon.Reserve}"; } if (x.ListElement.RangeLabel) diff --git a/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs b/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs index d1d0f1317..95a59f52b 100644 --- a/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs +++ b/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs @@ -1,4 +1,6 @@ +using System.Collections.Generic; using System.Linq; +using static CultMath.math; using Xunit; // Ruling ballistics-real-ammo: generation stocks combatants with rounds, because a magazine weapon reloads from cargo and a ship with @@ -54,4 +56,76 @@ public sealed partial class RunStartTests } Assert.True(fed > 0, "fixture: some generated turret carries an ammunition-fed weapon"); } + + private static int[] FedTypesStocked(Entity ship, out int fed) + { + var keys = ship.Weapons.Select(w => w.WeaponData.AmmoType).Where(t => t.IsSet()).Select(t => t.Key).Distinct().ToArray(); + fed = keys.Length; + return keys.Select(key => ship.CountItemsInCargo(key)).ToArray(); + } + + // A test hull, a one-cell ammunition-fed gun (a magazine of none, so the single-round rule is in play) and a bay, + // in the shared catalog: the smallest authored ship that can carry crates. + private (string Hull, (string, CultMath.int2, ItemRotation)[] Slots) FedFit(bool bay) + { + var shape = new Shape(7, 7); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + var hullData = new HullData { Name = "Fed Hull", HullType = HullType.Ship, Shape = shape, Durability = 10, Mass = 100 }; + _cache.Upsert(hullData); + var rounds = _cache.Upsert(new SimpleCommodityData { Name = "Fed Rounds", Shape = new Shape(), Price = 1, MaxStack = 100 }); + _cache.Upsert(new WeaponItemData + { + Name = "Fed Gun", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 1, + Behaviors = { new InstantWeaponData { AmmoType = rounds, MagazineSize = 0 } } + }); + var interior = new Shape(4, 4); + foreach (var cell in interior.AllCoordinates) interior[cell] = true; + _cache.Upsert(new CargoBayData { Name = "Fed Bay", Shape = new Shape(), InteriorShape = interior, Price = 20, Durability = 4 }); + var slots = new List<(string, CultMath.int2, ItemRotation)> { ("Fed Gun", int2(3, 3), ItemRotation.None) }; + if (bay) slots.Add(("Fed Bay", int2(4, 3), ItemRotation.None)); + return ("Fed Hull", slots.ToArray()); + } + + // A ship a scenario fits slot by slot (stage.Fit, no generator) that carries a bay and an ammunition-fed weapon ends with the crates that + // weapon draws, and its own Reserve reads them. Kills: Materialize returning the entity unstocked (the authored ship fires one magazine). + [Fact] + public void AScenarioFitWithAFedWeaponAndABayCarriesItsCrates() + { + var (hull, slots) = FedFit(bay: true); + var (_, _, staged, failures) = Launch(new Scripted(false, stage => stage.Player(stage.Fit(hull, slots), float2(0, 0))), Inputs(() => GalaxySeed)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + var weapon = Assert.Single(staged.Player.Weapons); + Assert.True(weapon.WeaponData.AmmoType.IsSet(), "fixture: the gun draws ammunition"); + Assert.Equal(LoadoutGenerator.AmmunitionCrates, weapon.Reserve); + } + + // With no hold to put crates in there are none, and the fit still builds: stocking is bounded by what the ship can carry, never a failure. + [Fact] + public void AScenarioFitWithNoBayCarriesNoCratesAndStillBuilds() + { + var (hull, slots) = FedFit(bay: false); + var (_, _, staged, failures) = Launch(new Scripted(false, stage => stage.Player(stage.Fit(hull, slots), float2(0, 0))), Inputs(() => GalaxySeed)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + Assert.Equal(0, Assert.Single(staged.Player.Weapons).Reserve); + } + + // The new run's player ship (stage.Generated at the starting hull) and every ship the shipped main-galaxy scenario generates carry the crates + // their weapons draw: nothing that reaches play with ammunition-fed weapons is left to one magazine. + [Fact] + public void ANewRunPlayerShipCarriesTheCratesItsWeaponsDraw() + { + var fed = 0; + for (uint seed = GalaxySeed; seed < GalaxySeed + 8; seed++) + { + var (_, _, staged, failures) = Launch(new Scripted(false, stage => stage.Player(stage.Generated(stage.StartingHull), float2(0, 0)), seed), + Inputs(() => seed)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + foreach (var count in FedTypesStocked(staged.Player, out var types)) + { + Assert.Equal(LoadoutGenerator.AmmunitionCrates, count); + fed += types; + } + } + Assert.True(fed > 0, "fixture: some new-run player ship carries an ammunition-fed weapon"); + } } diff --git a/tests/Aetheria.Shared.Tests/FireControlPerWeaponTests.cs b/tests/Aetheria.Shared.Tests/FireControlPerWeaponTests.cs index 690bd27d3..95260b713 100644 --- a/tests/Aetheria.Shared.Tests/FireControlPerWeaponTests.cs +++ b/tests/Aetheria.Shared.Tests/FireControlPerWeaponTests.cs @@ -1328,9 +1328,9 @@ public sealed class FireControlPerWeaponTests : IDisposable // One launcher-shaped weapon (magazine 2, reload 3 s, Missiles) held on its trigger at no target, `crates` of Missiles in the // hold. Returns the rig and a counter of committed shots. - private (Rig Rig, Func<int> Shots) AmmoRig(int crates) + private (Rig Rig, Func<int> Shots) AmmoRig(int crates, int magazine = 2) { - var r = Build(fuse: WeaponFuse.Proximity, blast: 30f, range: 40f, magazine: 2, auto: true, crates: crates, reload: 3f); + var r = Build(fuse: WeaponFuse.Proximity, blast: 30f, range: 40f, magazine: magazine, auto: true, crates: crates, reload: 3f); r.Shooter.SetTarget(TargetRef.None); Aim(r, float2(0, 1)); var shots = 0; @@ -1406,4 +1406,48 @@ public sealed class FireControlPerWeaponTests : IDisposable Run(r, 30f); Assert.True(shots > 4, $"an unfed magazine weapon fires past its first magazine, fired {shots}"); } + + // A weapon that names an AmmoType is magazine-fed whatever MagazineSize says (0 or 1 is a magazine of one): it fires one round, every + // reload takes a crate, and with none it fires no more. Kills: UseAmmo/reload ignoring AmmoType at MagazineSize <= 1 (free fire, or + // fire that never touches the cargo). + [Theory] + [InlineData(0)] + [InlineData(1)] + public void ASingleRoundAmmunitionFedWeaponFiresOnePerCrateAndNoMore(int magazine) + { + var (r, shots) = AmmoRig(crates: 2, magazine: magazine); + Assert.Equal(1, r.Gun.Weapon.Ammo); + Run(r, 2f); + Assert.Equal(1, shots()); + Assert.Equal(2, r.Gun.Weapon.Reserve); + Run(r, 30f); + Assert.Equal(3, shots()); + Assert.Equal(0, r.Gun.Weapon.Reserve); + Assert.Equal(0, r.Gun.Weapon.Ammo); + } + + [Theory] + [InlineData(0)] + [InlineData(1)] + public void ASingleRoundAmmunitionFedWeaponWithNoCrateFiresOnceAndNoMore(int magazine) + { + var (r, shots) = AmmoRig(crates: 0, magazine: magazine); + Run(r, 30f); + Assert.Equal(1, shots()); + } + + // With no AmmoType a magazine of 0 or 1 is no magazine: the weapon fires free, as before. Kills: the new rule leaking onto unfed weapons. + [Theory] + [InlineData(0)] + [InlineData(1)] + public void AWeaponWithNoAmmunitionTypeAndNoRealMagazineFiresFree(int magazine) + { + var r = Build(fuse: WeaponFuse.Proximity, blast: 30f, range: 40f, magazine: magazine, auto: true, reload: 3f); + r.Shooter.SetTarget(TargetRef.None); + Aim(r, float2(0, 1)); + var shots = 0; + r.Zone.ShotCommitted.Subscribe(_ => shots++); + Run(r, 30f); + Assert.True(shots > 4, $"an unfed weapon fires on, fired {shots}"); + } } From ded74e8b109f7e3406b81706a0195b0012f94103 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 03:40:33 +0000 Subject: [PATCH 025/190] Scenario fits are stocked unless the scenario authors their cargo Materialize takes stockAmmunition (default true: boss, console ship). ScenarioStage passes false and stocks at the end of staging only the fitted entities whose cargo the scenario did not author with Cargo, so a scenario that names what a hold carries gets exactly that. A packed (saved) fit is never stocked. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/Loadout.cs | 7 ++++--- Assets/Scripts/ServerShared/RunStart.cs | 1 + Assets/Scripts/ServerShared/ScenarioStage.cs | 16 +++++++++++++++- .../AmmunitionStockingTests.cs | 12 ++++++++++++ 4 files changed, 32 insertions(+), 4 deletions(-) diff --git a/Assets/Scripts/ServerShared/Loadout.cs b/Assets/Scripts/ServerShared/Loadout.cs index f327837e2..4866aa406 100644 --- a/Assets/Scripts/ServerShared/Loadout.cs +++ b/Assets/Scripts/ServerShared/Loadout.cs @@ -157,11 +157,12 @@ public static class Loadouts // spawner is to pass LoadoutGenerator.ChooseProduct, with no fallback to any manufacturer; RunStart does, and so does the // boss in ZoneGenerator, which is built here too from its faction's Loadout (Loadouts.BossOf). The hull's type // picks the entity: a ship hull builds a Ship, a turret hull an OrbitalEntity with no orbit, which stays where it is - // put; a station hull is refused. The entity always gets exactly WeaponGroupCount groups; a loadout with fewer is + // put; a station hull is refused. The entity is stocked with the crates its weapons draw (StockAmmunition) unless the caller + // authors the cargo itself and passes stockAmmunition false. The entity always gets exactly WeaponGroupCount groups; a loadout with fewer is // padded with empty groups. A stated quality mints every lot of the fit at it, drawing nothing (a scenario states // one for a fit its checks rest on). public static Entity Materialize(ItemManager itemManager, Zone liveZone, Loadout loadout, - Func<CraftedItemData, FactionProductData> choose, List<string> failures, float? quality = null) + Func<CraftedItemData, FactionProductData> choose, List<string> failures, float? quality = null, bool stockAmmunition = true) { var cache = itemManager.ItemData; var reported = failures.Count; @@ -202,7 +203,7 @@ public static class Loadouts built[g] = (items.Select(item => item.GetBehavior<Weapon>()).ToList(), items); } entity.WeaponGroups = built; - StockAmmunition(itemManager, entity); + if (stockAmmunition) StockAmmunition(itemManager, entity); return entity; } diff --git a/Assets/Scripts/ServerShared/RunStart.cs b/Assets/Scripts/ServerShared/RunStart.cs index 20269e84c..cadd66bcc 100644 --- a/Assets/Scripts/ServerShared/RunStart.cs +++ b/Assets/Scripts/ServerShared/RunStart.cs @@ -44,6 +44,7 @@ public static class RunStart if (!stage.PlayerPlaced) failures.Add("player: the scenario places no player"); if (failures.Count > reported) return null; + stage.StockUnauthoredAmmunition(); var player = stage.PlayerShip; player.IsPlayerShip = true; diff --git a/Assets/Scripts/ServerShared/ScenarioStage.cs b/Assets/Scripts/ServerShared/ScenarioStage.cs index 453ede8ec..a813bbf49 100644 --- a/Assets/Scripts/ServerShared/ScenarioStage.cs +++ b/Assets/Scripts/ServerShared/ScenarioStage.cs @@ -18,6 +18,10 @@ public sealed class ScenarioStage private readonly List<string> _failures = new List<string>(); private readonly List<Placement> _placed = new List<Placement>(); private int _placements; + // The entities this stage built from a fit (a packed fit is a saved ship, whose cargo is its own) and those whose cargo the scenario + // authored with Cargo: the rest are stocked with the crates their weapons draw when staging ends (StockUnauthoredAmmunition). + private readonly HashSet<Entity> _fitted = new HashSet<Entity>(); + private readonly HashSet<Entity> _cargoAuthored = new HashSet<Entity>(); internal ScenarioStage(ItemManager items, Zone arena, string startingHull, TutorialGenerationSettings tutorialGenerationSettings) { @@ -40,6 +44,14 @@ public sealed class ScenarioStage public int Credits { get; set; } internal IReadOnlyList<string> Failures => _failures; + + // Staging's last step: a fitted entity whose cargo the scenario did not author gets the crates its weapons draw, like every other + // newly built armed entity (Loadouts.StockAmmunition). Draws nothing, so it moves no item roll. + internal void StockUnauthoredAmmunition() + { + foreach (var entity in _fitted.Where(entity => !_cargoAuthored.Contains(entity))) + Loadouts.StockAmmunition(_items, entity); + } internal bool PlayerPlaced { get; private set; } internal Ship PlayerShip { get; private set; } internal IReadOnlyList<Placement> Placed => _placed; @@ -160,6 +172,7 @@ public sealed class ScenarioStage public void Cargo(Entity entity, params string[] names) { if (entity == null) return; + _cargoAuthored.Add(entity); var where = $"cargo of {entity.Name}"; var bay = entity.CargoBays.FirstOrDefault(); foreach (var name in names) @@ -183,7 +196,8 @@ public sealed class ScenarioStage else { var failures = new List<string>(); - entity = Loadouts.Materialize(_items, Arena, fit.Loadout, _choose, failures, fit.Quality); + entity = Loadouts.Materialize(_items, Arena, fit.Loadout, _choose, failures, fit.Quality, stockAmmunition: false); + if (entity != null) _fitted.Add(entity); _failures.AddRange(failures.Select(failure => $"{where} ({fit.Loadout.Name}): {failure}")); if (entity == null) return null; } diff --git a/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs b/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs index 95a59f52b..cd91df321 100644 --- a/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs +++ b/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs @@ -99,6 +99,18 @@ public sealed partial class RunStartTests Assert.Equal(LoadoutGenerator.AmmunitionCrates, weapon.Reserve); } + // A scenario that authors a fit's cargo (stage.Cargo) gets exactly that cargo: its author named what the hold holds, so no crates are added. + // Kills: stocking that ignores authored cargo and puts missiles into a scenario whose check counts what the hold carries. + [Fact] + public void AScenarioFitWhoseCargoIsAuthoredIsNotStocked() + { + var (hull, slots) = FedFit(bay: true); + var (_, _, staged, failures) = Launch(new Scripted(false, stage => + stage.Cargo(stage.Player(stage.Fit(hull, slots), float2(0, 0)), "Fed Gun")), Inputs(() => GalaxySeed)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + Assert.Equal(0, Assert.Single(staged.Player.Weapons).Reserve); + } + // With no hold to put crates in there are none, and the fit still builds: stocking is bounded by what the ship can carry, never a failure. [Fact] public void AScenarioFitWithNoBayCarriesNoCratesAndStillBuilds() From 36a74478b6852f3578fc915d7fea909505b2a118 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 04:26:16 +0000 Subject: [PATCH 026/190] Test: a Loadout-built ship is stocked by Materialize's default Pins the default path the boss and the console fly use: a fed gun leaves the ship with AmmunitionCrates, a gun that draws nothing leaves none. Removing the default StockAmmunition call fails the fed case. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../AmmunitionStockingTests.cs | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs b/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs index cd91df321..a5e7e53c9 100644 --- a/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs +++ b/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs @@ -78,6 +78,11 @@ public sealed partial class RunStartTests Name = "Fed Gun", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 1, Behaviors = { new InstantWeaponData { AmmoType = rounds, MagazineSize = 0 } } }); + _cache.Upsert(new WeaponItemData + { + Name = "Plain Gun", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 1, + Behaviors = { new InstantWeaponData { MagazineSize = 0 } } + }); var interior = new Shape(4, 4); foreach (var cell in interior.AllCoordinates) interior[cell] = true; _cache.Upsert(new CargoBayData { Name = "Fed Bay", Shape = new Shape(), InteriorShape = interior, Price = 20, Durability = 4 }); @@ -99,6 +104,27 @@ public sealed partial class RunStartTests Assert.Equal(LoadoutGenerator.AmmunitionCrates, weapon.Reserve); } + // The Loadout path with the DEFAULT stocking argument (what the boss in ZoneGenerator and the console `fly` call): a ship built from a + // Loadout holds the crates its fed weapon draws, and one whose only weapon draws nothing holds none. Kills: Materialize + // dropping its default StockAmmunition (every Loadout-built armed ship fires one magazine). + [Theory] + [InlineData("Fed Gun", LoadoutGenerator.AmmunitionCrates)] + [InlineData("Plain Gun", 0)] + public void ALoadoutBuiltShipIsStockedByDefaultWithWhatItsWeaponsDraw(string gun, int crates) + { + var (hull, _) = FedFit(bay: true); + EquippableItemData Design(string name) => _cache.GetAll<EquippableItemData>().Single(item => item.Name == name); + var loadout = new Loadout { Name = "default stock", Hull = _cache.RefOf(_cache.GetAll<HullData>().Single(h => h.Name == hull)), WeaponGroups = new int[0][] }; + loadout.Slots.Add(new LoadoutSlot { Position = int2(3, 3), Rotation = ItemRotation.None, Design = _cache.RefOf(Design(gun)) }); + loadout.Slots.Add(new LoadoutSlot { Position = int2(4, 3), Rotation = ItemRotation.None, Design = _cache.RefOf(Design("Fed Bay")) }); + var failures = new List<string>(); + var ship = Loadouts.Materialize(_items, null, loadout, _ => null, failures); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + var weapon = Assert.Single(ship.Weapons); + Assert.Equal(gun == "Fed Gun", weapon.WeaponData.AmmoType.IsSet()); + Assert.Equal(crates, ship.CargoBays.Sum(bay => bay.Cargo.Keys.OfType<SimpleCommodity>().Sum(c => c.Quantity))); + } + // A scenario that authors a fit's cargo (stage.Cargo) gets exactly that cargo: its author named what the hold holds, so no crates are added. // Kills: stocking that ignores authored cargo and puts missiles into a scenario whose check counts what the hold carries. [Fact] From 1013e2a2e4450a29be11701ed615ac009772a56d Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 04:35:18 +0000 Subject: [PATCH 027/190] Test: the Economy console-never-written probes keep only the calling thread's writes The two tests capture Console.Out to prove the commands write to the writer they are given. Console is process-global, so in a full-suite run other tests' diagnostic prints landed in the capture and failed the author dry-run test. ConsoleProbe keeps only writes made on the thread running the command, and serialises probes so two cannot restore each other's writer. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../EconomyCommandTests.cs | 52 ++++++++++++++----- 1 file changed, 38 insertions(+), 14 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/EconomyCommandTests.cs b/tests/Aetheria.Shared.Tests/EconomyCommandTests.cs index c0c04f89c..ec1010812 100644 --- a/tests/Aetheria.Shared.Tests/EconomyCommandTests.cs +++ b/tests/Aetheria.Shared.Tests/EconomyCommandTests.cs @@ -5,6 +5,38 @@ using System.Linq; using GameCult.Caching; using Xunit; +// What the calling thread writes to Console while an action runs. Console is process-global and tests run in parallel, so a plain +// SetOut capture also collects other tests' diagnostic prints (the race that failed these tests in full-suite runs): the probe +// keeps only writes made on the thread that runs the action, and the gate keeps two probes from restoring each other's writer. +internal static class ConsoleProbe +{ + private static readonly object Gate = new object(); + + public static string WrittenBy(Action act) + { + lock (Gate) + { + var previous = Console.Out; + var probe = new ThreadWriter(Environment.CurrentManagedThreadId); + Console.SetOut(probe); + try { act(); } + finally { Console.SetOut(previous); } + return probe.Mine.ToString(); + } + } + + private sealed class ThreadWriter : TextWriter + { + private readonly int _thread; + public readonly System.Text.StringBuilder Mine = new System.Text.StringBuilder(); + public ThreadWriter(int thread) => _thread = thread; + public override System.Text.Encoding Encoding => System.Text.Encoding.UTF8; + public override void Write(char value) { if (Environment.CurrentManagedThreadId == _thread) lock (Mine) Mine.Append(value); } + public override void Write(string value) { if (Environment.CurrentManagedThreadId == _thread) lock (Mine) Mine.Append(value); } + public override void Write(char[] buffer, int index, int count) { if (Environment.CurrentManagedThreadId == _thread) lock (Mine) Mine.Append(buffer, index, count); } + } +} + public sealed class EconomyCommandTests { private sealed class Lambda : EconomyBatch @@ -286,17 +318,13 @@ public sealed class EconomyCommandTests using var db = AetherDb.Open(); var expected = new StringWriter(); var expectedCode = EconomyCommand.Report(db.Cache, expected); - var console = new StringWriter(); - var previous = Console.Out; - Console.SetOut(console); var output = new StringWriter(); - int code; - try { code = EconomyCommand.Run(new[] { "report" }, output); } - finally { Console.SetOut(previous); } + int code = 0; + var console = ConsoleProbe.WrittenBy(() => code = EconomyCommand.Run(new[] { "report" }, output)); Assert.Equal(expectedCode, code); Assert.NotEmpty(expected.ToString()); Assert.Equal(expected.ToString(), output.ToString()); - Assert.Empty(console.ToString()); + Assert.Empty(console); } [Fact] @@ -306,17 +334,13 @@ public sealed class EconomyCommandTests var before = File.ReadAllBytes(path); var expected = new StringWriter(); var expectedCode = EconomyCommand.Author(path, new EconomyBatch[] { new Munitions() }, false, expected); - var console = new StringWriter(); - var previous = Console.Out; - Console.SetOut(console); var output = new StringWriter(); - int code; - try { code = EconomyCommand.Run(new[] { "author", "Munitions" }, output); } - finally { Console.SetOut(previous); } + int code = 0; + var console = ConsoleProbe.WrittenBy(() => code = EconomyCommand.Run(new[] { "author", "Munitions" }, output)); Assert.Equal(expectedCode, code); Assert.NotEmpty(expected.ToString()); Assert.Equal(expected.ToString(), output.ToString()); - Assert.Empty(console.ToString()); + Assert.Empty(console); Assert.Equal(before, File.ReadAllBytes(path)); } From ac45a5c836a6e14704d39186e4db46dcfd3c626f Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 04:35:18 +0000 Subject: [PATCH 028/190] AetherDb: mining and volatiles descriptions name Diamond and Ammonia; the ExtractionKindDescriptions batch restates them Every commodity a kind extracts (a recipe with no inputs) is named in that kind's description: checked over the shipped catalog, only these two kinds broke it. The batch applies in the catalog commit that follows; until then the catalog tests for it fail. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../StationKindDescriptionTests.cs | 37 +++++++++++++++++++ .../Economy/ExtractionKindDescriptions.cs | 24 ++++++++++++ tools/AetherDb/StationKindsCatalog.cs | 7 +++- 3 files changed, 66 insertions(+), 2 deletions(-) create mode 100644 tests/Aetheria.Shared.Tests/StationKindDescriptionTests.cs create mode 100644 tools/AetherDb/Economy/ExtractionKindDescriptions.cs diff --git a/tests/Aetheria.Shared.Tests/StationKindDescriptionTests.cs b/tests/Aetheria.Shared.Tests/StationKindDescriptionTests.cs new file mode 100644 index 000000000..234df007a --- /dev/null +++ b/tests/Aetheria.Shared.Tests/StationKindDescriptionTests.cs @@ -0,0 +1,37 @@ +using System.Linq; +using GameCult.Caching; +using Xunit; + +// A station kind's description is what a player and a planner read of what it does; the recipes at the kind are what it does. +public sealed class StationKindDescriptionTests +{ + // Every good the shipped catalog extracts at a station kind (a commodity recipe with no inputs; a gear recipe is a design on offer, not raw) is named in that kind's description. + // Kills: a kind that gains an extraction recipe (Diamond at mining, Ammonia at volatiles) while its description still lists the old set. + [Fact] + public void EveryRawGoodAKindExtractsIsNamedInItsDescription() + { + using var db = AetherDb.Open(); + var cache = db.Cache; + var unnamed = cache.GetAll<RecipeData>().Where(recipe => recipe.Inputs.Count == 0 && recipe.StationKind.IsSet()) + .Select(recipe => (Kind: cache.Get(recipe.StationKind), Output: cache.Get(recipe.Output))) + .Where(pair => pair.Kind != null && (pair.Output is SimpleCommodityData || pair.Output is CompoundCommodityData) && !pair.Kind.Description.Contains(pair.Output.Name)) + .Select(pair => $"{pair.Kind.Name} extracts {pair.Output.Name}, which its description omits") + .Distinct().OrderBy(line => line).ToList(); + Assert.True(unnamed.Count == 0, string.Join("\n", unnamed)); + } + + // The two kinds the rule was cut for, by name, so the rule cannot pass by the catalog having lost the recipes. + [Fact] + public void MiningExtractsDiamondAndVolatilesAmmonia() + { + using var db = AetherDb.Open(); + var cache = db.Cache; + string Extracted(string kindId) => string.Join(",", cache.GetAll<RecipeData>() + .Where(recipe => recipe.Inputs.Count == 0 && recipe.StationKind.IsSet() && recipe.StationKind.Key.Equals(StationKindData.KeyOf(kindId))) + .Select(recipe => cache.Get(recipe.Output).Name)); + Assert.Contains("Diamond", Extracted("mining")); + Assert.Contains("Ammonia", Extracted("volatiles")); + Assert.Contains("Diamond", cache.Get<StationKindData>(StationKindData.KeyOf("mining")).Description); + Assert.Contains("Ammonia", cache.Get<StationKindData>(StationKindData.KeyOf("volatiles")).Description); + } +} diff --git a/tools/AetherDb/Economy/ExtractionKindDescriptions.cs b/tools/AetherDb/Economy/ExtractionKindDescriptions.cs new file mode 100644 index 000000000..b581af0d0 --- /dev/null +++ b/tools/AetherDb/Economy/ExtractionKindDescriptions.cs @@ -0,0 +1,24 @@ +using System; +using GameCult.Caching; + +// Economy content, batch 1c: the mining and volatiles station-kind descriptions name every good their kind now extracts. +// MunitionsFeed gave mining a Diamond recipe and volatiles an Ammonia recipe; the descriptions the station-round bench +// wrote predate them. The same text is StationKindsCatalog.Table's, so a catalog authored fresh says the same thing. +// Sets the description whatever it was, so a rerun converges. +public sealed class ExtractionKindDescriptions : EconomyBatch +{ + public override void Author(EconomyAuthor author) + { + foreach (var (id, description) in new[] + { + ("mining", StationKindsCatalog.DescriptionOf("mining")), + ("volatiles", StationKindsCatalog.DescriptionOf("volatiles")), + }) + { + var key = StationKindData.KeyOf(id); + var kind = author.Catalog.Get<StationKindData>(key) ?? throw new InvalidOperationException($"The catalog holds no station kind '{id}'."); + kind.Description = description; + author.Put(kind, key); + } + } +} diff --git a/tools/AetherDb/StationKindsCatalog.cs b/tools/AetherDb/StationKindsCatalog.cs index a450d2ff7..81e5aee4d 100644 --- a/tools/AetherDb/StationKindsCatalog.cs +++ b/tools/AetherDb/StationKindsCatalog.cs @@ -14,8 +14,8 @@ public static class StationKindsCatalog private static readonly (string id, string name, string description)[] Table = { - ("mining", "Mining Station", "Extracts ore (Rock, New Metals, Gold, Uranium, Potassium) from bodies and belts; consumes tools and food."), - ("volatiles", "Volatiles Station", "Skims Hydrogen, Methane and Water from gas giants and ice; consumes tools."), + ("mining", "Mining Station", "Extracts ore (Rock, New Metals, Gold, Uranium, Potassium) and Diamond from bodies and belts; consumes tools and food."), + ("volatiles", "Volatiles Station", "Skims Hydrogen, Methane, Ammonia and Water from gas giants and ice; consumes tools."), ("agriculture", "Agriculture Station", "Grows Organics (Algae, Fungi, Bacteria, Animal Products) from Water and Potassium; feeds residential."), ("processing", "Processing Station", "Refines ore and volatiles into Metals, Alloys and Compounds."), ("fabrication", "Fabrication Station", "Turns Alloys and Compounds into Manufacturing compounds, Assemblies, gear, Ammo and consumer goods."), @@ -33,6 +33,9 @@ public static class StationKindsCatalog ("waystation", "Waystation", "Fuel, repair and medicine along a corridor."), }; + // A kind's authored description: the one text a fresh catalog gets and an economy batch restates. + public static string DescriptionOf(string id) => Table.Single(row => row.id == id).description; + public static int Run(CultCache cache, bool apply, TextWriter output) { var held = cache.GetAll<StationKindData>().Select(kind => cache.RefOf(kind).Key.Value).ToHashSet(StringComparer.Ordinal); From 908712b2eef6e4151fcc44da8f21733697c316f8 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 04:36:56 +0000 Subject: [PATCH 029/190] HUD: a weapon says what its ammunition label shows; a beam reads its reserve alone ConstantWeapon names an AmmoType but has no magazine (a crate per AmmoInterval straight from the cargo), so the label printed its unfilled magazine ("1/N"). Weapon.AmmoReadout owns the label's text, HasMagazine says whether there is a magazine to show, and SchematicDisplay reads it. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../ServerShared/Behaviors/ConstantWeapon.cs | 1 + .../Scripts/ServerShared/Behaviors/Weapon.cs | 6 ++++ Assets/Scripts/UI/HUD/SchematicDisplay.cs | 2 +- .../AmmunitionStockingTests.cs | 28 +++++++++++++++++++ 4 files changed, 36 insertions(+), 1 deletion(-) diff --git a/Assets/Scripts/ServerShared/Behaviors/ConstantWeapon.cs b/Assets/Scripts/ServerShared/Behaviors/ConstantWeapon.cs index b90a124da..8e44075ed 100644 --- a/Assets/Scripts/ServerShared/Behaviors/ConstantWeapon.cs +++ b/Assets/Scripts/ServerShared/Behaviors/ConstantWeapon.cs @@ -46,6 +46,7 @@ public class ConstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerC { get => _ammo; } + public override bool HasMagazine => false; public float Progress { diff --git a/Assets/Scripts/ServerShared/Behaviors/Weapon.cs b/Assets/Scripts/ServerShared/Behaviors/Weapon.cs index 62e4f4b14..f4cb9bc07 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Weapon.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Weapon.cs @@ -104,6 +104,12 @@ public abstract class Weapon : ActivatedBehavior public abstract int Ammo { get; } // Rounds in the ship's cargo that reload this weapon's magazine: crates of AmmoType, 0 when the weapon draws none. public int Reserve => _data.AmmoType.IsSet() ? Entity.CountItemsInCargo(_data.AmmoType.Key) : 0; + // Whether Ammo counts a magazine. A weapon that names an AmmoType and fires from one (InstantWeapon) does; a beam (ConstantWeapon) draws one + // crate per AmmoInterval straight from the cargo and has none. + public virtual bool HasMagazine => true; + // What the HUD's ammunition label shows: "magazine/reserve" for a magazine weapon, the reserve alone for one without a magazine, empty when + // the weapon draws no ammunition. The one rule the HUD reads, so the label cannot show a magazine a weapon does not have. + public string AmmoReadout => !_data.AmmoType.IsSet() ? "" : HasMagazine ? $"{Ammo}/{Reserve}" : Reserve.ToString(); public WeaponData WeaponData => _data; public float RangeFactor(float at) => WeaponData.RangeFactor(MinRange, EffectiveRange, Range, _data.DamageAtMaxRange, at); diff --git a/Assets/Scripts/UI/HUD/SchematicDisplay.cs b/Assets/Scripts/UI/HUD/SchematicDisplay.cs index 526a83c80..ac49c1297 100644 --- a/Assets/Scripts/UI/HUD/SchematicDisplay.cs +++ b/Assets/Scripts/UI/HUD/SchematicDisplay.cs @@ -234,7 +234,7 @@ public class SchematicDisplay : MonoBehaviour x.ListElement.CooldownFill.anchorMax = new Vector2(x.Cooldown.Progress, 1); x.ListElement.DurabilityLabel.text = $"{(int)(x.Row.Item.EquippableItem.Durability / itemData.Durability * 100)}%"; if (x.Weapon.WeaponData.AmmoType.IsSet()) - x.ListElement.AmmoLabel.text = $"{x.Weapon.Ammo}/{x.Weapon.Reserve}"; + x.ListElement.AmmoLabel.text = x.Weapon.AmmoReadout; } if (x.ListElement.RangeLabel) diff --git a/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs b/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs index a5e7e53c9..2a52e1535 100644 --- a/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs +++ b/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs @@ -166,4 +166,32 @@ public sealed partial class RunStartTests } Assert.True(fed > 0, "fixture: some new-run player ship carries an ammunition-fed weapon"); } + + // The HUD's ammunition label (Weapon.AmmoReadout): a magazine gun reads "magazine/reserve", a beam that names an AmmoType has no magazine (it + // draws a crate per interval) and reads its reserve alone, a weapon that draws nothing reads empty. Kills: a label that prints the beam's + // never-filled magazine as "0/N", or one that drops the magazine from a gun's. + [Fact] + public void TheAmmoLabelShowsAMagazineOnlyForAWeaponThatHasOne() + { + var (hull, _) = FedFit(bay: true); + var rounds = _cache.GetAll<WeaponItemData>().Single(item => item.Name == "Fed Gun").Behaviors.OfType<WeaponData>().Single().AmmoType; + _cache.Upsert(new WeaponItemData + { + Name = "Fed Beam", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 1, + Behaviors = { new ConstantWeaponData { AmmoType = rounds } } + }); + EquippableItemData Design(string name) => _cache.GetAll<EquippableItemData>().Single(item => item.Name == name); + var loadout = new Loadout { Name = "label", Hull = _cache.RefOf(_cache.GetAll<HullData>().Single(h => h.Name == hull)), WeaponGroups = new int[0][] }; + foreach (var (name, x) in new[] { ("Fed Gun", 3), ("Fed Beam", 2), ("Plain Gun", 1), ("Fed Bay", 4) }) + loadout.Slots.Add(new LoadoutSlot { Position = int2(x, 3), Rotation = ItemRotation.None, Design = _cache.RefOf(Design(name)) }); + var failures = new List<string>(); + var ship = Loadouts.Materialize(_items, null, loadout, _ => null, failures); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + + string Label(string name) => ship.Weapons.Single(weapon => _items.GetData(weapon.Item.EquippableItem).Name == name).AmmoReadout; + var reserve = LoadoutGenerator.AmmunitionCrates; + Assert.Equal(reserve.ToString(), Label("Fed Beam")); + Assert.Equal($"{ship.Weapons.Single(w => _items.GetData(w.Item.EquippableItem).Name == "Fed Gun").Ammo}/{reserve}", Label("Fed Gun")); + Assert.Equal("", Label("Plain Gun")); + } } From bd3563dee3b9936c965b0412a505f092b980c2cc Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 04:44:31 +0000 Subject: [PATCH 030/190] Scenarios: the Arcs turret and the Pursuit player carry the crates their guns reload from Arcs' hostile turret fits two 100-round Light Machine Guns and had no hold, so it fell silent after one magazine; it now fits a bay and carries 30 crates of Ammo (about 8 minutes of both guns firing without pause). Pursuit's authored cargo had no Mines, capping the player at one magazine of six; it now carries 10 crates (sixty-six mines). ScenarioStage.Cargo admits a commodity name as one unit, so authored cargo can state crates. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/ScenarioStage.cs | 10 ++- Assets/Scripts/ServerShared/Scenarios/Arcs.cs | 9 ++- .../Scripts/ServerShared/Scenarios/Pursuit.cs | 5 +- .../ScenarioAmmunitionTests.cs | 67 +++++++++++++++++++ 4 files changed, 87 insertions(+), 4 deletions(-) create mode 100644 tests/Aetheria.Shared.Tests/ScenarioAmmunitionTests.cs diff --git a/Assets/Scripts/ServerShared/ScenarioStage.cs b/Assets/Scripts/ServerShared/ScenarioStage.cs index a813bbf49..b7a19b87f 100644 --- a/Assets/Scripts/ServerShared/ScenarioStage.cs +++ b/Assets/Scripts/ServerShared/ScenarioStage.cs @@ -168,7 +168,8 @@ public sealed class ScenarioStage } // Items in the entity's first cargo bay, one per name. A name is an equippable or consumable design (open: the stage - // chooses its product) or a product of one (pinned); a name that is neither is a failure. + // chooses its product) or a product of one (pinned), or a commodity (one unit: the crates an AmmoType weapon reloads + // from); a name that is none of these is a failure. public void Cargo(Entity entity, params string[] names) { if (entity == null) return; @@ -177,6 +178,13 @@ public sealed class ScenarioStage var bay = entity.CargoBays.FirstOrDefault(); foreach (var name in names) { + var commodity = _items.ItemData.GetAll<SimpleCommodityData>().FirstOrDefault(data => data.Name == name); + if (commodity != null) + { + if (bay == null || !bay.TryStore(new SimpleCommodity { Data = new CultRecordRef<ItemData>(_items.ItemData.RefOf<ItemData>(commodity).Key), Quantity = 1 })) + _failures.Add($"{where}: no room for {name}"); + continue; + } var (data, product) = NamedOrProduct<CraftedItemData>(name, where, found => found is EquippableItemData || found is ConsumableItemData); if (data == null) continue; var build = Loadouts.Resolve(_items, _items.ItemData.RefOf(data), diff --git a/Assets/Scripts/ServerShared/Scenarios/Arcs.cs b/Assets/Scripts/ServerShared/Scenarios/Arcs.cs index f0c3f5553..fd5076075 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Arcs.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Arcs.cs @@ -1,3 +1,4 @@ +using System.Linq; using static CultMath.math; using static ItemRotation; @@ -20,6 +21,8 @@ public sealed class Arcs : Scenario public static readonly CultMath.float2 Bow = float2(0, 400), Stern = float2(0, -400), Turret = float2(600, 300), Port = float2(-400, 0), Starboard = float2(400, 0); + public const int TurretAmmoCrates = 30; + public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(); public override void Stage(ScenarioStage stage) @@ -49,12 +52,14 @@ public sealed class Arcs : Scenario ("Compact Reactor", int2(3, 3), None), ("Turret Control Module", int2(3, 5), None), ("not if i see you first", int2(4, 5), None), // Compact Sensor - ("Panopticon Prime", int2(3, 6), None)); // Fire Control Array + ("Panopticon Prime", int2(3, 6), None), // Fire Control Array + ("Store-All Plus", int2(3, 1), None)); // Cargo Bay: the only 2x2 the turret hull has free stage.Player(fighter, float2(0, 0), facing: float2(0, 1)); stage.Place(stage.Bare("Longinus"), Bow); stage.Place(stage.Bare("Longinus"), Stern); - stage.Place(turret, Turret, stance: ScenarioStance.Hostile); + // The turret's guns reload from its hold, a crate of Ammo per 100-round magazine: both guns firing without pause spend about 3.5 crates a minute, so 30 outlast any session. + stage.Cargo(stage.Place(turret, Turret, stance: ScenarioStance.Hostile), Enumerable.Repeat("Ammo", TurretAmmoCrates).ToArray()); stage.Place(stage.Bare("Longinus"), Port); stage.Place(stage.Bare("Longinus"), Starboard); } diff --git a/Assets/Scripts/ServerShared/Scenarios/Pursuit.cs b/Assets/Scripts/ServerShared/Scenarios/Pursuit.cs index d6d630a88..20ad157a1 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Pursuit.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Pursuit.cs @@ -1,3 +1,4 @@ +using System.Linq; using static CultMath.math; using static ItemRotation; @@ -7,6 +8,7 @@ public sealed class Pursuit : Scenario // cloud breaking a sensor's lock, and well outside the 40 at which AStrongCloseSensorBurnsThrough shows a close // sensor burning through. private const float Astern = 300; + public const int MineCrates = 10; public override string Name => "Pursuit"; public override string Id => "pursuit"; @@ -55,7 +57,8 @@ public sealed class Pursuit : Scenario ("Store-All Plus", int2(2, 8), None)); // Cargo Bay var player = stage.Player(layer, float2(0, 0), facing: float2(0, 1)); - stage.Cargo(player, "Morning Fog", "Morning Fog", "Morning Fog", "send it", "send it"); + // The Mine Launcher reloads a magazine of six from a crate of Mines: ten crates are sixty-six mines, minutes of laying at its cooldown, more than a chase lasts. + stage.Cargo(player, new[] { "Morning Fog", "Morning Fog", "Morning Fog", "send it", "send it" }.Concat(Enumerable.Repeat("Mines", MineCrates)).ToArray()); stage.Place(pursuer, float2(0, -Astern), facing: float2(0, 1), stance: ScenarioStance.Hostile, piloted: true); } } diff --git a/tests/Aetheria.Shared.Tests/ScenarioAmmunitionTests.cs b/tests/Aetheria.Shared.Tests/ScenarioAmmunitionTests.cs new file mode 100644 index 000000000..740e793a2 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ScenarioAmmunitionTests.cs @@ -0,0 +1,67 @@ +using System.Collections.Generic; +using System.Linq; +using UniRx; +using Xunit; + +// Scenarios that author a weapon's ammunition-fed crates in a hold (ruling ballistics-real-ammo): the staged hold is what the weapon reloads from, so a +// scenario whose check rests on a weapon firing past its first magazine states the crates it needs. Each test launches through the production path. +public sealed partial class RunStartTests +{ + // The Arcs turret fits two Light Machine Guns of a hundred rounds and a bay of Ammo: its hold holds what the scenario states, and across a minute + // in range of the player it fires past both first magazines, each reload taking a crate. Kills: a turret fit without a bay or with no authored + // crates (silent after one magazine), and Cargo failing to admit a commodity. + [Fact] + public void TheArcsTurretKeepsFiringPastItsFirstMagazine() + { + var (_, arena, staged, failures) = Launch(new Arcs(), Inputs(() => GalaxySeed)); + Assert.Empty(failures); + var player = staged.Player; + var turret = Assert.IsType<OrbitalEntity>(staged.Entities[2]); + var guns = turret.Weapons.ToList(); + Assert.Equal(2, guns.Count); + var ammo = guns[0].WeaponData.AmmoType.Key; + Assert.Equal(Arcs.TurretAmmoCrates, turret.CountItemsInCargo(ammo)); + + // The guns are Auto weapons: they fire on a hostile inside their range (400 m) with no pilot. The player starts 775 m off, so it flies up to 200 m. + arena.Update(0); + player.Position = turret.Position + new CultMath.float3(-200, 0, 0); + var shots = 0; + using var sub = arena.ShotCommitted.Subscribe(outcome => { if (ReferenceEquals(outcome.Source, turret)) shots++; }); + for (var tick = 0; tick < System.MathF.Round(60f / SimClock.GameStep); tick++) arena.Update(SimClock.GameStep); + + var firstMagazines = guns.Sum(gun => gun.WeaponData.MagazineSize); + Assert.True(shots > firstMagazines, $"the turret fired {shots} rounds, no more than its two first magazines of {firstMagazines}"); + Assert.True(turret.CountItemsInCargo(ammo) < Arcs.TurretAmmoCrates, "the turret reloaded without taking a crate"); + } + + // The Pursuit player's Mine Launcher draws its magazine of six from crates of Mines it carries beside the consumables: it lays past six, and the + // crate count falls by one per reload. Kills: authored cargo with no Mines (at most six mines), a reload that takes no crate. + [Fact] + public void ThePursuitPlayerLaysMoreThanOneMagazineOfMinesFromItsCrates() + { + var (_, arena, staged, failures) = Launch(new Pursuit(), Inputs(() => GalaxySeed)); + Assert.Empty(failures); + var player = staged.Player; + var launcher = player.Weapons.Single(weapon => weapon.WeaponData is MineLayerData); + var mines = launcher.WeaponData.AmmoType.Key; + Assert.Equal(Pursuit.MineCrates, player.CountItemsInCargo(mines)); + Assert.Equal(3, HeldOf(player, "Coolant Vent")); + + arena.Update(0); + var laid = 0; + using var sub = arena.Mines.ObserveAdd().Subscribe(_ => laid++); + var reloaded = new List<int>(); + var last = Pursuit.MineCrates; + for (var tick = 0; tick < System.MathF.Round(120f / SimClock.GameStep) && laid <= 18; tick++) + { + launcher.Activate(); + arena.Update(SimClock.GameStep); + var crates = player.CountItemsInCargo(mines); + if (crates != last) { reloaded.Add(last - crates); last = crates; } + } + + Assert.True(laid > launcher.WeaponData.MagazineSize, $"the player laid {laid} mines, no more than one magazine of {launcher.WeaponData.MagazineSize}"); + Assert.NotEmpty(reloaded); + Assert.All(reloaded, step => Assert.Equal(1, step)); + } +} From 0e9b10c3ae9bdb26cb026bf64c8a2d8d716a5d84 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 05:03:57 +0000 Subject: [PATCH 031/190] Crossing: the crosser is launched at the speed it should cross at, since a hull no longer decays below top speed 845f6c3aa (aetheria-gravity:ruling:no-drag-below-top-speed) removed hull drag below a hull's top speed. The crosser was staged at the Djinni's 50 m/s cap on the premise that drag slowed it to ~25 m/s at the bow line; it now holds 50 m/s and crosses at 2.57 s, 50 m/s relative, 1.1 rad/s, outside the tuned encounter (3.6 s, 25 m/s, 0.56 rad/s) that the Brief, the pass window and CrossingHoldsAcrossTheStartWindow all describe. CrossingConditions and CrossingHoldsAcrossTheStartWindow failed on that stale tuning, not on a defect. The encounter is restaged to reproduce its tuning under the ruled physics: launched at 25 m/s from 90 m out (probed over speed x start; constant-speed passes are dx / v seconds, 45 m ahead). The pass lands at 3.63 s, 44.7 m, 24.9 m/s relative, 0.56 rad/s. The test's launch-speed assertions now pin the scenario's 25 m/s instead of "most of the cap"; the time, distance, relative-speed and angular-rate windows are unchanged. If drag below top speed returns, the crosser decays and the pass leaves the window. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/Scenarios/Crossing.cs | 12 +++++++----- tests/Aetheria.Shared.Tests/CrossingScenarioTests.cs | 10 +++++----- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/Assets/Scripts/ServerShared/Scenarios/Crossing.cs b/Assets/Scripts/ServerShared/Scenarios/Crossing.cs index 61529d6d9..e77f50166 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Crossing.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Crossing.cs @@ -6,8 +6,8 @@ public sealed class Crossing : Scenario public override string Name => "Crossing"; public override string Id => "crossing"; public override string Brief => "A Lightning Projector at the starboard gun and a Cell Blaster at the port gun, an unpiloted Djinni coasting across the bow " + - "close ahead and an unpiloted one waiting at range. The crosser is launched to port at 50 m/s and only coasts: nothing steers it, " + - "its hull drag slows it to about 25 m/s at the bow line, and it does not shoot back. Make the pass coasting: give no throttle until the Djinni has crossed the bow, then fly freely " + + "close ahead and an unpiloted one waiting at range. The crosser is launched to port at 25 m/s and only coasts: nothing steers it, " + + "a hull coasts at its launch speed below its top speed, and it does not shoot back. Make the pass coasting: give no throttle until the Djinni has crossed the bow, then fly freely " + "(thrusting from the start carries you past it). Verify: as the Djinni crosses close, FastBlast lands some and projector " + "almost none; against the Djinni at range both land. Fly it again without the Fire Control Array: " + "with it the small gun lands more."; @@ -16,13 +16,15 @@ public sealed class Crossing : Scenario // Where the Djinni sit: the player is at Origin facing +z. Origin is 250 m or more from every body, where the zone's // pull is weakest (about 1.4 u/s^2; the sum of the wells never drops to nothing, and at the old origin the player sat on the star). - // The crosser is unpiloted and placed moving at the Djinni's 50 m/s cap, so its pass is ballistic: bent by the field and slowed - // by hull drag (it reaches the bow line at about 25 m/s relative to the player, 3.6 s in), and nothing steers it. + // The crosser is unpiloted and placed moving at 25 m/s, well under the Djinni's 50 m/s top speed, so its pass is ballistic: a hull + // coasts below its top speed (aetheria-gravity:ruling:no-drag-below-top-speed) and only the field bends it, so it reaches the + // bow line at 25 m/s relative to the player, 3.6 s in, and nothing steers it. (Launched at the cap with drag slowing it to 25 m/s, + // as this scenario was first tuned, it would now hold 50 m/s and cross in 2.6 s.) // CrosserAt is the centre of the start window in which the pass holds: shifting it by 10 m along either axis keeps the pass // inside the test's time and distance windows (CrossingHoldsAcrossTheStartWindow). // The waiting Djinni sits inside the Lightning Projector's arc at 80% of its Range. public static readonly CultMath.float2 Origin = float2(724, 124); - public static readonly CultMath.float2 CrosserAt = Origin + float2(-128, 45), CrosserFacing = float2(1, 0), CrosserVelocity = float2(50, 0); + public static readonly CultMath.float2 CrosserAt = Origin + float2(-90, 45), CrosserFacing = float2(1, 0), CrosserVelocity = float2(25, 0); // The fighter is staged at this quality, so its gear and the range below do not ride the item stream. public const float StagedQuality = .6f; // The Lightning Projector's Range in metres at the staged fit: 996.99 after the three seconds the test settles for diff --git a/tests/Aetheria.Shared.Tests/CrossingScenarioTests.cs b/tests/Aetheria.Shared.Tests/CrossingScenarioTests.cs index 9c827b968..efaa4998d 100644 --- a/tests/Aetheria.Shared.Tests/CrossingScenarioTests.cs +++ b/tests/Aetheria.Shared.Tests/CrossingScenarioTests.cs @@ -10,7 +10,7 @@ using float3 = CultMath.float3; public sealed partial class RunStartTests { // Crossing: the demo's cast; projector and Cell Blaster fitted in separate weapon groups with the Fire Control Array - // aboard; an unpiloted hostile Djinni, coasting at the Djinni's speed cap, that crosses the bow inside 400 m; and an unpiloted neutral one inside the Lightning Projector's + // aboard; an unpiloted hostile Djinni, coasting at 25 m/s, that crosses the bow inside 400 m; and an unpiloted neutral one inside the Lightning Projector's // arc, short of its Range and beyond three quarters of it. [Fact] public void CrossingConditions() @@ -43,12 +43,12 @@ public sealed partial class RunStartTests Assert.True(toCrosser.z > 0, "the crosser starts ahead"); Assert.True(abs(dot(crosser.Direction, player.Direction)) <= sin(radians(30f)) + 1e-4f, "the crosser faces within 30 degrees of perpendicular to the player's bow"); - // It is placed moving: toward the bow line at most of the Djinni's 50 m/s cap, so its run is its own and not only the + // It is placed moving: toward the bow line at the scenario's 25 m/s, so its run is its own and not only the // arena's pull on the player. var crosserVelocity = ((Ship) crosser).Velocity; Assert.True(crosserVelocity.x * toCrosser.x < 0, "the crosser starts moving toward the bow line"); - Assert.True(abs(crosserVelocity.x) >= 40f, "the crosser's speed toward the bow line is most of the Djinni's speed cap"); - Assert.True(length(crosserVelocity) >= 40f, "the crosser starts at most of the Djinni's speed cap"); + Assert.Equal(25f, abs(crosserVelocity.x), 3); + Assert.Equal(25f, length(crosserVelocity), 3); Assert.False(player.IsHostileTo(waiting) || waiting.IsHostileTo(player), "the waiting Djinni is neutral"); Assert.Equal(0, AgentsOf(arena, waiting)); @@ -71,7 +71,7 @@ public sealed partial class RunStartTests Assert.True(length(pass.Ahead) < CrossingMetres, "the crosser passes inside the stated distance"); Assert.True(FireControl.InArc(small, float3(pass.Ahead.x, 0, pass.Ahead.y)), "Cell Blaster bears on the crosser as it crosses"); Assert.True(dot(FireControl.MountDirection(small), float3(player.Direction.x, 0, player.Direction.y)) > 0, "Cell Blaster mounts forward"); - // At seed 112 with no input the pass is at about 3.6 s and 45 m; a seed, field or staging change that loses it moves these. + // At seed 112 with no input the pass is at about 3.6 s and 45 m, at 25 m/s relative (a hull under its top speed coasts, so the launch speed holds); a seed, field or staging change that loses it moves these. Assert.InRange(pass.Seconds, CrossingEarliest, CrossingLatest); Assert.InRange(length(pass.Ahead), 30f, 60f); } From b2a2da9d2754f0ba845d699c69239f52539178cf Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 05:06:09 +0000 Subject: [PATCH 032/190] MiningCut3Tests: ChunkInfo's pinned bits are per host class; the Linux bits are the base's own ChunkInfoIsBitIdenticalToItsValueBeforeTheExtraction never passed on Linux: at c86f28e93 (the commit that added it) it already measures 1039274088 for the second observer where the recording says 1039274086, and base 12dfcef5, the code the recording claims to be taken from, measures the same ...088 on Linux (CultMath 0.4.1 and 0.5.0 alike). The sensor's bearing term (acos, curve) is libm arithmetic, which rounds differently on Windows, where the recording was made. It is a host-class recording read as universal, not a regression: no commit moved it. The pin is now per host class like the two-AI digest (ruling replays-per-host-class): windows-x64 keeps the original recording, linux-x64 is base 12dfcef5 run on Linux, and the current code equals it. A host with no recording fails and prints its bits. RunStartTests.HostClass is now internal, the one host-class name. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../DeterminismLedgerTests.cs | 2 +- tests/Aetheria.Shared.Tests/MiningCut3Tests.cs | 18 ++++++++++++++---- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/DeterminismLedgerTests.cs b/tests/Aetheria.Shared.Tests/DeterminismLedgerTests.cs index 6029d3647..aafadcbbd 100644 --- a/tests/Aetheria.Shared.Tests/DeterminismLedgerTests.cs +++ b/tests/Aetheria.Shared.Tests/DeterminismLedgerTests.cs @@ -255,7 +255,7 @@ public sealed partial class RunStartTests Assert.Equal(first.digest, second.digest); } - private static string HostClass() => + internal static string HostClass() => (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? "linux" : RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "windows" : RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? "osx" : "other") diff --git a/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs b/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs index 5ac322c01..dc6ffd628 100644 --- a/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs +++ b/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs @@ -308,9 +308,17 @@ public sealed partial class MiningCut3Tests : IDisposable // ChunkInfo's value is not changed by moving its arithmetic under PassiveInfo: six observers at different // places and bearings, one with a second sensor so the average is live, read the same chunk, and every value - // matches the bits recorded at base 12dfcef5, before the extraction (a different order of the multiplication - // by the chunk's brightness moves them in the last bits). - private static readonly uint[] ChunkInfoAtBase = new uint[] { 1045120030u, 1039274086u, 1030543422u, 1029120970u, 1036363351u, 1035122917u }; + // matches the bits the code before the extraction (base 12dfcef5) gives on the same host class (a different order of + // the multiplication by the chunk's brightness moves them in the last bits). The bits are per host class because + // the sensor's bearing term (acos, curve) is libm arithmetic, which rounds differently on Windows and Linux; replays + // are trusted only on the host class that recorded them (ruling replays-per-host-class). windows-x64 is the recording the + // test was written with; linux-x64 is base 12dfcef5 run on Linux, which gives 1039274088 where Windows gave 1039274086 for + // the second observer, and the current code gives the same bits as that base. + private static readonly System.Collections.Generic.Dictionary<string, uint[]> ChunkInfoAtBase = new() + { + ["windows-x64"] = new uint[] { 1045120030u, 1039274086u, 1030543422u, 1029120970u, 1036363351u, 1035122917u }, + ["linux-x64"] = new uint[] { 1045120030u, 1039274088u, 1030543422u, 1029120970u, 1036363351u, 1035122917u }, + }; [Fact] public void ChunkInfoIsBitIdenticalToItsValueBeforeTheExtraction() @@ -329,7 +337,9 @@ public sealed partial class MiningCut3Tests : IDisposable Assert.All(values, v => Assert.InRange(v, 1e-4f, .99f)); // a live, unsaturated reading at every place var actual = values.Select(Bits).ToArray(); - Assert.True(actual.SequenceEqual(ChunkInfoAtBase), "ChunkInfo bits: " + string.Join(",", actual)); + var host = RunStartTests.HostClass(); + Assert.True(ChunkInfoAtBase.TryGetValue(host, out var pinned), $"ChunkInfo bits: host class {host} has no recording; measured " + string.Join(",", actual)); + Assert.True(actual.SequenceEqual(pinned), $"ChunkInfo bits on {host}: " + string.Join(",", actual) + " pinned " + string.Join(",", pinned)); } // A chunk outside every sun's light is dark: no visibility, no info, and it cannot be picked, while a lit From 85f1a933d483728cbb330c25e07902116d6325a5 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 05:07:47 +0000 Subject: [PATCH 033/190] GetAllChildClasses: the type memo is concurrent A plain Dictionary written by parallel catalog loads corrupted itself ("Operations that change non-concurrent collections must have exclusive access") and failed unrelated tests at random, through ValidateStatModifiers. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/Extensions.cs | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/Assets/Scripts/ServerShared/Extensions.cs b/Assets/Scripts/ServerShared/Extensions.cs index 97433a299..6ac7b5186 100644 --- a/Assets/Scripts/ServerShared/Extensions.cs +++ b/Assets/Scripts/ServerShared/Extensions.cs @@ -32,16 +32,13 @@ public static class Extensions // Every loadable type assignable to this one. An assembly whose dependencies are missing (a Unity plugin // referencing UnityEngine outside Unity) still yields the types that do load. - private static readonly Dictionary<Type, Type[]> ChildClasses = new Dictionary<Type, Type[]>(); - public static Type[] GetAllChildClasses(this Type type) + // Read from parallel loaders (catalog validation, parallel tests), so the memo is concurrent. + private static readonly System.Collections.Concurrent.ConcurrentDictionary<Type, Type[]> ChildClasses = new System.Collections.Concurrent.ConcurrentDictionary<Type, Type[]>(); + public static Type[] GetAllChildClasses(this Type type) => ChildClasses.GetOrAdd(type, t => AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => { - if (ChildClasses.TryGetValue(type, out var children)) return children; - return ChildClasses[type] = AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => - { - try { return assembly.GetTypes(); } - catch (ReflectionTypeLoadException e) { return e.Types.Where(t => t != null); } - }).Where(type.IsAssignableFrom).ToArray(); - } + try { return assembly.GetTypes(); } + catch (ReflectionTypeLoadException e) { return e.Types.Where(x => x != null); } + }).Where(t.IsAssignableFrom).ToArray()); public static string SplitCamelCase(this string str) => Regex.Replace(Regex.Replace(str, @"(\P{Ll})(\P{Ll}\p{Ll})", "$1 $2"), @"(\p{Ll})(\P{Ll})", "$1 $2"); From ee49f95843aec147342d17bff758d5f3b7b41bab Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 05:07:47 +0000 Subject: [PATCH 034/190] AetherDb economy: Author takes the scratch root; TheTrialCopyIsRemoved audits its own, not the shared temp folder The test counted aetherdb-economy-* directories in the machine's temp folder, which every parallel test running the command also writes to. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../EconomyCommandTests.cs | 17 +++++++++++++---- tools/AetherDb/EconomyCommand.cs | 7 ++++--- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/EconomyCommandTests.cs b/tests/Aetheria.Shared.Tests/EconomyCommandTests.cs index ec1010812..9319dbb1c 100644 --- a/tests/Aetheria.Shared.Tests/EconomyCommandTests.cs +++ b/tests/Aetheria.Shared.Tests/EconomyCommandTests.cs @@ -178,10 +178,19 @@ public sealed class EconomyCommandTests public void TheTrialCopyIsRemoved() { using var f = EconomyFixture.Healthy(); - var before = Directory.GetDirectories(Path.GetTempPath(), "aetherdb-economy-*").Length; - Author(f, false, out _, a => Good(f, a, "coal")); - Author(f, true, out _, a => Good(f, a, "tar", lore: "")); - Assert.Equal(before, Directory.GetDirectories(Path.GetTempPath(), "aetherdb-economy-*").Length); + // A private scratch root: the temp folder is shared with every parallel test that runs the command, so counting it races. + var scratchRoot = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "aetherdb-economy-audit-" + Guid.NewGuid().ToString("N"))).FullName; + try + { + foreach (var apply in new[] { false, true }) + { + Flush(f); + var batch = new Lambda(a => Good(f, a, apply ? "tar" : "coal", lore: apply ? "" : "a good")); + EconomyCommand.Author(f.CatalogPath, new EconomyBatch[] { batch }, apply, new StringWriter(), TestCatalog.Registry(), scratchRoot); + } + Assert.Empty(Directory.GetFileSystemEntries(scratchRoot)); + } + finally { Directory.Delete(scratchRoot, true); } } [Fact] diff --git a/tools/AetherDb/EconomyCommand.cs b/tools/AetherDb/EconomyCommand.cs index 244fc4279..cf536cd9e 100644 --- a/tools/AetherDb/EconomyCommand.cs +++ b/tools/AetherDb/EconomyCommand.cs @@ -107,15 +107,16 @@ public static class EconomyCommand // atomically, so a refusal leaves Aetheria.cc byte-identical. A batch is compiled code and is reviewed as code: it is trusted not // to touch the real file, and the command refuses by name if the file changed under it. Added, changed and unchanged are read by // comparing the original and the copy on disk. A shape fault the batches introduce (present after, absent before, by rule and - // record) refuses; faults the catalog already held print and do not. - public static int Author(string catalogPath, IReadOnlyList<EconomyBatch> batches, bool apply, TextWriter output, CultDocumentRegistry registry = null) + // record) refuses; faults the catalog already held print and do not. The trial copy lives under scratchRoot (the temp folder unless a caller + // that audits it names a private one). + public static int Author(string catalogPath, IReadOnlyList<EconomyBatch> batches, bool apply, TextWriter output, CultDocumentRegistry registry = null, string scratchRoot = null) { if (apply && new FileInfo(catalogPath).IsReadOnly) { output.WriteLine("The batches are refused: Aetheria.cc is read-only. Clear the read-only flag, or check it out, and run again. The catalog is unchanged."); return 1; } - var scratch = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "aetherdb-economy-" + Guid.NewGuid().ToString("N"))).FullName; + var scratch = Directory.CreateDirectory(Path.Combine(scratchRoot ?? Path.GetTempPath(), "aetherdb-economy-" + Guid.NewGuid().ToString("N"))).FullName; try { var trial = Path.Combine(scratch, "Aetheria.cc"); From 601ce3cc18c66392cb45ac3a3c5ea54e7e64876e Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 05:14:40 +0000 Subject: [PATCH 035/190] Catalog: mining names Diamond, volatiles names Ammonia (economy author ExtractionKindDescriptions) Applied through AetherDb: 0 added, 2 changed (station-kind:mining, station-kind:volatiles), 0 removed. economy report fault count unchanged at 126. GameData/Aetheria.cc sha256 956a1573fa2aa69d7f72861e10dd17d7d3255d114e878da81802869efcfe31e9 (before: 0f81d35d4cec8f57178220f20bca98ffaa6709783349efe3cc28aa64ea1f02b1). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- GameData/Aetheria.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GameData/Aetheria.cc b/GameData/Aetheria.cc index 553e6bcce..3bf502c21 100644 --- a/GameData/Aetheria.cc +++ b/GameData/Aetheria.cc @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:0f81d35d4cec8f57178220f20bca98ffaa6709783349efe3cc28aa64ea1f02b1 -size 220607 +oid sha256:956a1573fa2aa69d7f72861e10dd17d7d3255d114e878da81802869efcfe31e9 +size 220628 From 3458f0d7b3b2fe80188bb892518c2ac9e474dffa Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 05:20:46 +0000 Subject: [PATCH 036/190] TwoAiDigestIsPinned: repin linux-x64 to 52fbb10d and name the flight-model commits that moved it Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- tests/Aetheria.Shared.Tests/DeterminismLedgerTests.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/tests/Aetheria.Shared.Tests/DeterminismLedgerTests.cs b/tests/Aetheria.Shared.Tests/DeterminismLedgerTests.cs index aafadcbbd..31b71dba0 100644 --- a/tests/Aetheria.Shared.Tests/DeterminismLedgerTests.cs +++ b/tests/Aetheria.Shared.Tests/DeterminismLedgerTests.cs @@ -48,7 +48,13 @@ public sealed partial class RunStartTests // go of a held weapon it no longer commands (target gone, untracked, another group the pick, Combat ended), where a held gun fired on // until a later step selected its group (the candidate change reverted: d9493bbe). Both together: the digest below. Releasing a beam or a // lock the same way (h7) moved nothing. - private const string TwoAiPinnedDigest = "85e85c46cfc66693c819dd294ad02f3cd0eae5486c8f152a97e2e2787f854274"; + // Repinned an eighth time, once (suite-honest), for the flight-model changes that landed after h6 and never repinned this + // entry (bisected on master, each intended): e0c1daa4e made ThrustScale default 0.1, 845f6c3aa removed drag below top speed, + // ffdba39ac made ThrustScale scale the push only, and 8c5a904cb pinned the fixtures to ThrustScale=1. Pull requests 8 and 9 + // moved the digest and returned it to 52fbb10d, which master already measured before this cut. The authored-cargo and + // ammunition-data blob of this cut moved nothing (52fbb10d measured with it merged in). Fixtures run ThrustScale=1 while play + // uses 0.1, so this digest pins the fight's logic, not the shipped feel. + private const string TwoAiPinnedDigest = "52fbb10df2559829a11f3a38aae0783f3f1858b0499f6f46794a267a747adacb"; private const float TwoAiSeconds = 60f; [Fact] From 036f75a0d8e68f4e77d9194ae1dc2a2d56409b22 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 05:58:27 +0000 Subject: [PATCH 037/190] CoastingTests: a ship launched below top speed keeps it at the play ThrustScale 0.1 and at 1 Reads only the ship's velocity after the zone steps; reintroducing drag below top speed fails both cases (50 -> 18.39 in 10 s). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- tests/Aetheria.Shared.Tests/CoastingTests.cs | 48 ++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 tests/Aetheria.Shared.Tests/CoastingTests.cs diff --git a/tests/Aetheria.Shared.Tests/CoastingTests.cs b/tests/Aetheria.Shared.Tests/CoastingTests.cs new file mode 100644 index 000000000..56b33151e --- /dev/null +++ b/tests/Aetheria.Shared.Tests/CoastingTests.cs @@ -0,0 +1,48 @@ +using System; +using CultMath; +using Xunit; +using static CultMath.math; +using float3 = CultMath.float3; +using Random = CultMath.Random; + +// The consumer's side of aetheria-gravity:ruling:no-drag-below-top-speed: a ship launched below its hull's top speed and +// left alone keeps that speed, at the global thrust tuning the game ships with (GameplaySettings.ThrustScale 0.1) as well as +// at the fixtures' 1. Reads only the ship's velocity after the zone steps: not Drag, DragScale or any field of the fix. +// Kills: drag reintroduced below top speed, or any deceleration whose size depends on ThrustScale. +public sealed class CoastingTests +{ + private const float PlayThrustScale = .1f; // GameplaySettings.ThrustScale's default, the value play runs at + + private static float CoastedSpeed(float thrustScale, float launchSpeed, float seconds) + { + using var cache = RestoredHullsTests.OpenCatalog(); + var hull = cache.GetByName<HullData>("Longinus"); + var settings = RestoredHullsTests.Settings(); + settings.ThrustScale = thrustScale; + var items = new ItemManager(1u, cache, new ProvenanceLedger(), settings, _ => { }); + items.Random = new Random(1u); + var random = new Random(1); + var pack = new LoadoutGenerator(ref random, items, null, null, null, .5f).GenerateShipLoadout(candidate => candidate == hull); + Assert.NotNull(pack); + var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test", Owner = null }, null); + var ship = (Ship) EntitySerializer.Unpack(items, zone, pack); + zone.Admit(ship, piloted: false); + ship.Position = float3.zero; + zone.Update(0f); + + ship.MovementDirection = float2(0, 0); + ship.Velocity = float2(0, launchSpeed); + for (var i = 0; i < (int) (seconds * 60); i++) zone.Update(1f / 60f); + return length(ship.Velocity); + } + + [Theory] + [InlineData(PlayThrustScale)] + [InlineData(1f)] + public void AShipLaunchedBelowTopSpeedKeepsItsSpeed(float thrustScale) + { + const float launch = 50f; // Longinus's top speed is 100 + var speed = CoastedSpeed(thrustScale, launch, 10f); + Assert.True(speed >= launch - .01f, $"ThrustScale {thrustScale}: launched at {launch}, coasting 10 s left it at {speed}"); + } +} From eee5f213bfa82903044cad99c31b5220c118177d Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 05:59:30 +0000 Subject: [PATCH 038/190] Ammo label visibility is Weapon.ShowsAmmoReadout: the HUD's three AmmoType.IsSet() decisions move into Shared and are tested Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/Behaviors/Weapon.cs | 4 +++- Assets/Scripts/UI/HUD/SchematicDisplay.cs | 6 +++--- tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs | 5 +++++ 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/Assets/Scripts/ServerShared/Behaviors/Weapon.cs b/Assets/Scripts/ServerShared/Behaviors/Weapon.cs index f4cb9bc07..52b69d196 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Weapon.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Weapon.cs @@ -109,7 +109,9 @@ public abstract class Weapon : ActivatedBehavior public virtual bool HasMagazine => true; // What the HUD's ammunition label shows: "magazine/reserve" for a magazine weapon, the reserve alone for one without a magazine, empty when // the weapon draws no ammunition. The one rule the HUD reads, so the label cannot show a magazine a weapon does not have. - public string AmmoReadout => !_data.AmmoType.IsSet() ? "" : HasMagazine ? $"{Ammo}/{Reserve}" : Reserve.ToString(); + public string AmmoReadout => !ShowsAmmoReadout ? "" : HasMagazine ? $"{Ammo}/{Reserve}" : Reserve.ToString(); + // Whether the HUD shows the ammunition label at all (and not the infinite-ammunition icon): the weapon names an AmmoType. + public bool ShowsAmmoReadout => _data.AmmoType.IsSet(); public WeaponData WeaponData => _data; public float RangeFactor(float at) => WeaponData.RangeFactor(MinRange, EffectiveRange, Range, _data.DamageAtMaxRange, at); diff --git a/Assets/Scripts/UI/HUD/SchematicDisplay.cs b/Assets/Scripts/UI/HUD/SchematicDisplay.cs index ac49c1297..90b4271d3 100644 --- a/Assets/Scripts/UI/HUD/SchematicDisplay.cs +++ b/Assets/Scripts/UI/HUD/SchematicDisplay.cs @@ -132,8 +132,8 @@ public class SchematicDisplay : MonoBehaviour //x.ListElement.Label.text = x.Item.EquippableItem.Name; if (!_enemy) { - x.ListElement.InfiniteAmmoIcon.gameObject.SetActive(!x.Weapon.WeaponData.AmmoType.IsSet()); - x.ListElement.AmmoLabel.gameObject.SetActive(x.Weapon.WeaponData.AmmoType.IsSet()); + x.ListElement.InfiniteAmmoIcon.gameObject.SetActive(!x.Weapon.ShowsAmmoReadout); + x.ListElement.AmmoLabel.gameObject.SetActive(x.Weapon.ShowsAmmoReadout); } } } @@ -233,7 +233,7 @@ public class SchematicDisplay : MonoBehaviour if (x.Cooldown != null) x.ListElement.CooldownFill.anchorMax = new Vector2(x.Cooldown.Progress, 1); x.ListElement.DurabilityLabel.text = $"{(int)(x.Row.Item.EquippableItem.Durability / itemData.Durability * 100)}%"; - if (x.Weapon.WeaponData.AmmoType.IsSet()) + if (x.Weapon.ShowsAmmoReadout) x.ListElement.AmmoLabel.text = x.Weapon.AmmoReadout; } diff --git a/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs b/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs index 2a52e1535..dfdb9d040 100644 --- a/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs +++ b/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs @@ -193,5 +193,10 @@ public sealed partial class RunStartTests Assert.Equal(reserve.ToString(), Label("Fed Beam")); Assert.Equal($"{ship.Weapons.Single(w => _items.GetData(w.Item.EquippableItem).Name == "Fed Gun").Ammo}/{reserve}", Label("Fed Gun")); Assert.Equal("", Label("Plain Gun")); + // The HUD shows the label (not the infinite-ammunition icon) exactly for the weapons that read something. + bool Shown(string name) => ship.Weapons.Single(weapon => _items.GetData(weapon.Item.EquippableItem).Name == name).ShowsAmmoReadout; + Assert.True(Shown("Fed Gun")); + Assert.True(Shown("Fed Beam")); + Assert.False(Shown("Plain Gun")); } } From 58c4fa10c193e09adc18b102fe9ac5ecaa2c277b Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 05:59:30 +0000 Subject: [PATCH 039/190] ShipProductTests and ShipModCatalogTests capture Console through ConsoleProbe.Capture so restores cannot interleave Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../EconomyCommandTests.cs | 25 ++++++++++++++----- .../ShipModCatalogTests.cs | 8 ++---- .../Aetheria.Shared.Tests/ShipProductTests.cs | 8 ++---- 3 files changed, 23 insertions(+), 18 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/EconomyCommandTests.cs b/tests/Aetheria.Shared.Tests/EconomyCommandTests.cs index 9319dbb1c..9557f27a1 100644 --- a/tests/Aetheria.Shared.Tests/EconomyCommandTests.cs +++ b/tests/Aetheria.Shared.Tests/EconomyCommandTests.cs @@ -13,15 +13,28 @@ internal static class ConsoleProbe private static readonly object Gate = new object(); public static string WrittenBy(Action act) + { + Capture<int>(() => { act(); return 0; }, out var output, out _); + return output; + } + + // The action's result with what it wrote to Console.Out and Console.Error on this thread. + public static T Capture<T>(Func<T> act, out string output, out string error) { lock (Gate) { - var previous = Console.Out; - var probe = new ThreadWriter(Environment.CurrentManagedThreadId); - Console.SetOut(probe); - try { act(); } - finally { Console.SetOut(previous); } - return probe.Mine.ToString(); + var (previousOut, previousError) = (Console.Out, Console.Error); + var (probeOut, probeError) = (new ThreadWriter(Environment.CurrentManagedThreadId), new ThreadWriter(Environment.CurrentManagedThreadId)); + Console.SetOut(probeOut); + Console.SetError(probeError); + try { return act(); } + finally + { + Console.SetOut(previousOut); + Console.SetError(previousError); + output = probeOut.Mine.ToString(); + error = probeError.Mine.ToString(); + } } } diff --git a/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs b/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs index 3def3e6dd..cbda4266b 100644 --- a/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs @@ -546,12 +546,8 @@ public sealed class ShipModCatalogTests : IDisposable private static (int Code, string Output, string Error) Run(params string[] args) { - var (output, error) = (new StringWriter(), new StringWriter()); - var (previousOut, previousError) = (Console.Out, Console.Error); - Console.SetOut(output); - Console.SetError(error); - try { return (ShipAuthoringCommands.Run(args), output.ToString(), error.ToString()); } - finally { Console.SetOut(previousOut); Console.SetError(previousError); } + var code = ConsoleProbe.Capture(() => ShipAuthoringCommands.Run(args), out var output, out var error); + return (code, output, error); } [Fact] diff --git a/tests/Aetheria.Shared.Tests/ShipProductTests.cs b/tests/Aetheria.Shared.Tests/ShipProductTests.cs index 343f35082..e14950b0d 100644 --- a/tests/Aetheria.Shared.Tests/ShipProductTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipProductTests.cs @@ -247,12 +247,8 @@ public sealed class ShipProductTests : IDisposable private static (int Code, string Output, string Error) Run(params string[] args) { - var (output, error) = (new StringWriter(), new StringWriter()); - var (previousOut, previousError) = (Console.Out, Console.Error); - Console.SetOut(output); - Console.SetError(error); - try { return (ShipAuthoringCommands.Run(args), output.ToString(), error.ToString()); } - finally { Console.SetOut(previousOut); Console.SetError(previousError); } + var code = ConsoleProbe.Capture(() => ShipAuthoringCommands.Run(args), out var output, out var error); + return (code, output, error); } [Fact] From dcd27cb3b04c376131029feeca84de2d42dcb94c Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 05:59:44 +0000 Subject: [PATCH 040/190] Station-kind descriptions name only goods a recipe makes or takes Uranium, Hydrogen (and Bacteria, Fungi, Animal Products) were named by mining, volatiles, agriculture, habitat-support and power descriptions with no recipe behind them. Dropped the claims (smaller than authoring a power chain); batch StationKindDescriptions restates the five kinds in the catalog; test pins the rule. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- GameData/Aetheria.cc | 4 +-- .../StationKindDescriptionTests.cs | 29 +++++++++++++++++++ .../Economy/ExtractionKindDescriptions.cs | 24 --------------- .../Economy/StationKindDescriptions.cs | 27 +++++++++++++++++ tools/AetherDb/StationKindsCatalog.cs | 10 +++---- 5 files changed, 63 insertions(+), 31 deletions(-) delete mode 100644 tools/AetherDb/Economy/ExtractionKindDescriptions.cs create mode 100644 tools/AetherDb/Economy/StationKindDescriptions.cs diff --git a/GameData/Aetheria.cc b/GameData/Aetheria.cc index 3bf502c21..da60f2dd3 100644 --- a/GameData/Aetheria.cc +++ b/GameData/Aetheria.cc @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:956a1573fa2aa69d7f72861e10dd17d7d3255d114e878da81802869efcfe31e9 -size 220628 +oid sha256:319c14830b174e4bd58fe849b1300f38d7724d91027e47a03a5c121741d38e51 +size 220537 diff --git a/tests/Aetheria.Shared.Tests/StationKindDescriptionTests.cs b/tests/Aetheria.Shared.Tests/StationKindDescriptionTests.cs index 234df007a..3e00ba91b 100644 --- a/tests/Aetheria.Shared.Tests/StationKindDescriptionTests.cs +++ b/tests/Aetheria.Shared.Tests/StationKindDescriptionTests.cs @@ -1,4 +1,5 @@ using System.Linq; +using System.Text.RegularExpressions; using GameCult.Caching; using Xunit; @@ -34,4 +35,32 @@ public sealed class StationKindDescriptionTests Assert.Contains("Diamond", cache.Get<StationKindData>(StationKindData.KeyOf("mining")).Description); Assert.Contains("Ammonia", cache.Get<StationKindData>(StationKindData.KeyOf("volatiles")).Description); } + + // Kills: a station-kind description naming a commodity no recipe yields or consumes (Uranium, Hydrogen, Bacteria, Fungi and + // Animal Products were named by the shipped descriptions with no recipe behind them). + [Fact] + public void EveryCommodityAStationKindNamesIsMadeOrTakenByARecipe() + { + using var db = AetherDb.Open(); + var c = db.Cache; + var used = c.GetAll<RecipeData>().SelectMany(r => r.Inputs.Select(i => i.Commodity.Key.Value).Append(r.Output.Key.Value)).ToHashSet(); + var commodities = c.GetAll<SimpleCommodityData>().ToArray(); + Assert.True(commodities.Length >= 20 && used.Count >= 20, $"fixture: the catalog holds its commodities and recipes ({commodities.Length}, {used.Count})"); + var kinds = c.GetAll<StationKindData>().ToArray(); + Assert.True(kinds.Length >= 17, $"fixture: the catalog holds its station kinds ({kinds.Length})"); + var orphans = from kind in kinds + from good in commodities + where Regex.IsMatch(kind.Description ?? "", @"\b" + Regex.Escape(good.Name) + @"\b") && !used.Contains(c.RefOf(good).Key.Value) + select $"{kind.Name} names {good.Name}"; + Assert.True(!orphans.Any(), string.Join("\n", orphans)); + } + + // Kills: the fresh-catalog text and the shipped catalog saying different things about the same kind. + [Fact] + public void TheShippedDescriptionsAreTheAuthoredTable() + { + using var db = AetherDb.Open(); + foreach (var id in new[] { "mining", "volatiles", "agriculture", "habitat-support", "power" }) + Assert.Equal(StationKindsCatalog.DescriptionOf(id), db.Cache.Get<StationKindData>(StationKindData.KeyOf(id)).Description); + } } diff --git a/tools/AetherDb/Economy/ExtractionKindDescriptions.cs b/tools/AetherDb/Economy/ExtractionKindDescriptions.cs deleted file mode 100644 index b581af0d0..000000000 --- a/tools/AetherDb/Economy/ExtractionKindDescriptions.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using GameCult.Caching; - -// Economy content, batch 1c: the mining and volatiles station-kind descriptions name every good their kind now extracts. -// MunitionsFeed gave mining a Diamond recipe and volatiles an Ammonia recipe; the descriptions the station-round bench -// wrote predate them. The same text is StationKindsCatalog.Table's, so a catalog authored fresh says the same thing. -// Sets the description whatever it was, so a rerun converges. -public sealed class ExtractionKindDescriptions : EconomyBatch -{ - public override void Author(EconomyAuthor author) - { - foreach (var (id, description) in new[] - { - ("mining", StationKindsCatalog.DescriptionOf("mining")), - ("volatiles", StationKindsCatalog.DescriptionOf("volatiles")), - }) - { - var key = StationKindData.KeyOf(id); - var kind = author.Catalog.Get<StationKindData>(key) ?? throw new InvalidOperationException($"The catalog holds no station kind '{id}'."); - kind.Description = description; - author.Put(kind, key); - } - } -} diff --git a/tools/AetherDb/Economy/StationKindDescriptions.cs b/tools/AetherDb/Economy/StationKindDescriptions.cs new file mode 100644 index 000000000..746847e2e --- /dev/null +++ b/tools/AetherDb/Economy/StationKindDescriptions.cs @@ -0,0 +1,27 @@ +using System; +using GameCult.Caching; + +// Economy content: station-kind descriptions that name only goods the recipe graph makes or takes. The station-round bench wrote +// descriptions naming Uranium, Hydrogen, Bacteria, Fungi and Animal Products, none of which any recipe yields or consumes; this +// restates the five kinds that named them (mining, volatiles, agriculture, habitat-support, power) as StationKindsCatalog.Table +// has them, so a catalog authored fresh says the same thing. Sets the description whatever it was, so a rerun converges. +public sealed class StationKindDescriptions : EconomyBatch +{ + public override void Author(EconomyAuthor author) + { + foreach (var (id, description) in new[] + { + ("mining", StationKindsCatalog.DescriptionOf("mining")), + ("volatiles", StationKindsCatalog.DescriptionOf("volatiles")), + ("agriculture", StationKindsCatalog.DescriptionOf("agriculture")), + ("habitat-support", StationKindsCatalog.DescriptionOf("habitat-support")), + ("power", StationKindsCatalog.DescriptionOf("power")), + }) + { + var key = StationKindData.KeyOf(id); + var kind = author.Catalog.Get<StationKindData>(key) ?? throw new InvalidOperationException($"The catalog holds no station kind '{id}'."); + kind.Description = description; + author.Put(kind, key); + } + } +} diff --git a/tools/AetherDb/StationKindsCatalog.cs b/tools/AetherDb/StationKindsCatalog.cs index 81e5aee4d..51d865f57 100644 --- a/tools/AetherDb/StationKindsCatalog.cs +++ b/tools/AetherDb/StationKindsCatalog.cs @@ -14,19 +14,19 @@ public static class StationKindsCatalog private static readonly (string id, string name, string description)[] Table = { - ("mining", "Mining Station", "Extracts ore (Rock, New Metals, Gold, Uranium, Potassium) and Diamond from bodies and belts; consumes tools and food."), - ("volatiles", "Volatiles Station", "Skims Hydrogen, Methane, Ammonia and Water from gas giants and ice; consumes tools."), - ("agriculture", "Agriculture Station", "Grows Organics (Algae, Fungi, Bacteria, Animal Products) from Water and Potassium; feeds residential."), + ("mining", "Mining Station", "Extracts ore (Rock, New Metals, Gold, Potassium) and Diamond from bodies and belts; consumes tools and food."), + ("volatiles", "Volatiles Station", "Skims Methane, Ammonia and Water from gas giants and ice; consumes tools."), + ("agriculture", "Agriculture Station", "Grows Algae from Water and Potassium; feeds residential."), ("processing", "Processing Station", "Refines ore and volatiles into Metals, Alloys and Compounds."), ("fabrication", "Fabrication Station", "Turns Alloys and Compounds into Manufacturing compounds, Assemblies, gear, Ammo and consumer goods."), ("shipyard", "Shipyard", "Assembles hulls from Assemblies and Alloys."), ("depot", "Depot", "Stores and dispatches stock; loads haulers and tenders."), ("trade-hub", "Trade Hub", "Exchanges every bloc's goods between haulers and takes a cut; produces nothing."), ("residential", "Residential Station", "A bloom: consumes food, water, Wearables, Consumables and Luxuries; supplies crews."), - ("habitat-support", "Habitat Support Station", "Air, water recycling, life support and medicine for nearby habitats; consumes Bacteria, Water, Compounds."), + ("habitat-support", "Habitat Support Station", "Air, water recycling, life support and medicine for nearby habitats; consumes Water and Compounds."), ("urban", "Urban Station", "Dense city and services: market, media, repair; consumes luxuries and food."), ("administrative", "Administrative Station", "Issues quotas, contracts and security; consumes luxuries."), - ("power", "Power Station", "Makes reactor fuel, reservoirs and capacitors from Uranium and Hydrogen."), + ("power", "Power Station", "Generates and distributes power for nearby stations."), ("research", "Research Station", "Certification, compute, prototypes; consumes Assemblies."), ("salvage", "Salvage Station", "Breaks wrecks into Metals and second-hand gear."), ("black-market", "Black Market", "Buys anything, fences stolen cargo."), From 465ab506665c1d5e2b7998885202f16d1a296132 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 06:34:46 +0000 Subject: [PATCH 041/190] Arcs player gets a bay; Arcs and Pursuit crates sized from a measured run The Arcs fighter had no hold, so its Autocannon and Cell Blasters went silent after one magazine: it now fits the one free 2x2 bay. The estimated crate counts are replaced by measured draws (ten minutes of play or death by heat) plus margin, authored for every ammunition-drawing shooter; ScenarioAmmunitionRunTests drives both scenarios and fails if any shooter is stocked below its measured draw. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/Scenarios/Arcs.cs | 13 ++- .../Scripts/ServerShared/Scenarios/Pursuit.cs | 13 ++- .../ScenarioAmmunitionRunTests.cs | 103 ++++++++++++++++++ 3 files changed, 121 insertions(+), 8 deletions(-) create mode 100644 tests/Aetheria.Shared.Tests/ScenarioAmmunitionRunTests.cs diff --git a/Assets/Scripts/ServerShared/Scenarios/Arcs.cs b/Assets/Scripts/ServerShared/Scenarios/Arcs.cs index fd5076075..459ee4e8b 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Arcs.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Arcs.cs @@ -21,7 +21,10 @@ public sealed class Arcs : Scenario public static readonly CultMath.float2 Bow = float2(0, 400), Stern = float2(0, -400), Turret = float2(600, 300), Port = float2(-400, 0), Starboard = float2(400, 0); - public const int TurretAmmoCrates = 30; + // Crates of ammunition each shooter's hold is stocked with: the measured draw over a run (ScenarioAmmunitionRunTests: ten minutes of play, + // or until the shooter dies of heat) plus half again and one. The turret drew 14 Ammo with the player in its range; the player drew 27 Ammo + // holding every gun down. The guided launchers fire only on a lock, which that run cannot give them, so they carry the default three crates. + public const int TurretAmmoCrates = 22, PlayerAmmoCrates = 42, PlayerMissileCrates = 3; public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(); @@ -43,7 +46,8 @@ public sealed class Arcs : Scenario ("not if i see you first", int2(5, 10), None), // Compact Sensor ("Panopticon Prime", int2(3, 6), Clockwise), // Fire Control Array ("🫳🔫", int2(8, 4), Clockwise), // Autocannon - ("ChargeBlast SG", int2(0, 4), CounterClockwise)); // Charged Scatter Blaster + ("ChargeBlast SG", int2(0, 4), CounterClockwise), // Charged Scatter Blaster + ("Store-All Plus", int2(4, 8), None)); // Cargo Bay: the only 2x2 the hull has free var turret = stage.Fit("Turret", ("ClearPath", int2(1, 2), None), // Light Machine Gun ("ClearPath", int2(5, 2), None), // Light Machine Gun @@ -55,10 +59,11 @@ public sealed class Arcs : Scenario ("Panopticon Prime", int2(3, 6), None), // Fire Control Array ("Store-All Plus", int2(3, 1), None)); // Cargo Bay: the only 2x2 the turret hull has free - stage.Player(fighter, float2(0, 0), facing: float2(0, 1)); + var player = stage.Player(fighter, float2(0, 0), facing: float2(0, 1)); + stage.Cargo(player, Enumerable.Repeat("Ammo", PlayerAmmoCrates).Concat(Enumerable.Repeat("Missiles", PlayerMissileCrates)).ToArray()); stage.Place(stage.Bare("Longinus"), Bow); stage.Place(stage.Bare("Longinus"), Stern); - // The turret's guns reload from its hold, a crate of Ammo per 100-round magazine: both guns firing without pause spend about 3.5 crates a minute, so 30 outlast any session. + // The turret's guns reload from its hold, a crate of Ammo per magazine. stage.Cargo(stage.Place(turret, Turret, stance: ScenarioStance.Hostile), Enumerable.Repeat("Ammo", TurretAmmoCrates).ToArray()); stage.Place(stage.Bare("Longinus"), Port); stage.Place(stage.Bare("Longinus"), Starboard); diff --git a/Assets/Scripts/ServerShared/Scenarios/Pursuit.cs b/Assets/Scripts/ServerShared/Scenarios/Pursuit.cs index 20ad157a1..157ea4f1f 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Pursuit.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Pursuit.cs @@ -8,7 +8,11 @@ public sealed class Pursuit : Scenario // cloud breaking a sensor's lock, and well outside the 40 at which AStrongCloseSensorBurnsThrough shows a close // sensor burning through. private const float Astern = 300; - public const int MineCrates = 10; + // Crates each shooter's hold is stocked with: the measured draw over a run (ScenarioAmmunitionRunTests: ten minutes of play, or until the + // shooter dies of heat) plus half again and one where the hold has room. The player laid four crates of Mines and drew + // 33 Ammo; its hold takes 54 crates after five consumables and Mines, so its Ammo stops at 39. The pursuer drew 31 Ammo and one Missiles. A launcher + // that drew under a reload carries the default three crates. + public const int MineCrates = 7, PlayerAmmoCrates = 39, PlayerMissileCrates = 3, PursuerAmmoCrates = 47, PursuerMissileCrates = 3; public override string Name => "Pursuit"; public override string Id => "pursuit"; @@ -57,8 +61,9 @@ public sealed class Pursuit : Scenario ("Store-All Plus", int2(2, 8), None)); // Cargo Bay var player = stage.Player(layer, float2(0, 0), facing: float2(0, 1)); - // The Mine Launcher reloads a magazine of six from a crate of Mines: ten crates are sixty-six mines, minutes of laying at its cooldown, more than a chase lasts. - stage.Cargo(player, new[] { "Morning Fog", "Morning Fog", "Morning Fog", "send it", "send it" }.Concat(Enumerable.Repeat("Mines", MineCrates)).ToArray()); - stage.Place(pursuer, float2(0, -Astern), facing: float2(0, 1), stance: ScenarioStance.Hostile, piloted: true); + stage.Cargo(player, new[] { "Morning Fog", "Morning Fog", "Morning Fog", "send it", "send it" } + .Concat(Enumerable.Repeat("Mines", MineCrates)).Concat(Enumerable.Repeat("Ammo", PlayerAmmoCrates)).Concat(Enumerable.Repeat("Missiles", PlayerMissileCrates)).ToArray()); + var hostile = stage.Place(pursuer, float2(0, -Astern), facing: float2(0, 1), stance: ScenarioStance.Hostile, piloted: true); + stage.Cargo(hostile, Enumerable.Repeat("Ammo", PursuerAmmoCrates).Concat(Enumerable.Repeat("Missiles", PursuerMissileCrates)).ToArray()); } } diff --git a/tests/Aetheria.Shared.Tests/ScenarioAmmunitionRunTests.cs b/tests/Aetheria.Shared.Tests/ScenarioAmmunitionRunTests.cs new file mode 100644 index 000000000..3a1921cbd --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ScenarioAmmunitionRunTests.cs @@ -0,0 +1,103 @@ +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; +using Xunit; + +// How much ammunition a staged scenario really spends over a run (ruling ballistics-real-ammo): the crates a scenario authors are pinned to +// this measurement, not to an estimate. A run is RunSeconds of continuous play: the player holds every ammunition-drawing weapon down with its +// hostile-or-flank hull standing in weapon range, an AI shooter fires on its own, and every hull keeps its armour so no shooter or target leaves +// the run early. The draw is counted in crates (one reload per crate) and each drawn crate is put back, so the count is not capped by the stock. +public sealed partial class RunStartTests +{ + // Ten minutes: longer than any session the Arcs and Pursuit briefs ask a tester for. + public const float RunSeconds = 600f; + + // Crates each armed entity of the scenario draws over the run, keyed by (index in the stage's entities, -1 for the player; ammunition name), + // and the crates each held when the run began. + private (Dictionary<(int, string), int> drawn, Dictionary<(int, string), int> stocked) RunAmmunition(Scenario scenario, bool playerFires, bool standNearHostile) + { + var (_, arena, staged, failures) = Launch(scenario, Inputs(() => GalaxySeed)); + Assert.Empty(failures); + arena.Update(0); + var shooters = staged.Entities.Select((entity, index) => (entity, index)).Append((staged.Player, -1)) + .Where(s => s.Item1.Weapons.Any(weapon => weapon.WeaponData.AmmoType.IsSet())).ToList(); + var drawn = new Dictionary<(int, string), int>(); + var stocked = new Dictionary<(int, string), int>(); + var held = new Dictionary<(int, string), int>(); + string NameOf(CultRecordKey key) => _items.ItemData.Get<SimpleCommodityData>(key).Name; + foreach (var (entity, index) in shooters) + foreach (var key in entity.Weapons.Where(weapon => weapon.WeaponData.AmmoType.IsSet()).Select(weapon => weapon.WeaponData.AmmoType.Key).Distinct()) + { + stocked[(index, NameOf(key))] = entity.CountItemsInCargo(key); + // A shooter with no crate cannot reload at all, so a run could not show what it would draw: it is given one to start. + if (stocked[(index, NameOf(key))] == 0) + entity.CargoBays.First().TryStore(new SimpleCommodity { Data = new CultRecordRef<ItemData>(key), Quantity = 1 }); + drawn[(index, NameOf(key))] = 0; + held[(index, NameOf(key))] = entity.CountItemsInCargo(key); + } + var everyone = staged.Entities.Append(staged.Player).ToList(); + var player = staged.Player; + var sound = everyone.SelectMany(entity => entity.Equipment).ToDictionary(item => item, item => item.EquippableItem.Durability); + var hostile = standNearHostile ? staged.Entities.First(entity => player.IsHostileTo(entity)) : null; + for (var tick = 0; tick < System.MathF.Round(RunSeconds / SimClock.GameStep); tick++) + { + foreach (var entity in everyone) + for (var x = 0; x < entity.Armor.GetLength(0); x++) + for (var y = 0; y < entity.Armor.GetLength(1); y++) + entity.Armor[x, y] = entity.MaxArmor[x, y]; + foreach (var (item, durability) in sound) item.EquippableItem.Durability = durability; + if (hostile != null) player.Position = hostile.Position + CultMath.math.float3(-200, 0, 0); + if (playerFires) + foreach (var weapon in player.Weapons.Where(weapon => weapon.WeaponData.AmmoType.IsSet())) weapon.Activate(); + arena.Update(SimClock.GameStep); + if (false) System.IO.File.AppendAllText(System.Environment.GetEnvironmentVariable("TMPDIR") + "/dbg.txt", $"{scenario.Name} t={tick*SimClock.GameStep:F0} active={player.Active} me={player.Position} " + string.Join(",", player.Weapons.Select(w => w.WeaponData.AmmoType.IsSet() ? w.Ammo + "/" + w.Reserve : "e")) + "\n"); + foreach (var (entity, index) in shooters) + foreach (var key in entity.Weapons.Where(weapon => weapon.WeaponData.AmmoType.IsSet()).Select(weapon => weapon.WeaponData.AmmoType.Key).Distinct()) + { + var slot = (index, NameOf(key)); + var spent = held[slot] - entity.CountItemsInCargo(key); + if (spent <= 0) continue; + drawn[slot] += spent; + for (var crate = 0; crate < spent; crate++) + entity.CargoBays.First().TryStore(new SimpleCommodity { Data = new CultRecordRef<ItemData>(key), Quantity = 1 }); + } + } + return (drawn, stocked); + } + + // The most crates each shooter draws in any of the modes, and what it was stocked with. + private List<(int shooter, string ammo, int drawn, int stocked)> WorstRun(Scenario scenario, params (bool playerFires, bool standNearHostile)[] modes) + { + var worst = new Dictionary<(int, string), (int drawn, int stocked)>(); + foreach (var (fires, near) in modes) + { + var (drawn, stocked) = RunAmmunition(scenario, fires, near); + foreach (var slot in drawn.Keys) + worst[slot] = (System.Math.Max(drawn[slot], worst.TryGetValue(slot, out var seen) ? seen.drawn : 0), stocked[slot]); + } + return worst.Select(kv => (kv.Key.Item1, kv.Key.Item2, kv.Value.drawn, kv.Value.stocked)).ToList(); + } + + // Arcs, run to its end twice: the player holding every gun down, and the player standing in the hostile turret's range while the turret + // shoots. Kills: a crate count nobody measured (the turret's 30 and the player's none were estimates), a scenario shooter stocked below + // what a run draws so its guns go silent, and a harness that measures nothing. + [Fact] + public void ArcsStocksEveryShooterForARun() + { + var run = WorstRun(new Arcs(), (true, false), (false, true)); + Assert.Contains(run, r => r.shooter == 2 && r.ammo == "Ammo" && r.drawn > 0); + Assert.Contains(run, r => r.shooter == -1 && r.ammo == "Ammo" && r.drawn > 0); + Assert.All(run, r => Assert.True(r.stocked >= r.drawn, $"Arcs shooter {r.shooter} drew {r.drawn} {r.ammo} over a run and was stocked {r.stocked}")); + } + + // Pursuit, the player holding every gun down and the pursuer shooting back, then the player idle. Kills: as above, for the Mine Launcher's + // crates and the pursuer's. + [Fact] + public void PursuitStocksEveryShooterForARun() + { + var run = WorstRun(new Pursuit(), (true, false), (false, false)); + Assert.Contains(run, r => r.shooter == -1 && r.ammo == "Mines" && r.drawn > 0); + Assert.Contains(run, r => r.shooter == 0 && r.ammo == "Ammo" && r.drawn > 0); + Assert.All(run, r => Assert.True(r.stocked >= r.drawn, $"Pursuit shooter {r.shooter} drew {r.drawn} {r.ammo} over a run and was stocked {r.stocked}")); + } +} From f856021997d77b131db9c770ac9efde55955eb3c Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 07:16:40 +0000 Subject: [PATCH 042/190] Ammunition run: say the real window (heat death ~260 s, not ten minutes) and drop a dead debug line Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/Scenarios/Arcs.cs | 4 ++-- Assets/Scripts/ServerShared/Scenarios/Pursuit.cs | 4 ++-- tests/Aetheria.Shared.Tests/ScenarioAmmunitionRunTests.cs | 3 +-- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/Assets/Scripts/ServerShared/Scenarios/Arcs.cs b/Assets/Scripts/ServerShared/Scenarios/Arcs.cs index 459ee4e8b..8846d006b 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Arcs.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Arcs.cs @@ -21,8 +21,8 @@ public sealed class Arcs : Scenario public static readonly CultMath.float2 Bow = float2(0, 400), Stern = float2(0, -400), Turret = float2(600, 300), Port = float2(-400, 0), Starboard = float2(400, 0); - // Crates of ammunition each shooter's hold is stocked with: the measured draw over a run (ScenarioAmmunitionRunTests: ten minutes of play, - // or until the shooter dies of heat) plus half again and one. The turret drew 14 Ammo with the player in its range; the player drew 27 Ammo + // Crates of ammunition each shooter's hold is stocked with: the measured draw over a run (ScenarioAmmunitionRunTests: at most ten minutes of play, and in + // practice the ~260 s a shooter holding every gun down lasts before it dies of heat; a pilot who vents heat is unmeasured) plus half again and one. The turret drew 14 Ammo with the player in its range; the player drew 27 Ammo // holding every gun down. The guided launchers fire only on a lock, which that run cannot give them, so they carry the default three crates. public const int TurretAmmoCrates = 22, PlayerAmmoCrates = 42, PlayerMissileCrates = 3; diff --git a/Assets/Scripts/ServerShared/Scenarios/Pursuit.cs b/Assets/Scripts/ServerShared/Scenarios/Pursuit.cs index 157ea4f1f..2e490a2a6 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Pursuit.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Pursuit.cs @@ -8,8 +8,8 @@ public sealed class Pursuit : Scenario // cloud breaking a sensor's lock, and well outside the 40 at which AStrongCloseSensorBurnsThrough shows a close // sensor burning through. private const float Astern = 300; - // Crates each shooter's hold is stocked with: the measured draw over a run (ScenarioAmmunitionRunTests: ten minutes of play, or until the - // shooter dies of heat) plus half again and one where the hold has room. The player laid four crates of Mines and drew + // Crates each shooter's hold is stocked with: the measured draw over a run (ScenarioAmmunitionRunTests: at most ten minutes of play, and in + // practice the ~250-270 s a shooter holding every gun down lasts before it dies of heat; a pilot who vents heat is unmeasured) plus half again and one where the hold has room. The player laid four crates of Mines and drew // 33 Ammo; its hold takes 54 crates after five consumables and Mines, so its Ammo stops at 39. The pursuer drew 31 Ammo and one Missiles. A launcher // that drew under a reload carries the default three crates. public const int MineCrates = 7, PlayerAmmoCrates = 39, PlayerMissileCrates = 3, PursuerAmmoCrates = 47, PursuerMissileCrates = 3; diff --git a/tests/Aetheria.Shared.Tests/ScenarioAmmunitionRunTests.cs b/tests/Aetheria.Shared.Tests/ScenarioAmmunitionRunTests.cs index 3a1921cbd..43dec542a 100644 --- a/tests/Aetheria.Shared.Tests/ScenarioAmmunitionRunTests.cs +++ b/tests/Aetheria.Shared.Tests/ScenarioAmmunitionRunTests.cs @@ -9,7 +9,7 @@ using Xunit; // the run early. The draw is counted in crates (one reload per crate) and each drawn crate is put back, so the count is not capped by the stock. public sealed partial class RunStartTests { - // Ten minutes: longer than any session the Arcs and Pursuit briefs ask a tester for. + // Ceiling of the window: a shooter holding every gun down dies of heat at ~250-270 s, so the draws are bounded by heat death, not by this. public const float RunSeconds = 600f; // Crates each armed entity of the scenario draws over the run, keyed by (index in the stage's entities, -1 for the player; ammunition name), @@ -50,7 +50,6 @@ public sealed partial class RunStartTests if (playerFires) foreach (var weapon in player.Weapons.Where(weapon => weapon.WeaponData.AmmoType.IsSet())) weapon.Activate(); arena.Update(SimClock.GameStep); - if (false) System.IO.File.AppendAllText(System.Environment.GetEnvironmentVariable("TMPDIR") + "/dbg.txt", $"{scenario.Name} t={tick*SimClock.GameStep:F0} active={player.Active} me={player.Position} " + string.Join(",", player.Weapons.Select(w => w.WeaponData.AmmoType.IsSet() ? w.Ammo + "/" + w.Reserve : "e")) + "\n"); foreach (var (entity, index) in shooters) foreach (var key in entity.Weapons.Where(weapon => weapon.WeaponData.AmmoType.IsSet()).Select(weapon => weapon.WeaponData.AmmoType.Key).Distinct()) { From feb7cf86069ec8fa6547a60817f4e1e60a1ad43f Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 11:53:16 +0000 Subject: [PATCH 043/190] Shaders: GalaxyMap, Clouds, Lightning, SimplexBrush use cultmath_snoise from CultMath.hlsl CPU snoise (CultMath C#) and the GPU shaders now share one implementation, so fBm agrees. Deletes the GPU Noise copies nothing includes any more (Classic 2D/3D, Simplex 3D, SimplexGrad 3D). Background.shader keeps SimplexNoise2D/SimplexNoiseGrad2D: CultMath has no 2D gradient (cultmath_snoise_grad is float3 -> float4 only). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Plugins/GPU Noise/ClassicNoise2D.cginc | 129 ------------ .../GPU Noise/ClassicNoise2D.cginc.meta | 5 - Assets/Plugins/GPU Noise/ClassicNoise3D.cginc | 194 ------------------ .../GPU Noise/ClassicNoise3D.cginc.meta | 5 - Assets/Plugins/GPU Noise/SimplexNoise3D.cginc | 114 ---------- .../GPU Noise/SimplexNoise3D.cginc.meta | 9 - .../GPU Noise/SimplexNoiseGrad3D.cginc | 118 ----------- .../GPU Noise/SimplexNoiseGrad3D.cginc.meta | 9 - 8 files changed, 583 deletions(-) delete mode 100644 Assets/Plugins/GPU Noise/ClassicNoise2D.cginc delete mode 100644 Assets/Plugins/GPU Noise/ClassicNoise2D.cginc.meta delete mode 100644 Assets/Plugins/GPU Noise/ClassicNoise3D.cginc delete mode 100644 Assets/Plugins/GPU Noise/ClassicNoise3D.cginc.meta delete mode 100644 Assets/Plugins/GPU Noise/SimplexNoise3D.cginc delete mode 100644 Assets/Plugins/GPU Noise/SimplexNoise3D.cginc.meta delete mode 100644 Assets/Plugins/GPU Noise/SimplexNoiseGrad3D.cginc delete mode 100644 Assets/Plugins/GPU Noise/SimplexNoiseGrad3D.cginc.meta diff --git a/Assets/Plugins/GPU Noise/ClassicNoise2D.cginc b/Assets/Plugins/GPU Noise/ClassicNoise2D.cginc deleted file mode 100644 index ef6b2e96c..000000000 --- a/Assets/Plugins/GPU Noise/ClassicNoise2D.cginc +++ /dev/null @@ -1,129 +0,0 @@ -// -// Noise Shader Library for Unity - https://github.com/keijiro/NoiseShader -// -// Original work (webgl-noise) Copyright (C) 2011 Stefan Gustavson -// Translation and modification was made by Keijiro Takahashi. -// -// This shader is based on the webgl-noise GLSL shader. For further details -// of the original shader, please see the following description from the -// original source code. -// - -// -// GLSL textureless classic 2D noise "cnoise", -// with an RSL-style periodic variant "pnoise". -// Author: Stefan Gustavson (stefan.gustavson@liu.se) -// Version: 2011-08-22 -// -// Many thanks to Ian McEwan of Ashima Arts for the -// ideas for permutation and gradient selection. -// -// Copyright (c) 2011 Stefan Gustavson. All rights reserved. -// Distributed under the MIT license. See LICENSE file. -// https://github.com/ashima/webgl-noise -// - -float4 mod(float4 x, float4 y) -{ - return x - y * floor(x / y); -} - -float4 mod289(float4 x) -{ - return x - floor(x / 289.0) * 289.0; -} - -float4 permute(float4 x) -{ - return mod289(((x*34.0)+1.0)*x); -} - -float4 taylorInvSqrt(float4 r) -{ - return (float4)1.79284291400159 - r * 0.85373472095314; -} - -float2 fade(float2 t) { - return t*t*t*(t*(t*6.0-15.0)+10.0); -} - -// Classic Perlin noise -float cnoise(float2 P) -{ - float4 Pi = floor(P.xyxy) + float4(0.0, 0.0, 1.0, 1.0); - float4 Pf = frac (P.xyxy) - float4(0.0, 0.0, 1.0, 1.0); - Pi = mod289(Pi); // To avoid truncation effects in permutation - float4 ix = Pi.xzxz; - float4 iy = Pi.yyww; - float4 fx = Pf.xzxz; - float4 fy = Pf.yyww; - - float4 i = permute(permute(ix) + iy); - - float4 gx = frac(i / 41.0) * 2.0 - 1.0 ; - float4 gy = abs(gx) - 0.5 ; - float4 tx = floor(gx + 0.5); - gx = gx - tx; - - float2 g00 = float2(gx.x,gy.x); - float2 g10 = float2(gx.y,gy.y); - float2 g01 = float2(gx.z,gy.z); - float2 g11 = float2(gx.w,gy.w); - - float4 norm = taylorInvSqrt(float4(dot(g00, g00), dot(g01, g01), dot(g10, g10), dot(g11, g11))); - g00 *= norm.x; - g01 *= norm.y; - g10 *= norm.z; - g11 *= norm.w; - - float n00 = dot(g00, float2(fx.x, fy.x)); - float n10 = dot(g10, float2(fx.y, fy.y)); - float n01 = dot(g01, float2(fx.z, fy.z)); - float n11 = dot(g11, float2(fx.w, fy.w)); - - float2 fade_xy = fade(Pf.xy); - float2 n_x = lerp(float2(n00, n01), float2(n10, n11), fade_xy.x); - float n_xy = lerp(n_x.x, n_x.y, fade_xy.y); - return 2.3 * n_xy; -} - -// Classic Perlin noise, periodic variant -float pnoise(float2 P, float2 rep) -{ - float4 Pi = floor(P.xyxy) + float4(0.0, 0.0, 1.0, 1.0); - float4 Pf = frac (P.xyxy) - float4(0.0, 0.0, 1.0, 1.0); - Pi = mod(Pi, rep.xyxy); // To create noise with explicit period - Pi = mod289(Pi); // To avoid truncation effects in permutation - float4 ix = Pi.xzxz; - float4 iy = Pi.yyww; - float4 fx = Pf.xzxz; - float4 fy = Pf.yyww; - - float4 i = permute(permute(ix) + iy); - - float4 gx = frac(i / 41.0) * 2.0 - 1.0 ; - float4 gy = abs(gx) - 0.5 ; - float4 tx = floor(gx + 0.5); - gx = gx - tx; - - float2 g00 = float2(gx.x,gy.x); - float2 g10 = float2(gx.y,gy.y); - float2 g01 = float2(gx.z,gy.z); - float2 g11 = float2(gx.w,gy.w); - - float4 norm = taylorInvSqrt(float4(dot(g00, g00), dot(g01, g01), dot(g10, g10), dot(g11, g11))); - g00 *= norm.x; - g01 *= norm.y; - g10 *= norm.z; - g11 *= norm.w; - - float n00 = dot(g00, float2(fx.x, fy.x)); - float n10 = dot(g10, float2(fx.y, fy.y)); - float n01 = dot(g01, float2(fx.z, fy.z)); - float n11 = dot(g11, float2(fx.w, fy.w)); - - float2 fade_xy = fade(Pf.xy); - float2 n_x = lerp(float2(n00, n01), float2(n10, n11), fade_xy.x); - float n_xy = lerp(n_x.x, n_x.y, fade_xy.y); - return 2.3 * n_xy; -} diff --git a/Assets/Plugins/GPU Noise/ClassicNoise2D.cginc.meta b/Assets/Plugins/GPU Noise/ClassicNoise2D.cginc.meta deleted file mode 100644 index ff437e70a..000000000 --- a/Assets/Plugins/GPU Noise/ClassicNoise2D.cginc.meta +++ /dev/null @@ -1,5 +0,0 @@ -fileFormatVersion: 2 -guid: e1b0b5fd6a4e44923b40d856017562e1 -ShaderImporter: - defaultTextures: [] - userData: diff --git a/Assets/Plugins/GPU Noise/ClassicNoise3D.cginc b/Assets/Plugins/GPU Noise/ClassicNoise3D.cginc deleted file mode 100644 index 738f6d12a..000000000 --- a/Assets/Plugins/GPU Noise/ClassicNoise3D.cginc +++ /dev/null @@ -1,194 +0,0 @@ -// -// Noise Shader Library for Unity - https://github.com/keijiro/NoiseShader -// -// Original work (webgl-noise) Copyright (C) 2011 Stefan Gustavson -// Translation and modification was made by Keijiro Takahashi. -// -// This shader is based on the webgl-noise GLSL shader. For further details -// of the original shader, please see the following description from the -// original source code. -// - -// -// GLSL textureless classic 3D noise "cnoise", -// with an RSL-style periodic variant "pnoise". -// Author: Stefan Gustavson (stefan.gustavson@liu.se) -// Version: 2011-10-11 -// -// Many thanks to Ian McEwan of Ashima Arts for the -// ideas for permutation and gradient selection. -// -// Copyright (c) 2011 Stefan Gustavson. All rights reserved. -// Distributed under the MIT license. See LICENSE file. -// https://github.com/ashima/webgl-noise -// - -float3 mod(float3 x, float3 y) -{ - return x - y * floor(x / y); -} - -float3 mod289(float3 x) -{ - return x - floor(x / 289.0) * 289.0; -} - -float4 mod289(float4 x) -{ - return x - floor(x / 289.0) * 289.0; -} - -float4 permute(float4 x) -{ - return mod289(((x*34.0)+1.0)*x); -} - -float4 taylorInvSqrt(float4 r) -{ - return (float4)1.79284291400159 - r * 0.85373472095314; -} - -float3 fade(float3 t) { - return t*t*t*(t*(t*6.0-15.0)+10.0); -} - -// Classic Perlin noise -float cnoise(float3 P) -{ - float3 Pi0 = floor(P); // Integer part for indexing - float3 Pi1 = Pi0 + (float3)1.0; // Integer part + 1 - Pi0 = mod289(Pi0); - Pi1 = mod289(Pi1); - float3 Pf0 = frac(P); // Fractional part for interpolation - float3 Pf1 = Pf0 - (float3)1.0; // Fractional part - 1.0 - float4 ix = float4(Pi0.x, Pi1.x, Pi0.x, Pi1.x); - float4 iy = float4(Pi0.y, Pi0.y, Pi1.y, Pi1.y); - float4 iz0 = (float4)Pi0.z; - float4 iz1 = (float4)Pi1.z; - - float4 ixy = permute(permute(ix) + iy); - float4 ixy0 = permute(ixy + iz0); - float4 ixy1 = permute(ixy + iz1); - - float4 gx0 = ixy0 / 7.0; - float4 gy0 = frac(floor(gx0) / 7.0) - 0.5; - gx0 = frac(gx0); - float4 gz0 = (float4)0.5 - abs(gx0) - abs(gy0); - float4 sz0 = step(gz0, (float4)0.0); - gx0 -= sz0 * (step((float4)0.0, gx0) - 0.5); - gy0 -= sz0 * (step((float4)0.0, gy0) - 0.5); - - float4 gx1 = ixy1 / 7.0; - float4 gy1 = frac(floor(gx1) / 7.0) - 0.5; - gx1 = frac(gx1); - float4 gz1 = (float4)0.5 - abs(gx1) - abs(gy1); - float4 sz1 = step(gz1, (float4)0.0); - gx1 -= sz1 * (step((float4)0.0, gx1) - 0.5); - gy1 -= sz1 * (step((float4)0.0, gy1) - 0.5); - - float3 g000 = float3(gx0.x,gy0.x,gz0.x); - float3 g100 = float3(gx0.y,gy0.y,gz0.y); - float3 g010 = float3(gx0.z,gy0.z,gz0.z); - float3 g110 = float3(gx0.w,gy0.w,gz0.w); - float3 g001 = float3(gx1.x,gy1.x,gz1.x); - float3 g101 = float3(gx1.y,gy1.y,gz1.y); - float3 g011 = float3(gx1.z,gy1.z,gz1.z); - float3 g111 = float3(gx1.w,gy1.w,gz1.w); - - float4 norm0 = taylorInvSqrt(float4(dot(g000, g000), dot(g010, g010), dot(g100, g100), dot(g110, g110))); - g000 *= norm0.x; - g010 *= norm0.y; - g100 *= norm0.z; - g110 *= norm0.w; - - float4 norm1 = taylorInvSqrt(float4(dot(g001, g001), dot(g011, g011), dot(g101, g101), dot(g111, g111))); - g001 *= norm1.x; - g011 *= norm1.y; - g101 *= norm1.z; - g111 *= norm1.w; - - float n000 = dot(g000, Pf0); - float n100 = dot(g100, float3(Pf1.x, Pf0.y, Pf0.z)); - float n010 = dot(g010, float3(Pf0.x, Pf1.y, Pf0.z)); - float n110 = dot(g110, float3(Pf1.x, Pf1.y, Pf0.z)); - float n001 = dot(g001, float3(Pf0.x, Pf0.y, Pf1.z)); - float n101 = dot(g101, float3(Pf1.x, Pf0.y, Pf1.z)); - float n011 = dot(g011, float3(Pf0.x, Pf1.y, Pf1.z)); - float n111 = dot(g111, Pf1); - - float3 fade_xyz = fade(Pf0); - float4 n_z = lerp(float4(n000, n100, n010, n110), float4(n001, n101, n011, n111), fade_xyz.z); - float2 n_yz = lerp(n_z.xy, n_z.zw, fade_xyz.y); - float n_xyz = lerp(n_yz.x, n_yz.y, fade_xyz.x); - return 2.2 * n_xyz; -} - -// Classic Perlin noise, periodic variant -float pnoise(float3 P, float3 rep) -{ - float3 Pi0 = mod(floor(P), rep); // Integer part, modulo period - float3 Pi1 = mod(Pi0 + (float3)1.0, rep); // Integer part + 1, mod period - Pi0 = mod289(Pi0); - Pi1 = mod289(Pi1); - float3 Pf0 = frac(P); // Fractional part for interpolation - float3 Pf1 = Pf0 - (float3)1.0; // Fractional part - 1.0 - float4 ix = float4(Pi0.x, Pi1.x, Pi0.x, Pi1.x); - float4 iy = float4(Pi0.y, Pi0.y, Pi1.y, Pi1.y); - float4 iz0 = (float4)Pi0.z; - float4 iz1 = (float4)Pi1.z; - - float4 ixy = permute(permute(ix) + iy); - float4 ixy0 = permute(ixy + iz0); - float4 ixy1 = permute(ixy + iz1); - - float4 gx0 = ixy0 / 7.0; - float4 gy0 = frac(floor(gx0) / 7.0) - 0.5; - gx0 = frac(gx0); - float4 gz0 = (float4)0.5 - abs(gx0) - abs(gy0); - float4 sz0 = step(gz0, (float4)0.0); - gx0 -= sz0 * (step((float4)0.0, gx0) - 0.5); - gy0 -= sz0 * (step((float4)0.0, gy0) - 0.5); - - float4 gx1 = ixy1 / 7.0; - float4 gy1 = frac(floor(gx1) / 7.0) - 0.5; - gx1 = frac(gx1); - float4 gz1 = (float4)0.5 - abs(gx1) - abs(gy1); - float4 sz1 = step(gz1, (float4)0.0); - gx1 -= sz1 * (step((float4)0.0, gx1) - 0.5); - gy1 -= sz1 * (step((float4)0.0, gy1) - 0.5); - - float3 g000 = float3(gx0.x,gy0.x,gz0.x); - float3 g100 = float3(gx0.y,gy0.y,gz0.y); - float3 g010 = float3(gx0.z,gy0.z,gz0.z); - float3 g110 = float3(gx0.w,gy0.w,gz0.w); - float3 g001 = float3(gx1.x,gy1.x,gz1.x); - float3 g101 = float3(gx1.y,gy1.y,gz1.y); - float3 g011 = float3(gx1.z,gy1.z,gz1.z); - float3 g111 = float3(gx1.w,gy1.w,gz1.w); - - float4 norm0 = taylorInvSqrt(float4(dot(g000, g000), dot(g010, g010), dot(g100, g100), dot(g110, g110))); - g000 *= norm0.x; - g010 *= norm0.y; - g100 *= norm0.z; - g110 *= norm0.w; - float4 norm1 = taylorInvSqrt(float4(dot(g001, g001), dot(g011, g011), dot(g101, g101), dot(g111, g111))); - g001 *= norm1.x; - g011 *= norm1.y; - g101 *= norm1.z; - g111 *= norm1.w; - - float n000 = dot(g000, Pf0); - float n100 = dot(g100, float3(Pf1.x, Pf0.y, Pf0.z)); - float n010 = dot(g010, float3(Pf0.x, Pf1.y, Pf0.z)); - float n110 = dot(g110, float3(Pf1.x, Pf1.y, Pf0.z)); - float n001 = dot(g001, float3(Pf0.x, Pf0.y, Pf1.z)); - float n101 = dot(g101, float3(Pf1.x, Pf0.y, Pf1.z)); - float n011 = dot(g011, float3(Pf0.x, Pf1.y, Pf1.z)); - float n111 = dot(g111, Pf1); - - float3 fade_xyz = fade(Pf0); - float4 n_z = lerp(float4(n000, n100, n010, n110), float4(n001, n101, n011, n111), fade_xyz.z); - float2 n_yz = lerp(n_z.xy, n_z.zw, fade_xyz.y); - float n_xyz = lerp(n_yz.x, n_yz.y, fade_xyz.x); - return 2.2 * n_xyz; -} diff --git a/Assets/Plugins/GPU Noise/ClassicNoise3D.cginc.meta b/Assets/Plugins/GPU Noise/ClassicNoise3D.cginc.meta deleted file mode 100644 index b4dd551ab..000000000 --- a/Assets/Plugins/GPU Noise/ClassicNoise3D.cginc.meta +++ /dev/null @@ -1,5 +0,0 @@ -fileFormatVersion: 2 -guid: 3ba1abd1cb44c47b68fbb577c6c4ba3e -ShaderImporter: - defaultTextures: [] - userData: diff --git a/Assets/Plugins/GPU Noise/SimplexNoise3D.cginc b/Assets/Plugins/GPU Noise/SimplexNoise3D.cginc deleted file mode 100644 index 0b7add240..000000000 --- a/Assets/Plugins/GPU Noise/SimplexNoise3D.cginc +++ /dev/null @@ -1,114 +0,0 @@ -// -// Noise Shader Library for Unity - https://github.com/keijiro/NoiseShader -// -// Original work (webgl-noise) Copyright (C) 2011 Ashima Arts. -// Translation and modification was made by Keijiro Takahashi. -// -// This shader is based on the webgl-noise GLSL shader. For further details -// of the original shader, please see the following description from the -// original source code. -// - -// -// Description : Array and textureless GLSL 2D/3D/4D simplex -// noise functions. -// Author : Ian McEwan, Ashima Arts. -// Maintainer : ijm -// Lastmod : 20110822 (ijm) -// License : Copyright (C) 2011 Ashima Arts. All rights reserved. -// Distributed under the MIT License. See LICENSE file. -// https://github.com/ashima/webgl-noise -// - -float3 mod289(float3 x) -{ - return x - floor(x / 289.0) * 289.0; -} - -float4 mod289(float4 x) -{ - return x - floor(x / 289.0) * 289.0; -} - -float4 permute(float4 x) -{ - return mod289((x * 34.0 + 1.0) * x); -} - -float4 taylorInvSqrt(float4 r) -{ - return 1.79284291400159 - r * 0.85373472095314; -} - -float snoise(float3 v) -{ - const float2 C = float2(1.0 / 6.0, 1.0 / 3.0); - - // First corner - float3 i = floor(v + dot(v, C.yyy)); - float3 x0 = v - i + dot(i, C.xxx); - - // Other corners - float3 g = step(x0.yzx, x0.xyz); - float3 l = 1.0 - g; - float3 i1 = min(g.xyz, l.zxy); - float3 i2 = max(g.xyz, l.zxy); - - // x1 = x0 - i1 + 1.0 * C.xxx; - // x2 = x0 - i2 + 2.0 * C.xxx; - // x3 = x0 - 1.0 + 3.0 * C.xxx; - float3 x1 = x0 - i1 + C.xxx; - float3 x2 = x0 - i2 + C.yyy; - float3 x3 = x0 - 0.5; - - // Permutations - i = mod289(i); // Avoid truncation effects in permutation - float4 p = - permute(permute(permute(i.z + float4(0.0, i1.z, i2.z, 1.0)) - + i.y + float4(0.0, i1.y, i2.y, 1.0)) - + i.x + float4(0.0, i1.x, i2.x, 1.0)); - - // Gradients: 7x7 points over a square, mapped onto an octahedron. - // The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294) - float4 j = p - 49.0 * floor(p / 49.0); // mod(p,7*7) - - float4 x_ = floor(j / 7.0); - float4 y_ = floor(j - 7.0 * x_); // mod(j,N) - - float4 x = (x_ * 2.0 + 0.5) / 7.0 - 1.0; - float4 y = (y_ * 2.0 + 0.5) / 7.0 - 1.0; - - float4 h = 1.0 - abs(x) - abs(y); - - float4 b0 = float4(x.xy, y.xy); - float4 b1 = float4(x.zw, y.zw); - - //float4 s0 = float4(lessThan(b0, 0.0)) * 2.0 - 1.0; - //float4 s1 = float4(lessThan(b1, 0.0)) * 2.0 - 1.0; - float4 s0 = floor(b0) * 2.0 + 1.0; - float4 s1 = floor(b1) * 2.0 + 1.0; - float4 sh = -step(h, 0.0); - - float4 a0 = b0.xzyw + s0.xzyw * sh.xxyy; - float4 a1 = b1.xzyw + s1.xzyw * sh.zzww; - - float3 g0 = float3(a0.xy, h.x); - float3 g1 = float3(a0.zw, h.y); - float3 g2 = float3(a1.xy, h.z); - float3 g3 = float3(a1.zw, h.w); - - // Normalise gradients - float4 norm = taylorInvSqrt(float4(dot(g0, g0), dot(g1, g1), dot(g2, g2), dot(g3, g3))); - g0 *= norm.x; - g1 *= norm.y; - g2 *= norm.z; - g3 *= norm.w; - - // Mix final noise value - float4 m = max(0.6 - float4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0); - m = m * m; - m = m * m; - - float4 px = float4(dot(x0, g0), dot(x1, g1), dot(x2, g2), dot(x3, g3)); - return 42.0 * dot(m, px); -} diff --git a/Assets/Plugins/GPU Noise/SimplexNoise3D.cginc.meta b/Assets/Plugins/GPU Noise/SimplexNoise3D.cginc.meta deleted file mode 100644 index 612bd9ef0..000000000 --- a/Assets/Plugins/GPU Noise/SimplexNoise3D.cginc.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: b577a94f58a1398409bfcfe9cd5dbf99 -timeCreated: 1448788105 -licenseType: Pro -ShaderImporter: - defaultTextures: [] - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/GPU Noise/SimplexNoiseGrad3D.cginc b/Assets/Plugins/GPU Noise/SimplexNoiseGrad3D.cginc deleted file mode 100644 index 4cfef835a..000000000 --- a/Assets/Plugins/GPU Noise/SimplexNoiseGrad3D.cginc +++ /dev/null @@ -1,118 +0,0 @@ -// -// Noise Shader Library for Unity - https://github.com/keijiro/NoiseShader -// -// Original work (webgl-noise) Copyright (C) 2011 Ashima Arts. -// Translation and modification was made by Keijiro Takahashi. -// -// This shader is based on the webgl-noise GLSL shader. For further details -// of the original shader, please see the following description from the -// original source code. -// - -// -// Description : Array and textureless GLSL 2D/3D/4D simplex -// noise functions. -// Author : Ian McEwan, Ashima Arts. -// Maintainer : ijm -// Lastmod : 20110822 (ijm) -// License : Copyright (C) 2011 Ashima Arts. All rights reserved. -// Distributed under the MIT License. See LICENSE file. -// https://github.com/ashima/webgl-noise -// - -float3 mod289(float3 x) -{ - return x - floor(x / 289.0) * 289.0; -} - -float4 mod289(float4 x) -{ - return x - floor(x / 289.0) * 289.0; -} - -float4 permute(float4 x) -{ - return mod289((x * 34.0 + 1.0) * x); -} - -float4 taylorInvSqrt(float4 r) -{ - return 1.79284291400159 - r * 0.85373472095314; -} - -float3 snoise_grad(float3 v) -{ - const float2 C = float2(1.0 / 6.0, 1.0 / 3.0); - - // First corner - float3 i = floor(v + dot(v, C.yyy)); - float3 x0 = v - i + dot(i, C.xxx); - - // Other corners - float3 g = step(x0.yzx, x0.xyz); - float3 l = 1.0 - g; - float3 i1 = min(g.xyz, l.zxy); - float3 i2 = max(g.xyz, l.zxy); - - // x1 = x0 - i1 + 1.0 * C.xxx; - // x2 = x0 - i2 + 2.0 * C.xxx; - // x3 = x0 - 1.0 + 3.0 * C.xxx; - float3 x1 = x0 - i1 + C.xxx; - float3 x2 = x0 - i2 + C.yyy; - float3 x3 = x0 - 0.5; - - // Permutations - i = mod289(i); // Avoid truncation effects in permutation - float4 p = - permute(permute(permute(i.z + float4(0.0, i1.z, i2.z, 1.0)) - + i.y + float4(0.0, i1.y, i2.y, 1.0)) - + i.x + float4(0.0, i1.x, i2.x, 1.0)); - - // Gradients: 7x7 points over a square, mapped onto an octahedron. - // The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294) - float4 j = p - 49.0 * floor(p / 49.0); // mod(p,7*7) - - float4 x_ = floor(j / 7.0); - float4 y_ = floor(j - 7.0 * x_); // mod(j,N) - - float4 x = (x_ * 2.0 + 0.5) / 7.0 - 1.0; - float4 y = (y_ * 2.0 + 0.5) / 7.0 - 1.0; - - float4 h = 1.0 - abs(x) - abs(y); - - float4 b0 = float4(x.xy, y.xy); - float4 b1 = float4(x.zw, y.zw); - - //float4 s0 = float4(lessThan(b0, 0.0)) * 2.0 - 1.0; - //float4 s1 = float4(lessThan(b1, 0.0)) * 2.0 - 1.0; - float4 s0 = floor(b0) * 2.0 + 1.0; - float4 s1 = floor(b1) * 2.0 + 1.0; - float4 sh = -step(h, 0.0); - - float4 a0 = b0.xzyw + s0.xzyw * sh.xxyy; - float4 a1 = b1.xzyw + s1.xzyw * sh.zzww; - - float3 g0 = float3(a0.xy, h.x); - float3 g1 = float3(a0.zw, h.y); - float3 g2 = float3(a1.xy, h.z); - float3 g3 = float3(a1.zw, h.w); - - // Normalise gradients - float4 norm = taylorInvSqrt(float4(dot(g0, g0), dot(g1, g1), dot(g2, g2), dot(g3, g3))); - g0 *= norm.x; - g1 *= norm.y; - g2 *= norm.z; - g3 *= norm.w; - - // Compute gradient of noise function at P - float4 m = max(0.6 - float4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0); - float4 m2 = m * m; - float4 m3 = m2 * m; - float4 m4 = m2 * m2; - float3 grad = - -6.0 * m3.x * x0 * dot(x0, g0) + m4.x * g0 + - -6.0 * m3.y * x1 * dot(x1, g1) + m4.y * g1 + - -6.0 * m3.z * x2 * dot(x2, g2) + m4.z * g2 + - -6.0 * m3.w * x3 * dot(x3, g3) + m4.w * g3; - return 42.0 * grad; -} diff --git a/Assets/Plugins/GPU Noise/SimplexNoiseGrad3D.cginc.meta b/Assets/Plugins/GPU Noise/SimplexNoiseGrad3D.cginc.meta deleted file mode 100644 index 250b646fa..000000000 --- a/Assets/Plugins/GPU Noise/SimplexNoiseGrad3D.cginc.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: a7111eafc2463224faacf7be3bddb9a4 -timeCreated: 1449292284 -licenseType: Pro -ShaderImporter: - defaultTextures: [] - userData: - assetBundleName: - assetBundleVariant: From b6c428d6827a63710ee931c4c317196cc9bc8038 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 12:08:15 +0000 Subject: [PATCH 044/190] Shaders: GalaxyMap, Clouds, SimplexBrush and Lightning.compute call cultmath_snoise The previous commit deleted the GPU Noise includes; this one carries the call-site edits it described. Release map notes Background's remaining 2D gradient copy. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Shaders/Brushes/SimplexBrush.shader | 4 ++-- Assets/Shaders/Clouds.shader | 6 +++--- Assets/Shaders/Compute/Lightning/Lightning.compute | 4 ++-- Assets/Shaders/GalaxyMap.shader | 6 +++--- docs/aetheria-release-map.md | 4 +++- 5 files changed, 13 insertions(+), 11 deletions(-) diff --git a/Assets/Shaders/Brushes/SimplexBrush.shader b/Assets/Shaders/Brushes/SimplexBrush.shader index 3a6bf56e5..af54035b2 100644 --- a/Assets/Shaders/Brushes/SimplexBrush.shader +++ b/Assets/Shaders/Brushes/SimplexBrush.shader @@ -25,7 +25,7 @@ Category { #pragma target 2.0 #include "UnityCG.cginc" - #include "Assets/Plugins/GPU Noise/SimplexNoise3D.cginc" + #include "Packages/org.gamecult.cultmath/Shaders/CultMath.hlsl" float _Depth; float _Power; @@ -68,7 +68,7 @@ Category { fixed4 frag (v2f i) : SV_Target { float dist = length(i.texcoord - float2(.5,.5)); - return powerPulse(dist * 2,_Power) * (_Depth * abs(snoise(float3(i.texcoord1.xy*_Frequency,_Time.y*_Speed)))+_Constant); + return powerPulse(dist * 2,_Power) * (_Depth * abs(cultmath_snoise(float3(i.texcoord1.xy*_Frequency,_Time.y*_Speed)))+_Constant); } ENDCG } diff --git a/Assets/Shaders/Clouds.shader b/Assets/Shaders/Clouds.shader index 11e3fe0a3..ccbda8835 100644 --- a/Assets/Shaders/Clouds.shader +++ b/Assets/Shaders/Clouds.shader @@ -29,7 +29,7 @@ #pragma fragment frag #include "UnityCG.cginc" - #include "Assets/Plugins/GPU Noise/SimplexNoise3D.cginc" + #include "Packages/org.gamecult.cultmath/Shaders/CultMath.hlsl" struct appdata { @@ -64,7 +64,7 @@ float sum = 0; for(int i = 0; i < 6; i++) { - sum += snoise(p * freq + Parallax * ParallaxDirection) * amp; + sum += cultmath_snoise(p * freq + Parallax * ParallaxDirection) * amp; parallax /= ParallaxLacunarity; freq *= NoiseLacunarity; amp *= NoiseGain; @@ -83,7 +83,7 @@ fixed4 frag (v2f i) : SV_Target { float3 p = float3(i.uv,_Time.x*Speed); - float noise = saturate((1-abs(snoise(p*NoiseFrequency/2))) * fbm(p)); + float noise = saturate((1-abs(cultmath_snoise(p*NoiseFrequency/2))) * fbm(p)); return noise * _Color * (1-length(i.uv)/FadeDistance); } ENDCG diff --git a/Assets/Shaders/Compute/Lightning/Lightning.compute b/Assets/Shaders/Compute/Lightning/Lightning.compute index 0750006b9..7edd707d4 100644 --- a/Assets/Shaders/Compute/Lightning/Lightning.compute +++ b/Assets/Shaders/Compute/Lightning/Lightning.compute @@ -5,7 +5,7 @@ #define NUM_THREAD_X 64 #include "LightningVertex.cginc" -#include "Assets/Plugins/GPU Noise/SimplexNoise2D.cginc" +#include "Packages/org.gamecult.cultmath/Shaders/CultMath.hlsl" struct Node { @@ -46,7 +46,7 @@ float fbm(float2 p) float sum = 0; for(int i = 0; i < 4; i++) { - sum += snoise(p * freq) * amp; + sum += cultmath_snoise(p * freq) * amp; freq *= _NoiseLacunarity; amp *= _NoiseGain; } diff --git a/Assets/Shaders/GalaxyMap.shader b/Assets/Shaders/GalaxyMap.shader index 567396a35..109cd96d0 100644 --- a/Assets/Shaders/GalaxyMap.shader +++ b/Assets/Shaders/GalaxyMap.shader @@ -36,7 +36,7 @@ Shader "Unlit/GalaxyMap" #pragma fragment frag #include "UnityCG.cginc" - #include "Assets/Plugins/GPU Noise/SimplexNoise2D.cginc" + #include "Packages/org.gamecult.cultmath/Shaders/CultMath.hlsl" struct appdata { @@ -86,8 +86,8 @@ Shader "Unlit/GalaxyMap" for(int i = 0; i < octaves; i++) { if(i<4) - sum += (1-abs(snoise(p * freq))) * amp; - else sum += abs(snoise(p * freq)) * amp; + sum += (1-abs(cultmath_snoise(p * freq))) * amp; + else sum += abs(cultmath_snoise(p * freq)) * amp; freq *= NoiseLacunarity; amp *= NoiseGain; } diff --git a/docs/aetheria-release-map.md b/docs/aetheria-release-map.md index 18f9b6941..72e96f22e 100644 --- a/docs/aetheria-release-map.md +++ b/docs/aetheria-release-map.md @@ -7459,7 +7459,9 @@ That file's Cut 4 (AI heading planner) and Cut 5 (combat facing) are carried as is `stage.Generated("Djinni")`, `EvasionTermTests.cs:520`, so the target's fit follows the galaxy). The cause is 0.3.0's breaking `snoise` kernel (its CHANGELOG), read in C# by `Settings.cs:72-73` (galaxy cloud density), `GlobalData.cs:30` and `Environment.cs:132,144`. Shaders use the GPU Noise plugin, not - CultMath (`Background.shader:39`), so nothing on the GPU moves. Every other DemoTerminus test passes. + CultMath (`Background.shader:39`), so nothing on the GPU moved at 0.3.0. GalaxyMap, Clouds, SimplexBrush and + Lightning.compute now include `CultMath.hlsl`; Background keeps its 2D gradient copy because CultMath has no 2D + `snoise_grad`. Every other DemoTerminus test passes. Between the tags CultMath also adds `phacelle` (MPL-2.0 files), `cellular`, `smin_grad`, the `*_grad` noises and `BoundedLeastSquares`; no existing signature changes. - **TA9. The pin guard.** `Directory.Build.targets:21` conditions `VerifyCultLibRevision` on a From 3c78dbcbd1cc8cc74d740cd1436fd601f78791c9 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 12:10:37 +0000 Subject: [PATCH 045/190] Fauna map B29: Aetheria pins cultmath-unity-v0.5.0 Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- docs/aetheria-fauna-map.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/aetheria-fauna-map.md b/docs/aetheria-fauna-map.md index b698baf41..05034c92a 100644 --- a/docs/aetheria-fauna-map.md +++ b/docs/aetheria-fauna-map.md @@ -398,7 +398,7 @@ the lore branch `eureka/aetheria-fauna-lore` `74c7e212`, note `Open Water` (`OW` | # | Question | Result | |---|---|---| | B28 | What does CultMath already give a node library? | Integer PCG hashes `pcg`, `pcg3d`, `pcg4d` (Jarzynski and Olano), "integer-only, so dxc and C# agree bit for bit" (`packages/cultmath/src/CultMath/math.cs:393-426`, `shaders/CultMath.hlsl:396-426`). `cellular(float3)`: Worley F1 and F2 - F1 with analytic gradients, jitter from `pcg3d` of the integer cell, 3D, unweighted (`math.cs:849-975`, `CultMath.hlsl:440-503`). `smin_grad` (`math.cs:831-847`, `CultMath.hlsl:428-437`). `distance_to_segment` in C# only (`math.cs:319`; no HLSL twin). No weighted cellular, no diagram over explicit weighted sites, no site-graph gate. | -| B29 | How does CultMath own parity? | Two legs, one owner each (`packages/cultmath/docs/design.md:202-206`): HLSL against C# by the mirror test, which compiles the text of `CultMath.hlsl` as C# and compares float32 bit patterns (`design.md:118-124`), plus a clean `dxc -T lib_6_3` compile (`design.md:114-116`); GLSL against C# by golden fixtures run on a device. The mirror proves the composition in the text, not that a GPU agrees (`design.md:119-121`); device HLSL runs are consumers' today (Asura `gpu-snoise-parity`; Aetheria `FlowFieldParityVerify`). CultMath ships a Unity compute smoke (`packages/cultmath/scripts/unity-smoke/`). Aetheria pins `cultmath-unity-v0.4.1` (`Packages/manifest.json`). | +| B29 | How does CultMath own parity? | Two legs, one owner each (`packages/cultmath/docs/design.md:202-206`): HLSL against C# by the mirror test, which compiles the text of `CultMath.hlsl` as C# and compares float32 bit patterns (`design.md:118-124`), plus a clean `dxc -T lib_6_3` compile (`design.md:114-116`); GLSL against C# by golden fixtures run on a device. The mirror proves the composition in the text, not that a GPU agrees (`design.md:119-121`); device HLSL runs are consumers' today (Asura `gpu-snoise-parity`; Aetheria `FlowFieldParityVerify`). CultMath ships a Unity compute smoke (`packages/cultmath/scripts/unity-smoke/`). Aetheria pins `cultmath-unity-v0.5.0` (`Packages/manifest.json`). | | B30 | Does Aetheria already keep a math twin outside CultMath? | Yes. `FlowField` uses CultMath's `math`, but its `Tri`, `Tri3` and `Tri3D` are Aetheria functions (`FlowField.cs:66-72`) whose HLSL twin is `Volumetric.cginc`, pinned by Aetheria's own `FlowFieldParityVerify` (`RelativeTolerance` 1.5e-4). That is a second parity owner beside CultMath. | | B31 | What is parked in CultMath that a DAG would use? | The tape: steps 2-5 (expression graph lowered to bytecode with C# evaluators, pruning, an HLSL interpreter, meshing) are parked until Asura is stable (`docs/cultmath-tape-target.md:3-8`, ruling `tape-target-unparks-when-asura-stable`). "Truth and lowerings" (`:84-92`): the field is a typed CultCache document, and the CPU evaluator and the HLSL interpreter are lowerings of it. Step 1 (intervals) and affine forms are on main. | | B32 | Do the candidates make filaments? (`docs/research/2026-10-14-trophic-dag-probe/`, README there; wells orbit, slope terms on, t = 0) | `skein` draws strands between neighbouring wells, bent by the flow (`density_skein.png`); `lattice` draws a fine cellular web, dense on the shoulders, dim elsewhere, with no long links (`density_lattice.png`); `skein-web` draws both: strands from well to well with a web hanging off them (`density_skein-web.png`, `layer_L2-krill.png`). Correlation with the B20 Physarum map at 64x32 blocks (this measures the envelope, not filaments: a block is 62 u, wider than a strand): band .512, lattice .359, skein-web .296, krill .277, skein .225, slack .171. Hosted krill at 16 u: band 2,075, skein-web 1,475, skein 639, lattice 419. | From b1dae6218e80eeaf28a260d0a3754ed179dc95d3 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 12:43:37 +0000 Subject: [PATCH 046/190] Entity.ItemFits: an equipped item is judged without its own cells, so a gun moves within its hardpoint The public ItemFits(item, coord) the inventory drag asks counted the dragged equipped item's own cells as occupied, so a nudge overlapping its current cells was refused. The private rule now takes the item being moved as an excluded occupant. TryEquip and TryFindSpace pass none and stay strict, so equipping an equipped item twice is still refused; the UI keeps TryUnequip then TryEquip (cargo bay emptiness rule). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/Entity.cs | 23 +++++--- .../HardpointOwnershipTests.cs | 59 +++++++++++++++++++ 2 files changed, 74 insertions(+), 8 deletions(-) diff --git a/Assets/Scripts/ServerShared/Entity.cs b/Assets/Scripts/ServerShared/Entity.cs index 2394a6134..43d9729d9 100644 --- a/Assets/Scripts/ServerShared/Entity.cs +++ b/Assets/Scripts/ServerShared/Entity.cs @@ -1525,7 +1525,8 @@ public abstract class Entity // Check whether the given item will fit when its origin is placed at the given coordinate. For hardpoint gear, // hardpoint is the one hardpoint the item would occupy there (HardpointAt); Tool gear occupies none. - private bool ItemFits(EquippableItemData itemData, HullData hullData, EquippableItem item, int2 hullCoord, out HardpointData hardpoint) + private bool ItemFits(EquippableItemData itemData, HullData hullData, EquippableItem item, int2 hullCoord, out HardpointData hardpoint, + EquippedItem moving = null) { hardpoint = null; // Items without specific hardpoints on the ship can be freely rotated and placed anywhere @@ -1538,13 +1539,13 @@ public abstract class Entity // general gear may take it until hardpoint gear claims it, which is the same rule // UnoccupiedSpace reports, so what generation is offered and what equipping accepts agree. var itemCoord = hullCoord + itemData.Shape.Rotate(i, item.Rotation); - if (!hullData.InteriorCells[itemCoord] || GearOccupancy[itemCoord.x, itemCoord.y] != null) + if (!hullData.InteriorCells[itemCoord] || !IsFree(itemCoord.x, itemCoord.y, moving)) return false; } } else { - hardpoint = HardpointAt(itemData, hullData, hullCoord); + hardpoint = HardpointAt(itemData, hullData, hullCoord, moving); if (hardpoint == null) return false; item.Rotation = hardpoint.Rotation; } @@ -1552,27 +1553,33 @@ public abstract class Entity return true; } + // A cell is free when no gear occupies it, or when the only occupant is the item being moved: a re-place of + // equipped gear is judged against the hull minus that item's own cells (the caller unequips, then equips). + private bool IsFree(int x, int y, EquippedItem moving) => GearOccupancy[x, y] == null || GearOccupancy[x, y] == moving; + // The one placement rule for hardpoint gear. At this origin the item lies within a hardpoint of its type, turned to // that hardpoint's rotation (HardpointData.TakesAt, the fit rule); its own cells are free, since a hardpoint's // leftover cells may hold general gear (operator, 2026-09-30: "saving slots in a hardpoint can be a valid tradeoff // for crowded ships"); and that hardpoint holds no other hardpoint item, since it holds one at most. - private HardpointData HardpointAt(EquippableItemData itemData, HullData hullData, int2 hullCoord) + private HardpointData HardpointAt(EquippableItemData itemData, HullData hullData, int2 hullCoord, EquippedItem moving) { foreach (var hardpoint in hullData.Hardpoints) { if (!hardpoint.TakesAt(itemData, hullCoord - hardpoint.Position)) continue; var ownCellsFree = itemData.Shape.Coordinates .Select(v => hullCoord + itemData.Shape.Rotate(v, hardpoint.Rotation)) - .All(c => GearOccupancy[c.x, c.y] == null); + .All(c => IsFree(c.x, c.y, moving)); var holdsAnother = hardpoint.Shape.Coordinates .Select(v => GearOccupancy[hardpoint.Position.x + v.x, hardpoint.Position.y + v.y]) - .Any(occupant => occupant != null && occupant.Data.HardpointType != HardpointType.Tool); + .Any(occupant => occupant != null && occupant != moving && occupant.Data.HardpointType != HardpointType.Tool); if (ownCellsFree && !holdsAnother) return hardpoint; } return null; } - // Check whether the given item will fit when its origin is placed at the given coordinate on the hull + // Check whether the given item will fit when its origin is placed at the given coordinate on the hull. An item that + // is already equipped here is judged without its own cells, so a gun can be moved within its own hardpoint; + // TryEquip stays strict (it never sees an item as its own occupant), so equipping an equipped item twice is refused. public bool ItemFits(EquippableItem item, int2 hullCoord) { // Don't allow equipping while deployed @@ -1580,7 +1587,7 @@ public abstract class Entity var itemData = ItemManager.GetData(item); var hullData = ItemManager.GetData(Hull) as HullData; - return ItemFits(itemData, hullData, item, hullCoord, out _); + return ItemFits(itemData, hullData, item, hullCoord, out _, Equipment.FirstOrDefault(e => e.EquippableItem == item)); } public bool TryFindSpace(EquippableItem item, out int2 hullCoord) diff --git a/tests/Aetheria.Shared.Tests/HardpointOwnershipTests.cs b/tests/Aetheria.Shared.Tests/HardpointOwnershipTests.cs index 2b8fa2270..1ddc1d10b 100644 --- a/tests/Aetheria.Shared.Tests/HardpointOwnershipTests.cs +++ b/tests/Aetheria.Shared.Tests/HardpointOwnershipTests.cs @@ -142,6 +142,65 @@ public sealed partial class RunStartTests Assert.Null(entity.EquippedHull.Hardpoint); } + private static Shape Bar(int width) + { + var bar = new Shape(width, 1); + foreach (var cell in bar.AllCoordinates) bar[cell] = true; + return bar; + } + + // Scenarios batch-4 minor: dragging an equipped gun within its own hardpoint. The UI asks ItemFits about the dragged + // item at its current and nudged origin, then TryUnequip and TryEquip at the target. The gun's own cells are not + // occupied against itself, so the nudge that overlaps its current cells is accepted and the sequence lands there. + [Fact] + public void AnEquippedGunCanBeMovedWithinItsOwnHardpoint() + { + var hull = ScratchHull("Minor Drag Mount", 9, Mount(HardpointType.Ballistic, 1, 1, Bar(3))); + var gun = ScratchGear("Minor Drag Gun", HardpointType.Ballistic, Bar(2)); + var entity = BareHull(hull); + var unit = Instance(gun); + Assert.True(entity.TryEquip(unit, int2(1, 1))); + var equipped = entity.Equipment.Single(i => i.Data == gun); + + Assert.True(entity.ItemFits(unit, int2(1, 1)), "its current origin"); + Assert.True(entity.ItemFits(unit, int2(2, 1)), "nudged one cell, overlapping its own cells"); + + Assert.NotNull(entity.TryUnequip(equipped)); + Assert.True(entity.TryEquip(unit, int2(2, 1))); + Assert.Equal(int2(2, 1), entity.Equipment.Single(i => i.Data == gun).Position); + Assert.Same(hull.Hardpoints[0], entity.Equipment.Single(i => i.Data == gun).Hardpoint); + } + + // Ignoring the item's own cells does not ignore anyone else's: a second hardpoint item cannot share the hardpoint, + // and TryEquip never treats an item as its own occupant, so equipping an equipped item again is refused. + [Fact] + public void MovingAnEquippedItemStillRespectsOtherOccupantsAndTryEquipStaysStrict() + { + var hull = ScratchHull("Minor Drag Strict", 9, Mount(HardpointType.Ballistic, 1, 1, Bar(4))); + var gun = ScratchGear("Minor Strict Gun", HardpointType.Ballistic, Bar(2)); + var other = ScratchGear("Minor Strict Other", HardpointType.Ballistic, Bar(1)); + var entity = BareHull(hull); + var unit = Instance(gun); + Assert.True(entity.TryEquip(unit, int2(1, 1))); + Assert.False(entity.TryEquip(Instance(other), int2(3, 1)), "the hardpoint holds one hardpoint item"); + Assert.False(entity.TryEquip(unit, int2(2, 1)), "TryEquip is strict: no duplicate of an equipped item"); + Assert.Single(entity.Equipment, i => i.Data == gun); + } + + // A tool dragged within its own cells is judged the same way. + [Fact] + public void AnEquippedToolCanBeMovedOverItsOwnCells() + { + var hull = ScratchHull("Minor Drag Tool Hull", 9); + var tool = ScratchGear("Minor Drag Tool", HardpointType.Tool, Bar(2)); + var entity = BareHull(hull); + var unit = Instance(tool); + Assert.True(entity.TryEquip(unit, int2(1, 1))); + Assert.True(entity.ItemFits(unit, int2(2, 1)), "nudged over its own cell"); + Assert.False(entity.TryEquip(unit, int2(2, 1)), "TryEquip never sees an item as its own occupant"); + Assert.Single(entity.Equipment, i => i.Data == tool); + } + // The design's cells, turned to a rotation, moved so the lowest x and y are zero. Written here from the cells alone // (the game's turn directions, up to translation), so it is not Shape.Rotate checking itself. private static HashSet<(int x, int y)> Normalized(IEnumerable<int2> cells, ItemRotation rotation) From 4c6dcfea739f231acbbb914011b262f85afebb1b Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 12:43:37 +0000 Subject: [PATCH 047/190] AetherDb station-reactor-spread [apply]: station reactor products regain their sources' quality spread f458206c7 authored the five per-manufacturer station reactor products with bare ProductRole entries (the .5 / .15 default). The command copies each source product's Mean and StandardDeviation per role to a role still at the default, and was applied to the catalog. TwoAiDigest repinned for the catalog move. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- GameData/Aetheria.cc | 2 +- .../DeterminismLedgerTests.cs | 5 +- .../StationReactorSpreadTests.cs | 99 +++++++++++++++++++ tools/AetherDb/Program.cs | 1 + tools/AetherDb/StationReactorSpreadCommand.cs | 82 +++++++++++++++ 5 files changed, 187 insertions(+), 2 deletions(-) create mode 100644 tests/Aetheria.Shared.Tests/StationReactorSpreadTests.cs create mode 100644 tools/AetherDb/StationReactorSpreadCommand.cs diff --git a/GameData/Aetheria.cc b/GameData/Aetheria.cc index da60f2dd3..f4cfdc4a3 100644 --- a/GameData/Aetheria.cc +++ b/GameData/Aetheria.cc @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:319c14830b174e4bd58fe849b1300f38d7724d91027e47a03a5c121741d38e51 +oid sha256:9edc8434524f43f751c89416479cf07fba03b424f266cb8bfc1870bd46eef6a7 size 220537 diff --git a/tests/Aetheria.Shared.Tests/DeterminismLedgerTests.cs b/tests/Aetheria.Shared.Tests/DeterminismLedgerTests.cs index 31b71dba0..c7b5cb79a 100644 --- a/tests/Aetheria.Shared.Tests/DeterminismLedgerTests.cs +++ b/tests/Aetheria.Shared.Tests/DeterminismLedgerTests.cs @@ -54,7 +54,10 @@ public sealed partial class RunStartTests // moved the digest and returned it to 52fbb10d, which master already measured before this cut. The authored-cargo and // ammunition-data blob of this cut moved nothing (52fbb10d measured with it merged in). Fixtures run ThrustScale=1 while play // uses 0.1, so this digest pins the fight's logic, not the shipped feel. - private const string TwoAiPinnedDigest = "52fbb10df2559829a11f3a38aae0783f3f1858b0499f6f46794a267a747adacb"; + // Repinned a ninth time, once (scenarios-batch4-minors): the catalog restores the five station-reactor products' quality + // spread (station-reactor-spread), and that blob alone moved the digest (the same tree with the old catalog measured 52fbb10d; + // the path from role spread to the fight was not traced). + private const string TwoAiPinnedDigest = "9c70a3ee234fb3b879f721a4a4abf13dd83bf56fd8733690d356b89b8a392258"; private const float TwoAiSeconds = 60f; [Fact] diff --git a/tests/Aetheria.Shared.Tests/StationReactorSpreadTests.cs b/tests/Aetheria.Shared.Tests/StationReactorSpreadTests.cs new file mode 100644 index 000000000..41161975a --- /dev/null +++ b/tests/Aetheria.Shared.Tests/StationReactorSpreadTests.cs @@ -0,0 +1,99 @@ +using System; +using System.IO; +using System.Linq; +using GameCult.Caching; +using Xunit; + +// station-reactor-spread (aetheria-release follow-up scenarios-batch4-minors): a station reactor's product keeps the +// quality spread of the reactor product it was scaled from. The mint reads a product's Roles (Mean, StandardDeviation) per +// design role, and a role missing or left at the unauthored default draws a flat .5 / .15 instead of the maker's spread. +public sealed class StationReactorSpreadTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-station-spread-" + Guid.NewGuid().ToString("N")); + private string Catalog => Path.Combine(_root, "Aetheria.cc"); + + public StationReactorSpreadTests() => Directory.CreateDirectory(_root); + public void Dispose() => Directory.Delete(_root, true); + + // Read the way the mint does (ItemManager.Mint): the product's own Roles, matched by role name. + [Fact] + public void ShippedStationReactorProductsCarryTheirSourcesSpread() + { + using var cache = RestoredHullsTests.OpenCatalog(); + var products = cache.GetAll<FactionProductData>().ToArray(); + FactionProductData Find(string name, string maker) => + products.Single(p => p.Name == name && cache.Get(p.Manufacturer)?.ShortName == maker); + + foreach (var (stationName, sourceName, maker) in StationReactorSpreadCommand.Rows) + { + var station = Find(stationName, maker); + var source = Find(sourceName, maker); + Assert.NotEmpty(station.Roles); + foreach (var role in station.Roles) + { + var from = source.Roles.Single(r => r.Role == role.Role); + Assert.Equal(from.Mean, role.Mean); + Assert.Equal(from.StandardDeviation, role.StandardDeviation); + } + Assert.Contains(station.Roles, r => r.Mean != .5f || r.StandardDeviation != .15f); + } + } + + private void Seed() + { + using var cache = AetheriaStores.Open(Catalog, catalogWritable: true); + cache.Upsert(new VerseGrammar { Revision = 1 }); + var maker = cache.Upsert(new Faction { Name = "Maker", ShortName = "M" }); + var gear = cache.Upsert(new GearData { Name = "Lamp", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 10 }); + var design = new CultRecordRef<CraftedItemData>(gear.Key); + cache.Upsert(new FactionProductData + { + Name = "Source", Design = design, Manufacturer = maker, + Roles = { new ProductRole { Role = "core", Mean = .7f, StandardDeviation = .05f }, new ProductRole { Role = "regulator", Mean = .3f, StandardDeviation = .2f } } + }); + cache.Upsert(new FactionProductData + { + Name = "Source Station", Design = design, Manufacturer = maker, + Roles = { new ProductRole { Role = "core" }, new ProductRole { Role = "regulator", Mean = .9f, StandardDeviation = .01f } } + }); + cache.FlushAsync().Wait(); + } + + private static readonly (string Station, string Source, string Maker)[] Fixture = { ("Source Station", "Source", "M") }; + + private string Run(bool apply) + { + using var cache = AetheriaStores.Open(Catalog, catalogWritable: apply); + var output = new StringWriter(); + Assert.Equal(0, StationReactorSpreadCommand.Run(cache, apply, output, Fixture)); + cache.FlushAsync().Wait(); + return output.ToString(); + } + + private ProductRole RoleOf(string role) + { + using var cache = AetheriaStores.Open(Catalog); + return cache.GetAll<FactionProductData>().Single(p => p.Name == "Source Station").Roles.Single(r => r.Role == role); + } + + // A role at the unauthored default takes the source's pair, a role tuned in Studio is kept, a dry run writes nothing, + // and a second apply has nothing to do. + [Fact] + public void CopiesOnlyUnauthoredRolesAndReplaysToNothing() + { + Seed(); + var before = File.ReadAllBytes(Catalog); + Assert.Contains("core", Run(apply: false)); + Assert.Equal(before, File.ReadAllBytes(Catalog)); + + Run(apply: true); + Assert.Equal(.7f, RoleOf("core").Mean, 3); + Assert.Equal(.05f, RoleOf("core").StandardDeviation, 3); + Assert.Equal(.9f, RoleOf("regulator").Mean, 3); + Assert.Equal(.01f, RoleOf("regulator").StandardDeviation, 3); + + var written = File.ReadAllBytes(Catalog); + Assert.Contains("No changes", Run(apply: true)); + Assert.Equal(written, File.ReadAllBytes(Catalog)); + } +} diff --git a/tools/AetherDb/Program.cs b/tools/AetherDb/Program.cs index 5d3d18e93..2caaaed4b 100644 --- a/tools/AetherDb/Program.cs +++ b/tools/AetherDb/Program.cs @@ -59,6 +59,7 @@ public static class Program case "inspection-scanner": return InspectionScannerCatalog(args.Contains("apply")); case "product-lines": return ProductLinesCommand.Run(args.Skip(1).ToArray()); case "minor-power-factions": return MinorPowerFactionsCommand.Run(args.Skip(1).ToArray()); + case "station-reactor-spread": return StationReactorSpreadCommand.Run(AetherDb.Open(catalogWritable: args.Contains("apply")).Cache, args.Contains("apply"), Console.Out); case "assembly-from-maker": return AssemblyFromMakerCommand.Run(AetherDb.Open(catalogWritable: args.Contains("apply")).Cache, args.Contains("apply"), Console.Out); case "place-names": Console.OutputEncoding = new System.Text.UTF8Encoding(false); diff --git a/tools/AetherDb/StationReactorSpreadCommand.cs b/tools/AetherDb/StationReactorSpreadCommand.cs new file mode 100644 index 000000000..6f7064fb3 --- /dev/null +++ b/tools/AetherDb/StationReactorSpreadCommand.cs @@ -0,0 +1,82 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using GameCult.Caching; + +// station-reactor-spread [apply] (aetheria-release follow-up scenarios-batch4-minors): the per-manufacturer station reactors +// (f458206c7) were authored as scaled copies of each maker's largest reactor, but their products were authored with a bare +// ProductRole { Role } for each role, which is the .5 / .15 default, so they lost the source product's quality spread. This +// gives each station product the Mean and StandardDeviation the source product holds for the same role. It writes only a role +// still at the default pair, so a spread tuned in Studio survives every replay, and a second apply has nothing to do. Replays +// before assembly-from-maker (which derives from role means) when that command has an unauthored maker to fill. Dry run +// unless apply. +public static class StationReactorSpreadCommand +{ + // The role pair an unauthored ProductRole carries (ProductRole's field defaults). + private static readonly ProductRole Unauthored = new ProductRole(); + + // (station product, source product, maker short name): the source is the maker's product of the reactor the station + // design was scaled from. + public static readonly (string Station, string Source, string Maker)[] Rows = + { + ("Steadfast Station", "Steadfast", "R&D"), + ("Manhattan Station", "Manhattan", "Zhestokost"), + ("Notorious Station", "Notorious", "Lucent"), + ("Vulcan Station", "Vulcan", "AU"), + ("MoveOnPro Station", "MoveOnPro", "NiteLife"), + }; + + public static int Run(CultCache cache, bool apply, TextWriter output, (string Station, string Source, string Maker)[] rows = null) + { + var products = cache.GetAll<FactionProductData>().ToArray(); + FactionProductData Find(string name, string maker) + { + var found = products.Where(p => p.Name == name && cache.Get(p.Manufacturer)?.ShortName == maker).ToArray(); + if (found.Length != 1) throw new InvalidOperationException($"Station reactor row \"{name}\" by {maker}: {found.Length} products match."); + return found[0]; + } + + var changed = new List<FactionProductData>(); + foreach (var (stationName, sourceName, maker) in rows ?? Rows) + { + var station = Find(stationName, maker); + var source = Find(sourceName, maker); + foreach (var role in station.Roles) + { + var from = source.Roles.SingleOrDefault(r => r.Role == role.Role) + ?? throw new InvalidOperationException($"\"{sourceName}\" holds no \"{role.Role}\" role to copy to \"{stationName}\"."); + if (role.Mean != Unauthored.Mean || role.StandardDeviation != Unauthored.StandardDeviation) continue; + if (from.Mean == role.Mean && from.StandardDeviation == role.StandardDeviation) continue; + output.WriteLine($"{stationName} ({maker}) {role.Role}: {role.Mean:0.###}±{role.StandardDeviation:0.###} -> {from.Mean:0.###}±{from.StandardDeviation:0.###}"); + role.Mean = from.Mean; + role.StandardDeviation = from.StandardDeviation; + if (!changed.Contains(station)) changed.Add(station); + } + } + + if (changed.Count == 0) + { + output.WriteLine("No changes."); + return 0; + } + + if (!apply) + { + output.WriteLine($"\nDry run. Pass \"apply\" to write {changed.Count} products."); + return 0; + } + + foreach (var product in changed) CultRecordRefs.Validate(product); + cache.Commit(batch => + { + foreach (var product in changed) batch.Upsert(typeof(FactionProductData), product, cache.RefOf(product).Key); + }); + output.WriteLine($"\nWrote {changed.Count} products in Aetheria.cc"); + return 0; + } +} From 156d7c5a19fe31eabaeb305dfe5930c619609e1d Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 13:10:13 +0000 Subject: [PATCH 048/190] Determinism ledger: record why the station-reactor spread moves the two-AI digest Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- tests/Aetheria.Shared.Tests/DeterminismLedgerTests.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/Aetheria.Shared.Tests/DeterminismLedgerTests.cs b/tests/Aetheria.Shared.Tests/DeterminismLedgerTests.cs index c7b5cb79a..7b7182400 100644 --- a/tests/Aetheria.Shared.Tests/DeterminismLedgerTests.cs +++ b/tests/Aetheria.Shared.Tests/DeterminismLedgerTests.cs @@ -56,7 +56,8 @@ public sealed partial class RunStartTests // uses 0.1, so this digest pins the fight's logic, not the shipped feel. // Repinned a ninth time, once (scenarios-batch4-minors): the catalog restores the five station-reactor products' quality // spread (station-reactor-spread), and that blob alone moved the digest (the same tree with the old catalog measured 52fbb10d; - // the path from role spread to the fight was not traced). + // traced: only Notorious Station moves it, because the zone's station Zenith carries a Notorious Station reactor lot whose + // minted quality changes with the role spread, and Snapshot hashes every zone entity's heat and shield). private const string TwoAiPinnedDigest = "9c70a3ee234fb3b879f721a4a4abf13dd83bf56fd8733690d356b89b8a392258"; private const float TwoAiSeconds = 60f; From ff54fe7b463b99ad490b5530085f25e34cab9cfa Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 09:50:22 +0000 Subject: [PATCH 049/190] Pin CultLib abd1a92e: element ids on every list element type, tests follow the new wire and write rules Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../ServerShared/Behaviors/Behaviors.cs | 4 ++ Assets/Scripts/ServerShared/Corporations.cs | 3 + .../Scripts/ServerShared/EntitySerializer.cs | 3 + Assets/Scripts/ServerShared/FactionProduct.cs | 3 + Assets/Scripts/ServerShared/InputLayout.cs | 8 ++- Assets/Scripts/ServerShared/ItemData.cs | 9 +++ Assets/Scripts/ServerShared/Loadout.cs | 3 + Assets/Scripts/ServerShared/Provenance.cs | 6 ++ Assets/Scripts/ServerShared/Recipes.cs | 6 ++ Assets/Scripts/ServerShared/SavedGame.cs | 9 +++ Assets/Scripts/ServerShared/ShipAuthoring.cs | 9 +++ Assets/Scripts/ServerShared/StationKinds.cs | 3 + Assets/Scripts/ServerShared/VerseGrammar.cs | 3 + Assets/Scripts/ServerShared/ZoneData.cs | 15 +++++ Directory.Build.props | 4 +- docs/element-ids.md | 29 ++++++++++ tests/Aetheria.Shared.Tests/ElementIdBlind.cs | 57 +++++++++++++++++++ .../ElementIdUpgradeTests.cs | 56 ++++++++++++++++++ tests/Aetheria.Shared.Tests/EmissionTests.cs | 2 +- .../InspectionScannerCommandTests.cs | 2 +- .../LaunchSuppressorCommandTests.cs | 2 +- .../LaunchSuppressorTests.cs | 2 +- tests/Aetheria.Shared.Tests/ListenerTests.cs | 2 +- tests/Aetheria.Shared.Tests/PaintModeTests.cs | 2 +- tests/Aetheria.Shared.Tests/ScannerTests.cs | 2 +- .../ShipAuthoringTests.cs | 16 ++---- .../ShipModCatalogTests.cs | 2 +- .../Aetheria.Shared.Tests/ShipProductTests.cs | 2 +- tests/Aetheria.Shared.Tests/ShipRigTests.cs | 4 +- tests/Aetheria.Shared.Tests/SignatureTests.cs | 2 +- .../SmokeRoundsCommandTests.cs | 2 +- .../Aetheria.Shared.Tests/VapourCloudTests.cs | 2 +- tools/AetherDb/EconomyCommand.cs | 4 ++ 33 files changed, 251 insertions(+), 27 deletions(-) create mode 100644 docs/element-ids.md create mode 100644 tests/Aetheria.Shared.Tests/ElementIdBlind.cs create mode 100644 tests/Aetheria.Shared.Tests/ElementIdUpgradeTests.cs diff --git a/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs b/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs index 6b899ee35..300229d3f 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs @@ -6,6 +6,7 @@ using System; using System.Collections; using System.Collections.Generic; using System.Linq; +using GameCult.Caching; using MessagePack; using Newtonsoft.Json; using CultMath; @@ -212,4 +213,7 @@ public abstract class BehaviorData { return base.ToString().FormatTypeName(); } + + // Element identity: minted by the cache on write; "" means unset. + [Key(37)] [CultElementId] public string Id = ""; } \ No newline at end of file diff --git a/Assets/Scripts/ServerShared/Corporations.cs b/Assets/Scripts/ServerShared/Corporations.cs index e527606d9..080f42aac 100644 --- a/Assets/Scripts/ServerShared/Corporations.cs +++ b/Assets/Scripts/ServerShared/Corporations.cs @@ -84,5 +84,8 @@ public class FactionPlace // treats an invalid entry as absent; AetherDb place-names refuses a table that holds one. public static bool IsValidName(string name) => !string.IsNullOrEmpty(name) && name == name.Trim() && !name.StartsWith("EAC-", StringComparison.OrdinalIgnoreCase); + + // Element identity: minted by the cache on write; "" means unset. + [Key(2)] [CultElementId] public string Id = ""; } diff --git a/Assets/Scripts/ServerShared/EntitySerializer.cs b/Assets/Scripts/ServerShared/EntitySerializer.cs index 7f0f04ebd..9aefe5a19 100644 --- a/Assets/Scripts/ServerShared/EntitySerializer.cs +++ b/Assets/Scripts/ServerShared/EntitySerializer.cs @@ -294,4 +294,7 @@ public abstract class EntityPack return _price; } + + // Element identity: minted by the cache on write; "" means unset. + [Key(23)] [CultElementId] public string Id = ""; } diff --git a/Assets/Scripts/ServerShared/FactionProduct.cs b/Assets/Scripts/ServerShared/FactionProduct.cs index 14f7af57d..87ac72f7d 100644 --- a/Assets/Scripts/ServerShared/FactionProduct.cs +++ b/Assets/Scripts/ServerShared/FactionProduct.cs @@ -61,6 +61,9 @@ public class ProductRole [Inspectable, JsonProperty("standardDeviation"), Key(2)] public float StandardDeviation = .15f; + + // Element identity: minted by the cache on write; "" means unset. + [Key(3)] [CultElementId] public string Id = ""; } // A bin of one of the maker's lines (ruling maker-design-tiers-allowed): the line it bins (the same design and maker, itself diff --git a/Assets/Scripts/ServerShared/InputLayout.cs b/Assets/Scripts/ServerShared/InputLayout.cs index a688598b2..7e942c519 100644 --- a/Assets/Scripts/ServerShared/InputLayout.cs +++ b/Assets/Scripts/ServerShared/InputLayout.cs @@ -29,7 +29,10 @@ public class InputLayout Union(0, typeof(InputLayoutRowSpacer)), Union(1, typeof(InputLayoutKeyRow)) ] -public abstract class InputLayoutRow { } +public abstract class InputLayoutRow { + // Element identity: minted by the cache on write; "" means unset. + [Key(1)] [CultElementId] public string Id = ""; +} [MessagePackObject, JsonObject(MemberSerialization.OptIn)] public class InputLayoutRowSpacer : InputLayoutRow @@ -52,6 +55,9 @@ public class InputLayoutKeyRow : InputLayoutRow public abstract class InputLayoutColumn { [Key(0), JsonProperty("width")] public float Width; + + // Element identity: minted by the cache on write; "" means unset. + [Key(5)] [CultElementId] public string Id = ""; } [MessagePackObject, JsonObject(MemberSerialization.OptIn)] diff --git a/Assets/Scripts/ServerShared/ItemData.cs b/Assets/Scripts/ServerShared/ItemData.cs index 72c07fc9a..ab9c9dcfc 100644 --- a/Assets/Scripts/ServerShared/ItemData.cs +++ b/Assets/Scripts/ServerShared/ItemData.cs @@ -348,6 +348,9 @@ public class ItemRole [Inspectable, JsonProperty("count"), Key(1)] public int Count = 1; + + // Element identity: minted by the cache on write; "" means unset. + [Key(2)] [CultElementId] public string Id = ""; } [CultDocument("aetheria.compoundcommoditydata", "1"), Inspectable, MessagePackObject] @@ -635,6 +638,9 @@ public class HardpointData } private static Dictionary<HardpointType, float3> _tintColors; + + // Element identity: minted by the cache on write; "" means unset. + [Key(8)] [CultElementId] public string Id = ""; } // What a PerformanceStat reads to resolve one number: the lot it prices quality against, and the per-context @@ -680,6 +686,9 @@ public class StatTerm // The design role whose part quality this term reads; unset reads the item's effective quality (Lot.EffectiveQuality). // Njordr states the same rule as a derivation over dimensions; this is that rule with one dimension. [Inspectable, JsonProperty("role"), Key(2)] public string Role; + + // Element identity: minted by the cache on write; "" means unset. + [Key(3)] [CultElementId] public string Id = ""; } [MessagePackObject, JsonObject(MemberSerialization.OptIn)] diff --git a/Assets/Scripts/ServerShared/Loadout.cs b/Assets/Scripts/ServerShared/Loadout.cs index 4866aa406..b423eb1a0 100644 --- a/Assets/Scripts/ServerShared/Loadout.cs +++ b/Assets/Scripts/ServerShared/Loadout.cs @@ -28,6 +28,9 @@ public class LoadoutSlot [Key(1)] public ItemRotation Rotation; [Key(2)] public CultRecordRef<EquippableItemData> Design; [Key(3)] public CultRecordRef<FactionProductData> Product; // unset: design-only, chosen at materialization + + // Element identity: minted by the cache on write; "" means unset. + [Key(4)] [CultElementId] public string Id = ""; } // Why a faction has no boss Loadout to build; see Loadouts.BossOf. diff --git a/Assets/Scripts/ServerShared/Provenance.cs b/Assets/Scripts/ServerShared/Provenance.cs index 4121332d6..25a4a6175 100644 --- a/Assets/Scripts/ServerShared/Provenance.cs +++ b/Assets/Scripts/ServerShared/Provenance.cs @@ -92,6 +92,9 @@ public class Lot foreach (var fill in Roles) sum += Math.Min(fill.Quality, Quality); return sum / Roles.Count; } + + // Element identity: minted by the cache on write; "" means unset. + [Key(5)] [CultElementId] public string Id = ""; } // One filled slot: the design's role name and how good the part that went into it turned out to be. Stats read it through @@ -101,6 +104,9 @@ public class RoleFill { [Key(0)] public string Role; [Key(1)] public float Quality; + + // Element identity: minted by the cache on write; "" means unset. + [Key(2)] [CultElementId] public string Id = ""; } // Who built a lot, where, and from what. Terminus mints Attributed placeholders; Produced and Extracted are the diff --git a/Assets/Scripts/ServerShared/Recipes.cs b/Assets/Scripts/ServerShared/Recipes.cs index e434a84a5..f9aa3ee4a 100644 --- a/Assets/Scripts/ServerShared/Recipes.cs +++ b/Assets/Scripts/ServerShared/Recipes.cs @@ -63,6 +63,9 @@ public class CommodityCount [JsonProperty("count"), Key(1)] public int Count = 1; + + // Element identity: minted by the cache on write; "" means unset. + [Key(2)] [CultElementId] public string Id = ""; } // A region gate's trade with the world beyond it: what the outside buys and sells, at what price and at most how fast. @@ -96,6 +99,9 @@ public class OutsideMarketRow [JsonProperty("ratePerHour"), Key(4)] public float RatePerHour; + + // Element identity: minted by the cache on write; "" means unset. + [Key(5)] [CultElementId] public string Id = ""; } // The one reader of recipes: which recipe makes a good, a recipe's role slots (RoleInputsOf), which commodities fill a role, and diff --git a/Assets/Scripts/ServerShared/SavedGame.cs b/Assets/Scripts/ServerShared/SavedGame.cs index 88ff8c9bf..5f42de446 100644 --- a/Assets/Scripts/ServerShared/SavedGame.cs +++ b/Assets/Scripts/ServerShared/SavedGame.cs @@ -78,6 +78,9 @@ public class SavedStanding [Key(1)] public FactionRelationship Relationship; + + // Element identity: minted by the cache on write; "" means unset. + [Key(2)] [CultElementId] public string Id = ""; } [MessagePackObject] @@ -88,6 +91,9 @@ public class SavedProvince [Key(1)] public CultRecordRef<ProvinceData> Type; + + // Element identity: minted by the cache on write; "" means unset. + [Key(2)] [CultElementId] public string Id = ""; } // The run's lifecycle over the run store. Only Commit creates SavedGame, SavedZone and ProvenanceLedger records; @@ -301,6 +307,9 @@ public class SavedZone ] public abstract class SavedActionBarBinding { + + // Element identity: minted by the cache on write; "" means unset. + [Key(2)] [CultElementId] public string Id = ""; } [MessagePackObject] diff --git a/Assets/Scripts/ServerShared/ShipAuthoring.cs b/Assets/Scripts/ServerShared/ShipAuthoring.cs index 3962fa468..8441d0332 100644 --- a/Assets/Scripts/ServerShared/ShipAuthoring.cs +++ b/Assets/Scripts/ServerShared/ShipAuthoring.cs @@ -33,6 +33,9 @@ public sealed class ShipJoint [Key(2)] public float[] Axes; [Key(3)] public float[] Min; [Key(4)] public float[] Max; + + // Element identity, derived from the bone id so it never changes across rewrites. + [Key(5)] [CultElementId(nameof(Id))] public string ElementId = ""; } [MessagePackObject] @@ -50,6 +53,9 @@ public sealed class ShipAnchor [Key(4)] public int Order; // On a weapon-mount anchor: the id of the nearest joint above its node in the model; null or empty is a fixed mount. [Key(5)] public string Joint; + + // Element identity, derived from the anchor id so it never changes across rewrites. + [Key(6)] [CultElementId(nameof(Id))] public string ElementId = ""; } // Evaluated or baked Grease Pencil stroke coordinates in Blender's right-handed Z-up @@ -64,6 +70,9 @@ public sealed class ShipPolyline [Key(4)] public float[] Opacities; [Key(5)] public bool Cyclic; [Key(6)] public float[] Color; + + // Element identity: minted by the cache on write; "" means unset. + [Key(7)] [CultElementId] public string Id = ""; } public static class ShipAuthoringStore diff --git a/Assets/Scripts/ServerShared/StationKinds.cs b/Assets/Scripts/ServerShared/StationKinds.cs index dad1ce2aa..eb2662eee 100644 --- a/Assets/Scripts/ServerShared/StationKinds.cs +++ b/Assets/Scripts/ServerShared/StationKinds.cs @@ -35,6 +35,9 @@ public class StationKindStandIn // The kind whose model this faction builds in place of the owning kind's. [JsonProperty("kind"), Key(1)] public CultRecordRef<StationKindData> Kind; + + // Element identity: minted by the cache on write; "" means unset. + [Key(2)] [CultElementId] public string Id = ""; } // The one owner of which kinds a faction builds, which kind a station gets, and which hull kind stands in. diff --git a/Assets/Scripts/ServerShared/VerseGrammar.cs b/Assets/Scripts/ServerShared/VerseGrammar.cs index 00e24833d..1219e70b6 100644 --- a/Assets/Scripts/ServerShared/VerseGrammar.cs +++ b/Assets/Scripts/ServerShared/VerseGrammar.cs @@ -40,6 +40,9 @@ public class VerseRole { [Key(1)] public string Name; [Key(2)] public VerseReferentKind Binds; + + // Element identity: minted by the cache on write; "" means unset. + [Key(3)] [CultElementId] public string Id = ""; } // The actor is the invoking subject and is never a role. diff --git a/Assets/Scripts/ServerShared/ZoneData.cs b/Assets/Scripts/ServerShared/ZoneData.cs index a08895aaa..e76963a43 100644 --- a/Assets/Scripts/ServerShared/ZoneData.cs +++ b/Assets/Scripts/ServerShared/ZoneData.cs @@ -67,6 +67,9 @@ public class ChunkWearPack [JsonProperty("brokenUntil"), Key(3)] public double? BrokenUntil; + + // Element identity: minted by the cache on write; "" means unset. + [Key(4)] [CultElementId] public string Id = ""; } [JsonObject(MemberSerialization.OptIn)] @@ -149,6 +152,9 @@ public class FieldYield [JsonProperty("regional"), Key(2)] public bool Regional; + + // Element identity: minted by the cache on write; "" means unset. + [Key(3)] [CultElementId] public string Id = ""; } // Ore geography (rulings provinces-within-regions, ores-are-regional): a kind of ground, authored. A region deals its @@ -182,6 +188,9 @@ public class ProvinceKindWeight [JsonProperty("weight"), Key(1)] public float Weight = 1; + + // Element identity: minted by the cache on write; "" means unset. + [Key(2)] [CultElementId] public string Id = ""; } [MessagePackObject, JsonObject(MemberSerialization.OptIn)] @@ -192,6 +201,9 @@ public class ProvinceOre [JsonProperty("weight"), Key(1)] public float Weight = 1; + + // Element identity: minted by the cache on write; "" means unset. + [Key(2)] [CultElementId] public string Id = ""; } // Mining Cut 3 (Q16 B): the one owner of which kind a belt is. Ore geography: and of what it yields. @@ -485,6 +497,9 @@ public class Asteroid [JsonProperty("rotationSpeed"), Key(3)] public float RotationSpeed; + + // Element identity: minted by the cache on write; "" means unset. + [Key(4)] [CultElementId] public string Id = ""; } [CultDocument("aetheria.orbitdata", "1"), MessagePackObject, JsonObject(MemberSerialization.OptIn)] diff --git a/Directory.Build.props b/Directory.Build.props index 05d5e4d22..66ff67e19 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -2,8 +2,8 @@ <PropertyGroup> <CultLibRoot Condition="'$(CultLibRoot)' == '' and '$(CULTLIB_ROOT)' != ''">$(CULTLIB_ROOT)</CultLibRoot> <CultLibRoot Condition="'$(CultLibRoot)' == ''">$(MSBuildThisFileDirectory)..\CultLib</CultLibRoot> - <!-- CultCache: caching-unity-v2.0.0 / cultlib-unity-v2.0.1 in Packages/manifest.json. --> - <CultLibRevision>b8fc5eb07720a187a0421424ac2cb3aa2966ca1d</CultLibRevision> + <!-- CultCache: abd1a92e (CultLib 3.0.0 unreleased; the Unity manifest tags still pin 2.0.x until a release is tagged). --> + <CultLibRevision>abd1a92eb24e1af3fc7cdd1bf98a88dbdebc2938</CultLibRevision> <CultMathRoot Condition="'$(CultMathRoot)' == '' and '$(CULTMATH_ROOT)' != ''">$(CULTMATH_ROOT)</CultMathRoot> <CultMathRoot Condition="'$(CultMathRoot)' == ''">$(CultLibRoot)</CultMathRoot> <!-- CultMath: cultmath-unity-v0.5.0 in Packages/manifest.json. --> diff --git a/docs/element-ids.md b/docs/element-ids.md new file mode 100644 index 000000000..31cc92e17 --- /dev/null +++ b/docs/element-ids.md @@ -0,0 +1,29 @@ +# Element ids and the CultLib pin (abd1a92e) + +CultLib 3.0 (unreleased; headless pin `abd1a92e`, `Directory.Build.props`) gives every element of an object list an identity. Every +element type reachable through a list of a `[CultDocument]` type carries one string member with `[Key(n)]` and `[CultElementId]`; +the registry refuses to open otherwise, naming the type and list. + +- **Where the slot goes.** A union base takes the member above its subclasses' highest key. `BehaviorData.Id` is key 37, so an + array-format behavior is 38 slots on the wire (`PaintModeTests`, `ShipRigTests` pin it). A new `BehaviorData` subclass must keep + its keys below 37 or move the slot, which is a wire change. +- **Derived ids.** `ShipJoint` and `ShipAnchor` already had a readable `Id`; CultLib refuses a readable id inside a marked member, + so each gained a trailing `ElementId` marked `[CultElementId(nameof(Id))]`. +- **Minting.** A writer mints random ids for elements that have none. A store written before ids (every file under `GameData/`) + loads with ids minted in memory and persists them on its next write; `CultCache.MintElementIds()` does that in one pass. + `ElementIdUpgradeTests` opens a copy of the shipped catalog, mints, flushes and reopens it. +- **Comparing content.** Random ids differ between two writes of the same content. Tests that compare bytes use + `ElementIdBlind`. +- **One list element is one object.** The same instance twice in a list is refused (`CultElementIdException`). +- **Retyping.** Writing a different type onto a held key is refused unless the record is removed first + (`EconomyAuthor.Write` does). + +## The bump is one-way + +A store holding element ids is format v3 (single file) or v5 (directory). A pin older than `abd1a92e` can open a single-file v3 +store without error and drops the ids on its next write (CultLib #98). So: upgrade readers before writers, keep a pre-upgrade +copy of any real store (`GameData/Aetheria.cc` and the mod packages are tracked in git; player saves and run stores are not), +and do not roll the pin back after a store has been written under the new one. + +The Unity manifest (`Packages/manifest.json`) still pins `caching-unity-v2.0.0` / `cultlib-unity-v2.0.1`; those move when CultLib +tags a Unity release of 3.0. Until then the editor and the headless build consume different CultLib revisions. diff --git a/tests/Aetheria.Shared.Tests/ElementIdBlind.cs b/tests/Aetheria.Shared.Tests/ElementIdBlind.cs new file mode 100644 index 000000000..6c340ea8f --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ElementIdBlind.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections; +using System.Linq; +using System.Reflection; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; + +// Element ids are minted at random when a record is written, so two writes of the same content differ in exactly those slots. +// A test that asks "is this the same content" compares the bytes with every element id blank. +public static class ElementIdBlind +{ + private static readonly MessagePackSerializerOptions Options = CultDocumentMessagePackSerialization.OptionsFor(typeof(ItemData).Assembly); + + // The document's bytes with every [CultElementId] member blank, on a copy: the document is untouched. + public static byte[] Pack(object document, Type type = null) + { + type ??= document.GetType(); + var copy = MessagePackSerializer.Deserialize(type, MessagePackSerializer.Serialize(type, document, Options), Options); + Blank(copy); + return MessagePackSerializer.Serialize(type, copy, Options); + } + + // A stored payload of the schema, re-encoded with every element id blank. + public static byte[] Payload(CultDocumentRegistry registry, string schemaId, byte[] payload) + { + var type = registry.GetRequiredBySchemaId(schemaId).DocumentType; + var value = MessagePackSerializer.Deserialize(type, payload, Options); + Blank(value); + return MessagePackSerializer.Serialize(type, value, Options); + } + + private static void Blank(object value) + { + if (value == null || value is string || value.GetType().IsPrimitive || value.GetType().IsEnum) return; + if (value is IEnumerable items && !(value is string)) + { + foreach (var item in items) Blank(item); + return; + } + for (var type = value.GetType(); type != null && type != typeof(object); type = type.BaseType) + foreach (var member in type.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)) + { + if (member is FieldInfo field) + { + if (field.GetCustomAttribute<CultElementIdAttribute>() != null) field.SetValue(value, ""); + else if (!field.FieldType.IsPrimitive && field.GetCustomAttribute<IgnoreMemberAttribute>() == null && field.GetCustomAttribute<KeyAttribute>() != null) + Blank(field.GetValue(value)); + } + else if (member is PropertyInfo property && property.GetIndexParameters().Length == 0 && property.GetCustomAttribute<KeyAttribute>() != null) + { + if (property.GetCustomAttribute<CultElementIdAttribute>() != null) property.SetValue(value, ""); + else Blank(property.GetValue(value)); + } + } + } +} diff --git a/tests/Aetheria.Shared.Tests/ElementIdUpgradeTests.cs b/tests/Aetheria.Shared.Tests/ElementIdUpgradeTests.cs new file mode 100644 index 000000000..7a38e4622 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ElementIdUpgradeTests.cs @@ -0,0 +1,56 @@ +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using GameCult.Caching; +using Xunit; + +// The CultLib pin that requires element ids (abd1a92e) reads the stores written before it (b8fc5eb0 and older), which carry none. +// The shipped GameData stores are those stores, byte for byte: they have never been rewritten under the new pin. +// Upgrading is one-way: once a store is written under the new pin it holds element ids, and an older pin can read it only by +// dropping them (CultLib #98). Readers upgrade before writers. +public class ElementIdUpgradeTests +{ + private static string Shipped => Path.Combine(RunStartTests.FindRepoRoot(), "GameData", "Aetheria.cc"); + + [Fact] + public async Task AStoreWrittenBeforeElementIdsOpensMintsThemOnceAndKeepsEveryRecord() + { + using var directory = new TempDirectory(); + var copy = Path.Combine(directory.Path, "Aetheria.cc"); + File.Copy(Shipped, copy); + + int records, minted; + using (var cache = AetheriaStores.Open(copy, catalogWritable: true, registry: TestCatalog.Registry())) + { + records = cache.AllStoredDocuments.Count(); + Assert.True(records > 0); + minted = cache.MintElementIds(); + Assert.True(minted > 0, "the shipped catalog predates element ids; opening it must have minted some"); + Assert.Equal(0, cache.MintElementIds()); + await cache.FlushAsync(); + } + + using var reopened = AetheriaStores.Open(copy, registry: TestCatalog.Registry()); + Assert.Equal(records, reopened.AllStoredDocuments.Count()); + Assert.Equal(0, reopened.MintElementIds()); + foreach (var hull in reopened.GetAll<HullData>()) + { + var ids = hull.Hardpoints.Select(hardpoint => hardpoint.Id).ToArray(); + Assert.All(ids, id => Assert.False(string.IsNullOrEmpty(id))); + Assert.Equal(ids.Length, ids.Distinct().Count()); + } + } + + [Fact] + public void EveryShippedModPackageStillLoads() + { + var packages = Directory.GetDirectories(Path.Combine(RunStartTests.FindRepoRoot(), "GameData", "Mods")); + Assert.NotEmpty(packages); + foreach (var package in packages) + { + var (hull, visual, _) = ShipAuthoringStore.Load(Path.Combine(package, "ship.cc")); + Assert.NotNull(hull); + Assert.NotNull(visual); + } + } +} diff --git a/tests/Aetheria.Shared.Tests/EmissionTests.cs b/tests/Aetheria.Shared.Tests/EmissionTests.cs index 831f6f520..da8d99e6d 100644 --- a/tests/Aetheria.Shared.Tests/EmissionTests.cs +++ b/tests/Aetheria.Shared.Tests/EmissionTests.cs @@ -281,7 +281,7 @@ public sealed partial class ContactRevealTests var reader = new MessagePackReader(sensor); Assert.Equal(2, reader.ReadArrayHeader()); Assert.Equal(5, reader.ReadInt32()); - Assert.Equal(14, reader.ReadArrayHeader()); + Assert.Equal(38, reader.ReadArrayHeader()); for (var slot = 0; slot < 13; slot++) reader.Skip(); Assert.Equal(2f, MessagePackSerializer.Deserialize<PerformanceStat>(ref reader, EmissionWire).Min); Assert.Equal(2f, JObject.Parse(JsonConvert.SerializeObject(new SensorData { InterceptFactor = Const(2) }))["interceptFactor"].ToObject<PerformanceStat>().Min); diff --git a/tests/Aetheria.Shared.Tests/InspectionScannerCommandTests.cs b/tests/Aetheria.Shared.Tests/InspectionScannerCommandTests.cs index e2d453f51..8dbc47873 100644 --- a/tests/Aetheria.Shared.Tests/InspectionScannerCommandTests.cs +++ b/tests/Aetheria.Shared.Tests/InspectionScannerCommandTests.cs @@ -22,7 +22,7 @@ public sealed class InspectionScannerCommandTests : IDisposable private readonly string[] _shippedProducts; private static byte[] Pack(GearData design) => - MessagePackSerializer.Serialize(design, CultDocumentMessagePackSerialization.OptionsFor(typeof(GearData).Assembly)); + ElementIdBlind.Pack(design, typeof(GearData)); private static string Describe(CultCache cache, FactionProductData product) => $"{cache.Get(product.Design).Name} | {product.Name} | {cache.Get(product.Manufacturer).ShortName} | {product.Description} | " + diff --git a/tests/Aetheria.Shared.Tests/LaunchSuppressorCommandTests.cs b/tests/Aetheria.Shared.Tests/LaunchSuppressorCommandTests.cs index 90c1d3873..47cc9a29e 100644 --- a/tests/Aetheria.Shared.Tests/LaunchSuppressorCommandTests.cs +++ b/tests/Aetheria.Shared.Tests/LaunchSuppressorCommandTests.cs @@ -22,7 +22,7 @@ public sealed class LaunchSuppressorCommandTests : IDisposable private readonly string[] _shippedProducts; private static byte[] Pack(GearData design) => - MessagePackSerializer.Serialize(design, CultDocumentMessagePackSerialization.OptionsFor(typeof(GearData).Assembly)); + ElementIdBlind.Pack(design, typeof(GearData)); private static string Describe(CultCache cache, FactionProductData product) => $"{cache.Get(product.Design).Name} | {product.Name} | {cache.Get(product.Manufacturer).ShortName} | {product.Description} | " + diff --git a/tests/Aetheria.Shared.Tests/LaunchSuppressorTests.cs b/tests/Aetheria.Shared.Tests/LaunchSuppressorTests.cs index eb2ed3ab8..d3dd3ae03 100644 --- a/tests/Aetheria.Shared.Tests/LaunchSuppressorTests.cs +++ b/tests/Aetheria.Shared.Tests/LaunchSuppressorTests.cs @@ -299,7 +299,7 @@ public sealed partial class ContactRevealTests var reader = new MessagePackReader(bytes); Assert.Equal(2, reader.ReadArrayHeader()); Assert.Equal(49, reader.ReadInt32()); // loot-2 holds 48; a key reused across branches would collide on the wire - Assert.Equal(4, reader.ReadArrayHeader()); // Group is key 0, then the three stats + Assert.Equal(38, reader.ReadArrayHeader()); // array-format union: the base's element id sits at key 37, so every behavior row is 38 long; Group is key 0, then the three stats var back = Assert.IsType<LaunchSuppressorData>(MessagePackSerializer.Deserialize<BehaviorData>(bytes, options)); Assert.Equal(.25f, back.Factor.Min); diff --git a/tests/Aetheria.Shared.Tests/ListenerTests.cs b/tests/Aetheria.Shared.Tests/ListenerTests.cs index 9fe4abf81..1bf1059ae 100644 --- a/tests/Aetheria.Shared.Tests/ListenerTests.cs +++ b/tests/Aetheria.Shared.Tests/ListenerTests.cs @@ -203,7 +203,7 @@ public sealed partial class ContactRevealTests var reader = new MessagePackReader(bytes); Assert.Equal(2, reader.ReadArrayHeader()); Assert.Equal(50, reader.ReadInt32()); - Assert.Equal(2, reader.ReadArrayHeader()); // Group is key 0, then Multiple + Assert.Equal(38, reader.ReadArrayHeader()); // array-format union: the base's element id sits at key 37, so every behavior row is 38 long; Group is key 0, then Multiple var back = Assert.IsType<ListenerData>(MessagePackSerializer.Deserialize<BehaviorData>(bytes, options)); Assert.Equal(2.5f, back.Multiple.Min); diff --git a/tests/Aetheria.Shared.Tests/PaintModeTests.cs b/tests/Aetheria.Shared.Tests/PaintModeTests.cs index 89b6fb39f..ab195813f 100644 --- a/tests/Aetheria.Shared.Tests/PaintModeTests.cs +++ b/tests/Aetheria.Shared.Tests/PaintModeTests.cs @@ -724,7 +724,7 @@ public sealed class PaintModeTests : IDisposable var reader = new MessagePackReader(bytes); Assert.Equal(2, reader.ReadArrayHeader()); Assert.Equal(5, reader.ReadInt32()); - Assert.Equal(14, reader.ReadArrayHeader()); + Assert.Equal(38, reader.ReadArrayHeader()); for (var slot = 0; slot < 12; slot++) reader.Skip(); Assert.Equal(90f, MessagePackSerializer.Deserialize<PerformanceStat>(ref reader, WireOptions).Min); diff --git a/tests/Aetheria.Shared.Tests/ScannerTests.cs b/tests/Aetheria.Shared.Tests/ScannerTests.cs index b470d2ae0..7184659b2 100644 --- a/tests/Aetheria.Shared.Tests/ScannerTests.cs +++ b/tests/Aetheria.Shared.Tests/ScannerTests.cs @@ -484,7 +484,7 @@ public sealed partial class ContactRevealTests var reader = new MessagePackReader(bytes); Assert.Equal(2, reader.ReadArrayHeader()); Assert.Equal(51, reader.ReadInt32()); // sensor-catalog holds 50; a key reused across branches would collide on the wire - Assert.Equal(4, reader.ReadArrayHeader()); // Group is key 0, then the three stats + Assert.Equal(38, reader.ReadArrayHeader()); // array-format union: the base's element id sits at key 37, so every behavior row is 38 long; Group is key 0, then the three stats reader.Skip(); Assert.Equal(200f, MessagePackSerializer.Deserialize<PerformanceStat>(ref reader, options).Min); // key 1 Range Assert.Equal(2f, MessagePackSerializer.Deserialize<PerformanceStat>(ref reader, options).Min); // key 2 ScanTime diff --git a/tests/Aetheria.Shared.Tests/ShipAuthoringTests.cs b/tests/Aetheria.Shared.Tests/ShipAuthoringTests.cs index 850e83dfd..7ed2b84be 100644 --- a/tests/Aetheria.Shared.Tests/ShipAuthoringTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipAuthoringTests.cs @@ -180,24 +180,20 @@ public sealed class ShipAuthoringTests Assert.IsAssignableFrom<MessagePackSerializationException>(pull.InnerException); } - // A store header with a nil format stamp is refused by the runtime with NotSupportedException; Load names the file. + // A store header with a nil format stamp is refused by the runtime with CultStoreUnreadableException; Load names the file. [Fact] public void LoadNamesTheFileWhoseFormatStampIsNil() { using var directory = new TempDirectory(); var path = Path.Combine(directory.Path, "nilstamp.cc"); - File.WriteAllBytes(path, CultDocumentMessagePackSerialization.SerializeSnapshot(new CultPersistedStoreSnapshot - { - FormatVersion = null, - SchemaCatalog = Array.Empty<CultSchemaCatalogEntry>(), - Records = Array.Empty<CultPersistedRecord>(), - })); + // The runtime no longer writes a store without a format stamp, so the header is spelled by hand: [nil, [], []]. + File.WriteAllBytes(path, new byte[] { 0x93, 0xC0, 0x90, 0x90 }); var error = Assert.Throws<InvalidOperationException>(() => ShipAuthoringStore.Load(path)); Assert.Contains(path, error.Message); - Assert.IsType<NotSupportedException>(error.InnerException); + Assert.IsType<CultStoreUnreadableException>(error.InnerException); } - // A store format this runtime does not know is refused on read with NotSupportedException from the attach; Load names the file. + // A store format this runtime does not know is refused on read with CultStoreUnreadableException from the attach; Load names the file. [Fact] public async Task LoadNamesTheFileWhoseStoreFormatIsNewer() { @@ -213,7 +209,7 @@ public sealed class ShipAuthoringTests File.WriteAllBytes(path, CultDocumentMessagePackSerialization.SerializeSnapshot(snapshot)); var error = Assert.Throws<InvalidOperationException>(() => ShipAuthoringStore.Load(path)); Assert.Contains(path, error.Message); - Assert.IsType<NotSupportedException>(error.InnerException); + Assert.IsType<CultStoreUnreadableException>(error.InnerException); } // Decodes one record's payload of the named schema to its slot array, lets the edit change it, and stores it again. diff --git a/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs b/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs index cbda4266b..f2b51496f 100644 --- a/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs @@ -796,7 +796,7 @@ public sealed class ShipModCatalogTests : IDisposable // Every stored record's key, schema and payload bytes. StoredAt is a write timestamp, not record content. private static Dictionary<string, string> Records(string path) => GameCult.Caching.MessagePack.CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(path)).Records - .ToDictionary(record => record.Key, record => record.SchemaId + ":" + Convert.ToHexString(record.Payload)); + .ToDictionary(record => record.Key, record => record.SchemaId + ":" + Convert.ToHexString(ElementIdBlind.Payload(TestCatalog.Registry(), record.SchemaId, record.Payload))); private void AssertOnlyTheDerivedFile() { diff --git a/tests/Aetheria.Shared.Tests/ShipProductTests.cs b/tests/Aetheria.Shared.Tests/ShipProductTests.cs index e14950b0d..82f094e88 100644 --- a/tests/Aetheria.Shared.Tests/ShipProductTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipProductTests.cs @@ -331,7 +331,7 @@ public sealed class ShipProductTests : IDisposable var path = Package("mod.skiff", "Skiffhull", 0); var bare = Path.Combine(ShipFixture.WritePackage(Mods, "mod.bare", "Barehull", tweak: ship => ship.Hull.Behaviors.Clear()), "ship.cc"); var twin = Path.Combine(ShipFixture.WritePackage(Mods, "mod.twin", "Twinhull", - tweak: ship => ship.Hull.Behaviors.Add(ship.Hull.Behaviors.OfType<VelocityLimitData>().First())), "ship.cc"); + tweak: ship => ship.Hull.Behaviors.Add(new VelocityLimitData())), "ship.cc"); void RefusedAndUntouched(string file, params string[] flags) { var before = File.ReadAllBytes(file); diff --git a/tests/Aetheria.Shared.Tests/ShipRigTests.cs b/tests/Aetheria.Shared.Tests/ShipRigTests.cs index 4bed1989b..34581f34a 100644 --- a/tests/Aetheria.Shared.Tests/ShipRigTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipRigTests.cs @@ -833,7 +833,7 @@ public sealed class ShipRigTests : IDisposable var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(HardpointData).Assembly); var hardpoint = new HardpointData { Type = HardpointType.Thruster, Shape = new Shape(), Transform = "t", FiringArc = 40f, Row = "left" }; var fields = MessagePackSerializer.Deserialize<object[]>(MessagePackSerializer.Serialize(hardpoint, options), options); - Assert.Equal(8, fields.Length); + Assert.Equal(9, fields.Length); Assert.Equal(40f, Convert.ToSingle(fields[6])); Assert.Equal("left", fields[7]); Assert.Null(MessagePackSerializer.Deserialize<object[]>(MessagePackSerializer.Serialize(new HardpointData { Shape = new Shape() }, options), options)[7]); @@ -842,7 +842,7 @@ public sealed class ShipRigTests : IDisposable thruster.Thrust.Max = 5f; thruster.Slew.Max = 90f; var slew = MessagePackSerializer.Deserialize<object[]>(MessagePackSerializer.Serialize(thruster, options), options); - Assert.Equal(7, slew.Length); + Assert.Equal(38, slew.Length); // the behavior base's element id is key 37 Assert.Equal(MessagePackSerializer.ConvertToJson(MessagePackSerializer.Serialize(thruster.Slew, options), options), MessagePackSerializer.ConvertToJson(MessagePackSerializer.Serialize(slew[6], options), options)); Assert.NotEqual(MessagePackSerializer.ConvertToJson(MessagePackSerializer.Serialize(thruster.Thrust, options), options), diff --git a/tests/Aetheria.Shared.Tests/SignatureTests.cs b/tests/Aetheria.Shared.Tests/SignatureTests.cs index 50d0bc824..21bdd7644 100644 --- a/tests/Aetheria.Shared.Tests/SignatureTests.cs +++ b/tests/Aetheria.Shared.Tests/SignatureTests.cs @@ -501,7 +501,7 @@ public sealed class SignatureTests : IDisposable var reader = new MessagePackReader(bytes); Assert.Equal(2, reader.ReadArrayHeader()); Assert.Equal(22, reader.ReadInt32()); - Assert.Equal(4, reader.ReadArrayHeader()); + Assert.Equal(38, reader.ReadArrayHeader()); reader.Skip(); // Group Assert.Equal(1f, MessagePackSerializer.Deserialize<PerformanceStat>(ref reader, Options).Min); Assert.Equal(2f, MessagePackSerializer.Deserialize<PerformanceStat>(ref reader, Options).Min); diff --git a/tests/Aetheria.Shared.Tests/SmokeRoundsCommandTests.cs b/tests/Aetheria.Shared.Tests/SmokeRoundsCommandTests.cs index 40a47eec6..83013d766 100644 --- a/tests/Aetheria.Shared.Tests/SmokeRoundsCommandTests.cs +++ b/tests/Aetheria.Shared.Tests/SmokeRoundsCommandTests.cs @@ -21,7 +21,7 @@ public sealed class SmokeRoundsCommandTests : IDisposable private readonly Dictionary<string, byte[]> _shipped = new Dictionary<string, byte[]>(); private static byte[] Pack(WeaponItemData design) => - MessagePackSerializer.Serialize(design, CultDocumentMessagePackSerialization.OptionsFor(typeof(WeaponItemData).Assembly)); + ElementIdBlind.Pack(design, typeof(WeaponItemData)); public SmokeRoundsCommandTests() { diff --git a/tests/Aetheria.Shared.Tests/VapourCloudTests.cs b/tests/Aetheria.Shared.Tests/VapourCloudTests.cs index 6945de2a8..3cd4ab34a 100644 --- a/tests/Aetheria.Shared.Tests/VapourCloudTests.cs +++ b/tests/Aetheria.Shared.Tests/VapourCloudTests.cs @@ -419,7 +419,7 @@ public sealed class VapourCloudTests : IDisposable var reader = new MessagePackReader(bytes); Assert.Equal(2, reader.ReadArrayHeader()); Assert.Equal(42, reader.ReadInt32()); - Assert.Equal(4, reader.ReadArrayHeader()); + Assert.Equal(38, reader.ReadArrayHeader()); reader.Skip(); Assert.Equal(1f, MessagePackSerializer.Deserialize<PerformanceStat>(ref reader, options).Min); Assert.Equal(2f, MessagePackSerializer.Deserialize<PerformanceStat>(ref reader, options).Min); diff --git a/tools/AetherDb/EconomyCommand.cs b/tools/AetherDb/EconomyCommand.cs index cf536cd9e..83349a1c0 100644 --- a/tools/AetherDb/EconomyCommand.cs +++ b/tools/AetherDb/EconomyCommand.cs @@ -45,6 +45,10 @@ public sealed class EconomyAuthor private void Write(Type type, object document, CultRecordKey key) { if (!_touched.Contains(key.Value)) _touched.Add(key.Value); + // A cache refuses to write one type onto a key another type holds (write ownership by written type): a batch that turns + // a compound good into a raw one removes the old record first. + var held = _catalog.Get(key); + if (held != null && held.GetType() != type) _catalog.Remove(key); _catalog.UpsertAsync(type, document, key).GetAwaiter().GetResult(); } } From 9512e35d6280223f852b9258dc9945e27ad543ae Mon Sep 17 00:00:00 2001 From: Nibu <nibu@gamecult.org> Date: Wed, 11 Nov 2026 09:57:46 +0000 Subject: [PATCH 050/190] EmissionTests: launcher row is 38 slots with the element id Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- tests/Aetheria.Shared.Tests/EmissionTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Aetheria.Shared.Tests/EmissionTests.cs b/tests/Aetheria.Shared.Tests/EmissionTests.cs index da8d99e6d..68ee5854d 100644 --- a/tests/Aetheria.Shared.Tests/EmissionTests.cs +++ b/tests/Aetheria.Shared.Tests/EmissionTests.cs @@ -291,7 +291,7 @@ public sealed partial class ContactRevealTests reader = new MessagePackReader(bytes); Assert.Equal(2, reader.ReadArrayHeader()); reader.Skip(); // the arm's union index - Assert.Equal(37, reader.ReadArrayHeader()); // 35 and 36 are the weapon base's EffectiveRange and DamageAtMaxRange + Assert.Equal(38, reader.ReadArrayHeader()); // 35 and 36 are the weapon base's EffectiveRange and DamageAtMaxRange, 37 the element id for (var slot = 0; slot < 34; slot++) reader.Skip(); Assert.Equal(3f, MessagePackSerializer.Deserialize<PerformanceStat>(ref reader, EmissionWire).Min); Assert.Equal(3f, JObject.Parse(JsonConvert.SerializeObject(new LauncherData { InterceptFactor = Const(3) }))["interceptFactor"].ToObject<PerformanceStat>().Min); From 6cb7b9455170e48404a87bbe112147b6cd65d51b Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 10:12:39 +0000 Subject: [PATCH 051/190] element-ids doc: the old pin refuses v3, shipped mod packages are not rewritable, Unity cannot compile the attribute yet Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- docs/element-ids.md | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/docs/element-ids.md b/docs/element-ids.md index 31cc92e17..386dcfc31 100644 --- a/docs/element-ids.md +++ b/docs/element-ids.md @@ -20,10 +20,15 @@ the registry refuses to open otherwise, naming the type and list. ## The bump is one-way -A store holding element ids is format v3 (single file) or v5 (directory). A pin older than `abd1a92e` can open a single-file v3 -store without error and drops the ids on its next write (CultLib #98). So: upgrade readers before writers, keep a pre-upgrade -copy of any real store (`GameData/Aetheria.cc` and the mod packages are tracked in git; player saves and run stores are not), -and do not roll the pin back after a store has been written under the new one. +A store holding element ids is format v3 (single file) or v5 (directory). The previous pin, `b8fc5eb0`, refuses a v3 store loudly +(`NotSupportedException: Store format cultcache.store.v3 is not readable`; checked by Soul on PR 12). CultLib #98 (`7002c252`) records +that some intermediate pins read a single-file v3 store silently and drop the ids on the next write. So: upgrade readers before +writers, keep a pre-upgrade copy of any real store (`GameData/Aetheria.cc` and the mod packages are tracked in git; player saves and +run stores are not), and do not roll the pin back after a store has been written under the new one. + +Shipped mod packages (`GameData/Mods/*/ship.cc`) hold values in retired `HullData` slots 21 and 22. They read, but the new CultLib +refuses to write over them (`CultSchemaConflictException`), so an in-place rewrite of those two files fails until their schema ids are +declared compatible or the files are regenerated. A rewritten catalog is about 15% larger: every behavior row is 38 slots, mostly nil. The Unity manifest (`Packages/manifest.json`) still pins `caching-unity-v2.0.0` / `cultlib-unity-v2.0.1`; those move when CultLib -tags a Unity release of 3.0. Until then the editor and the headless build consume different CultLib revisions. +tags a Unity release of 3.0. Until then the Unity editor cannot compile `[CultElementId]` (the plugin DLLs at those tags lack the attribute): this branch is headless-only and must not merge to master before a Unity-consumable CultLib exists. From 7675296ec4e1f64957a61b26e8369a2f51793625 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 13:09:14 +0000 Subject: [PATCH 052/190] Pin CultLib cultlib-unity-v3.0.0 (7225835d) and CultMath cultmath-unity-v0.5.1 (f1edfa45) in the manifest and the headless build The v3.0.0 plugin GameCult.Caching.dll exports CultElementIdAttribute; caching-unity stays at v2.0.0 (editor tooling, unchanged). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Directory.Build.props | 8 ++++---- Packages/manifest.json | 4 ++-- Packages/packages-lock.json | 10 +++++----- docs/aetheria-fauna-map.md | 2 +- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 66ff67e19..62160b34f 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -2,12 +2,12 @@ <PropertyGroup> <CultLibRoot Condition="'$(CultLibRoot)' == '' and '$(CULTLIB_ROOT)' != ''">$(CULTLIB_ROOT)</CultLibRoot> <CultLibRoot Condition="'$(CultLibRoot)' == ''">$(MSBuildThisFileDirectory)..\CultLib</CultLibRoot> - <!-- CultCache: abd1a92e (CultLib 3.0.0 unreleased; the Unity manifest tags still pin 2.0.x until a release is tagged). --> - <CultLibRevision>abd1a92eb24e1af3fc7cdd1bf98a88dbdebc2938</CultLibRevision> + <!-- CultCache: cultlib-unity-v3.0.0 in Packages/manifest.json. --> + <CultLibRevision>7225835d11fd08a3de2a2ef24742fc351b3b08fb</CultLibRevision> <CultMathRoot Condition="'$(CultMathRoot)' == '' and '$(CULTMATH_ROOT)' != ''">$(CULTMATH_ROOT)</CultMathRoot> <CultMathRoot Condition="'$(CultMathRoot)' == ''">$(CultLibRoot)</CultMathRoot> - <!-- CultMath: cultmath-unity-v0.5.0 in Packages/manifest.json. --> - <CultMathRevision>7a8933b085468e1fc6f9d3bce4a85e7d101aaca3</CultMathRevision> + <!-- CultMath: cultmath-unity-v0.5.1 in Packages/manifest.json. --> + <CultMathRevision>f1edfa458dd8e7e107214e9d9884254359475b8c</CultMathRevision> <GitExecutable Condition="'$(GitExecutable)' == '' and Exists('C:\Program Files\Git\cmd\git.exe')">C:\Program Files\Git\cmd\git.exe</GitExecutable> <GitExecutable Condition="'$(GitExecutable)' == ''">git</GitExecutable> </PropertyGroup> diff --git a/Packages/manifest.json b/Packages/manifest.json index 7693bd94f..ef01307a8 100644 --- a/Packages/manifest.json +++ b/Packages/manifest.json @@ -53,7 +53,7 @@ "com.unity.modules.wind": "1.0.0", "com.unity.modules.xr": "1.0.0", "org.gamecult.caching.unity": "https://github.com/GameCult/CultLib.git?path=/src/GameCult.Unity/Assets/Caching#caching-unity-v2.0.0", - "org.gamecult.cultlib": "https://github.com/GameCult/CultLib.git?path=/unity/org.gamecult.cultlib#cultlib-unity-v2.0.1", - "org.gamecult.cultmath": "https://github.com/GameCult/CultLib.git?path=/packages/cultmath/unity/org.gamecult.cultmath#cultmath-unity-v0.5.0" + "org.gamecult.cultlib": "https://github.com/GameCult/CultLib.git?path=/unity/org.gamecult.cultlib#cultlib-unity-v3.0.0", + "org.gamecult.cultmath": "https://github.com/GameCult/CultLib.git?path=/packages/cultmath/unity/org.gamecult.cultmath#cultmath-unity-v0.5.1" } } diff --git a/Packages/packages-lock.json b/Packages/packages-lock.json index 919cf94d1..4db845c3b 100644 --- a/Packages/packages-lock.json +++ b/Packages/packages-lock.json @@ -265,20 +265,20 @@ "hash": "42dce3611a81adc5c5fac54cadbaa5637d6022d3" }, "org.gamecult.cultlib": { - "version": "https://github.com/GameCult/CultLib.git?path=/unity/org.gamecult.cultlib#cultlib-unity-v2.0.1", + "version": "https://github.com/GameCult/CultLib.git?path=/unity/org.gamecult.cultlib#cultlib-unity-v3.0.0", "depth": 0, "source": "git", "dependencies": { - "org.gamecult.cultmath": "0.5.0" + "org.gamecult.cultmath": "0.5.1" }, - "hash": "b8fc5eb07720a187a0421424ac2cb3aa2966ca1d" + "hash": "7225835d11fd08a3de2a2ef24742fc351b3b08fb" }, "org.gamecult.cultmath": { - "version": "https://github.com/GameCult/CultLib.git?path=/packages/cultmath/unity/org.gamecult.cultmath#cultmath-unity-v0.5.0", + "version": "https://github.com/GameCult/CultLib.git?path=/packages/cultmath/unity/org.gamecult.cultmath#cultmath-unity-v0.5.1", "depth": 0, "source": "git", "dependencies": {}, - "hash": "7a8933b085468e1fc6f9d3bce4a85e7d101aaca3" + "hash": "f1edfa458dd8e7e107214e9d9884254359475b8c" }, "com.unity.modules.accessibility": { "version": "1.0.0", diff --git a/docs/aetheria-fauna-map.md b/docs/aetheria-fauna-map.md index 05034c92a..5276db97e 100644 --- a/docs/aetheria-fauna-map.md +++ b/docs/aetheria-fauna-map.md @@ -398,7 +398,7 @@ the lore branch `eureka/aetheria-fauna-lore` `74c7e212`, note `Open Water` (`OW` | # | Question | Result | |---|---|---| | B28 | What does CultMath already give a node library? | Integer PCG hashes `pcg`, `pcg3d`, `pcg4d` (Jarzynski and Olano), "integer-only, so dxc and C# agree bit for bit" (`packages/cultmath/src/CultMath/math.cs:393-426`, `shaders/CultMath.hlsl:396-426`). `cellular(float3)`: Worley F1 and F2 - F1 with analytic gradients, jitter from `pcg3d` of the integer cell, 3D, unweighted (`math.cs:849-975`, `CultMath.hlsl:440-503`). `smin_grad` (`math.cs:831-847`, `CultMath.hlsl:428-437`). `distance_to_segment` in C# only (`math.cs:319`; no HLSL twin). No weighted cellular, no diagram over explicit weighted sites, no site-graph gate. | -| B29 | How does CultMath own parity? | Two legs, one owner each (`packages/cultmath/docs/design.md:202-206`): HLSL against C# by the mirror test, which compiles the text of `CultMath.hlsl` as C# and compares float32 bit patterns (`design.md:118-124`), plus a clean `dxc -T lib_6_3` compile (`design.md:114-116`); GLSL against C# by golden fixtures run on a device. The mirror proves the composition in the text, not that a GPU agrees (`design.md:119-121`); device HLSL runs are consumers' today (Asura `gpu-snoise-parity`; Aetheria `FlowFieldParityVerify`). CultMath ships a Unity compute smoke (`packages/cultmath/scripts/unity-smoke/`). Aetheria pins `cultmath-unity-v0.5.0` (`Packages/manifest.json`). | +| B29 | How does CultMath own parity? | Two legs, one owner each (`packages/cultmath/docs/design.md:202-206`): HLSL against C# by the mirror test, which compiles the text of `CultMath.hlsl` as C# and compares float32 bit patterns (`design.md:118-124`), plus a clean `dxc -T lib_6_3` compile (`design.md:114-116`); GLSL against C# by golden fixtures run on a device. The mirror proves the composition in the text, not that a GPU agrees (`design.md:119-121`); device HLSL runs are consumers' today (Asura `gpu-snoise-parity`; Aetheria `FlowFieldParityVerify`). CultMath ships a Unity compute smoke (`packages/cultmath/scripts/unity-smoke/`). Aetheria pins `cultmath-unity-v0.5.1` (`Packages/manifest.json`). | | B30 | Does Aetheria already keep a math twin outside CultMath? | Yes. `FlowField` uses CultMath's `math`, but its `Tri`, `Tri3` and `Tri3D` are Aetheria functions (`FlowField.cs:66-72`) whose HLSL twin is `Volumetric.cginc`, pinned by Aetheria's own `FlowFieldParityVerify` (`RelativeTolerance` 1.5e-4). That is a second parity owner beside CultMath. | | B31 | What is parked in CultMath that a DAG would use? | The tape: steps 2-5 (expression graph lowered to bytecode with C# evaluators, pruning, an HLSL interpreter, meshing) are parked until Asura is stable (`docs/cultmath-tape-target.md:3-8`, ruling `tape-target-unparks-when-asura-stable`). "Truth and lowerings" (`:84-92`): the field is a typed CultCache document, and the CPU evaluator and the HLSL interpreter are lowerings of it. Step 1 (intervals) and affine forms are on main. | | B32 | Do the candidates make filaments? (`docs/research/2026-10-14-trophic-dag-probe/`, README there; wells orbit, slope terms on, t = 0) | `skein` draws strands between neighbouring wells, bent by the flow (`density_skein.png`); `lattice` draws a fine cellular web, dense on the shoulders, dim elsewhere, with no long links (`density_lattice.png`); `skein-web` draws both: strands from well to well with a web hanging off them (`density_skein-web.png`, `layer_L2-krill.png`). Correlation with the B20 Physarum map at 64x32 blocks (this measures the envelope, not filaments: a block is 62 u, wider than a strand): band .512, lattice .359, skein-web .296, krill .277, skein .225, slack .171. Hosted krill at 16 u: band 2,075, skein-web 1,475, skein 639, lattice 419. | From 344ef3265c88657ba5689a7269d69ed98605bae1 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 13:09:14 +0000 Subject: [PATCH 053/190] Regenerate the shipped mod ship.cc files off the retired HullData slots; blind element ids only where they are irrelevant AetherDb ship-authoring regenerate rewrites a package under the current schema and requires it to read back identical. ElementIdUpgradeTests gains content preservation and a shipped-packages-writable check; ShipModCatalogTests compares mod records unblinded where the same packages are composed twice. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- GameData/Mods/aetheria.nakovalnya/ship.cc | 4 +- GameData/Mods/aetheria.wren/ship.cc | 4 +- docs/element-ids.md | 23 +++--- .../ElementIdUpgradeTests.cs | 70 ++++++++++++++++++- .../ShipModCatalogTests.cs | 14 ++-- tools/AetherDb/ShipAuthoringCommands.cs | 36 +++++++++- 6 files changed, 133 insertions(+), 18 deletions(-) diff --git a/GameData/Mods/aetheria.nakovalnya/ship.cc b/GameData/Mods/aetheria.nakovalnya/ship.cc index ebe05cd33..1def7b776 100644 --- a/GameData/Mods/aetheria.nakovalnya/ship.cc +++ b/GameData/Mods/aetheria.nakovalnya/ship.cc @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:87d8cbcca252460d1ec2bfeb895c1447ab185172a4a4449b237a297b83ea5057 -size 40059 +oid sha256:0228aa7ec3a2e060bd49e46aa64f52eea4c4cdb25951c164646c1d031ad17851 +size 30457 diff --git a/GameData/Mods/aetheria.wren/ship.cc b/GameData/Mods/aetheria.wren/ship.cc index d81f9bba5..71b71ef5a 100644 --- a/GameData/Mods/aetheria.wren/ship.cc +++ b/GameData/Mods/aetheria.wren/ship.cc @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:6b1744dfa7dd6c5325ca3bd04fba941408cdc1255c06d1fc0d52fa67c97dc100 -size 10514 +oid sha256:096ea08f7fe85b44c343b57dfbc84fd82b2ec1d450cc1eb49efc3c238f9a9678 +size 10528 diff --git a/docs/element-ids.md b/docs/element-ids.md index 386dcfc31..87446b7e5 100644 --- a/docs/element-ids.md +++ b/docs/element-ids.md @@ -1,6 +1,6 @@ -# Element ids and the CultLib pin (abd1a92e) +# Element ids and the CultLib pin (cultlib-unity-v3.0.0) -CultLib 3.0 (unreleased; headless pin `abd1a92e`, `Directory.Build.props`) gives every element of an object list an identity. Every +CultLib 3.0.0 (Unity tag `cultlib-unity-v3.0.0`, commit `7225835d`, which is the headless pin in `Directory.Build.props`; CultMath `cultmath-unity-v0.5.1`, `f1edfa45`) gives every element of an object list an identity. Every element type reachable through a list of a `[CultDocument]` type carries one string member with `[Key(n)]` and `[CultElementId]`; the registry refuses to open otherwise, naming the type and list. @@ -20,15 +20,22 @@ the registry refuses to open otherwise, naming the type and list. ## The bump is one-way -A store holding element ids is format v3 (single file) or v5 (directory). The previous pin, `b8fc5eb0`, refuses a v3 store loudly +A store holding element ids is format v3 (single file) or v5 (directory). The previous pin (`cultlib-unity-v2.0.1`, `b8fc5eb0`) refuses a v3 store loudly (`NotSupportedException: Store format cultcache.store.v3 is not readable`; checked by Soul on PR 12). CultLib #98 (`7002c252`) records that some intermediate pins read a single-file v3 store silently and drop the ids on the next write. So: upgrade readers before writers, keep a pre-upgrade copy of any real store (`GameData/Aetheria.cc` and the mod packages are tracked in git; player saves and run stores are not), and do not roll the pin back after a store has been written under the new one. -Shipped mod packages (`GameData/Mods/*/ship.cc`) hold values in retired `HullData` slots 21 and 22. They read, but the new CultLib -refuses to write over them (`CultSchemaConflictException`), so an in-place rewrite of those two files fails until their schema ids are -declared compatible or the files are regenerated. A rewritten catalog is about 15% larger: every behavior row is 38 slots, mostly nil. +The shipped mod packages (`GameData/Mods/aetheria.wren/ship.cc`, `aetheria.nakovalnya/ship.cc`) once held values in the retired +`HullData` slots 21 and 22 (Wwise sound bank and audio stats), which the new CultLib refuses to write over +(`CultSchemaConflictException`). They were regenerated with `AetherDb ship-authoring regenerate <ship.cc> apply`, which loads the +records, writes them into a fresh file under the current schema, requires them to read back identical and replaces the file. Both +now hold persisted element ids and nil in slots 21 and 22; `EveryShippedModPackageCanBeWrittenOver` fails if a package regresses. +A mod file that fails the same way is regenerated the same way. A rewritten catalog is about 15% larger: every behavior row is 38 +slots, mostly nil. -The Unity manifest (`Packages/manifest.json`) still pins `caching-unity-v2.0.0` / `cultlib-unity-v2.0.1`; those move when CultLib -tags a Unity release of 3.0. Until then the Unity editor cannot compile `[CultElementId]` (the plugin DLLs at those tags lack the attribute): this branch is headless-only and must not merge to master before a Unity-consumable CultLib exists. +The Unity manifest (`Packages/manifest.json`) pins `org.gamecult.cultlib` at `cultlib-unity-v3.0.0` and `org.gamecult.cultmath` at +`cultmath-unity-v0.5.1` (the version v3.0.0 depends on). `org.gamecult.caching.unity` stays at `caching-unity-v2.0.0`: it is editor +tooling, unchanged in v3.0.0. The v3.0.0 plugin `GameCult.Caching.dll` exports `CultElementIdAttribute` (sealed, fields and +properties, one optional `derivedFrom` argument), the shape `ServerShared` uses. The Unity editor compile of this branch has not +been run; the headless build and tests are the evidence so far. diff --git a/tests/Aetheria.Shared.Tests/ElementIdUpgradeTests.cs b/tests/Aetheria.Shared.Tests/ElementIdUpgradeTests.cs index 7a38e4622..d94222635 100644 --- a/tests/Aetheria.Shared.Tests/ElementIdUpgradeTests.cs +++ b/tests/Aetheria.Shared.Tests/ElementIdUpgradeTests.cs @@ -1,10 +1,12 @@ +using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using GameCult.Caching; using Xunit; -// The CultLib pin that requires element ids (abd1a92e) reads the stores written before it (b8fc5eb0 and older), which carry none. +// CultLib 3.0 requires element ids and reads the stores written before it (2.0 and older), which carry none. // The shipped GameData stores are those stores, byte for byte: they have never been rewritten under the new pin. // Upgrading is one-way: once a store is written under the new pin it holds element ids, and an older pin can read it only by // dropping them (CultLib #98). Readers upgrade before writers. @@ -41,6 +43,31 @@ public class ElementIdUpgradeTests } } + // Upgrading assigns ids and changes nothing else: every record of the old-format file decodes, once the id members are + // blank, to the same bytes before and after the mint, flush and reopen. + [Fact] + public async Task UpgradingKeepsEveryFieldOfEveryRecordAndOnlyAddsIds() + { + using var directory = new TempDirectory(); + var copy = Path.Combine(directory.Path, "Aetheria.cc"); + File.Copy(Shipped, copy); + var registry = TestCatalog.Registry(); + Dictionary<string, string> Content(string path) => + GameCult.Caching.MessagePack.CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(path)).Records + .ToDictionary(record => record.Key, record => record.SchemaId + ":" + Convert.ToHexString(ElementIdBlind.Payload(registry, record.SchemaId, record.Payload))); + var before = Content(copy); + + using (var cache = AetheriaStores.Open(copy, catalogWritable: true, registry: TestCatalog.Registry())) + { + Assert.True(cache.MintElementIds() > 0); + await cache.FlushAsync(); + } + + var after = Content(copy); + Assert.Equal(before.Count, after.Count); + foreach (var record in before) Assert.True(after[record.Key] == record.Value, $"{record.Key} changed content when its element ids were minted"); + } + [Fact] public void EveryShippedModPackageStillLoads() { @@ -53,4 +80,45 @@ public class ElementIdUpgradeTests Assert.NotNull(visual); } } + + // A package whose file still holds a retired slot reads but cannot be written over (CultSchemaConflictException). + [Fact] + public void EveryShippedModPackageCanBeWrittenOver() + { + foreach (var package in Directory.GetDirectories(Path.Combine(RunStartTests.FindRepoRoot(), "GameData", "Mods"))) + { + using var directory = new TempDirectory(); + var copy = Path.Combine(directory.Path, "ship.cc"); + File.Copy(Path.Combine(package, "ship.cc"), copy); + var (hull, visual, products) = ShipAuthoringStore.Load(copy); + using (var cache = ShipAuthoringStore.Open(copy, writable: true)) + { + ShipAuthoringStore.Write(cache, hull, visual); + foreach (var product in products) ShipAuthoringStore.WriteProduct(cache, visual.Id, product); + cache.FlushAsync().GetAwaiter().GetResult(); + } + Assert.Equal(visual.Id, ShipAuthoringStore.Load(copy).Visual.Id); + } + } + + // The tool that regenerated the shipped packages: a dry run touches nothing, apply keeps every record's content. + [Fact] + public void RegenerateDryRunLeavesTheFileAndApplyKeepsTheContent() + { + using var directory = new TempDirectory(); + var copy = Path.Combine(directory.Path, "ship.cc"); + File.Copy(Path.Combine(RunStartTests.FindRepoRoot(), "GameData", "Mods", "aetheria.wren", "ship.cc"), copy); + var bytes = File.ReadAllBytes(copy); + var (hull, visual, products) = ShipAuthoringStore.Load(copy); + + Assert.Equal(0, ShipAuthoringCommands.Run(new[] { "regenerate", copy })); + Assert.Equal(bytes, File.ReadAllBytes(copy)); + Assert.Equal(0, ShipAuthoringCommands.Run(new[] { "regenerate", copy, "apply" })); + + var (hull2, visual2, products2) = ShipAuthoringStore.Load(copy); + Assert.Equal(ElementIdBlind.Pack(hull), ElementIdBlind.Pack(hull2)); + Assert.Equal(ElementIdBlind.Pack(visual), ElementIdBlind.Pack(visual2)); + Assert.Equal(products.Length, products2.Length); + Assert.Equal(new[] { copy }, Directory.GetFiles(directory.Path).Where(file => !file.EndsWith(".lock")).ToArray()); + } } diff --git a/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs b/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs index f2b51496f..f439eecc9 100644 --- a/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs @@ -624,7 +624,8 @@ public sealed class ShipModCatalogTests : IDisposable ShipModCatalog.Compose(Shipped, second, secondMods); ShipModCatalog.Compose(Shipped, Path.Combine(_directory.Path, "Derived3", "Aetheria.modded.cc"), firstMods); - Assert.Equal(Records(Derived), Records(second)); + // Two packages written separately carry separately minted ids: same content, ids blank. + Assert.Equal(Records(Derived, blindMods: true), Records(second, blindMods: true)); Assert.Equal(Records(Derived), Records(Path.Combine(_directory.Path, "Derived3", "Aetheria.modded.cc"))); Assert.Contains(ShipModCatalog.HullKey("mod.c").Value, Records(Derived).Keys); } @@ -793,10 +794,15 @@ public sealed class ShipModCatalogTests : IDisposable ShipModCatalog.PackageOf(cache, hull, Mods)).Message); } - // Every stored record's key, schema and payload bytes. StoredAt is a write timestamp, not record content. - private static Dictionary<string, string> Records(string path) => + // Every stored record's key, schema and payload bytes. StoredAt is a write timestamp, not record content. The shipped + // catalog holds no element ids, so each open mints new random ones for the records Compose copies from it; those are + // always compared with ids blank. A mod package's records carry the ids its ship.cc persisted and are compared as stored, + // unless the two sides are packages written separately (blindMods), where each write minted its own. + private static Dictionary<string, string> Records(string path, bool blindMods = false) => GameCult.Caching.MessagePack.CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(path)).Records - .ToDictionary(record => record.Key, record => record.SchemaId + ":" + Convert.ToHexString(ElementIdBlind.Payload(TestCatalog.Registry(), record.SchemaId, record.Payload))); + .ToDictionary(record => record.Key, record => record.SchemaId + ":" + Convert.ToHexString( + !blindMods && ShipModCatalog.IsModKey(new CultRecordKey(record.Key)) ? record.Payload + : ElementIdBlind.Payload(TestCatalog.Registry(), record.SchemaId, record.Payload))); private void AssertOnlyTheDerivedFile() { diff --git a/tools/AetherDb/ShipAuthoringCommands.cs b/tools/AetherDb/ShipAuthoringCommands.cs index 841da957e..458ae4038 100644 --- a/tools/AetherDb/ShipAuthoringCommands.cs +++ b/tools/AetherDb/ShipAuthoringCommands.cs @@ -1,4 +1,5 @@ using GameCult.Caching; +using GameCult.Caching.MessagePack; using System; using System.Collections.Generic; using System.Globalization; @@ -8,7 +9,7 @@ using System.Linq; // Uses the existing database executable; mod authoring does not earn another binary target. public static class ShipAuthoringCommands { - private const string Usage = "ship-authoring create <ship.cc> <stable-id> <name> [--like <shipped hull name>] | starter <mods-dir> <stable-id> <name> --like <shipped hull name> | inspect <ship.cc> | centre <ship.cc> | validate <ship.cc> | product <ship.cc> <maker> (--name <name> [--description <text>] [--not-offered] | --remove) | price <ship.cc> <price> | stats <ship.cc> [--mass m] [--durability d] [--armor a] [--drag x] [--top-speed v] | compose <shipped.cc> <derived.cc> <mods-dir>"; + private const string Usage = "ship-authoring create <ship.cc> <stable-id> <name> [--like <shipped hull name>] | starter <mods-dir> <stable-id> <name> --like <shipped hull name> | regenerate <ship.cc> [apply] | inspect <ship.cc> | centre <ship.cc> | validate <ship.cc> | product <ship.cc> <maker> (--name <name> [--description <text>] [--not-offered] | --remove) | price <ship.cc> <price> | stats <ship.cc> [--mass m] [--durability d] [--armor a] [--drag x] [--top-speed v] | compose <shipped.cc> <derived.cc> <mods-dir>"; private static readonly string[] StatFlags = { "--mass", "--durability", "--armor", "--drag", "--top-speed" }; @@ -84,6 +85,39 @@ public static class ShipAuthoringCommands Console.WriteLine($"Wrote a flyable starter package {path}; replace its stand-in model through Blender and Package, then set price and product."); return 0; } + if (args[0] == "regenerate" && (args.Length == 2 || args.Length == 3 && args[2] == "apply")) + { + // A package written before a record dropped a persisted slot cannot be written over (CultSchemaConflictException, + // retired slots stay read-only). Its decoded records go into a fresh file under today's schema, which must read + // back identical, and the fresh file replaces the old only with `apply`. Retired slots are the only content lost. + var (hull, ship, products) = ShipAuthoringStore.Load(args[1]); + var fresh = Path.GetFullPath(args[1]) + ".regenerating"; + File.Delete(fresh); + try + { + using (var cache = ShipAuthoringStore.Open(fresh, writable: true)) + { + ShipAuthoringStore.Write(cache, hull, ship); + foreach (var product in products) ShipAuthoringStore.WriteProduct(cache, ship.Id, product); + cache.FlushAsync().Wait(); + } + var (hull2, ship2, products2) = ShipAuthoringStore.Load(fresh); + ShipAuthoringStore.ValidateLoaded(hull2, ship2, products2); + var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(HullData).Assembly); + byte[] Pack<T>(T value) => MessagePack.MessagePackSerializer.Serialize(value, options); + var same = Pack(hull).AsSpan().SequenceEqual(Pack(hull2)) && Pack(ship).AsSpan().SequenceEqual(Pack(ship2)) && + products.Length == products2.Length && + products.OrderBy(p => p.Manufacturer.Key.Value, StringComparer.Ordinal).Zip( + products2.OrderBy(p => p.Manufacturer.Key.Value, StringComparer.Ordinal), + (a, b) => Pack(a).AsSpan().SequenceEqual(Pack(b))).All(equal => equal); + if (!same) throw new InvalidOperationException($"{ship.Id}: the regenerated file does not read back as the records that went in; {args[1]} is untouched."); + Console.WriteLine($"{ship.Id}: {new FileInfo(args[1]).Length} bytes -> {new FileInfo(fresh).Length} bytes, {hull.Hardpoints.Count} hardpoints, {ship.Anchors.Count} anchors, {products.Length} products read back identical."); + if (args.Length == 3) File.Move(fresh, args[1], overwrite: true); + else Console.WriteLine("Dry run; add apply to replace the file."); + } + finally { File.Delete(fresh); File.Delete(fresh + ".lock"); } + return 0; + } if (args[0] == "price" && args.Length == 3) { // Judged before the file is touched: a refusal leaves it byte-identical. From 7f148f08f13b4f0870809998e2d70febf7001e4a Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Wed, 11 Nov 2026 13:44:28 +0000 Subject: [PATCH 054/190] element-ids doc: retired slots held placeholders, and why nakovalnya shrank Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- docs/element-ids.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/element-ids.md b/docs/element-ids.md index 87446b7e5..b4ae9584a 100644 --- a/docs/element-ids.md +++ b/docs/element-ids.md @@ -26,13 +26,14 @@ that some intermediate pins read a single-file v3 store silently and drop the id writers, keep a pre-upgrade copy of any real store (`GameData/Aetheria.cc` and the mod packages are tracked in git; player saves and run stores are not), and do not roll the pin back after a store has been written under the new one. -The shipped mod packages (`GameData/Mods/aetheria.wren/ship.cc`, `aetheria.nakovalnya/ship.cc`) once held values in the retired -`HullData` slots 21 and 22 (Wwise sound bank and audio stats), which the new CultLib refuses to write over +The shipped mod packages (`GameData/Mods/aetheria.wren/ship.cc`, `aetheria.nakovalnya/ship.cc`) held only default +placeholders (`0` and `[]`) in the retired `HullData` slots 21 and 22, which the new CultLib refuses to write over (`CultSchemaConflictException`). They were regenerated with `AetherDb ship-authoring regenerate <ship.cc> apply`, which loads the records, writes them into a fresh file under the current schema, requires them to read back identical and replaces the file. Both now hold persisted element ids and nil in slots 21 and 22; `EveryShippedModPackageCanBeWrittenOver` fails if a package regresses. A mod file that fails the same way is regenerated the same way. A rewritten catalog is about 15% larger: every behavior row is 38 -slots, mostly nil. +slots, mostly nil. A regenerated ship package can still shrink: the old nakovalnya file stored its floats as float64 and the +fresh write stores the typed `float` fields as float32 (40059 to 30457 bytes; each value equals the old one rounded to float32). The Unity manifest (`Packages/manifest.json`) pins `org.gamecult.cultlib` at `cultlib-unity-v3.0.0` and `org.gamecult.cultmath` at `cultmath-unity-v0.5.1` (the version v3.0.0 depends on). `org.gamecult.caching.unity` stays at `caching-unity-v2.0.0`: it is editor From b367f80e6d13c9a9dae716d02f9065611c5bb510 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Thu, 12 Nov 2026 09:47:53 +0000 Subject: [PATCH 055/190] Credits screen: one attribution list in Shared, reachable from the main menu Twemoji, Playdead and the Noun Project icon credits, held against the licence files under Assets by CreditsTests. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/Credits.cs | 73 +++++++++++++++++ Assets/Scripts/ServerShared/Credits.cs.meta | 11 +++ Assets/Scripts/UI/MainMenu.cs | 32 ++++++++ tests/Aetheria.Shared.Tests/CreditsTests.cs | 89 +++++++++++++++++++++ 4 files changed, 205 insertions(+) create mode 100644 Assets/Scripts/ServerShared/Credits.cs create mode 100644 Assets/Scripts/ServerShared/Credits.cs.meta create mode 100644 tests/Aetheria.Shared.Tests/CreditsTests.cs diff --git a/Assets/Scripts/ServerShared/Credits.cs b/Assets/Scripts/ServerShared/Credits.cs new file mode 100644 index 000000000..3501ed2c9 --- /dev/null +++ b/Assets/Scripts/ServerShared/Credits.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +// The third-party attributions the shipped game must show the player. One list, owned here: the credits screen only +// renders it, and CreditsTests holds it against the licence files in Assets. Unity-free so the headless build checks it. +public class Credit +{ + public string Name; + public string Licence; + // What the licence requires shown: copyright holders, and any change notice. + public string Notice; + // The licence file in the repo that carries the full text and that this entry answers for. + public string LicenceFile; +} + +public static class Credits +{ + public const string TwemojiFile = "Assets/Fonts/Emoji/LICENSE.txt"; + public const string PlaydeadFile = "Assets/Plugins/Playdead/LICENSE.txt"; + public const string NounProjectFile = "Assets/Resources/Sprites/Attribution.txt"; + // Where the player build loads the Noun Project credit lines from (Resources path, no extension). + public const string NounProjectResource = "Sprites/Attribution"; + + // The full list. The Noun Project icon credits are the lines of its attribution file, whose text the caller supplies + // (Unity reads it as a Resources TextAsset; tests read it from disk), so the file stays the one copy of those names. + public static IReadOnlyList<Credit> All(string nounProjectAttribution) + { + var credits = new List<Credit> + { + new Credit + { + Name = "Twemoji", + Licence = "CC BY 4.0", + Notice = "Copyright (c) 2022-present Jason Sofonia & Justine De Caires; copyright (c) 2014-2021 Twitter. " + + "Graphics licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). " + + "Converted to a colour font; the artwork itself is not edited.", + LicenceFile = TwemojiFile + }, + new Credit + { + Name = "Playdead temporal anti-aliasing", + Licence = "MIT", + Notice = "Copyright (c) 2015 Playdead", + LicenceFile = PlaydeadFile + }, + new Credit + { + Name = "Noun Project icons", + Licence = "Noun Project attribution licence", + Notice = string.Join("\n", NounProjectLines(nounProjectAttribution)), + LicenceFile = NounProjectFile + } + }; + Validate(credits); + return credits; + } + + // The icon credit lines of the attribution file: everything after its "Noun Project" heading. + public static IEnumerable<string> NounProjectLines(string attribution) => + (attribution ?? "").Split('\n').Select(line => line.Trim()).Where(line => line.Length > 0).Skip(1); + + // Throws on an entry a player-facing screen could not honestly show. + public static void Validate(IReadOnlyList<Credit> credits) + { + foreach (var credit in credits) + if (string.IsNullOrWhiteSpace(credit.Name) || string.IsNullOrWhiteSpace(credit.Licence) || + string.IsNullOrWhiteSpace(credit.Notice) || string.IsNullOrWhiteSpace(credit.LicenceFile)) + throw new InvalidOperationException($"Credit '{credit.Name}' is missing its name, licence, notice or licence file"); + var duplicate = credits.GroupBy(credit => credit.LicenceFile).FirstOrDefault(group => group.Count() > 1); + if (duplicate != null) throw new InvalidOperationException($"Licence file {duplicate.Key} is credited twice"); + } +} diff --git a/Assets/Scripts/ServerShared/Credits.cs.meta b/Assets/Scripts/ServerShared/Credits.cs.meta new file mode 100644 index 000000000..e88730bb6 --- /dev/null +++ b/Assets/Scripts/ServerShared/Credits.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b3333d3c0203441fbadd64fad27b60e5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/UI/MainMenu.cs b/Assets/Scripts/UI/MainMenu.cs index 9eef387ca..88600e516 100644 --- a/Assets/Scripts/UI/MainMenu.cs +++ b/Assets/Scripts/UI/MainMenu.cs @@ -136,9 +136,41 @@ public class MainMenu : MonoBehaviour ShowSettings(); Fade(true); }); + _nextMenu.panel.AddButton("Credits", + () => + { + ShowCredits(); + Fade(true); + }); _nextMenu.panel.AddButton("Quit", Application.Quit); } + // The third-party attributions the build must show, one button per entry with its notice in the detail pane. The + // list is Credits.All; this only renders it. + private void ShowCredits() + { + var credits = Credits.All(Resources.Load<TextAsset>(Credits.NounProjectResource).text); + Next("credits"); + _nextMenu.detail.gameObject.SetActive(true); + _nextMenu.detail.Title.text = _nextMenu.panel.Title.text; + _nextMenu.detail.Title.color = Color.clear; + var selected = 0; + _nextMenu.detail.AddProperty(() => credits[selected].Name); + _nextMenu.detail.AddProperty(() => credits[selected].Licence); + _nextMenu.detail.AddProperty(() => credits[selected].Notice); + for (var i = 0; i < credits.Count; i++) + { + var index = i; + _nextMenu.panel.AddButton(credits[i].Name, () => selected = index); + } + _nextMenu.panel.AddButton("Back", + () => + { + ShowMain(); + Fade(false); + }); + } + // New Game: every way to set up a run, each with its brief. A release build lists only the modes; the other ways // to set up a run and the test arenas are listed only in editor and development builds. private void ShowScenarios() diff --git a/tests/Aetheria.Shared.Tests/CreditsTests.cs b/tests/Aetheria.Shared.Tests/CreditsTests.cs new file mode 100644 index 000000000..8f2691cf7 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/CreditsTests.cs @@ -0,0 +1,89 @@ +using System; +using System.IO; +using System.Linq; +using Xunit; + +namespace Aetheria.Shared.Tests +{ + // The credits list against the repo's own licence files and the main menu that must reach it. + public class CreditsTests + { + private static string Root() + { + var dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir != null && !File.Exists(Path.Combine(dir.FullName, "Assets", "Scripts", "UI", "MainMenu.cs"))) dir = dir.Parent; + return dir?.FullName ?? throw new InvalidOperationException("repo root not found"); + } + + private static string Read(string relative) => File.ReadAllText(Path.Combine(Root(), relative)); + + private static System.Collections.Generic.IReadOnlyList<Credit> Load() => Credits.All(Read(Credits.NounProjectFile)); + + [Fact] + public void EveryLicenceFileUnderAssetsIsCredited() + { + var root = Root(); + var found = Directory.EnumerateFiles(Path.Combine(root, "Assets"), "*", SearchOption.AllDirectories) + .Where(path => !path.EndsWith(".meta")) + .Where(path => { var name = Path.GetFileName(path); return name.StartsWith("LICENSE", StringComparison.OrdinalIgnoreCase) || name.StartsWith("Attribution", StringComparison.OrdinalIgnoreCase); }) + .Select(path => Path.GetRelativePath(root, path).Replace('\\', '/')) + .ToArray(); + Assert.Contains(Credits.TwemojiFile, found); + var credited = Load().Select(credit => credit.LicenceFile).ToHashSet(); + Assert.Empty(found.Where(path => !credited.Contains(path))); + Assert.Empty(credited.Where(path => !File.Exists(Path.Combine(root, path)))); + } + + [Fact] + public void TwemojiComesFirstWithTheHoldersItsLicenceNames() + { + var twemoji = Load()[0]; + Assert.Equal("Twemoji", twemoji.Name); + Assert.Contains("CC BY 4.0", twemoji.Licence); + Assert.Contains("Jason Sofonia & Justine De Caires", Read(Credits.TwemojiFile)); + Assert.Contains("Jason Sofonia & Justine De Caires", twemoji.Notice); + Assert.Contains("Twitter", twemoji.Notice); + } + + [Fact] + public void EveryIconCreditInTheAttributionFileIsShown() + { + var lines = Credits.NounProjectLines(Read(Credits.NounProjectFile)).ToArray(); + Assert.True(lines.Length > 50); + var notice = Load().Single(credit => credit.LicenceFile == Credits.NounProjectFile).Notice.Split('\n'); + Assert.Equal(lines, notice); + } + + [Fact] + public void EntriesNameTheirLicenceAndHolder() + { + foreach (var credit in Load()) + { + Assert.False(string.IsNullOrWhiteSpace(credit.Name)); + Assert.False(string.IsNullOrWhiteSpace(credit.Licence)); + Assert.False(string.IsNullOrWhiteSpace(credit.Notice)); + } + Assert.Contains("Playdead", Read(Credits.PlaydeadFile)); + Assert.Contains("Playdead", Load().Single(credit => credit.LicenceFile == Credits.PlaydeadFile).Notice); + } + + [Fact] + public void AnEmptyEntryIsRefused() + { + Assert.Throws<InvalidOperationException>(() => Credits.Validate(new[] { new Credit { Name = "x", Licence = "", Notice = "n", LicenceFile = "f" } })); + } + + // The Unity menu is not compilable headlessly, so this reads its source: the main menu must offer Credits and + // the Credits screen must render the Shared list. It proves the wiring exists, not that the screen draws. + [Fact] + public void MainMenuOffersACreditsPathThatRendersTheList() + { + var menu = Read("Assets/Scripts/UI/MainMenu.cs"); + var main = menu.Substring(menu.IndexOf("private void ShowMain()", StringComparison.Ordinal)); + main = main.Substring(0, main.IndexOf("private void ShowScenarios()", StringComparison.Ordinal)); + Assert.Contains("AddButton(\"Credits\"", main); + Assert.Contains("ShowCredits()", main); + Assert.Contains("Credits.All(", menu); + } + } +} From 16cb82d096dabec3007396b8069bbf4ab9b155e8 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Thu, 12 Nov 2026 12:43:50 +0000 Subject: [PATCH 056/190] Credits: credit every third-party work whose own text states holder and licence; test discovers all licence-like files Adds Liberation Sans (OFL), UniRx, KDTree, webgl-noise simplex noise and ambientCG to the list. CreditsTests now matches LICEN[CS]E, COPYING, NOTICE, README, SOURCES, OFL files under Assets and requires each to be credited or listed as reviewed-not-credited with a reason; credit notices are checked against what their files state. The attribution heading is checked rather than skipped, the test states independent expectations, and the split Hurricane line is joined. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Resources/Sprites/Attribution.txt | 3 +- Assets/Scripts/ServerShared/Credits.cs | 58 +++++++- tests/Aetheria.Shared.Tests/CreditsTests.cs | 154 +++++++++++++++++--- 3 files changed, 189 insertions(+), 26 deletions(-) diff --git a/Assets/Resources/Sprites/Attribution.txt b/Assets/Resources/Sprites/Attribution.txt index 666742406..8ca89fb1b 100644 --- a/Assets/Resources/Sprites/Attribution.txt +++ b/Assets/Resources/Sprites/Attribution.txt @@ -2,8 +2,7 @@ Noun Project Tornado by Bart Laubsch Alien Abduction by Bart Laubsch -Hurricane by icon 54 from -Smashicons Space by Ben Davis +Hurricane by icon 54 from Smashicons Space by Ben Davis Space 2 - Solid by Ben Davis Filter by Karthik Aathis Search by il Capitano diff --git a/Assets/Scripts/ServerShared/Credits.cs b/Assets/Scripts/ServerShared/Credits.cs index 3501ed2c9..3bb0af84b 100644 --- a/Assets/Scripts/ServerShared/Credits.cs +++ b/Assets/Scripts/ServerShared/Credits.cs @@ -19,6 +19,13 @@ public static class Credits public const string TwemojiFile = "Assets/Fonts/Emoji/LICENSE.txt"; public const string PlaydeadFile = "Assets/Plugins/Playdead/LICENSE.txt"; public const string NounProjectFile = "Assets/Resources/Sprites/Attribution.txt"; + public const string LiberationFile = "Assets/TextMesh Pro/Fonts/LiberationSans - OFL.txt"; + public const string UniRxFile = "Assets/Plugins/UniRx/ReadMe.txt"; + public const string AmbientCgFile = "Assets/Materials/PBR/SOURCES.md"; + public const string KdTreeFile = "Assets/Scripts/ServerShared/NIH/KDTree/KDTree.cs"; + public const string SimplexNoiseFile = "Assets/Plugins/GPU Noise/SimplexNoise2D.cginc"; + // The first line of the attribution file; the icon credits are the lines after it. + public const string NounProjectHeading = "Noun Project"; // Where the player build loads the Noun Project credit lines from (Resources path, no extension). public const string NounProjectResource = "Sprites/Attribution"; @@ -45,6 +52,44 @@ public static class Credits LicenceFile = PlaydeadFile }, new Credit + { + Name = "Liberation Sans", + Licence = "SIL Open Font License 1.1", + Notice = "Digitized data copyright (c) 2010 Google Corporation with Reserved Font Arimo, Tinos and Cousine. " + + "Copyright (c) 2012 Red Hat, Inc. with Reserved Font Name Liberation.", + LicenceFile = LiberationFile + }, + new Credit + { + Name = "UniRx", + Licence = "MIT", + Notice = "Created by Yoshifumi Kawai (neuecc)", + LicenceFile = UniRxFile + }, + new Credit + { + Name = "KDTree", + Licence = "MIT", + Notice = "Copyright (c) 2018 Vili Volčini / viliwonka", + LicenceFile = KdTreeFile + }, + new Credit + { + Name = "webgl-noise simplex noise", + Licence = "MIT", + Notice = "Copyright (C) 2011 Ashima Arts. Author: Ian McEwan, Ashima Arts " + + "(https://github.com/ashima/webgl-noise). Translated to Unity shaders and modified by Keijiro Takahashi " + + "(https://github.com/keijiro/NoiseShader).", + LicenceFile = SimplexNoiseFile + }, + new Credit + { + Name = "ambientCG PBR materials", + Licence = "CC0 1.0 Universal", + Notice = "Texture sets from ambientCG (https://ambientcg.com), public domain", + LicenceFile = AmbientCgFile + }, + new Credit { Name = "Noun Project icons", Licence = "Noun Project attribution licence", @@ -56,9 +101,16 @@ public static class Credits return credits; } - // The icon credit lines of the attribution file: everything after its "Noun Project" heading. - public static IEnumerable<string> NounProjectLines(string attribution) => - (attribution ?? "").Split('\n').Select(line => line.Trim()).Where(line => line.Length > 0).Skip(1); + // The icon credit lines of the attribution file: everything after its "Noun Project" heading, one line per icon (the + // file's "Other" sub-heading and its lines follow in the same list). A file that does not open with the heading is + // refused rather than having its first line dropped. + public static IEnumerable<string> NounProjectLines(string attribution) + { + var lines = (attribution ?? "").Split('\n').Select(line => line.Trim()).Where(line => line.Length > 0).ToArray(); + if (lines.Length < 2 || lines[0] != NounProjectHeading) + throw new InvalidOperationException($"{NounProjectFile} must open with the heading '{NounProjectHeading}' followed by icon credits"); + return lines.Skip(1); + } // Throws on an entry a player-facing screen could not honestly show. public static void Validate(IReadOnlyList<Credit> credits) diff --git a/tests/Aetheria.Shared.Tests/CreditsTests.cs b/tests/Aetheria.Shared.Tests/CreditsTests.cs index 8f2691cf7..b346f1fca 100644 --- a/tests/Aetheria.Shared.Tests/CreditsTests.cs +++ b/tests/Aetheria.Shared.Tests/CreditsTests.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Linq; +using System.Text.RegularExpressions; using Xunit; namespace Aetheria.Shared.Tests @@ -19,41 +20,151 @@ namespace Aetheria.Shared.Tests private static System.Collections.Generic.IReadOnlyList<Credit> Load() => Credits.All(Read(Credits.NounProjectFile)); - [Fact] - public void EveryLicenceFileUnderAssetsIsCredited() + // A file under Assets that looks like a licence, attribution, notice, readme or sources list. Each one is either + // credited (the credit names it as its LicenceFile) or reviewed below with the reason it is not. + private static readonly Regex LicenceLike = new Regex( + @"^(LICEN[CS]E|COPYING|NOTICE|README|SOURCES|_SOURCES|Attribution)|OFL", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + private static readonly string[] SkippedDirectories = { "bin", "obj", "Library" }; + + // Discovered files whose own text names no holder and no licence, so there is nothing true to credit. A new + // licence-like file is not here until someone has read it and written the reason. + private static readonly System.Collections.Generic.Dictionary<string, string> ReviewedNotCredited = new System.Collections.Generic.Dictionary<string, string> + { + ["Assets/Scripts/ServerShared/NIH/LinqFaster/readme.txt"] = "usage guide for LinqFaster; names no holder and no licence", + ["Assets/Plugins/LowPoly_AsteroidsPack/README.pdf"] = "how to customise the asteroid pack; names no holder and no licence", + ["Assets/Plugins/Celestial Body/Textures/_Sources.txt"] = "URLs of the source textures only; states no licence", + }; + + // Bundled works with no licence-like file at all, found by reading Assets. Their licences are not stated in the + // repo, so they are not credited; each path must still exist, so this list cannot go stale unnoticed. + private static readonly string[] UnlicensedWorks = + { + "Assets/Fonts/Ubuntu", + "Assets/Fonts/Retro", + "Assets/Plugins/Ink", + "Assets/Plugins/GPUTrail", + "Assets/Plugins/com.unity.uiextensions", + "Assets/Shaders/StableFluids", + }; + + // What each credited file itself states, written here independently of the credit text: these strings must + // appear in the file and in the credit's notice. + private static readonly (string file, string[] stated)[] Holders = + { + (Credits.TwemojiFile, new[] { "Jason Sofonia & Justine De Caires", "Twitter", "CC BY 4.0" }), + (Credits.PlaydeadFile, new[] { "Playdead" }), + (Credits.LiberationFile, new[] { "Google Corporation", "Red Hat, Inc." }), + (Credits.UniRxFile, new[] { "Yoshifumi Kawai" }), + (Credits.KdTreeFile, new[] { "Vili Vol\u010dini / viliwonka" }), + (Credits.SimplexNoiseFile, new[] { "Ashima Arts", "Ian McEwan", "Keijiro Takahashi" }), + (Credits.AmbientCgFile, new[] { "ambientCG" }), + }; + + private static string[] LicenceLikeFiles() { var root = Root(); - var found = Directory.EnumerateFiles(Path.Combine(root, "Assets"), "*", SearchOption.AllDirectories) + return Directory.EnumerateFiles(Path.Combine(root, "Assets"), "*", SearchOption.AllDirectories) .Where(path => !path.EndsWith(".meta")) - .Where(path => { var name = Path.GetFileName(path); return name.StartsWith("LICENSE", StringComparison.OrdinalIgnoreCase) || name.StartsWith("Attribution", StringComparison.OrdinalIgnoreCase); }) .Select(path => Path.GetRelativePath(root, path).Replace('\\', '/')) + .Where(path => !path.Split('/').Any(segment => SkippedDirectories.Contains(segment))) + .Where(path => LicenceLike.IsMatch(Path.GetFileName(path))) + .OrderBy(path => path, StringComparer.Ordinal) .ToArray(); - Assert.Contains(Credits.TwemojiFile, found); - var credited = Load().Select(credit => credit.LicenceFile).ToHashSet(); - Assert.Empty(found.Where(path => !credited.Contains(path))); - Assert.Empty(credited.Where(path => !File.Exists(Path.Combine(root, path)))); } + // The ways a licence-like file can be accounted for; shared so the mutations in the report hit the same rule. + private static string[] Unaccounted(string[] found, System.Collections.Generic.IEnumerable<string> credited) => + found.Where(path => !credited.Contains(path) && !ReviewedNotCredited.ContainsKey(path)).ToArray(); + [Fact] - public void TwemojiComesFirstWithTheHoldersItsLicenceNames() + public void EveryLicenceLikeFileUnderAssetsIsCreditedOrReviewed() + { + var root = Root(); + var found = LicenceLikeFiles(); + Assert.Contains(Credits.TwemojiFile, found); + Assert.Contains(Credits.LiberationFile, found); + var credited = Load().Select(credit => credit.LicenceFile).ToArray(); + Assert.Equal(Array.Empty<string>(), Unaccounted(found, credited)); + Assert.Equal(Array.Empty<string>(), credited.Where(path => !File.Exists(Path.Combine(root, path))).ToArray()); + Assert.Equal(Array.Empty<string>(), ReviewedNotCredited.Keys.Where(path => !found.Contains(path)).ToArray()); + Assert.Equal(Array.Empty<string>(), ReviewedNotCredited.Keys.Where(path => credited.Contains(path)).ToArray()); + Assert.Equal(Array.Empty<string>(), UnlicensedWorks.Where(path => !Directory.Exists(Path.Combine(root, path))).ToArray()); + } + + // Every holder the licence file states is in the credit that answers for it; the notices are typed into + // Credits.cs, so this is what keeps them true to the files. + [Fact] + public void EveryCreditShowsTheHoldersItsOwnFileStates() + { + var credits = Load(); + Assert.Equal(Holders.Select(h => h.file).Append(Credits.NounProjectFile).OrderBy(f => f, StringComparer.Ordinal), + credits.Select(credit => credit.LicenceFile).OrderBy(f => f, StringComparer.Ordinal)); + foreach (var (file, stated) in Holders) + { + var text = Normal(Read(file)); + var notice = Normal(credits.Single(credit => credit.LicenceFile == file).Notice); + foreach (var holder in stated) + { + Assert.True(text.Contains(Normal(holder)), $"{file} does not state '{holder}'"); + Assert.True(notice.Contains(Normal(holder)), $"the credit for {file} omits '{holder}'"); + } + // And every copyright line the file carries, whatever the table above says. + foreach (var line in Read(file).Split('\n')) + { + var match = CopyrightLine.Match(line); + if (!match.Success) continue; + var body = Regex.Replace(match.Groups[1].Value.Replace("[", "").Replace("]", "").Trim(), @"(\s*All rights reserved)?\.?$", "", RegexOptions.IgnoreCase); + Assert.True(notice.Contains(Normal(body)), $"the credit for {file} omits its copyright line '{body}'"); + } + } + } + + private static readonly Regex CopyrightLine = new Regex(@"copyright\s*(?:\(c\)|\u00a9)?\s*(\[?\d.*)$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + // Dash variants and case folded, so the file's en dash and the screen's hyphen compare equal. + private static string Normal(string text) => text.Replace('\u2013', '-').Replace('\u2014', '-').Replace("\r", "").ToLowerInvariant(); + + [Fact] + public void TwemojiComesFirst() { var twemoji = Load()[0]; Assert.Equal("Twemoji", twemoji.Name); Assert.Contains("CC BY 4.0", twemoji.Licence); - Assert.Contains("Jason Sofonia & Justine De Caires", Read(Credits.TwemojiFile)); - Assert.Contains("Jason Sofonia & Justine De Caires", twemoji.Notice); - Assert.Contains("Twitter", twemoji.Notice); } + // The expectations are stated here, not derived from the parser: 81 icon credits between the heading and the + // "Other" sub-heading's two artists, named at the ends and at the line that was once split across two. [Fact] public void EveryIconCreditInTheAttributionFileIsShown() { - var lines = Credits.NounProjectLines(Read(Credits.NounProjectFile)).ToArray(); - Assert.True(lines.Length > 50); + var text = Read(Credits.NounProjectFile); + Assert.StartsWith(Credits.NounProjectHeading, text.TrimStart('\uFEFF')); + var lines = Credits.NounProjectLines(text).ToArray(); + Assert.Equal(82, lines.Length); + Assert.Equal("Tornado by Bart Laubsch", lines[0]); + Assert.Equal("Alien Abduction by Bart Laubsch", lines[1]); + Assert.Equal("Hurricane by icon 54 from Smashicons Space by Ben Davis", lines[2]); + Assert.Equal("Space 2 - Solid by Ben Davis", lines[3]); + Assert.Contains("Other", lines); + Assert.Equal("Missile War Weapon by Freepik", lines[^1]); + // One credit per line: every line but the sub-heading names an artist and does not stop mid-sentence. + foreach (var line in lines.Where(line => line != "Other")) + { + Assert.Contains(" by ", line, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotMatch(@"\s(from|by)$", line); + } var notice = Load().Single(credit => credit.LicenceFile == Credits.NounProjectFile).Notice.Split('\n'); Assert.Equal(lines, notice); } + [Fact] + public void AnAttributionFileWithoutItsHeadingIsRefused() + { + Assert.Throws<InvalidOperationException>(() => Credits.NounProjectLines("Tornado by Bart Laubsch\nAlien Abduction by Bart Laubsch").ToArray()); + Assert.Throws<InvalidOperationException>(() => Credits.NounProjectLines("Noun Project\n\n").ToArray()); + } + [Fact] public void EntriesNameTheirLicenceAndHolder() { @@ -63,8 +174,6 @@ namespace Aetheria.Shared.Tests Assert.False(string.IsNullOrWhiteSpace(credit.Licence)); Assert.False(string.IsNullOrWhiteSpace(credit.Notice)); } - Assert.Contains("Playdead", Read(Credits.PlaydeadFile)); - Assert.Contains("Playdead", Load().Single(credit => credit.LicenceFile == Credits.PlaydeadFile).Notice); } [Fact] @@ -73,17 +182,20 @@ namespace Aetheria.Shared.Tests Assert.Throws<InvalidOperationException>(() => Credits.Validate(new[] { new Credit { Name = "x", Licence = "", Notice = "n", LicenceFile = "f" } })); } - // The Unity menu is not compilable headlessly, so this reads its source: the main menu must offer Credits and - // the Credits screen must render the Shared list. It proves the wiring exists, not that the screen draws. + // The Unity menu is not compilable headlessly, so this reads its source with comments removed (a commented-out + // button or call must not satisfy it): the main menu must offer Credits, and ShowCredits must build the Shared + // list. It proves the wiring exists, not that the screen draws. [Fact] public void MainMenuOffersACreditsPathThatRendersTheList() { - var menu = Read("Assets/Scripts/UI/MainMenu.cs"); + var menu = Regex.Replace(Read("Assets/Scripts/UI/MainMenu.cs"), @"/\*.*?\*/|//[^\n]*", "", RegexOptions.Singleline); var main = menu.Substring(menu.IndexOf("private void ShowMain()", StringComparison.Ordinal)); - main = main.Substring(0, main.IndexOf("private void ShowScenarios()", StringComparison.Ordinal)); + main = main.Substring(0, main.IndexOf("private void ShowCredits()", StringComparison.Ordinal)); Assert.Contains("AddButton(\"Credits\"", main); Assert.Contains("ShowCredits()", main); - Assert.Contains("Credits.All(", menu); + var credits = menu.Substring(menu.IndexOf("private void ShowCredits()", StringComparison.Ordinal)); + credits = credits.Substring(0, credits.IndexOf("private void ShowScenarios()", StringComparison.Ordinal)); + Assert.Contains("Credits.All(", credits); } } } From 390b4c7a457bff9bd87e2e4149f0057cea7d8832 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Thu, 12 Nov 2026 12:48:52 +0000 Subject: [PATCH 057/190] Credits screen: one row per notice line, refuse a missing attribution file, follow the New Game focus handling ShowCredits renders the selected credit as property rows instead of one multi-line label, refuses with a dialog when the attribution TextAsset is missing or malformed, takes list rows out of automatic navigation, steps with Up/Down on the focused Back button and leaves on Cancel. ScenarioPicker's focus hold moves to FocusHold so both screens share it. The menu wiring test now strips comments before matching. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/UI/MainMenu.cs | 80 +++++++++++++++------ Assets/Scripts/UI/ScenarioPicker.cs | 30 ++++---- tests/Aetheria.Shared.Tests/CreditsTests.cs | 7 +- 3 files changed, 83 insertions(+), 34 deletions(-) diff --git a/Assets/Scripts/UI/MainMenu.cs b/Assets/Scripts/UI/MainMenu.cs index 88600e516..e7aba3357 100644 --- a/Assets/Scripts/UI/MainMenu.cs +++ b/Assets/Scripts/UI/MainMenu.cs @@ -7,7 +7,9 @@ using System.Threading; using System.Threading.Tasks; using TMPro; using UniRx; +using UniRx.Triggers; using UnityEngine; +using UnityEngine.EventSystems; using UnityEngine.SceneManagement; using UnityEngine.UI; using static CultMath.math; @@ -139,36 +141,74 @@ public class MainMenu : MonoBehaviour _nextMenu.panel.AddButton("Credits", () => { - ShowCredits(); - Fade(true); + if (ShowCredits()) Fade(true); }); _nextMenu.panel.AddButton("Quit", Application.Quit); } - // The third-party attributions the build must show, one button per entry with its notice in the detail pane. The - // list is Credits.All; this only renders it. - private void ShowCredits() + // The third-party attributions the build must show, one button per entry; the selected entry's name, licence and one + // row per notice line fill the detail pane. The list is Credits.All; this only renders it. The screen follows the + // New Game screen: list rows are out of automatic navigation, the focused Back button takes Up and Down to step the + // selection and Cancel to leave, and a click on empty space does not drop that focus. + // False when the list could not be built and a dialog says why; the menu stays where it was. + private bool ShowCredits() { - var credits = Credits.All(Resources.Load<TextAsset>(Credits.NounProjectResource).text); + var attribution = Resources.Load<TextAsset>(Credits.NounProjectResource); + if (attribution == null) + { + Refuse("Credits are unavailable", $"{Credits.NounProjectResource} is missing from this build."); + return false; + } + IReadOnlyList<Credit> credits; + try { credits = Credits.All(attribution.text); } + catch (InvalidOperationException error) + { + Refuse("Credits are unavailable", error.Message); + return false; + } Next("credits"); - _nextMenu.detail.gameObject.SetActive(true); - _nextMenu.detail.Title.text = _nextMenu.panel.Title.text; - _nextMenu.detail.Title.color = Color.clear; - var selected = 0; - _nextMenu.detail.AddProperty(() => credits[selected].Name); - _nextMenu.detail.AddProperty(() => credits[selected].Licence); - _nextMenu.detail.AddProperty(() => credits[selected].Notice); + var list = _nextMenu.panel; + var detail = _nextMenu.detail; + detail.gameObject.SetActive(true); + var focus = new FocusHold(); + var selected = -1; + Button back = null; + void Leave() + { + FocusHold.Focus(null); + focus.Release(); + ShowMain(); + Fade(false); + } + void Select(int index) + { + selected = Mathf.Clamp(index, 0, credits.Count - 1); + var credit = credits[selected]; + detail.Clear(); + detail.Title.text = list.Title.text; + detail.Title.color = Color.clear; + detail.AddProperty(() => credit.Name); + detail.AddProperty(() => credit.Licence); + detail.AddSpacer(); + foreach (var line in credit.Notice.Split('\n')) detail.AddProperty(() => line); + FocusHold.Focus(back.gameObject); + } for (var i = 0; i < credits.Count; i++) { var index = i; - _nextMenu.panel.AddButton(credits[i].Name, () => selected = index); + list.AddButton(credits[i].Name, () => Select(index)).Button.navigation = new Navigation { mode = Navigation.Mode.None }; } - _nextMenu.panel.AddButton("Back", - () => - { - ShowMain(); - Fade(false); - }); + back = list.AddButton("Back", Leave).Button; + back.navigation = new Navigation { mode = Navigation.Mode.None }; + back.OnMoveAsObservable().Subscribe(move => + { + if (move.moveDir == MoveDirection.Up) Select(selected - 1); + else if (move.moveDir == MoveDirection.Down) Select(selected + 1); + }); + back.OnCancelAsObservable().Subscribe(_ => Leave()); + focus.Hold(); + Select(0); + return true; } // New Game: every way to set up a run, each with its brief. A release build lists only the modes; the other ways diff --git a/Assets/Scripts/UI/ScenarioPicker.cs b/Assets/Scripts/UI/ScenarioPicker.cs index e0cd93134..f5f3a1ca4 100644 --- a/Assets/Scripts/UI/ScenarioPicker.cs +++ b/Assets/Scripts/UI/ScenarioPicker.cs @@ -30,7 +30,7 @@ public sealed class ScenarioPicker private static readonly Color Accent = new Color(1, .4458f, .05f); private int _selected; private bool _launched; - private bool _restoreDeselect; + private readonly FocusHold _focus = new FocusHold(); private ScenarioPicker(PropertiesPanel list, PropertiesPanel detail, Action<Scenario> launch, Action back) { @@ -115,7 +115,7 @@ public sealed class ScenarioPicker picker._launchButton.OnCancelAsObservable().Subscribe(_ => picker.Back()); picker.StyleScrollbars(); - picker.HoldFocus(); + picker._focus.Hold(); picker.Select(0); // Layout is not live until the frame after Show; edit mode has no frames. if (Application.isPlaying) Observable.NextFrame().Subscribe(_ => picker.FitViewport()); @@ -229,7 +229,7 @@ public sealed class ScenarioPicker _rows[i].colors = colors; _rows[i].targetGraphic.color = i == _selected ? Accent : _rowFills[i]; } - Focus(_launchButton.gameObject); + FocusHold.Focus(_launchButton.gameObject); Reveal((RectTransform) _rows[_selected].transform); } @@ -253,36 +253,42 @@ public sealed class ScenarioPicker { if (_launched) return; _launched = true; - Focus(null); - ReleaseFocus(); + FocusHold.Focus(null); + _focus.Release(); _launch(Selected); } // Leaves the screen; the same path for the Back button and Cancel. private void Back() { - Focus(null); - ReleaseFocus(); + FocusHold.Focus(null); + _focus.Release(); _back(); } +} - // While the picker is up, a click on empty space must not drop focus from Launch, or the arrows and Enter go dead. - // The input module's flag is scene-wide, so the picker takes it for its own lifetime and gives it back on leaving. - private void HoldFocus() +// Keeps keyboard and gamepad focus on one control while a menu screen is up. While held, a click on empty space must +// not drop focus, or the arrows and Enter go dead. The input module's flag is scene-wide, so the screen takes it for its +// own lifetime and gives it back on leaving. The New Game and Credits screens both use it. +public sealed class FocusHold +{ + private bool _restoreDeselect; + + public void Hold() { if (EventSystem.current == null || !(EventSystem.current.currentInputModule is InputSystemUIInputModule module) || !module.deselectOnBackgroundClick) return; module.deselectOnBackgroundClick = false; _restoreDeselect = true; } - private void ReleaseFocus() + public void Release() { if (!_restoreDeselect) return; _restoreDeselect = false; if (EventSystem.current != null && EventSystem.current.currentInputModule is InputSystemUIInputModule module) module.deselectOnBackgroundClick = true; } - private static void Focus(GameObject target) + public static void Focus(GameObject target) { if (EventSystem.current != null) EventSystem.current.SetSelectedGameObject(target); } diff --git a/tests/Aetheria.Shared.Tests/CreditsTests.cs b/tests/Aetheria.Shared.Tests/CreditsTests.cs index b346f1fca..ed322bef4 100644 --- a/tests/Aetheria.Shared.Tests/CreditsTests.cs +++ b/tests/Aetheria.Shared.Tests/CreditsTests.cs @@ -190,12 +190,15 @@ namespace Aetheria.Shared.Tests { var menu = Regex.Replace(Read("Assets/Scripts/UI/MainMenu.cs"), @"/\*.*?\*/|//[^\n]*", "", RegexOptions.Singleline); var main = menu.Substring(menu.IndexOf("private void ShowMain()", StringComparison.Ordinal)); - main = main.Substring(0, main.IndexOf("private void ShowCredits()", StringComparison.Ordinal)); + main = main.Substring(0, main.IndexOf("private bool ShowCredits()", StringComparison.Ordinal)); Assert.Contains("AddButton(\"Credits\"", main); Assert.Contains("ShowCredits()", main); - var credits = menu.Substring(menu.IndexOf("private void ShowCredits()", StringComparison.Ordinal)); + var credits = menu.Substring(menu.IndexOf("private bool ShowCredits()", StringComparison.Ordinal)); credits = credits.Substring(0, credits.IndexOf("private void ShowScenarios()", StringComparison.Ordinal)); Assert.Contains("Credits.All(", credits); + // A build missing the attribution file refuses with a dialog instead of throwing in the click handler. + Assert.Contains("attribution == null", credits); + Assert.Contains("Refuse(", credits); } } } From 1537bc2c52e72da9615f0512bf78c0f7cdead3f3 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Thu, 12 Nov 2026 14:37:48 +0000 Subject: [PATCH 058/190] Credits: credit the Ubuntu and Montserrat fonts from their embedded notices; review unreferenced fonts; stop skipping obj/bin/Library under Assets Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/Credits.cs | 17 ++++ tests/Aetheria.Shared.Tests/CreditsTests.cs | 106 ++++++++++++++++++-- 2 files changed, 117 insertions(+), 6 deletions(-) diff --git a/Assets/Scripts/ServerShared/Credits.cs b/Assets/Scripts/ServerShared/Credits.cs index 3bb0af84b..cfc3028fb 100644 --- a/Assets/Scripts/ServerShared/Credits.cs +++ b/Assets/Scripts/ServerShared/Credits.cs @@ -20,6 +20,9 @@ public static class Credits public const string PlaydeadFile = "Assets/Plugins/Playdead/LICENSE.txt"; public const string NounProjectFile = "Assets/Resources/Sprites/Attribution.txt"; public const string LiberationFile = "Assets/TextMesh Pro/Fonts/LiberationSans - OFL.txt"; + // Fonts state their holder and licence in their own name tables; these are the font files the credit answers for. + public const string UbuntuFontFile = "Assets/Fonts/Ubuntu/Ubuntu-R.ttf"; + public const string MontserratFontFile = "Assets/Fonts/Ubuntu/Montserrat-Thin.ttf"; public const string UniRxFile = "Assets/Plugins/UniRx/ReadMe.txt"; public const string AmbientCgFile = "Assets/Materials/PBR/SOURCES.md"; public const string KdTreeFile = "Assets/Scripts/ServerShared/NIH/KDTree/KDTree.cs"; @@ -60,6 +63,20 @@ public static class Credits LicenceFile = LiberationFile }, new Credit + { + Name = "Ubuntu and Ubuntu Mono fonts", + Licence = "Ubuntu Font Licence 1.0", + Notice = "Copyright 2011 Canonical Ltd.", + LicenceFile = UbuntuFontFile + }, + new Credit + { + Name = "Montserrat", + Licence = "SIL Open Font License 1.1", + Notice = "Copyright(c) 2014 by Julieta Ulanovsky", + LicenceFile = MontserratFontFile + }, + new Credit { Name = "UniRx", Licence = "MIT", diff --git a/tests/Aetheria.Shared.Tests/CreditsTests.cs b/tests/Aetheria.Shared.Tests/CreditsTests.cs index ed322bef4..8d4a4a6b9 100644 --- a/tests/Aetheria.Shared.Tests/CreditsTests.cs +++ b/tests/Aetheria.Shared.Tests/CreditsTests.cs @@ -25,8 +25,6 @@ namespace Aetheria.Shared.Tests private static readonly Regex LicenceLike = new Regex( @"^(LICEN[CS]E|COPYING|NOTICE|README|SOURCES|_SOURCES|Attribution)|OFL", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - private static readonly string[] SkippedDirectories = { "bin", "obj", "Library" }; - // Discovered files whose own text names no holder and no licence, so there is nothing true to credit. A new // licence-like file is not here until someone has read it and written the reason. private static readonly System.Collections.Generic.Dictionary<string, string> ReviewedNotCredited = new System.Collections.Generic.Dictionary<string, string> @@ -40,8 +38,6 @@ namespace Aetheria.Shared.Tests // repo, so they are not credited; each path must still exist, so this list cannot go stale unnoticed. private static readonly string[] UnlicensedWorks = { - "Assets/Fonts/Ubuntu", - "Assets/Fonts/Retro", "Assets/Plugins/Ink", "Assets/Plugins/GPUTrail", "Assets/Plugins/com.unity.uiextensions", @@ -61,13 +57,70 @@ namespace Aetheria.Shared.Tests (Credits.AmbientCgFile, new[] { "ambientCG" }), }; + // Fonts that state holder and licence in their own name tables: the credit's LicenceFile is the first font, and + // every font listed must embed the stated string (read from the file, not from the credit) and be shown by the + // credit. The ids are TrueType name ids: 0 is the copyright notice. + private static readonly (string credit, string[] fonts, string embedded)[] FontCredits = + { + (Credits.UbuntuFontFile, new[] { "Assets/Fonts/Ubuntu/Ubuntu-R.ttf", "Assets/Fonts/Ubuntu/Ubuntu-L.ttf", "Assets/Fonts/Ubuntu/Ubuntu-B.ttf", "Assets/Fonts/Ubuntu/UbuntuMono-R.ttf" }, + "Copyright 2011 Canonical Ltd."), + (Credits.MontserratFontFile, new[] { "Assets/Fonts/Ubuntu/Montserrat-Thin.ttf" }, "Copyright(c) 2014 by Julieta Ulanovsky"), + }; + + // Fonts credited through a licence file in the repo (see Holders), not through their own text. + private static readonly string[] FontsCreditedByLicenceFile = { "Assets/Fonts/Emoji/Twemoji.ttf", "Assets/TextMesh Pro/Fonts/LiberationSans.ttf" }; + + // Fonts under Assets that are not credited, each with the reason; every one must be unreferenced by any prefab, + // scene, material or asset outside Assets/Fonts (checked), so shipping it is not a decision made by accident. + private static readonly System.Collections.Generic.Dictionary<string, string> ReviewedFonts = new System.Collections.Generic.Dictionary<string, string> + { + ["Assets/Fonts/Retro/LRT Oksana.ttf"] = "EULA forbids more than personal use; unreferenced; decision owed", + ["Assets/Fonts/Retro/LRT Oksana Bold.ttf"] = "EULA forbids more than personal use; unreferenced; decision owed", + ["Assets/Fonts/Ubuntu/UbuntuMono-B.ttf"] = "unreferenced; same holder and licence as UbuntuMono-R, which the Ubuntu credit covers", + ["Assets/Fonts/ftn_SourceSansPro-Regular.otf"] = "unreferenced; embeds Adobe copyright under the SIL OFL 1.1; credit it if it is ever used", + }; + + private static string[] FontFiles() + { + var root = Root(); + return Directory.EnumerateFiles(Path.Combine(root, "Assets"), "*", SearchOption.AllDirectories) + .Select(path => Path.GetRelativePath(root, path).Replace('\\', '/')) + .Where(path => path.EndsWith(".ttf", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".otf", StringComparison.OrdinalIgnoreCase)) + .OrderBy(path => path, StringComparer.Ordinal) + .ToArray(); + } + + // Every name-table record of a TrueType/OpenType file with the given name id, decoded (platform 3 as UTF-16BE, + // platform 1 as Latin-1). + private static System.Collections.Generic.List<string> NameRecords(string relative, int nameId) + { + var d = File.ReadAllBytes(Path.Combine(Root(), relative)); + int U16(int at) => (d[at] << 8) | d[at + 1]; + long U32(int at) => ((long)d[at] << 24) | ((long)d[at + 1] << 16) | ((long)d[at + 2] << 8) | d[at + 3]; + var found = new System.Collections.Generic.List<string>(); + for (int i = 0, n = U16(4); i < n; i++) + { + var rec = 12 + 16 * i; + if (System.Text.Encoding.ASCII.GetString(d, rec, 4) != "name") continue; + var table = (int)U32(rec + 8); + int count = U16(table + 2), strings = table + U16(table + 4); + for (var j = 0; j < count; j++) + { + var r = table + 6 + 12 * j; + if (U16(r + 6) != nameId) continue; + var text = System.Text.Encoding.GetEncoding(U16(r) == 3 ? "utf-16BE" : "latin1").GetString(d, strings + U16(r + 10), U16(r + 8)); + found.Add(text.Replace("\r", "").Trim()); + } + } + return found; + } + private static string[] LicenceLikeFiles() { var root = Root(); return Directory.EnumerateFiles(Path.Combine(root, "Assets"), "*", SearchOption.AllDirectories) .Where(path => !path.EndsWith(".meta")) .Select(path => Path.GetRelativePath(root, path).Replace('\\', '/')) - .Where(path => !path.Split('/').Any(segment => SkippedDirectories.Contains(segment))) .Where(path => LicenceLike.IsMatch(Path.GetFileName(path))) .OrderBy(path => path, StringComparer.Ordinal) .ToArray(); @@ -98,7 +151,7 @@ namespace Aetheria.Shared.Tests public void EveryCreditShowsTheHoldersItsOwnFileStates() { var credits = Load(); - Assert.Equal(Holders.Select(h => h.file).Append(Credits.NounProjectFile).OrderBy(f => f, StringComparer.Ordinal), + Assert.Equal(Holders.Select(h => h.file).Append(Credits.NounProjectFile).Concat(FontCredits.Select(f => f.credit)).OrderBy(f => f, StringComparer.Ordinal), credits.Select(credit => credit.LicenceFile).OrderBy(f => f, StringComparer.Ordinal)); foreach (var (file, stated) in Holders) { @@ -125,6 +178,47 @@ namespace Aetheria.Shared.Tests // Dash variants and case folded, so the file's en dash and the screen's hyphen compare equal. private static string Normal(string text) => text.Replace('\u2013', '-').Replace('\u2014', '-').Replace("\r", "").ToLowerInvariant(); + // The credit text is typed; the font files are the authority on who holds them. A wrong holder, or a font in the + // family that does not carry it, fails here. + [Fact] + public void FontCreditsShowWhatTheFontsThemselvesEmbed() + { + var credits = Load(); + foreach (var (creditFile, fonts, embedded) in FontCredits) + { + var notice = credits.Single(credit => credit.LicenceFile == creditFile).Notice; + Assert.Equal(creditFile, fonts[0]); + Assert.Contains(embedded, notice); + foreach (var font in fonts) + Assert.True(NameRecords(font, 0).Count > 0 && NameRecords(font, 0).All(record => record.StartsWith(embedded)), + $"{font} does not embed '{embedded}' as its copyright"); + } + Assert.Contains("Ubuntu Font Licence 1.0", NameRecords(Credits.UbuntuFontFile, 0)[0]); + Assert.Contains("Ubuntu Font Licence 1.0", credits.Single(credit => credit.LicenceFile == Credits.UbuntuFontFile).Licence); + Assert.Contains("SIL Open Font License, Version 1.1", NameRecords(Credits.MontserratFontFile, 13)[0]); + Assert.Contains("SIL Open Font License 1.1", credits.Single(credit => credit.LicenceFile == Credits.MontserratFontFile).Licence); + } + + [Fact] + public void EveryFontUnderAssetsIsCreditedOrReviewedAsUnreferenced() + { + var root = Root(); + var accounted = FontCredits.SelectMany(f => f.fonts).Concat(FontsCreditedByLicenceFile).Concat(ReviewedFonts.Keys).ToArray(); + var fonts = FontFiles(); + Assert.Equal(Array.Empty<string>(), fonts.Where(font => !accounted.Contains(font)).ToArray()); + Assert.Equal(Array.Empty<string>(), accounted.Where(font => !fonts.Contains(font)).ToArray()); + // A reviewed font stays out of the credits only while nothing outside Assets/Fonts uses it. + var guids = ReviewedFonts.Keys.ToDictionary(font => font, font => Regex.Match(Read(font + ".meta"), @"guid: (\w+)").Groups[1].Value); + Assert.All(guids.Values, guid => Assert.Equal(32, guid.Length)); + var users = Directory.EnumerateFiles(Path.Combine(root, "Assets"), "*", SearchOption.AllDirectories) + .Select(path => Path.GetRelativePath(root, path).Replace('\\', '/')) + .Where(path => !path.StartsWith("Assets/Fonts/") && new[] { ".prefab", ".unity", ".mat", ".asset", ".controller" }.Any(ext => path.EndsWith(ext))) + .Select(path => (path, text: Read(path))) + .ToArray(); + foreach (var (font, guid) in guids) + Assert.Equal(Array.Empty<string>(), users.Where(user => user.text.Contains(guid)).Select(user => user.path).ToArray()); + } + [Fact] public void TwemojiComesFirst() { From a04c6414e1a644a63c55499b40e0345bd72df2c6 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Thu, 12 Nov 2026 16:10:24 +0000 Subject: [PATCH 059/190] Credits test: follow a reviewed font to its SDF asset and fallback tables Prefabs reference the TMP SDF asset made from a font, not the .ttf, so matching the font file guid alone could never fail. The unreferenced-font check now follows the font guid and the guid of every Assets/Fonts file that references a guid already followed (the font's own SDF asset, any SDF asset listing it as a fallback); a file outside Assets/Fonts naming any of them is a use. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- tests/Aetheria.Shared.Tests/CreditsTests.cs | 27 +++++++++++++++------ 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/CreditsTests.cs b/tests/Aetheria.Shared.Tests/CreditsTests.cs index 8d4a4a6b9..6e9869844 100644 --- a/tests/Aetheria.Shared.Tests/CreditsTests.cs +++ b/tests/Aetheria.Shared.Tests/CreditsTests.cs @@ -207,16 +207,29 @@ namespace Aetheria.Shared.Tests var fonts = FontFiles(); Assert.Equal(Array.Empty<string>(), fonts.Where(font => !accounted.Contains(font)).ToArray()); Assert.Equal(Array.Empty<string>(), accounted.Where(font => !fonts.Contains(font)).ToArray()); - // A reviewed font stays out of the credits only while nothing outside Assets/Fonts uses it. - var guids = ReviewedFonts.Keys.ToDictionary(font => font, font => Regex.Match(Read(font + ".meta"), @"guid: (\w+)").Groups[1].Value); - Assert.All(guids.Values, guid => Assert.Equal(32, guid.Length)); - var users = Directory.EnumerateFiles(Path.Combine(root, "Assets"), "*", SearchOption.AllDirectories) + // A reviewed font stays out of the credits only while nothing outside Assets/Fonts uses it. Prefabs and scenes + // reference the TMP SDF asset made from the font, not the .ttf, so the search follows the font guid, then the + // guid of every file under Assets/Fonts that references a guid already followed: the font's own SDF asset, and + // any other SDF asset carrying it in a fallback table. A use is a file outside Assets/Fonts naming any of them. + var files = Directory.EnumerateFiles(Path.Combine(root, "Assets"), "*", SearchOption.AllDirectories) .Select(path => Path.GetRelativePath(root, path).Replace('\\', '/')) - .Where(path => !path.StartsWith("Assets/Fonts/") && new[] { ".prefab", ".unity", ".mat", ".asset", ".controller" }.Any(ext => path.EndsWith(ext))) + .Where(path => new[] { ".prefab", ".unity", ".mat", ".asset", ".controller" }.Any(ext => path.EndsWith(ext))) .Select(path => (path, text: Read(path))) .ToArray(); - foreach (var (font, guid) in guids) - Assert.Equal(Array.Empty<string>(), users.Where(user => user.text.Contains(guid)).Select(user => user.path).ToArray()); + var inFonts = files.Where(file => file.path.StartsWith("Assets/Fonts/")).ToArray(); + var outside = files.Where(file => !file.path.StartsWith("Assets/Fonts/")).ToArray(); + foreach (var font in ReviewedFonts.Keys) + { + var followed = new System.Collections.Generic.HashSet<string> { Regex.Match(Read(font + ".meta"), @"guid: (\w+)").Groups[1].Value }; + Assert.All(followed, guid => Assert.Equal(32, guid.Length)); + for (var grew = true; grew;) + { + grew = false; + foreach (var file in inFonts.Where(file => followed.Any(guid => file.text.Contains(guid))).ToArray()) + grew |= followed.Add(Regex.Match(Read(file.path + ".meta"), @"guid: (\w+)").Groups[1].Value); + } + Assert.Equal(Array.Empty<string>(), outside.Where(user => followed.Any(guid => user.text.Contains(guid))).Select(user => user.path).ToArray()); + } } [Fact] From 43be42fb529b7dabcc65e5f94221352dae77708b Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Thu, 12 Nov 2026 16:16:25 +0000 Subject: [PATCH 060/190] Credits: credit the works whose notice is only a source header; test scans headers Commit 16cb82d09 said every third-party work whose own text states holder and licence was credited. That was false: header-only notices were missed. Now credited, holder and licence taken from each file's own text: Academy of Motion Picture Arts and Sciences (ACES.hlsl, 2015), Unity Technologies 2016 MIT (the built-in shader sources Particle Standard Unlit, StretchedSkybox, MaskedWorldSpaceUI, MaskedWorldSpaceAdditiveUI and the three AdditiveUI shaders), Supyrb 2017 (AdditiveUI shaders; the header states no licence for that portion), and Stefan Gustavson 2011 MIT (Celestial Body SimplexNoise2.cginc). The discovery test now also scans every Copyright line in .shader/.hlsl/.cginc/.cs/.compute under Assets; its holder must appear in a credit notice or in ReviewedHeaders with the reason. Microsoft Open Technologies (UniRx headers, no licence stated, points at a License.txt that is not in the repo) is the one reviewed entry. The Unity headers point at a license.txt that is likewise not in the repo. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/Credits.cs | 38 +++++++++++++++ tests/Aetheria.Shared.Tests/CreditsTests.cs | 53 ++++++++++++++++++++- 2 files changed, 89 insertions(+), 2 deletions(-) diff --git a/Assets/Scripts/ServerShared/Credits.cs b/Assets/Scripts/ServerShared/Credits.cs index cfc3028fb..2746b6074 100644 --- a/Assets/Scripts/ServerShared/Credits.cs +++ b/Assets/Scripts/ServerShared/Credits.cs @@ -27,6 +27,11 @@ public static class Credits public const string AmbientCgFile = "Assets/Materials/PBR/SOURCES.md"; public const string KdTreeFile = "Assets/Scripts/ServerShared/NIH/KDTree/KDTree.cs"; public const string SimplexNoiseFile = "Assets/Plugins/GPU Noise/SimplexNoise2D.cginc"; + // Works whose notice is only a source-file header; each answers through the file whose header states it. + public const string UnityShaderFile = "Assets/Shaders/Particle Standard Unlit.shader"; + public const string AdditiveUiFile = "Assets/Shaders/AdditiveUI.shader"; + public const string AcesFile = "Assets/Shaders/CustomDoF/ACES.hlsl"; + public const string ClassicNoiseFile = "Assets/Plugins/Celestial Body/Scripts/Shaders/Includes/SimplexNoise2.cginc"; // The first line of the attribution file; the icon credits are the lines after it. public const string NounProjectHeading = "Noun Project"; // Where the player build loads the Noun Project credit lines from (Resources path, no extension). @@ -100,6 +105,39 @@ public static class Credits LicenceFile = SimplexNoiseFile }, new Credit + { + Name = "Celestial Body noise shaders", + Licence = "MIT", + Notice = "Copyright (C) 2011 Ashima Arts. Copyright (C) 2011 by Ashima Arts (Simplex noise). " + + "Copyright (C) 2011 by Stefan Gustavson (Classic noise).", + LicenceFile = ClassicNoiseFile + }, + new Credit + { + Name = "Unity built-in shaders", + Licence = "MIT", + Notice = "Copyright (c) 2016 Unity Technologies. Shader source adapted from Unity's built-in shaders " + + "(Particle Standard Unlit, StretchedSkybox, MaskedWorldSpaceUI, MaskedWorldSpaceAdditiveUI).", + LicenceFile = UnityShaderFile + }, + new Credit + { + Name = "AdditiveUI shaders", + Licence = "MIT for the Unity Technologies portion; the Supyrb portion states no licence", + Notice = "Copyright (c) 2017 Supyrb. All rights reserved. Author: Johannes Deml. " + + "Built on Unity's built-in UI shader, copyright (c) 2016 Unity Technologies, MIT.", + LicenceFile = AdditiveUiFile + }, + new Credit + { + Name = "ACES colour transforms", + Licence = "Academy Color Encoding System licence", + Notice = "Copyright 2015 Academy of Motion Picture Arts and Sciences (A.M.P.A.S.). " + + "Portions contributed by others as indicated. All rights reserved. " + + "Source: https://github.com/ampas/aces-dev", + LicenceFile = AcesFile + }, + new Credit { Name = "ambientCG PBR materials", Licence = "CC0 1.0 Universal", diff --git a/tests/Aetheria.Shared.Tests/CreditsTests.cs b/tests/Aetheria.Shared.Tests/CreditsTests.cs index 6e9869844..625820571 100644 --- a/tests/Aetheria.Shared.Tests/CreditsTests.cs +++ b/tests/Aetheria.Shared.Tests/CreditsTests.cs @@ -34,6 +34,12 @@ namespace Aetheria.Shared.Tests ["Assets/Plugins/Celestial Body/Textures/_Sources.txt"] = "URLs of the source textures only; states no licence", }; + // Copyright lines found in source headers whose holder no credit shows, each with the reason; keyed like HeaderKeys. + private static readonly System.Collections.Generic.Dictionary<string, string> ReviewedHeaders = new System.Collections.Generic.Dictionary<string, string> + { + ["microsoftopen"] = "UniRx files derived from Rx.NET: the header names Microsoft Open Technologies and points at a License.txt that is not in the repo, so no licence is stated; decision owed", + }; + // Bundled works with no licence-like file at all, found by reading Assets. Their licences are not stated in the // repo, so they are not credited; each path must still exist, so this list cannot go stale unnoticed. private static readonly string[] UnlicensedWorks = @@ -55,6 +61,10 @@ namespace Aetheria.Shared.Tests (Credits.KdTreeFile, new[] { "Vili Vol\u010dini / viliwonka" }), (Credits.SimplexNoiseFile, new[] { "Ashima Arts", "Ian McEwan", "Keijiro Takahashi" }), (Credits.AmbientCgFile, new[] { "ambientCG" }), + (Credits.UnityShaderFile, new[] { "Unity Technologies" }), + (Credits.AdditiveUiFile, new[] { "Unity Technologies", "Supyrb", "Johannes Deml" }), + (Credits.AcesFile, new[] { "Academy of Motion Picture Arts and Sciences", "A.M.P.A.S." }), + (Credits.ClassicNoiseFile, new[] { "Ashima Arts", "Stefan Gustavson" }), }; // Fonts that state holder and licence in their own name tables: the credit's LicenceFile is the first font, and @@ -130,6 +140,45 @@ namespace Aetheria.Shared.Tests private static string[] Unaccounted(string[] found, System.Collections.Generic.IEnumerable<string> credited) => found.Where(path => !credited.Contains(path) && !ReviewedNotCredited.ContainsKey(path)).ToArray(); + // The holder keys of every "Copyright ..." line in the source files under Assets: the year (when there is one) and + // the first two words of the holder, letters and digits only, lower case. Credits.cs is the credit text itself. + private static readonly Regex HeaderCopyright = new Regex(@"Copyright\s*(?:\([cC]\))?\s*(?:by\s+)?[<\[]?((?:\d{4}|[A-Z])[^\r\n]*)", RegexOptions.CultureInvariant); + + private static string Key(string text) => new string(text.Where(char.IsLetterOrDigit).ToArray()).ToLowerInvariant(); + + private static System.Collections.Generic.Dictionary<string, string> HeaderKeys() + { + var root = Root(); + var keys = new System.Collections.Generic.Dictionary<string, string>(); + foreach (var path in Directory.EnumerateFiles(Path.Combine(root, "Assets"), "*", SearchOption.AllDirectories) + .Select(path => Path.GetRelativePath(root, path).Replace('\\', '/')) + .Where(path => new[] { ".shader", ".hlsl", ".cginc", ".cs", ".compute" }.Any(ext => path.EndsWith(ext)) && path != "Assets/Scripts/ServerShared/Credits.cs")) + foreach (var line in Read(path).Split('\n')) + foreach (Match match in HeaderCopyright.Matches(line)) + { + var words = Regex.Replace(Regex.Replace(match.Groups[1].Value, @"\.\s.*", ""), @"[<>,]", " ").Split(' ', StringSplitOptions.RemoveEmptyEntries) + .Where(word => word != "by").ToArray(); + var year = words.Length > 0 && Regex.IsMatch(words[0], @"^\d{4}") ? 1 : 0; + if (year == 0 && !Regex.IsMatch(line, @"\([cC]\)")) continue; + keys.TryAdd(Key(string.Concat(words.Take(year + 2))), path); + } + return keys; + } + + // A copyright line in a source header is a notice the licence requires shown, so its holder is in a credit or in + // ReviewedHeaders with the reason; a removed credit, or a newly pasted header, fails here. + [Fact] + public void EveryCopyrightHolderInASourceHeaderIsCreditedOrReviewed() + { + var keys = HeaderKeys(); + Assert.Contains("2015academyof", keys.Keys); + Assert.Contains("2016unitytechnologies", keys.Keys); + Assert.Contains("2017supyrb", keys.Keys); + var shown = Key(string.Join(" ", Load().Select(credit => Normal(credit.Notice)))); + Assert.Equal(Array.Empty<string>(), keys.Where(k => !shown.Contains(k.Key) && !ReviewedHeaders.ContainsKey(k.Key)).Select(k => $"{k.Key} in {k.Value}").ToArray()); + Assert.Equal(Array.Empty<string>(), ReviewedHeaders.Keys.Where(k => !keys.ContainsKey(k)).ToArray()); + } + [Fact] public void EveryLicenceLikeFileUnderAssetsIsCreditedOrReviewed() { @@ -167,7 +216,7 @@ namespace Aetheria.Shared.Tests { var match = CopyrightLine.Match(line); if (!match.Success) continue; - var body = Regex.Replace(match.Groups[1].Value.Replace("[", "").Replace("]", "").Trim(), @"(\s*All rights reserved)?\.?$", "", RegexOptions.IgnoreCase); + var body = Regex.Replace(match.Groups[1].Value.Replace("[", "").Replace("]", "").Trim(), @"(\.\s.*|\s*All rights reserved)?\.?$", "", RegexOptions.IgnoreCase); Assert.True(notice.Contains(Normal(body)), $"the credit for {file} omits its copyright line '{body}'"); } } @@ -176,7 +225,7 @@ namespace Aetheria.Shared.Tests private static readonly Regex CopyrightLine = new Regex(@"copyright\s*(?:\(c\)|\u00a9)?\s*(\[?\d.*)$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); // Dash variants and case folded, so the file's en dash and the screen's hyphen compare equal. - private static string Normal(string text) => text.Replace('\u2013', '-').Replace('\u2014', '-').Replace("\r", "").ToLowerInvariant(); + private static string Normal(string text) => text.Replace('\u2013', '-').Replace('\u2014', '-').Replace("\r", "").Replace(" by ", " ").ToLowerInvariant(); // The credit text is typed; the font files are the authority on who holds them. A wrong holder, or a font in the // family that does not carry it, fails here. From 63403c8441afe5724208a7fc6b8d4b131a589b43 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Thu, 12 Nov 2026 16:20:52 +0000 Subject: [PATCH 061/190] Credits: ship the Ubuntu Font Licence 1.0 and SIL OFL 1.1 texts beside the fonts UFL-1.0.txt is the upstream Ubuntu Font Licence 1.0 text (google/fonts ufl/ubuntu/UFL.txt). Montserrat-OFL-1.1.txt is the OFL 1.1 body, byte-for-byte the text already shipped with Liberation Sans, headed by the copyright the Montserrat font embeds (Copyright(c) 2014 by Julieta Ulanovsky) rather than the project's later authors line. The Ubuntu and Montserrat credits now name these files as their LicenceFile; the test checks each carries its licence, sits beside its fonts, and (OFL) the embedded holder. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Fonts/Ubuntu/Montserrat-OFL-1.1.txt | 93 ++++++++++++++++++ .../Fonts/Ubuntu/Montserrat-OFL-1.1.txt.meta | 7 ++ Assets/Fonts/Ubuntu/UFL-1.0.txt | 96 +++++++++++++++++++ Assets/Fonts/Ubuntu/UFL-1.0.txt.meta | 7 ++ Assets/Scripts/ServerShared/Credits.cs | 10 +- tests/Aetheria.Shared.Tests/CreditsTests.cs | 23 +++-- 6 files changed, 221 insertions(+), 15 deletions(-) create mode 100644 Assets/Fonts/Ubuntu/Montserrat-OFL-1.1.txt create mode 100644 Assets/Fonts/Ubuntu/Montserrat-OFL-1.1.txt.meta create mode 100644 Assets/Fonts/Ubuntu/UFL-1.0.txt create mode 100644 Assets/Fonts/Ubuntu/UFL-1.0.txt.meta diff --git a/Assets/Fonts/Ubuntu/Montserrat-OFL-1.1.txt b/Assets/Fonts/Ubuntu/Montserrat-OFL-1.1.txt new file mode 100644 index 000000000..d2fcdf3eb --- /dev/null +++ b/Assets/Fonts/Ubuntu/Montserrat-OFL-1.1.txt @@ -0,0 +1,93 @@ +Copyright(c) 2014 by Julieta Ulanovsky + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. \ No newline at end of file diff --git a/Assets/Fonts/Ubuntu/Montserrat-OFL-1.1.txt.meta b/Assets/Fonts/Ubuntu/Montserrat-OFL-1.1.txt.meta new file mode 100644 index 000000000..c2ea6a451 --- /dev/null +++ b/Assets/Fonts/Ubuntu/Montserrat-OFL-1.1.txt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: dc84a6b2454445f9be69af26e86eb90c +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Fonts/Ubuntu/UFL-1.0.txt b/Assets/Fonts/Ubuntu/UFL-1.0.txt new file mode 100644 index 000000000..ae78a8f94 --- /dev/null +++ b/Assets/Fonts/Ubuntu/UFL-1.0.txt @@ -0,0 +1,96 @@ +------------------------------- +UBUNTU FONT LICENCE Version 1.0 +------------------------------- + +PREAMBLE +This licence allows the licensed fonts to be used, studied, modified and +redistributed freely. The fonts, including any derivative works, can be +bundled, embedded, and redistributed provided the terms of this licence +are met. The fonts and derivatives, however, cannot be released under +any other licence. The requirement for fonts to remain under this +licence does not require any document created using the fonts or their +derivatives to be published under this licence, as long as the primary +purpose of the document is not to be a vehicle for the distribution of +the fonts. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this licence and clearly marked as such. This may +include source files, build scripts and documentation. + +"Original Version" refers to the collection of Font Software components +as received under this licence. + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to +a new environment. + +"Copyright Holder(s)" refers to all individuals and companies who have a +copyright ownership of the Font Software. + +"Substantially Changed" refers to Modified Versions which can be easily +identified as dissimilar to the Font Software by users of the Font +Software comparing the Original Version with the Modified Version. + +To "Propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification and with or without charging +a redistribution fee), making available to the public, and in some +countries other activities as well. + +PERMISSION & CONDITIONS +This licence does not grant any rights under trademark law and all such +rights are reserved. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of the Font Software, to propagate the Font Software, subject to +the below conditions: + +1) Each copy of the Font Software must contain the above copyright +notice and this licence. These can be included either as stand-alone +text files, human-readable headers or in the appropriate machine- +readable metadata fields within text or binary files as long as those +fields can be easily viewed by the user. + +2) The font name complies with the following: +(a) The Original Version must retain its name, unmodified. +(b) Modified Versions which are Substantially Changed must be renamed to +avoid use of the name of the Original Version or similar names entirely. +(c) Modified Versions which are not Substantially Changed must be +renamed to both (i) retain the name of the Original Version and (ii) add +additional naming elements to distinguish the Modified Version from the +Original Version. The name of such Modified Versions must be the name of +the Original Version, with "derivative X" where X represents the name of +the new work, appended to that name. + +3) The name(s) of the Copyright Holder(s) and any contributor to the +Font Software shall not be used to promote, endorse or advertise any +Modified Version, except (i) as required by this licence, (ii) to +acknowledge the contribution(s) of the Copyright Holder(s) or (iii) with +their explicit written permission. + +4) The Font Software, modified or unmodified, in part or in whole, must +be distributed entirely under this licence, and must not be distributed +under any other licence. The requirement for fonts to remain under this +licence does not affect any document created using the Font Software, +except any version of the Font Software extracted from a document +created using the Font Software may only be distributed under this +licence. + +TERMINATION +This licence becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER +DEALINGS IN THE FONT SOFTWARE. diff --git a/Assets/Fonts/Ubuntu/UFL-1.0.txt.meta b/Assets/Fonts/Ubuntu/UFL-1.0.txt.meta new file mode 100644 index 000000000..33790c1ab --- /dev/null +++ b/Assets/Fonts/Ubuntu/UFL-1.0.txt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 331370618a0a473fb6a6837985b38a35 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/Credits.cs b/Assets/Scripts/ServerShared/Credits.cs index 2746b6074..45054187b 100644 --- a/Assets/Scripts/ServerShared/Credits.cs +++ b/Assets/Scripts/ServerShared/Credits.cs @@ -20,9 +20,9 @@ public static class Credits public const string PlaydeadFile = "Assets/Plugins/Playdead/LICENSE.txt"; public const string NounProjectFile = "Assets/Resources/Sprites/Attribution.txt"; public const string LiberationFile = "Assets/TextMesh Pro/Fonts/LiberationSans - OFL.txt"; - // Fonts state their holder and licence in their own name tables; these are the font files the credit answers for. - public const string UbuntuFontFile = "Assets/Fonts/Ubuntu/Ubuntu-R.ttf"; - public const string MontserratFontFile = "Assets/Fonts/Ubuntu/Montserrat-Thin.ttf"; + // Fonts state their holder and licence in their own name tables; the licence texts shipped beside them are these. + public const string UbuntuLicenceFile = "Assets/Fonts/Ubuntu/UFL-1.0.txt"; + public const string MontserratLicenceFile = "Assets/Fonts/Ubuntu/Montserrat-OFL-1.1.txt"; public const string UniRxFile = "Assets/Plugins/UniRx/ReadMe.txt"; public const string AmbientCgFile = "Assets/Materials/PBR/SOURCES.md"; public const string KdTreeFile = "Assets/Scripts/ServerShared/NIH/KDTree/KDTree.cs"; @@ -72,14 +72,14 @@ public static class Credits Name = "Ubuntu and Ubuntu Mono fonts", Licence = "Ubuntu Font Licence 1.0", Notice = "Copyright 2011 Canonical Ltd.", - LicenceFile = UbuntuFontFile + LicenceFile = UbuntuLicenceFile }, new Credit { Name = "Montserrat", Licence = "SIL Open Font License 1.1", Notice = "Copyright(c) 2014 by Julieta Ulanovsky", - LicenceFile = MontserratFontFile + LicenceFile = MontserratLicenceFile }, new Credit { diff --git a/tests/Aetheria.Shared.Tests/CreditsTests.cs b/tests/Aetheria.Shared.Tests/CreditsTests.cs index 625820571..68f9d68da 100644 --- a/tests/Aetheria.Shared.Tests/CreditsTests.cs +++ b/tests/Aetheria.Shared.Tests/CreditsTests.cs @@ -23,7 +23,7 @@ namespace Aetheria.Shared.Tests // A file under Assets that looks like a licence, attribution, notice, readme or sources list. Each one is either // credited (the credit names it as its LicenceFile) or reviewed below with the reason it is not. private static readonly Regex LicenceLike = new Regex( - @"^(LICEN[CS]E|COPYING|NOTICE|README|SOURCES|_SOURCES|Attribution)|OFL", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + @"^(LICEN[CS]E|COPYING|NOTICE|README|SOURCES|_SOURCES|Attribution|UFL)|OFL", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); // Discovered files whose own text names no holder and no licence, so there is nothing true to credit. A new // licence-like file is not here until someone has read it and written the reason. @@ -67,14 +67,14 @@ namespace Aetheria.Shared.Tests (Credits.ClassicNoiseFile, new[] { "Ashima Arts", "Stefan Gustavson" }), }; - // Fonts that state holder and licence in their own name tables: the credit's LicenceFile is the first font, and - // every font listed must embed the stated string (read from the file, not from the credit) and be shown by the + // Fonts that state holder and licence in their own name tables: the credit's LicenceFile is the licence text shipped + // beside them (which must carry the licence and the stated holder), and every font listed must embed the stated string (read from the file, not from the credit) and be shown by the // credit. The ids are TrueType name ids: 0 is the copyright notice. private static readonly (string credit, string[] fonts, string embedded)[] FontCredits = { - (Credits.UbuntuFontFile, new[] { "Assets/Fonts/Ubuntu/Ubuntu-R.ttf", "Assets/Fonts/Ubuntu/Ubuntu-L.ttf", "Assets/Fonts/Ubuntu/Ubuntu-B.ttf", "Assets/Fonts/Ubuntu/UbuntuMono-R.ttf" }, + (Credits.UbuntuLicenceFile, new[] { "Assets/Fonts/Ubuntu/Ubuntu-R.ttf", "Assets/Fonts/Ubuntu/Ubuntu-L.ttf", "Assets/Fonts/Ubuntu/Ubuntu-B.ttf", "Assets/Fonts/Ubuntu/UbuntuMono-R.ttf" }, "Copyright 2011 Canonical Ltd."), - (Credits.MontserratFontFile, new[] { "Assets/Fonts/Ubuntu/Montserrat-Thin.ttf" }, "Copyright(c) 2014 by Julieta Ulanovsky"), + (Credits.MontserratLicenceFile, new[] { "Assets/Fonts/Ubuntu/Montserrat-Thin.ttf" }, "Copyright(c) 2014 by Julieta Ulanovsky"), }; // Fonts credited through a licence file in the repo (see Holders), not through their own text. @@ -236,16 +236,19 @@ namespace Aetheria.Shared.Tests foreach (var (creditFile, fonts, embedded) in FontCredits) { var notice = credits.Single(credit => credit.LicenceFile == creditFile).Notice; - Assert.Equal(creditFile, fonts[0]); + var licenceText = Read(creditFile); + Assert.Contains(creditFile.Contains("UFL") ? "UBUNTU FONT LICENCE Version 1.0" : "SIL OPEN FONT LICENSE Version 1.1", licenceText); + Assert.True(Path.GetDirectoryName(creditFile) == Path.GetDirectoryName(fonts[0]).Replace('\\', '/'), "licence text sits beside its fonts"); + if (creditFile.Contains("OFL")) Assert.Contains(embedded, licenceText); Assert.Contains(embedded, notice); foreach (var font in fonts) Assert.True(NameRecords(font, 0).Count > 0 && NameRecords(font, 0).All(record => record.StartsWith(embedded)), $"{font} does not embed '{embedded}' as its copyright"); } - Assert.Contains("Ubuntu Font Licence 1.0", NameRecords(Credits.UbuntuFontFile, 0)[0]); - Assert.Contains("Ubuntu Font Licence 1.0", credits.Single(credit => credit.LicenceFile == Credits.UbuntuFontFile).Licence); - Assert.Contains("SIL Open Font License, Version 1.1", NameRecords(Credits.MontserratFontFile, 13)[0]); - Assert.Contains("SIL Open Font License 1.1", credits.Single(credit => credit.LicenceFile == Credits.MontserratFontFile).Licence); + Assert.Contains("Ubuntu Font Licence 1.0", NameRecords(FontCredits[0].fonts[0], 0)[0]); + Assert.Contains("Ubuntu Font Licence 1.0", credits.Single(credit => credit.LicenceFile == Credits.UbuntuLicenceFile).Licence); + Assert.Contains("SIL Open Font License, Version 1.1", NameRecords(FontCredits[1].fonts[0], 13)[0]); + Assert.Contains("SIL Open Font License 1.1", credits.Single(credit => credit.LicenceFile == Credits.MontserratLicenceFile).Licence); } [Fact] From 2071cea6e727a4e6ae1bb467f11b4772508ad662 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Thu, 12 Nov 2026 16:32:03 +0000 Subject: [PATCH 062/190] Credits test: header scan catches (c) and copyright-sign notices, lowercase copyright, 'Copyright:', every holder on a line, whole holder compared Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- tests/Aetheria.Shared.Tests/CreditsTests.cs | 43 ++++++++++++++------- 1 file changed, 28 insertions(+), 15 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/CreditsTests.cs b/tests/Aetheria.Shared.Tests/CreditsTests.cs index 68f9d68da..acce8d59e 100644 --- a/tests/Aetheria.Shared.Tests/CreditsTests.cs +++ b/tests/Aetheria.Shared.Tests/CreditsTests.cs @@ -37,7 +37,7 @@ namespace Aetheria.Shared.Tests // Copyright lines found in source headers whose holder no credit shows, each with the reason; keyed like HeaderKeys. private static readonly System.Collections.Generic.Dictionary<string, string> ReviewedHeaders = new System.Collections.Generic.Dictionary<string, string> { - ["microsoftopen"] = "UniRx files derived from Rx.NET: the header names Microsoft Open Technologies and points at a License.txt that is not in the repo, so no licence is stated; decision owed", + ["microsoftopentechnologiesinc"] = "UniRx files derived from Rx.NET: the header names Microsoft Open Technologies and points at a License.txt that is not in the repo, so no licence is stated; decision owed", }; // Bundled works with no licence-like file at all, found by reading Assets. Their licences are not stated in the @@ -140,12 +140,30 @@ namespace Aetheria.Shared.Tests private static string[] Unaccounted(string[] found, System.Collections.Generic.IEnumerable<string> credited) => found.Where(path => !credited.Contains(path) && !ReviewedNotCredited.ContainsKey(path)).ToArray(); - // The holder keys of every "Copyright ..." line in the source files under Assets: the year (when there is one) and - // the first two words of the holder, letters and digits only, lower case. Credits.cs is the credit text itself. - private static readonly Regex HeaderCopyright = new Regex(@"Copyright\s*(?:\([cC]\))?\s*(?:by\s+)?[<\[]?((?:\d{4}|[A-Z])[^\r\n]*)", RegexOptions.CultureInvariant); + // Every copyright marker in a source header: "Copyright", "copyright", "(c)" (not the tail of an identifier), the copyright sign, "Copyright (c)", with an optional + // colon and "by". A line is scanned marker by marker: a holder runs to the next marker or the end of the line, so a + // second holder on the same line is a holder of its own. Credits.cs is the credit text itself, so it is not scanned. + private const string Marker = @"(?:copyright(?:\s*(?:\(c\)|\u00a9))?|(?<!\w)\(c\)|\u00a9)"; + private static readonly Regex HeaderCopyright = new Regex( + Marker + @"(?<explicit>\s*:)?\s*(?:by\s+)?[<\[]?(?<holder>.+?)(?=" + Marker + @"|$)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); private static string Key(string text) => new string(text.Where(char.IsLetterOrDigit).ToArray()).ToLowerInvariant(); + // The holders a line of source states: the text after each marker, cut at the end of its sentence, as keys. A holder + // is a year or a capitalised name; "copyright notice" in licence prose names nobody. Without a year the marker must + // be "(c)", the copyright sign or a colon, so "Copyright Notice" prose is not a holder either. + private static System.Collections.Generic.IEnumerable<string> LineHolders(string line) + { + foreach (Match match in HeaderCopyright.Matches(line)) + { + var holder = Regex.Replace(match.Groups["holder"].Value.Trim(), @"(\.(\s.*)?|\s*All rights reserved.*)$", "", RegexOptions.IgnoreCase).Trim(' ', '\t', ',', ';', '>', ']'); + var marked = Regex.IsMatch(match.Value.Substring(0, match.Groups["holder"].Index - match.Index), @"\(c\)|\u00a9|:", RegexOptions.IgnoreCase); + var year = Regex.IsMatch(holder, @"^\d{4}"); + if (holder.Length == 0 || !(year || (marked && char.IsUpper(holder[0])))) continue; + yield return Key(Normal(holder)); + } + } + private static System.Collections.Generic.Dictionary<string, string> HeaderKeys() { var root = Root(); @@ -154,14 +172,8 @@ namespace Aetheria.Shared.Tests .Select(path => Path.GetRelativePath(root, path).Replace('\\', '/')) .Where(path => new[] { ".shader", ".hlsl", ".cginc", ".cs", ".compute" }.Any(ext => path.EndsWith(ext)) && path != "Assets/Scripts/ServerShared/Credits.cs")) foreach (var line in Read(path).Split('\n')) - foreach (Match match in HeaderCopyright.Matches(line)) - { - var words = Regex.Replace(Regex.Replace(match.Groups[1].Value, @"\.\s.*", ""), @"[<>,]", " ").Split(' ', StringSplitOptions.RemoveEmptyEntries) - .Where(word => word != "by").ToArray(); - var year = words.Length > 0 && Regex.IsMatch(words[0], @"^\d{4}") ? 1 : 0; - if (year == 0 && !Regex.IsMatch(line, @"\([cC]\)")) continue; - keys.TryAdd(Key(string.Concat(words.Take(year + 2))), path); - } + foreach (var key in LineHolders(line)) + keys.TryAdd(key, path); return keys; } @@ -171,11 +183,12 @@ namespace Aetheria.Shared.Tests public void EveryCopyrightHolderInASourceHeaderIsCreditedOrReviewed() { var keys = HeaderKeys(); - Assert.Contains("2015academyof", keys.Keys); + Assert.Contains(Key("2015 Academy of Motion Picture Arts and Sciences (A.M.P.A.S"), keys.Keys); Assert.Contains("2016unitytechnologies", keys.Keys); Assert.Contains("2017supyrb", keys.Keys); - var shown = Key(string.Join(" ", Load().Select(credit => Normal(credit.Notice)))); - Assert.Equal(Array.Empty<string>(), keys.Where(k => !shown.Contains(k.Key) && !ReviewedHeaders.ContainsKey(k.Key)).Select(k => $"{k.Key} in {k.Value}").ToArray()); + // The whole holder is compared, not a prefix of it, against each credit's notice on its own. + var shown = Load().Select(credit => Key(Normal(credit.Notice))).ToArray(); + Assert.Equal(Array.Empty<string>(), keys.Where(k => !shown.Any(notice => notice.Contains(k.Key)) && !ReviewedHeaders.ContainsKey(k.Key)).Select(k => $"{k.Key} in {k.Value}").ToArray()); Assert.Equal(Array.Empty<string>(), ReviewedHeaders.Keys.Where(k => !keys.ContainsKey(k)).ToArray()); } From 50ab1cd7f48e698ee60abc58c67cbe271c693b7a Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Thu, 12 Nov 2026 16:33:18 +0000 Subject: [PATCH 063/190] Credits: credit uiextensions' BezierPath (Tulleken); review the credit-only lines in StableFluids, Triplanar and uiextensions Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/Credits.cs | 9 +++++++ tests/Aetheria.Shared.Tests/CreditsTests.cs | 26 +++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/Assets/Scripts/ServerShared/Credits.cs b/Assets/Scripts/ServerShared/Credits.cs index 45054187b..9b7ac4226 100644 --- a/Assets/Scripts/ServerShared/Credits.cs +++ b/Assets/Scripts/ServerShared/Credits.cs @@ -31,6 +31,7 @@ public static class Credits public const string UnityShaderFile = "Assets/Shaders/Particle Standard Unlit.shader"; public const string AdditiveUiFile = "Assets/Shaders/AdditiveUI.shader"; public const string AcesFile = "Assets/Shaders/CustomDoF/ACES.hlsl"; + public const string BezierPathFile = "Assets/Plugins/com.unity.uiextensions/Runtime/Scripts/Utilities/BezierPath.cs"; public const string ClassicNoiseFile = "Assets/Plugins/Celestial Body/Scripts/Shaders/Includes/SimplexNoise2.cginc"; // The first line of the attribution file; the icon credits are the lines after it. public const string NounProjectHeading = "Noun Project"; @@ -138,6 +139,14 @@ public static class Credits LicenceFile = AcesFile }, new Credit + { + Name = "Bezier path (UI Extensions)", + Licence = "No named licence; permissive grant in the file header", + Notice = "Author: Herman Tulleken, dev.mag.org.za (http://devmag.org.za/2011/04/05/bzier-curves-a-tutorial/). " + + "Use this code as you wish, at your own risk.", + LicenceFile = BezierPathFile + }, + new Credit { Name = "ambientCG PBR materials", Licence = "CC0 1.0 Universal", diff --git a/tests/Aetheria.Shared.Tests/CreditsTests.cs b/tests/Aetheria.Shared.Tests/CreditsTests.cs index acce8d59e..2ef34f354 100644 --- a/tests/Aetheria.Shared.Tests/CreditsTests.cs +++ b/tests/Aetheria.Shared.Tests/CreditsTests.cs @@ -40,6 +40,31 @@ namespace Aetheria.Shared.Tests ["microsoftopentechnologiesinc"] = "UniRx files derived from Rx.NET: the header names Microsoft Open Technologies and points at a License.txt that is not in the repo, so no licence is stated; decision owed", }; + // Source headers that credit someone ("Credit X", "Based on ...", a source URL) without stating a copyright holder or + // a licence, so there is no true notice to show. Each is the exact line the file carries and the reason it is not a + // credit; the test reads the file, so a line that moves or goes cannot leave a stale entry. + private static readonly (string file, string line, string reason)[] ReviewedAttributionLines = + { + ("Assets/Shaders/StableFluids/Fluid.cs", "// https://github.com/keijiro/StableFluids", "names Keijiro's StableFluids as the source; states no holder and no licence"), + ("Assets/Shaders/StableFluids/Fluid.shader", "// https://github.com/keijiro/StableFluids", "names Keijiro's StableFluids as the source; states no holder and no licence"), + ("Assets/Shaders/StableFluids/Fluid.compute", "// Based on https://github.com/keijiro/StableFluids", "names Keijiro's StableFluids as the source; states no holder and no licence"), + ("Assets/Plugins/Celestial Body/Scripts/Shaders/Includes/Triplanar.cginc", "// Based on: medium.com/@bgolus/normal-mapping-for-a-triplanar-shader-10bf39dca05a", "cites bgolus's article for the technique; states no holder and no licence"), + ("Assets/Plugins/com.unity.uiextensions/Runtime/Scripts/Primitives/UILineTextureRenderer.cs", "/// Credit jonbro5556", "names a contributor; states no copyright and no licence"), + ("Assets/Plugins/com.unity.uiextensions/Runtime/Scripts/Primitives/UILineRenderer.cs", "/// Credit jack.sydorenko, firagon", "names contributors; states no copyright and no licence"), + ("Assets/Plugins/com.unity.uiextensions/Runtime/Scripts/Primitives/UILineRendererList.cs", "/// Credit jack.sydorenko, firagon", "names contributors; states no copyright and no licence"), + ("Assets/Plugins/com.unity.uiextensions/Runtime/Scripts/Utilities/CableCurve.cs", "/// Credit Farfarer", "names a contributor; states no copyright and no licence"), + ("Assets/Plugins/com.unity.uiextensions/Editor/BezierLineRendererEditor.cs", "///Credit Jason Horsburgh", "names a contributor; states no copyright and no licence"), + }; + + [Fact] + public void ReviewedAttributionLinesAreStillInTheirFiles() + { + Assert.Equal(Array.Empty<string>(), ReviewedAttributionLines + .Where(entry => !File.Exists(Path.Combine(Root(), entry.file)) || !Read(entry.file).Replace("\r", "").Split('\n').Any(line => line.Trim('\uFEFF', ' ', '\t') == entry.line)) + .Select(entry => $"{entry.line} in {entry.file}").ToArray()); + Assert.All(ReviewedAttributionLines, entry => Assert.False(string.IsNullOrWhiteSpace(entry.reason))); + } + // Bundled works with no licence-like file at all, found by reading Assets. Their licences are not stated in the // repo, so they are not credited; each path must still exist, so this list cannot go stale unnoticed. private static readonly string[] UnlicensedWorks = @@ -65,6 +90,7 @@ namespace Aetheria.Shared.Tests (Credits.AdditiveUiFile, new[] { "Unity Technologies", "Supyrb", "Johannes Deml" }), (Credits.AcesFile, new[] { "Academy of Motion Picture Arts and Sciences", "A.M.P.A.S." }), (Credits.ClassicNoiseFile, new[] { "Ashima Arts", "Stefan Gustavson" }), + (Credits.BezierPathFile, new[] { "Herman Tulleken", "Use this code as you wish" }), }; // Fonts that state holder and licence in their own name tables: the credit's LicenceFile is the licence text shipped From 61cea7d8c7a5fe2e8a209bca0a17c33ea355c806 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Thu, 12 Nov 2026 16:52:06 +0000 Subject: [PATCH 064/190] Credits test: header holders must equal a credited holder; scan Copyright followed by a bare name Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- tests/Aetheria.Shared.Tests/CreditsTests.cs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/CreditsTests.cs b/tests/Aetheria.Shared.Tests/CreditsTests.cs index 2ef34f354..9479e31e3 100644 --- a/tests/Aetheria.Shared.Tests/CreditsTests.cs +++ b/tests/Aetheria.Shared.Tests/CreditsTests.cs @@ -175,6 +175,11 @@ namespace Aetheria.Shared.Tests private static string Key(string text) => new string(text.Where(char.IsLetterOrDigit).ToArray()).ToLowerInvariant(); + // Words that follow "copyright" in licence and header prose and name no holder ("copyright notice", "COPYRIGHT HOLDERS BE + // LIABLE", "copyright laws"); a capitalised word after a bare "Copyright" is a holder unless it is one of these. + private static readonly string[] ProseAfterCopyright = + { "Notice", "Notices", "Holder", "Holders", "Owner", "Owners", "Law", "Laws", "Act", "Protection", "Statement", "Header", "Information", "Status", "Line", "Lines", "Text", "Licence", "License", "Material", "Works", "Work", "File", "Files" }; + // The holders a line of source states: the text after each marker, cut at the end of its sentence, as keys. A holder // is a year or a capitalised name; "copyright notice" in licence prose names nobody. Without a year the marker must // be "(c)", the copyright sign or a colon, so "Copyright Notice" prose is not a holder either. @@ -185,7 +190,9 @@ namespace Aetheria.Shared.Tests var holder = Regex.Replace(match.Groups["holder"].Value.Trim(), @"(\.(\s.*)?|\s*All rights reserved.*)$", "", RegexOptions.IgnoreCase).Trim(' ', '\t', ',', ';', '>', ']'); var marked = Regex.IsMatch(match.Value.Substring(0, match.Groups["holder"].Index - match.Index), @"\(c\)|\u00a9|:", RegexOptions.IgnoreCase); var year = Regex.IsMatch(holder, @"^\d{4}"); - if (holder.Length == 0 || !(year || (marked && char.IsUpper(holder[0])))) continue; + // "Copyright Epic Games, Inc." names a holder with no year or sign; licence prose after the word does not. + var named = holder.Length > 0 && char.IsUpper(holder[0]) && !ProseAfterCopyright.Contains(Regex.Match(holder, @"^\w+").Value, StringComparer.OrdinalIgnoreCase); + if (holder.Length == 0 || !(year || (named && (marked || Regex.IsMatch(match.Value, "^copyright", RegexOptions.IgnoreCase))))) continue; yield return Key(Normal(holder)); } } @@ -212,9 +219,10 @@ namespace Aetheria.Shared.Tests Assert.Contains(Key("2015 Academy of Motion Picture Arts and Sciences (A.M.P.A.S"), keys.Keys); Assert.Contains("2016unitytechnologies", keys.Keys); Assert.Contains("2017supyrb", keys.Keys); - // The whole holder is compared, not a prefix of it, against each credit's notice on its own. - var shown = Load().Select(credit => Key(Normal(credit.Notice))).ToArray(); - Assert.Equal(Array.Empty<string>(), keys.Where(k => !shown.Any(notice => notice.Contains(k.Key)) && !ReviewedHeaders.ContainsKey(k.Key)).Select(k => $"{k.Key} in {k.Value}").ToArray()); + // The whole holder must equal a holder some credit's notice states, read by the same extractor: a bare year, a short + // name, or a prefix of a credited name is a different key and fails. + var shown = Load().SelectMany(credit => credit.Notice.Split('\n')).SelectMany(LineHolders).ToHashSet(); + Assert.Equal(Array.Empty<string>(), keys.Where(k => !shown.Contains(k.Key) && !ReviewedHeaders.ContainsKey(k.Key)).Select(k => $"{k.Key} in {k.Value}").ToArray()); Assert.Equal(Array.Empty<string>(), ReviewedHeaders.Keys.Where(k => !keys.ContainsKey(k)).ToArray()); } From 2b3278ba3d9dd954deed41a36c52cda4bf668f93 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@noreply.eureka.gamecult.org> Date: Thu, 12 Nov 2026 22:42:48 +0000 Subject: [PATCH 065/190] Mining cut 4: rocks take blasts and shots through the one fire path (#18) --- Assets/Scripts/ServerShared/FireControl.cs | 304 +++++++++--- .../ServerShared/Targeting/BeltTargets.cs | 3 +- Assets/Scripts/ServerShared/Zone.cs | 27 +- .../Aetheria.Shared.Tests/MiningCut3Tests.cs | 20 +- .../Aetheria.Shared.Tests/MiningCut4aTests.cs | 279 +++++++++++ .../Aetheria.Shared.Tests/MiningCut4bTests.cs | 458 ++++++++++++++++++ 6 files changed, 999 insertions(+), 92 deletions(-) create mode 100644 tests/Aetheria.Shared.Tests/MiningCut4aTests.cs create mode 100644 tests/Aetheria.Shared.Tests/MiningCut4bTests.cs diff --git a/Assets/Scripts/ServerShared/FireControl.cs b/Assets/Scripts/ServerShared/FireControl.cs index 1581e3457..6cd860ab3 100644 --- a/Assets/Scripts/ServerShared/FireControl.cs +++ b/Assets/Scripts/ServerShared/FireControl.cs @@ -84,10 +84,10 @@ public static class FireControl // Whether the shooter's next round from this weapon is refused: the weapons ask before they spend anything, so // a refused round costs no ammo, energy, sound, heat, wear or visibility (operator ruling 2026-09-30). The // answer is Solve's own -- there is no second copy of the arming test. - public static bool Refuses(Weapon weapon, Entity shooter) => Refuses(weapon, shooter, shooter.Target.Value.Entity); + public static bool Refuses(Weapon weapon, Entity shooter) => Refuses(weapon, shooter, shooter.Target.Value); // The same answer against a target the shooter's pilot has commanded but not yet applied. - public static bool Refuses(Weapon weapon, Entity shooter, Entity target) => + public static bool Refuses(Weapon weapon, Entity shooter, TargetRef target) => !IsMineLayer(weapon) && Solve(weapon, weapon.Item, shooter, target).Outcome == FireOutcome.Refused; // A mine layer lays a body, not a round: it is never refused, never arc-gated, and Fire routes it to Lay. @@ -139,27 +139,18 @@ public static class FireControl // The one owner of a gun's solution against its subject (the designated target; ruling controls-solution-subject). // Bears: the gun can engage the subject, so the player fires on it without the aim. Free: the aim is inside the // arc, so the gun can fire along it. Direction: where a round from this gun travels and where its barrel points -- - // the subject's intercept when it bears, else the arc-clamped aim. A chunk subject bears through its pose and - // flies the aim, as an untargeted round (Subject is null for it). Derived on every read and never stored: turrets + // the subject's intercept when it bears (a rock's too), else the arc-clamped aim. Subject is null for a rock. Derived on every read and never stored: turrets // traverse instantly in the simulation. Traverse is the weapon's Tracking (ruling mount-arc-gun-traverse), priced in // TrackingRate; this holds no slew state, and a rig's slew is presentation. It never prices; HitProbability is the one price. public static GunSolution Solution(Weapon weapon, Entity shooter, TargetRef subject) { - var bears = false; - if (subject.Entity != null) bears = Bears(weapon, shooter, subject.Entity, out _); - else if (subject.Chunk is ChunkId chunk) - { - var at = shooter.Zone.ChunkPose(chunk.Field, chunk.Index).xy; - bears = InArc(weapon.Item, float3(at.x, 0, at.y) - shooter.Position); - } + var bears = Bears(weapon, shooter, subject, out _); return new GunSolution { Subject = subject.Entity, Bears = bears, Free = InArc(weapon.Item, shooter.Aim), - Direction = bears && subject.Entity != null - ? TravelDirection(weapon, shooter, subject.Entity) - : AimDirection(weapon.Item, shooter) + Direction = bears ? TravelDirection(weapon, shooter, subject) : AimDirection(weapon.Item, shooter) }; } @@ -224,8 +215,8 @@ public static class FireControl return degrees(abs(offset.x * relativeVelocity.y - offset.y * relativeVelocity.x) / (range * range)); } - public static float AngularVelocity(Entity source, Entity target) => - AngularVelocity((target.Position - source.Position).xz, target.Velocity - source.Velocity); + public static float AngularVelocity(Entity source, TargetRef target) => + AngularVelocity((PositionOf(source, target) - source.Position).xz, VelocityOf(source, target) - source.Velocity); // The gun's rate times the ship's gear over the unaided baseline (ruling tracking-per-gun, "gun times ship"): the // one product of the two. An unauthored gun is +infinity and so is its rate whatever the gear reads: a mount with no @@ -241,14 +232,31 @@ public static class FireControl // be judged against another. This is the one function; CombatState (and FireControl.Fire below) both call // it instead of touching CultMath.first_order_intercept directly. Planar: source velocity is never fed in // (no shooter here leads its own motion into the shot), matching every existing call site this replaces. - public static float3 PredictedIntercept(Weapon weapon, Entity source, Entity target) + // Mining Cut 4b: a target is an entity or a rock; its position and velocity come from PositionOf and VelocityOf. + public static float3 PredictedIntercept(Weapon weapon, Entity source, TargetRef target) { - var targetVelocity = float3(target.Velocity.x, 0, target.Velocity.y); + var position = PositionOf(source, target); + var velocity = VelocityOf(source, target); return weapon.Velocity > .01f - ? first_order_intercept(source.Position, float3.zero, weapon.Velocity, target.Position, targetVelocity) - : target.Position; + ? first_order_intercept(source.Position, float3.zero, weapon.Velocity, position, float3(velocity.x, 0, velocity.y)) + : position; } + // Where a target is now: an entity's position, a rock's pose at the shooter's height (everything here is planar). + private static float3 PositionOf(Entity source, TargetRef target) + { + if (target.Chunk is ChunkId chunk) + { + var at = source.Zone.ChunkPose(chunk.Field, chunk.Index).xy; + return float3(at.x, source.Position.y, at.y); + } + return target.Entity.Position; + } + + // How fast a target moves: an entity's velocity, a rock's from Zone.ChunkVelocity, the one owner. + private static float2 VelocityOf(Entity source, TargetRef target) => + target.Chunk is ChunkId chunk ? source.Zone.ChunkVelocity(chunk) : target.Entity.Velocity; + // Cut 3, R1/R3: the targeting solution (0b table) -- pure, no draw, recomputed fresh on every call. AI // reads this to decide whether a shot is worth taking; the HUD reads it to draw a number; Fire below reads // it once, at the instant the trigger is pulled, and freezes the result into the shot (R10, Q6). Two reads @@ -263,13 +271,13 @@ public static class FireControl // freezes (R10), gated exactly as HitProbability gates. Nothing about the target's facing or silhouette // enters here; that is Silhouette's and PSpread's job, priced fresh by HitProbability below and again, // live, by Commit at the commit tick. 0 the moment any gate closes. - private static float PFire(Weapon weapon, Entity source, Entity target) => PFire(weapon, source, target, out _, out _, out _); + private static float PFire(Weapon weapon, Entity source, TargetRef target) => PFire(weapon, source, target, out _, out _, out _); // The `out range` overload is HitProbability's own gate call -- one computation of `target.Position - // source.Position`, not two. HitProbability used to recompute its own copy for PSpread, which is exactly // the kind of split authority Cut 3 named as the risk (two places computing the same vector, free to // drift or to have their subtraction order flipped in only one of them). - private static float PFire(Weapon weapon, Entity source, Entity target, out float range) => + private static float PFire(Weapon weapon, Entity source, TargetRef target, out float range) => PFire(weapon, source, target, out range, out _, out _); // The one answer to "does the shooter hold valid targeting data on this target": visible, in range and locked @@ -279,25 +287,29 @@ public static class FireControl // visible, out of range) already denies the target. Planar (R7: the simulation is 2D): the range gate, the // burst reach and the range clamp all measure the same distance, so a target's height never moves one of // them without the others. - public static bool Designated(Weapon weapon, Entity source, Entity target, out float range) + // Mining Cut 4b: a rock is designated by the same range gates, seen when Entity.ChunkVisible says so; a + // LockWeapon (a launcher) is never designated on a rock (ruling Q12 = A, 2026-09-30). + public static bool Designated(Weapon weapon, Entity source, TargetRef target, out float range) { range = 0f; - if (target == null) return false; - range = length((target.Position - source.Position).xz); - return source.VisibleEntities.Contains(target) && range >= weapon.MinRange && range <= weapon.Range && + if (target.IsNone) return false; + range = length((PositionOf(source, target) - source.Position).xz); + var inRange = range >= weapon.MinRange && range <= weapon.Range; + if (target.Chunk is ChunkId chunk) return inRange && !(weapon is LockWeapon) && source.ChunkVisible(chunk); + return source.VisibleEntities.Contains(target.Entity) && inRange && !(weapon is LockWeapon lockWeapon && !lockWeapon.IsLocked); } // Whether this gun can engage this target: designated and inside the arc. The one test of it; PFire prices a shot // at zero unless it holds, and Solution reads it to decide whether the gun fires on the target. `designated` is // the answer above, kept apart for Solve's burst flight: a designated target out of arc still sets the burst range. - public static bool Bears(Weapon weapon, Entity source, Entity target, out float range) => + public static bool Bears(Weapon weapon, Entity source, TargetRef target, out float range) => Bears(weapon, source, target, out range, out _); - private static bool Bears(Weapon weapon, Entity source, Entity target, out float range, out bool designated) + private static bool Bears(Weapon weapon, Entity source, TargetRef target, out float range, out bool designated) { designated = Designated(weapon, source, target, out range); - return designated && InArc(weapon.Item, target.Position - source.Position); + return designated && InArc(weapon.Item, PositionOf(source, target) - source.Position); } // `designated` is the answer above. `inArc` is Bears, asked only once a target is designated. @@ -305,13 +317,14 @@ public static class FireControl // (operator rulings 2026-09-30): without valid data it has no target and bursts at max range; with data but // out of arc it bursts at the target's range, along the aim. The HUD reads Designated and the // arc from Solve and Inspect and decides nothing. - private static float PFire(Weapon weapon, Entity source, Entity target, out float range, out bool designated, out bool inArc) + private static float PFire(Weapon weapon, Entity source, TargetRef target, out float range, out bool designated, out bool inArc) { inArc = Bears(weapon, source, target, out range, out designated); if (!inArc) return 0f; var settings = source.ItemManager.GameplaySettings; - var info = source.EntityInfoGathered.TryGetValue(target, out var gathered) ? gathered : 0f; + var info = target.Chunk is ChunkId chunk ? source.ChunkInfo(chunk) + : source.EntityInfoGathered.TryGetValue(target.Entity, out var gathered) ? gathered : 0f; return Accuracy(source) * PSensor(settings, Resolution(source), info); } @@ -364,22 +377,33 @@ public static class FireControl return (sil, pSpread, evasion); } - public static float HitProbability(Weapon weapon, Entity source, Entity target) => + public static float HitProbability(Weapon weapon, Entity source, TargetRef target) => HitProbability(weapon, source, target, (AimTarget?) null); // Priced on `aim` rather than the source's aim slot: the aim its pilot commands this step. - public static float HitProbability(Weapon weapon, Entity source, Entity target, AimTarget aim) => + public static float HitProbability(Weapon weapon, Entity source, TargetRef target, AimTarget aim) => HitProbability(weapon, source, target, (AimTarget?) aim); // A null aim reads source.ResolvedAim, after the gate, so a gated-out shot reads nothing more. - private static float HitProbability(Weapon weapon, Entity source, Entity target, AimTarget? aim) + // Mining Cut 4b: a rock is priced by the same factors as a ship at equal range, precision and info -- its disc + // through the same integrator, its evasion 0 (a rock is not a Ship), and no aim point: the disc is aimed at. + private static float HitProbability(Weapon weapon, Entity source, TargetRef target, AimTarget? aim) { var pFire = PFire(weapon, source, target, out var range); if (pFire <= 0f) return 0f; - var targetHull = source.ItemManager.GetData(target.Hull) as HullData; - var (sil, pSpread, evasion) = Forecast(weapon, source, target, targetHull, Precision(source), range, aim ?? source.ResolvedAim); - return pFire * PMount(AngularVelocity(source, target), TrackingRate(weapon, source)) * pSpread * sil.POnHull * PDeviation(evasion, Tracking(source)); + var pMount = PMount(AngularVelocity(source, target), TrackingRate(weapon, source)); + if (target.Chunk is ChunkId chunk) + { + var mass = RockMass(source.Zone, chunk, Precision(source), out var span); + var pSpreadRock = PSpread(weapon.Spread, span, range, source.ItemManager.GameplaySettings.SchematicCellSize); + return pFire * pMount * pSpreadRock * mass * PDeviation(0f, Tracking(source)); + } + + var entity = target.Entity; + var targetHull = source.ItemManager.GetData(entity.Hull) as HullData; + var (sil, pSpread, evasion) = Forecast(weapon, source, entity, targetHull, Precision(source), range, aim ?? source.ResolvedAim); + return pFire * pMount * pSpread * sil.POnHull * PDeviation(evasion, Tracking(source)); } // Presentation only: the debug HUD's view of exactly the factors HitProbability multiplies. It computes @@ -457,7 +481,7 @@ public static class FireControl // at Fire (R10); HitProbability and Inspect recompute it fresh, at the current source/target positions, // for their forecast. Below a length of 1e-6 (point-blank, source and intercept coincide) it falls back // to world +z, the same fallback Apply used before this cut (`:463`). - public static float2 TravelDirection(Weapon weapon, Entity source, Entity target) + public static float2 TravelDirection(Weapon weapon, Entity source, TargetRef target) { var toIntercept = (PredictedIntercept(weapon, source, target) - source.Position).xz; return lengthsq(toIntercept) < 1e-6f ? float2(0, 1) : normalize(toIntercept); @@ -505,12 +529,21 @@ public static class FireControl // The commit price's deviation: what the target has already moved off the frozen forecast, plus what it can and // does move off the line of fire (Evasion). The second part applies at any flight time, so an instant weapon // (flight time 0, realized deviation 0) still feels a jinking target. - public static float DeviationProbability(PendingShot shot, float now, out float deviation) + // Mining Cut 4b: a rock's deviation is where its pose is now against that projection, with no evasion; its + // zone is the shooter's (a shot that outlives its shooter is resolved by Step, which passes the zone it runs in). + public static float DeviationProbability(PendingShot shot, float now, out float deviation) => + DeviationProbability(shot.Source?.Zone, shot, now, out deviation); + + private static float DeviationProbability(Zone zone, PendingShot shot, float now, out float deviation) { + deviation = 0f; + if (shot.Target == null && shot.Chunk == null) return 1f; var elapsed = now - shot.FireTime; var predicted = shot.FireTargetPosition + shot.FireTargetVelocity * elapsed; - deviation = shot.Target == null ? 0f : length((shot.Target.Position - predicted).xz) + Evasion(shot.Target, shot.TravelDirection); - return shot.Target == null ? 1f : PDeviation(deviation, shot.Tracking); + deviation = shot.Chunk is ChunkId chunk + ? length(zone.ChunkPose(chunk.Field, chunk.Index).xy - predicted.xz) + : length((shot.Target.Position - predicted).xz) + Evasion(shot.Target, shot.TravelDirection); + return PDeviation(deviation, shot.Tracking); } // How far a target can and does move off the line of fire in the solution window: the term DeviationProbability @@ -608,7 +641,7 @@ public static class FireControl // BurstReach the planar distance from the shooter at which the payload is delivered (a direct round's target, a fused // round's burst point, 0 for an untargeted direct round), which Fire's range factor reads for every outcome. Refused: a fused round whose blast // radius (its arming distance) exceeds the weapon's Range; it cannot be fired. - public static FireSolution Solve(Weapon weapon, EquippedItem item, Entity source, Entity target) + public static FireSolution Solve(Weapon weapon, EquippedItem item, Entity source, TargetRef target) { var pFire = PFire(weapon, source, target, out var fireRange, out var designated, out var inArc); @@ -639,14 +672,14 @@ public static class FireControl // that leaves the zone cancels it like any other. A round whose Range is shorter than the arming distance // cannot be fired at all: it is refused, per round, where Range is read after Execute refreshed it (a // burst's later rounds and a power-starved Range included). - var engaged = fuse != null && !(designated && inArc) ? null : target; + var engaged = fuse != null && !(designated && inArc) ? TargetRef.None : target; var origin = source.Position; var travelDirection = Solution(weapon, source, target).Direction; var arming = fuse != null ? blastRadius : 0f; - var burstPosition = engaged != null ? engaged.Position : origin; + var burstPosition = !engaged.IsNone ? PositionOf(source, engaged) : origin; var flightDistance = 0f; - if (fuse != null && engaged != null) + if (fuse != null && !engaged.IsNone) { // Nothing bursts beyond max range: an intercept a receding target leads the round past Range is // pulled back along its own line to Range. @@ -662,7 +695,7 @@ public static class FireControl burstPosition = Armed(origin, travelDirection, arming, origin + float3(travelDirection.x, 0, travelDirection.y) * reach); flightDistance = max(reach, arming); } - else if (engaged != null) flightDistance = fireRange; + else if (!engaged.IsNone) flightDistance = fireRange; var solution = new FireSolution { @@ -710,8 +743,7 @@ public static class FireControl Lay(weapon, item, source); return 0; } - // Mining Cut 3: a chunk target fires as an untargeted round until Cut 4 routes shots at chunks. - var target = source.Target.Value.Entity; + var target = source.Target.Value; var now = zone.Time - age; // R1's engage gate and the shooter-side probability, evaluated now and frozen: nothing at commit time @@ -721,7 +753,7 @@ public static class FireControl var solution = Solve(weapon, item, source, target); if (solution.Outcome == FireOutcome.Refused) return 0; // The mount factor is frozen with the shooter-side probability: nothing at commit time re-reads the sweep. - var pFire = solution.PFire * (solution.Engaged != null ? PMount(AngularVelocity(source, solution.Engaged), TrackingRate(weapon, source)) : 1f); + var pFire = solution.PFire * (!solution.Engaged.IsNone ? PMount(AngularVelocity(source, solution.Engaged), TrackingRate(weapon, source)) : 1f); var fireRange = solution.FireRange; var engaged = solution.Engaged; var travelDirection = solution.TravelDirection; @@ -732,10 +764,11 @@ public static class FireControl var targetVelocity = float3.zero; var targetPosition = origin; - if (engaged != null) + if (!engaged.IsNone) { - targetVelocity = float3(engaged.Velocity.x, 0, engaged.Velocity.y); - targetPosition = engaged.Position - targetVelocity * age; + var velocity = VelocityOf(source, engaged); + targetVelocity = float3(velocity.x, 0, velocity.y); + targetPosition = PositionOf(source, engaged) - targetVelocity * age; } var flightTime = weapon.Velocity > .01f ? solution.FlightDistance / weapon.Velocity : 0f; @@ -746,7 +779,8 @@ public static class FireControl { ShotId = zone.NextShotId(), Source = source, - Target = engaged, + Target = engaged.Entity, + Chunk = engaged.Chunk, Weapon = item, Aimed = aim.Item, AimedMount = aim.Mount, @@ -773,7 +807,7 @@ public static class FireControl // The commit horizon exists so the target's facing can be read late (Bearing timing). A round fired at // nothing has no facing to read, so it commits at Fire: its burst point is decided from the poses of // the moment it leaves, and a Contact round short of max range can arrive as early as it truly does. - CommitTime = fuse != null && engaged == null ? now : now + max(0f, flightTime - commitHorizon), + CommitTime = fuse != null && engaged.IsNone ? now : now + max(0f, flightTime - commitHorizon), BurstPosition = burstPosition, Fuse = fuse, BlastRadius = blastRadius, @@ -861,7 +895,7 @@ public static class FireControl { var shot = shots[i]; - var targetGone = shot.Target != null && !zone.Entities.Contains(shot.Target); + var targetGone = TargetGone(zone, shot); if (targetGone) { // Cut 11 (Soul C4): a shot whose target has left the zone resolves as a miss whichever @@ -908,7 +942,7 @@ public static class FireControl if (i < 0) continue; var shot = shots[i]; - var targetGone = shot.Target != null && !zone.Entities.Contains(shot.Target); + var targetGone = TargetGone(zone, shot); if (targetGone) { // As in the commit walk: a shot whose target left the zone in this step resolves as a miss. @@ -930,6 +964,10 @@ public static class FireControl } } + // A shot's target has left the zone, or a rock it flies at no longer exists (broken in flight): the shot is a miss. + private static bool TargetGone(Zone zone, PendingShot shot) => + (shot.Target != null && !zone.Entities.Contains(shot.Target)) || (shot.Chunk is ChunkId chunk && !zone.ChunkExists(chunk)); + // R3/R4: the one roll. p_base was frozen at fire, PFire carrying the mount factor; the only thing measured live is how far the target has // actually strayed, by now, from where a straight-line projection of its fire-time velocity said it would // be -- forgiven by the targeting system's Tracking, likewise frozen at fire. @@ -945,15 +983,25 @@ public static class FireControl // (bearing) -- is read live, here, at the commit tick. The Cut 7 guard extends to cover the new factors: // when PFire x pDeviation is already 0, no Silhouette is built. Shared by Commit's own roll and by the // debug HUD's forecast (TheHudEstimateIsTheCommitPrice) -- one function, one commit-time price. - public static float CommitProbability(PendingShot shot, float now, out Silhouette sil) + public static float CommitProbability(PendingShot shot, float now, out Silhouette sil) => + CommitProbability(shot.Source?.Zone, shot, now, out sil); + + // Mining Cut 4b: a rock's price is PFire x PDeviation x PSpread(span 2R) x the disc's mass; it reads no hull. + private static float CommitProbability(Zone zone, PendingShot shot, float now, out Silhouette sil) { sil = default; - if (shot.Target == null) return 0f; + if (shot.Target == null && shot.Chunk == null) return 0f; - var pDeviation = DeviationProbability(shot, now, out _); + var pDeviation = DeviationProbability(zone, shot, now, out _); var p = shot.PFire * pDeviation; if (p <= 0f) return 0f; + if (shot.Chunk is ChunkId chunk) + { + var mass = RockMass(zone, chunk, shot.Precision, out var span); + return p * PSpread(shot.Spread, span, shot.FireRange, zone.SchematicCellSize) * mass; + } + var bearing = Bearing(shot.Target, shot.TravelDirection); var hullData = shot.Target.ItemManager.GetData(shot.Target.Hull) as HullData; sil = Silhouette(shot.Target, hullData, shot.Aimed, bearing, shot.Precision, null, shot.AimedMount); @@ -984,7 +1032,7 @@ public static class FireControl // drawing once is the documented way to get a correlated first output, and a follow-up to give // CultMath.Random a mixed-seed entry point of its own is recorded for a separate CultLib cut. var random = new Random(SimulationDice.Mix((zone.CombatSeed * 2654435761u) ^ (uint) shot.ShotId | 1u)); - var p = CommitProbability(shot, now, out var sil); + var p = CommitProbability(zone, shot, now, out var sil); var hit = p > 0f && random.NextFloat() < p; var cell = int2.zero; @@ -993,7 +1041,8 @@ public static class FireControl var shielded = false; var shieldBroken = false; - if (hit) + // A rock hit has no lane and no shield: Cell, Bearing and Lateral stay zero (Apply wears the rock). + if (hit && shot.Chunk == null) { // Cut 12.2: the same silhouette pOnHull drew its mass from -- same bearing (live, at this commit // tick), same sigma (the frozen Precision). A shot that passed the roll always lands on metal (R3: @@ -1189,6 +1238,12 @@ public static class FireControl return; } + if (shot.Chunk is ChunkId rock) + { + ApplyRockHit(zone, shot, rock); + return; + } + switch (shot.Fuse) { case null: @@ -1201,6 +1256,27 @@ public static class FireControl } } + // Mining Cut 4b: a committed hit on a rock. A round without a fuse wears the rock by its Damage (the falloff was + // read at Fire) and publishes one absorb on the zone's ChunkCapabilities (through Publish, at height 0 like a blast's), at the + // rock's surface facing the shot and before the wear shrinks it. A contact or delayed round detonates at the rock's centre as it arrives (the + // arming rule kept), through Detonate, the one area owner. + private static void ApplyRockHit(Zone zone, PendingShot shot, ChunkId rock) + { + if (!shot.Outcome.Hit) return; + + var centre = zone.ChunkPose(rock.Field, rock.Index).xy; + if (shot.Fuse == null) + { + var direction = float3(shot.TravelDirection.x, 0, shot.TravelDirection.y); + var surface = centre - shot.TravelDirection * zone.ChunkRadius(rock); + Publish(zone.ChunkCapabilities, AbsorbLayer.Hull, float3(surface.x, 0f, surface.y), direction, shot.Damage, shot.DamageType); + zone.Wear(rock, shot.Damage); + return; + } + var point = Armed(shot.FireOrigin, shot.TravelDirection, shot.BlastRadius, float3(centre.x, shot.FireOrigin.y, centre.y)).xz; + Detonate(zone, point, shot.BlastRadius, shot.Damage, shot.DamageType); + } + // Cut 12.3 (docs/fire-control-cut.md, "How a direct hit travels"): replaces Entity.ApplyHit's 0.5-step // march and Entity.DamageSchematic's even split over the whole hit shape. Spread is width (Q12-2 = A): // 2n+1 parallel lanes, sharing the shot's damage evenly over whichever lanes actually meet metal -- the @@ -1221,7 +1297,7 @@ public static class FireControl if (shot.Outcome.Shielded) { - Publish(shot.Target, AbsorbLayer.Shield, ImpactPoint(shot.Target, shot.Outcome.Cell), + Publish(shot.Target.Capabilities, AbsorbLayer.Shield, ImpactPoint(shot.Target, shot.Outcome.Cell), float3(shot.TravelDirection.x, 0, shot.TravelDirection.y), shot.Damage, shot.DamageType); shot.Target.Shield.TakeHit(shot.DamageType, shot.Damage); return; @@ -1266,7 +1342,7 @@ public static class FireControl for (var li = 0; li < laneCount; li++) ArrayPool<LaneCell>.Shared.Return(buffers[li]); - Publish(target, AbsorbLayer.Hull, ImpactPoint(target, shot.Outcome.Cell), + Publish(target.Capabilities, AbsorbLayer.Hull, ImpactPoint(target, shot.Outcome.Cell), float3(shot.TravelDirection.x, 0, shot.TravelDirection.y), shot.Damage, shot.DamageType); target.DamageHull(hullDamage); } @@ -1278,17 +1354,18 @@ public static class FireControl return float3(world.x, target.Position.y, world.y); } - // The one publisher of an absorbed impact: once per receiver, on its Capabilities, before the damage it reports. - private static void Publish(Entity receiver, AbsorbLayer layer, float3 position, float3 direction, float magnitude, DamageType damageType) => - receiver.Capabilities.PublishAbsorb(new AbsorbEvent(position, direction, magnitude, damageType, layer)); + // The one publisher of an absorbed impact: once per receiver, on its CapabilityEvents (an entity's, or the zone's + // for a rock), before the damage it reports. + private static void Publish(CapabilityEvents receiver, AbsorbLayer layer, float3 position, float3 direction, float magnitude, DamageType damageType) => + receiver.PublishAbsorb(new AbsorbEvent(position, direction, magnitude, damageType, layer)); - // A blast's impact on one entity: at the blast point (on the entity's height), travelling from the blast out through - // the entity's centre, or zero when they coincide. - private static void PublishBlast(Entity entity, float2 blast, AbsorbLayer layer, float magnitude, DamageType damageType) + // A blast's impact on one receiver: at the blast point (at the receiver's height), travelling from the blast out + // through the receiver's planar centre, or zero when they coincide. An entity and a rock go through it alike. + private static void PublishBlast(CapabilityEvents receiver, float2 centre, float height, float2 blast, AbsorbLayer layer, float magnitude, DamageType damageType) { - var away = entity.Position.xz - blast; + var away = centre - blast; var direction = lengthsq(away) > 0f ? normalize(away) : float2.zero; - Publish(entity, layer, float3(blast.x, entity.Position.y, blast.y), float3(direction.x, 0, direction.y), magnitude, damageType); + Publish(receiver, layer, float3(blast.x, height, blast.y), float3(direction.x, 0, direction.y), magnitude, damageType); } // Cut 12.4(b) (docs/fire-control-cut.md, "Where P is"): a contact or delayed blast needs a committed hit -- @@ -1593,6 +1670,7 @@ public static class FireControl ShotId = shot.ShotId, Source = shot.Source, Target = shot.Target, + Chunk = shot.Chunk, Weapon = shot.Weapon, Result = result, Shielded = shielded, @@ -1607,7 +1685,13 @@ public static class FireControl // Cut 12.4(b) (docs/fire-control-cut.md, "Area, per entity"): the one owner of blast damage -- a blast is // an area, not a bundle of rays (Q12-7 dissolved the ray model's remainder question along with the rays - // themselves). Splash's signature with the point made planar (R7). Callers: Apply's three fuse branches. Nothing draws: every candidate entity in radius takes its share, unconditionally. + // themselves). Splash's signature with the point made planar (R7). Callers: Apply's three fuse branches and + // Zone's mine step. Nothing draws: every candidate entity in radius takes its share, unconditionally. + // + // Mining cut 4a (docs/mining-cut-refresh.md, Q10 = A): this is also the one owner of blast area over rocks. + // After the entity pass, every unbroken rock whose disc the blast disc overlaps takes its lens share of the + // damage -- damage * lens / (pi r^2), the cells' own normaliser -- through Zone.Wear, and publishes one absorb + // on Zone.ChunkCapabilities first. Overlapping bodies each take their own overlap; shares off every body are lost. // // For each candidate (an entity whose centre lies within radius plus half its own hull diagonal -- // CandidatesIncludeHullsWhoseCentreIsOutsideTheRadius, which Splash's centre-distance cull could not pass): @@ -1673,7 +1757,7 @@ public static class FireControl { if (shield.CanTakeHit(damageType, totalShare)) { - PublishBlast(entity, worldPlanar, AbsorbLayer.Shield, totalShare, damageType); + PublishBlast(entity.Capabilities, entity.Position.xz, entity.Position.y, worldPlanar, AbsorbLayer.Shield, totalShare, damageType); shield.TakeHit(damageType, totalShare); continue; } @@ -1703,11 +1787,37 @@ public static class FireControl for (var i = 0; i < amounts.Length; i++) hullTotal += amounts[i]; } - PublishBlast(entity, worldPlanar, AbsorbLayer.Hull, totalShare, damageType); + PublishBlast(entity.Capabilities, entity.Position.xz, entity.Position.y, worldPlanar, AbsorbLayer.Hull, totalShare, damageType); entity.DamageHull(hullTotal); } + + if (!(radius > 0f) || zone.AsteroidBelts.Count == 0) return; // no area, or no rocks to cover + // Rocks, through the targeting index (no observer: entities stay out of it). Reach is exact on a rock's + // centre, so it is the blast radius plus the widest any rock can be. Walked in (field, index) order so the + // order of wear -- and any later dice on it -- is fixed. + var rocks = _rockScratch ??= new List<TargetCandidate>(); + zone.Targets.Within(new TargetSearch(worldPlanar, radius + Zone.LargestChunkRadius(zone.Settings)), rocks); + rocks.RemoveAll(c => !c.Target.Chunk.HasValue); + rocks.Sort((a, b) => + { + var byField = string.CompareOrdinal(a.Target.Chunk.Value.Field.Value, b.Target.Chunk.Value.Field.Value); + return byField != 0 ? byField : a.Target.Chunk.Value.Index.CompareTo(b.Target.Chunk.Value.Index); + }); + var discArea = PI * radius * radius; + foreach (var rock in rocks) + { + var chunk = rock.Target.Chunk.Value; + if (!zone.ChunkExists(chunk)) continue; + var centre = zone.ChunkPose(chunk.Field, chunk.Index).xy; + var share = damage * CircleCircleOverlap(length(centre - worldPlanar), radius, zone.ChunkRadius(chunk)) / discArea; + if (!(share > 0f)) continue; + PublishBlast(zone.ChunkCapabilities, centre, 0f, worldPlanar, AbsorbLayer.Hull, share, damageType); + zone.Wear(chunk, share); + } } + [ThreadStatic] private static List<TargetCandidate> _rockScratch; + // Whether the disc reaches any occupied hull cell of the entity: Detonate's own coverage test (the same // ToSchematicPoint, SchematicCellSize and CircleSquareOverlap), so what triggers a mine and what its blast // reaches are one geometry. @@ -1721,6 +1831,19 @@ public static class FireControl return false; } + // Mining cut 4a: the exact area shared by two discs at centre distance d -- the lens. Exactly zero when they are + // disjoint or tangent, and the smaller disc's whole area when one contains the other. + public static float CircleCircleOverlap(float d, float r1, float r2) + { + if (r1 <= 0f || r2 <= 0f || d >= r1 + r2) return 0f; + var small = min(r1, r2); + if (d <= abs(r1 - r2)) return PI * small * small; + var a = (d * d + r1 * r1 - r2 * r2) / (2f * d * r1); + var b = (d * d + r2 * r2 - r1 * r1) / (2f * d * r2); + var k = (-d + r1 + r2) * (d + r1 - r2) * (d - r1 + r2) * (d + r1 + r2); + return r1 * r1 * acos(clamp(a, -1f, 1f)) + r2 * r2 * acos(clamp(b, -1f, 1f)) - .5f * sqrt(max(0f, k)); + } + // Cut 12.4(b) (docs/fire-control-cut.md, "Exact overlap, in float"): the exact area of a unit square, // centred on `cell` (the unit square centred on its integer coordinate, the same convention every other // frame rule uses), that lies inside a disc of radius `r` centred at `diskCentre` -- both in the same @@ -1876,9 +1999,7 @@ public static class FireControl var aimPoint = ResolveAimPoint(target, hull, aimed, mount); var a = dot(aimPoint, ell); - var pOnHull = 0f; - for (var i = 0; i < count; i++) - pOnHull += Phi((intervals[i].Hi - a) / sigma) - Phi((intervals[i].Lo - a) / sigma); + var pOnHull = Mass(new ReadOnlySpan<Interval>(intervals, 0, count), a, sigma); var span = count > 0 ? intervals[count - 1].Hi - intervals[0].Lo : 0f; @@ -1894,6 +2015,27 @@ public static class FireControl }; } + // The one Gaussian integrator: the mass a normal of `sigma` about `aim` puts inside the merged, disjoint + // `intervals`. A hull's shadow and a rock's disc (one interval about its aim) both read it. + private static float Mass(ReadOnlySpan<Interval> intervals, float aim, float sigma) + { + var mass = 0f; + foreach (var interval in intervals) + mass += Phi((interval.Hi - aim) / sigma) - Phi((interval.Lo - aim) / sigma); + return mass; + } + + // A rock is a disc of radius R schematic cells aimed at its centre: one interval [-R, R] about the aim, span 2R. + // The one price of it, read by HitProbability's forecast and by Commit, at the rock's radius now. + private static float RockMass(Zone zone, ChunkId chunk, float precision, out float span) + { + var radius = zone.ChunkCells(chunk); + span = 2f * radius; + Span<Interval> disc = stackalloc Interval[1]; + disc[0] = new Interval { Lo = -radius, Hi = radius }; + return saturate(Mass(disc, 0f, Sigma(precision))); + } + // Phi(z) = 1/2 (1 + erf(z / sqrt(2))): the standard normal CDF, CultMath's erf the one function underneath // every Gaussian-mass sum this cut computes. private static float Phi(float z) => .5f * (1f + erf(z * (1f / SQRT2))); @@ -2054,6 +2196,9 @@ public struct PendingShot public int ShotId; public Entity Source; public Entity Target; + // Mining Cut 4b: the rock a shot flies at, frozen at Fire; at most one of Target and Chunk is set. Unity reads + // Target only, so a rock shot draws untargeted until the Unity follow-up (mining-unity-chunk-presentation). + public ChunkId? Chunk; public EquippedItem Weapon; public EquippedItem Aimed; // The mount the aim was at, when it was at a mount rather than an item (Entity.ResolvedAim at Fire), frozen with Aimed: @@ -2113,7 +2258,7 @@ public struct PendingShot // A fused round with no target: where it bursts is decided at its commit (the first hull its aim line meets), so its // damage reads the falloff there rather than at Fire. - public bool DeliveredAtCommit => Fuse != null && Target == null; + public bool DeliveredAtCommit => Fuse != null && Target == null && Chunk == null; } // What a round does when fired (FireControl.Solve): Direct resolves against its target, Burst detonates at a @@ -2147,7 +2292,7 @@ public struct FireSolution public float FireRange; // Whether the shooter holds valid targeting data on the target (Designated); the HUD and the agents read it here. public bool Designated; - public Entity Engaged; + public TargetRef Engaged; public float2 TravelDirection; public float3 BurstPosition; public WeaponFuse? Fuse; @@ -2313,6 +2458,7 @@ public sealed class ShotOutcome public int ShotId; public Entity Source; public Entity Target; + public ChunkId? Chunk; public EquippedItem Weapon; // What the commit decided, typed: a shot rolled and missed, rolled and hit, or was a fused round with no // target and so burst without rolling, or a proximity round whose roll missed but which detonates anyway diff --git a/Assets/Scripts/ServerShared/Targeting/BeltTargets.cs b/Assets/Scripts/ServerShared/Targeting/BeltTargets.cs index 3e12536c3..a64e0c624 100644 --- a/Assets/Scripts/ServerShared/Targeting/BeltTargets.cs +++ b/Assets/Scripts/ServerShared/Targeting/BeltTargets.cs @@ -48,8 +48,7 @@ public sealed class BeltTargets : ITargetProvider _zone = zone; _field = field; _data = data; - var size = settings.AsteroidSize; - _largestRadius = size.Exponent > 0 ? max(abs(size.Minimum), abs(size.Maximum)) : float.PositiveInfinity; + _largestRadius = Zone.LargestChunkRadius(settings); var count = data.Asteroids.Length; _periods = new double[count]; diff --git a/Assets/Scripts/ServerShared/Zone.cs b/Assets/Scripts/ServerShared/Zone.cs index 6ba9ef7d7..d0c5b5330 100644 --- a/Assets/Scripts/ServerShared/Zone.cs +++ b/Assets/Scripts/ServerShared/Zone.cs @@ -62,6 +62,9 @@ public class Zone // the entities, and one provider per belt. The reticle, cycling and any range query over rocks go through it; // nothing else scans a belt. public readonly TargetingIndex Targets = new TargetingIndex(); + // Mining cut 4a: the receiver of every rock impact FireControl.Detonate publishes. Notification only: a presenter + // subscribes once per zone, and nothing in ServerShared reads it. + public readonly CapabilityEvents ChunkCapabilities = new CapabilityEvents(); private readonly List<Sun> _suns = new List<Sun>(); private HashSet<CultRecordKey> _updatedOrbits = new HashSet<CultRecordKey>(); @@ -674,6 +677,14 @@ public class Zone return belt.DamagedSize(chunk.Index, wear.Damage, Settings); } + // No rock of any belt, whole or worn, is wider than this (AsteroidSize's bound over every argument, so over the + // Asteroid.Size range the generator writes). The index's visibility bound and a blast's query reach both use it. + public static float LargestChunkRadius(PlanetSettings settings) + { + var size = settings.AsteroidSize; + return size.Exponent > 0 ? max(abs(size.Minimum), abs(size.Maximum)) : float.PositiveInfinity; + } + // Cut 2: the only writer of chunk wear. Returns whether this hit broke the chunk. The break threshold is // strictly greater-than, matching the deleted per-tick miner's own comparison against accumulated damage: // damage exactly equal to hitpoints does not yet break the chunk, only damage that exceeds them does. @@ -715,6 +726,20 @@ public class Zone return AsteroidBelts[belt].Pose(index, time, parentPosition, size); } + // Mining Cut 4b: the one owner of a chunk's planar velocity, the central difference of the pose function at zone + // time. Derived on every read, never stored: the intercept, the fire-time projection and the mount's sweep all + // read it here. + public float2 ChunkVelocity(ChunkId chunk) + { + const double h = .05; + var ahead = ChunkPose(chunk.Field, chunk.Index, _time + h).xy; + var behind = ChunkPose(chunk.Field, chunk.Index, _time - h).xy; + return (ahead - behind) / (float) (2 * h); + } + + // A chunk's radius in schematic cells: what visibility and a shot's silhouette both measure it in. + public float ChunkCells(ChunkId chunk) => ChunkRadius(chunk) / SchematicCellSize; + // Mining Cut 3 (docs/mining-cut-refresh.md): how bright a chunk is -- Reflector's rule (cross-section × the light // on it), with the field kind's reflectivity per schematic cell times the chunk's area in cells. Computed when // asked; nothing about it is stored. A worn chunk shrinks and dims; a broken one, or one of a kindless belt, is dark. @@ -723,7 +748,7 @@ public class Zone if (!ChunkExists(chunk)) return 0f; var kind = _itemManager.ItemData.Get(((AsteroidBeltData) Planets[chunk.Field]).Kind); if (kind == null) return 0f; - var cells = ChunkRadius(chunk) / _itemManager.GameplaySettings.SchematicCellSize; + var cells = ChunkCells(chunk); return kind.CrossSection * PI * cells * cells * GetLight(ChunkPose(chunk.Field, chunk.Index).xy); } diff --git a/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs b/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs index dc6ffd628..76a67472a 100644 --- a/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs +++ b/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs @@ -32,7 +32,7 @@ public sealed partial class MiningCut3Tests : IDisposable Directory.Delete(_root, true); } - private static PerformanceStat Constant(float v) => new PerformanceStat { Min = v, Max = v }; + internal static PerformanceStat Constant(float v) => new PerformanceStat { Min = v, Max = v }; private static GameplaySettings GameSettings() => new GameplaySettings { @@ -49,7 +49,7 @@ public sealed partial class MiningCut3Tests : IDisposable // Every sun carries a well (the belts circle in it, c = 9), one sun whose light reaches 1000 units, and the chunk // curves MiningCut2Tests uses, so sizes and wear vary over the fixture's range. - private static PlanetSettings PlanetSettings(float lightRadius = 1000f) => new PlanetSettings + internal static PlanetSettings PlanetSettings(float lightRadius = 1000f) => new PlanetSettings { WellStrength = new ExponentialCurve { Constant = 9f }, RocheLimit = new ExponentialCurve { Constant = 1f }, @@ -66,7 +66,7 @@ public sealed partial class MiningCut3Tests : IDisposable Keys = new[] { new float4(0, 1, 0, 0), new float4(1, .3f, 0, 0) } }; - private sealed class Scene + internal sealed class Scene { public CultCache Cache; public ItemManager Items; @@ -81,16 +81,16 @@ public sealed partial class MiningCut3Tests : IDisposable // A belt around the sun: its chunks orbit the origin at their own distances, so at zone time 0 a chunk of // phase p sits at distance × (cos 2πp, sin 2πp). `kind` null leaves the belt kindless, for the zone to assign. - private sealed class BeltSpec + internal sealed class BeltSpec { public Asteroid[] Asteroids; public FieldKindData Kind; } - private static Asteroid Rock(float distance, float phase = 0f, float size = .5f) => + internal static Asteroid Rock(float distance, float phase = 0f, float size = .5f) => new Asteroid { Distance = distance, Phase = phase, Size = size, RotationSpeed = .1f }; - private Scene BuildScene(FieldKindData[] kinds = null, params BeltSpec[] belts) => BuildSceneAt(float2.zero, kinds, belts); + internal Scene BuildScene(FieldKindData[] kinds = null, params BeltSpec[] belts) => BuildSceneAt(float2.zero, kinds, belts); // The same scene with its sun, and so every belt centre, at `sunAt`. private Scene BuildSceneAt(float2 sunAt, FieldKindData[] kinds, params BeltSpec[] belts) => @@ -165,10 +165,10 @@ public sealed partial class MiningCut3Tests : IDisposable return scene; } - private static FieldKindData Kind(string name, float crossSection, float weight = 1f) => + internal static FieldKindData Kind(string name, float crossSection, float weight = 1f) => new FieldKindData { Name = name, CrossSection = crossSection, GenerationWeight = weight }; - private static BeltSpec Belt(FieldKindData kind, params Asteroid[] asteroids) => new BeltSpec { Kind = kind, Asteroids = asteroids }; + internal static BeltSpec Belt(FieldKindData kind, params Asteroid[] asteroids) => new BeltSpec { Kind = kind, Asteroids = asteroids }; // A chunk's planar position now (zone time never advances in these tests). private static float2 At(Scene s, ChunkId chunk) => s.Zone.ChunkPose(chunk.Field, chunk.Index).xy; @@ -180,14 +180,14 @@ public sealed partial class MiningCut3Tests : IDisposable return kind.CrossSection * PI * cells * cells * s.Zone.GetLight(At(s, chunk)); } - private static GearData Gear(string name, BehaviorData behavior) => new GearData + internal static GearData Gear(string name, BehaviorData behavior) => new GearData { Name = name, Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 1, MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000, Behaviors = { behavior } }; - private static EquippableItem Mint(Scene s, ItemData design) => new EquippableItem + internal static EquippableItem Mint(Scene s, ItemData design) => new EquippableItem { Data = s.Cache.RefOf<ItemData>(design), Durability = design is EquippableItemData equippable ? equippable.Durability : 0, diff --git a/tests/Aetheria.Shared.Tests/MiningCut4aTests.cs b/tests/Aetheria.Shared.Tests/MiningCut4aTests.cs new file mode 100644 index 000000000..7d43c86d3 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/MiningCut4aTests.cs @@ -0,0 +1,279 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using System.Collections.Generic; +using System.Linq; +using CultMath; +using UniRx; +using Xunit; +using static CultMath.math; +using float2 = CultMath.float2; +using float3 = CultMath.float3; + +// Mining cut 4a (docs/mining-cut-refresh.md, Q10 = A): a blast's disc is shared by area over whatever it covers, hull +// cells or rocks, through FireControl.Detonate; each worn rock publishes one absorb on Zone.ChunkCapabilities. Reuses +// MiningCut3Tests' belt fixture (a partial of that class), so a filter on these tests names the methods below. +public sealed partial class MiningCut3Tests +{ + // A one-rock belt: the rock at phase 0 sits on +x of the belt centre, `size` its authored size. + private (Scene scene, ChunkId rock) OneRock(float size = .5f, float distance = 200f) + { + var kind = Kind("Asteroid", 4f); + var s = BuildScene(new[] { kind }, Belt(kind, Rock(distance, 0f, size))); + return (s, new ChunkId(s.Belts[0], 0)); + } + + private static List<AbsorbEvent> Absorbs(Scene s, List<IDisposable> subs) + { + var list = new List<AbsorbEvent>(); + subs.Add(s.Zone.ChunkCapabilities.Absorb.Subscribe(list.Add)); + return list; + } + + // The area of a disc at the origin of radius r1 and a disc at (d, 0) of radius r2, by midpoint integration of the + // chord overlap -- no formula of the code under test. + private static double NumericLens(double d, double r1, double r2) + { + var lo = Math.Max(-r1, d - r2); + var hi = Math.Min(r1, d + r2); + if (hi <= lo) return 0; + const int n = 400000; + var h = (hi - lo) / n; + var area = 0.0; + for (var i = 0; i < n; i++) + { + var x = lo + (i + .5) * h; + var a = Math.Sqrt(Math.Max(0, r1 * r1 - x * x)); + var b = Math.Sqrt(Math.Max(0, r2 * r2 - (x - d) * (x - d))); + area += 2 * Math.Min(a, b) * h; + } + return area; + } + + // The area of a disc centred (cx, cy) of radius r inside the axis-aligned rectangle, by the same integration. + private static double NumericDiscInRect(double cx, double cy, double r, double x0, double x1, double y0, double y1) + { + var lo = Math.Max(cx - r, x0); + var hi = Math.Min(cx + r, x1); + if (hi <= lo) return 0; + const int n = 400000; + var h = (hi - lo) / n; + var area = 0.0; + for (var i = 0; i < n; i++) + { + var x = lo + (i + .5) * h; + var half = Math.Sqrt(Math.Max(0, r * r - (x - cx) * (x - cx))); + area += Math.Max(0, Math.Min(cy + half, y1) - Math.Max(cy - half, y0)) * h; + } + return area; + } + + [Theory] + [InlineData(5f, 3f, 4f)] + [InlineData(1f, 3f, 4f)] + [InlineData(6.5f, 3f, 4f)] + [InlineData(2.5f, 2f, 5f)] + [InlineData(3f, 3f, 3f)] + public void CircleCircleOverlapIsTheLens(float d, float r1, float r2) + { + var expected = NumericLens(d, r1, r2); + Assert.Equal(expected, FireControl.CircleCircleOverlap(d, r1, r2), 3); + Assert.Equal(expected, FireControl.CircleCircleOverlap(d, r2, r1), 3); + } + + [Fact] + public void CircleCircleOverlapIsExactAtTheLimits() + { + Assert.Equal(0f, FireControl.CircleCircleOverlap(7f, 3f, 4f)); // tangent + Assert.Equal(0f, FireControl.CircleCircleOverlap(8f, 3f, 4f)); // disjoint + Assert.Equal(PI * 9f, FireControl.CircleCircleOverlap(1f, 3f, 4f), 3); // contained: the smaller disc + Assert.Equal(PI * 9f, FireControl.CircleCircleOverlap(0f, 4f, 3f), 3); // concentric + Assert.Equal(PI * 9f, FireControl.CircleCircleOverlap(1f, 3f, 4f), 3); + Assert.Equal(0f, FireControl.CircleCircleOverlap(0f, 0f, 3f)); + } + + [Fact] + public void ABlastBesideAnUntargetedRockWearsIt() + { + var (s, rock) = OneRock(); + var at = At(s, rock); + var radius = 5f; + var offset = 3f; + var undamaged = s.Zone.ChunkRadius(rock); + FireControl.Detonate(s.Zone, at + float2(offset, 0), radius, 10f, DamageType.Kinetic); + + var share = (float) (10.0 * NumericLens(offset, radius, undamaged) / (Math.PI * radius * radius)); + Assert.True(share > 0f); + Assert.Equal(s.Zone.AsteroidBelts[rock.Field].DamagedSize(rock.Index, share, s.Zone.Settings), s.Zone.ChunkRadius(rock), 3); + } + + [Fact] + public void ABlastSharesItsDiscOverCellsAndRocksByArea() + { + var (s, rock) = OneRock(); + var rockAt = At(s, rock); + var rockRadius = s.Zone.ChunkRadius(rock); + var ship = SpawnShip(s, rockAt + float2(-12f, 0f)); + var radius = 6f; + var blast = rockAt + float2(-5.5f, 0f); + var damage = 1f; + var subs = new List<IDisposable>(); + var hullAbsorbs = new List<AbsorbEvent>(); + subs.Add(ship.Capabilities.Absorb.Subscribe(hullAbsorbs.Add)); + var rockAbsorbs = Absorbs(s, subs); + + FireControl.Detonate(s.Zone, blast, radius, damage, DamageType.Kinetic); + foreach (var sub in subs) sub.Dispose(); + + // The hull is a 5 x 5 block of 2-unit cells about its position; the rock a disc; the two do not overlap. + var p = ship.Position.xz; + var area = Math.PI * radius * radius; + var hullArea = NumericDiscInRect(blast.x, blast.y, radius, p.x - 5, p.x + 5, p.y - 5, p.y + 5); + var rockArea = NumericLens(length(rockAt - blast), radius, rockRadius); + Assert.True(hullArea > 0 && rockArea > 0 && hullArea + rockArea < area, "fixture: both covered, some of the disc lost"); + var hull = Assert.Single(hullAbsorbs); + var worn = Assert.Single(rockAbsorbs); + Assert.Equal(damage * hullArea / area, hull.Magnitude, 4); + Assert.Equal(damage * rockArea / area, worn.Magnitude, 4); + var lost = damage * (area - hullArea - rockArea) / area; + Assert.Equal(damage, hull.Magnitude + worn.Magnitude + lost, 4); + } + + [Fact] + public void ARockWhoseCentreIsOutsideTheBlastIsStillWorn() + { + // The widest rock (size 1, radius 9) and a small blast: the blast radius 3 plus the rock's 9 exceeds the + // 8 between them, yet the centre is far outside the blast disc. + var (s, rock) = OneRock(size: 1f); + var at = At(s, rock); + var radius = 3f; + Assert.Equal(9f, s.Zone.ChunkRadius(rock), 3); + var subs = new List<IDisposable>(); + var absorbs = Absorbs(s, subs); + FireControl.Detonate(s.Zone, at + float2(8f, 0f), radius, 10f, DamageType.Kinetic); + subs.ForEach(x => x.Dispose()); + + var worn = Assert.Single(absorbs); + Assert.Equal(10.0 * NumericLens(8, radius, 9) / (Math.PI * radius * radius), worn.Magnitude, 4); + Assert.True(s.Zone.ChunkRadius(rock) < 9f); + } + + [Fact] + public void ATangentOrDistantBlastWearsNothing() + { + var (s, rock) = OneRock(); + var at = At(s, rock); + var radius = s.Zone.ChunkRadius(rock); + var subs = new List<IDisposable>(); + var absorbs = Absorbs(s, subs); + FireControl.Detonate(s.Zone, at + float2(2f * radius, 0f), radius, 10f, DamageType.Kinetic); + FireControl.Detonate(s.Zone, at + float2(60f, 0f), 5f, 10f, DamageType.Kinetic); + subs.ForEach(x => x.Dispose()); + + Assert.Empty(absorbs); + Assert.Equal(radius, s.Zone.ChunkRadius(rock)); + } + + [Fact] + public void ABrokenRockTakesNothingAndPublishesNothing() + { + var (s, rock) = OneRock(); + var at = At(s, rock); + Assert.True(s.Zone.Wear(rock, 1e6f)); + var subs = new List<IDisposable>(); + var absorbs = Absorbs(s, subs); + FireControl.Detonate(s.Zone, at, 8f, 10f, DamageType.Kinetic); + subs.ForEach(x => x.Dispose()); + + Assert.Empty(absorbs); + Assert.False(s.Zone.ChunkExists(rock)); + Assert.Equal(0f, s.Zone.ChunkRadius(rock)); + } + + [Fact] + public void EachWornRockPublishesOneAbsorb() + { + var kind = Kind("Asteroid", 4f); + // Two rocks side by side and a third out of reach, listed out of order of their distance. + var s = BuildScene(new[] { kind }, Belt(kind, Rock(200f, 0f, .5f), Rock(300f, 0f, .5f), Rock(205f, 0f, .5f))); + var a = new ChunkId(s.Belts[0], 0); + var b = new ChunkId(s.Belts[0], 2); + var far = new ChunkId(s.Belts[0], 1); + var blast = (At(s, a) + At(s, b)) / 2f; + var radius = 8f; + var damage = 10f; + var seen = new List<(AbsorbEvent e, float aRadius, float bRadius)>(); + using var sub = s.Zone.ChunkCapabilities.Absorb.Subscribe(e => seen.Add((e, s.Zone.ChunkRadius(a), s.Zone.ChunkRadius(b)))); + var undamagedA = s.Zone.ChunkRadius(a); + var undamagedB = s.Zone.ChunkRadius(b); + + FireControl.Detonate(s.Zone, blast, radius, damage, DamageType.Kinetic); + + Assert.Equal(2, seen.Count); + Assert.All(seen, x => Assert.Equal(AbsorbLayer.Hull, x.e.Layer)); + Assert.All(seen, x => Assert.Equal(0f, x.e.Position.y)); + // Walked in index order; each absorb lands before its own rock's wear, and the first rock's wear is already + // done when the second is published. + Assert.Equal(undamagedA, seen[0].aRadius); + Assert.Equal(undamagedB, seen[0].bRadius); + Assert.True(seen[1].aRadius < undamagedA); + Assert.Equal(undamagedB, seen[1].bRadius); + Assert.Equal(damage * NumericLens(length(At(s, a) - blast), radius, undamagedA) / (Math.PI * radius * radius), seen[0].e.Magnitude, 4); + Assert.Equal(damage * NumericLens(length(At(s, b) - blast), radius, undamagedB) / (Math.PI * radius * radius), seen[1].e.Magnitude, 4); + // The direction runs from the blast out through the rock. + var away = normalize(At(s, a) - blast); + Assert.Equal(away.x, seen[0].e.Direction.x, 4); + Assert.Equal(away.y, seen[0].e.Direction.z, 4); + Assert.Equal(s.Zone.AsteroidBelts[far.Field].UndamagedSize(far.Index, s.Zone.Settings), s.Zone.ChunkRadius(far)); + } + + // The walk is fixed: (field ordinal, index), whatever order the targeting index yields. Two belts, rocks scattered + // so the index's own order is not the sorted one; the absorbs come in sorted order. + [Fact] + public void RocksAreWornInFieldThenIndexOrder() + { + var kind = Kind("Asteroid", 4f); + var s = BuildScene(new[] { kind }, + Belt(kind, Rock(200f, .7f, .5f), Rock(200f, .1f, .5f), Rock(200f, .4f, .5f)), + Belt(kind, Rock(200f, .9f, .5f), Rock(200f, .2f, .5f))); + var rocks = new[] { 0, 1, 2 }.Select(i => new ChunkId(s.Belts[0], i)).Concat(new[] { 0, 1 }.Select(i => new ChunkId(s.Belts[1], i))).ToList(); + var blast = float2.zero; + var seen = new List<AbsorbEvent>(); + using var sub = s.Zone.ChunkCapabilities.Absorb.Subscribe(seen.Add); + + FireControl.Detonate(s.Zone, blast, 400f, 1000f, DamageType.Kinetic); + + Assert.Equal(rocks.Count, seen.Count); + var expected = rocks.OrderBy(r => r.Field.Value, StringComparer.Ordinal).ThenBy(r => r.Index).ToList(); + for (var i = 0; i < expected.Count; i++) + { + var away = normalize(At(s, expected[i]) - blast); + Assert.Equal(away.x, seen[i].Direction.x, 3); + Assert.Equal(away.y, seen[i].Direction.z, 3); + } + } + + [Fact] + public void AMineBlastWearsRocks() + { + var (s, rock) = OneRock(); + var at = At(s, rock); + var undamaged = s.Zone.ChunkRadius(rock); + var absorbs = new List<AbsorbEvent>(); + using var sub = s.Zone.ChunkCapabilities.Absorb.Subscribe(absorbs.Add); + s.Zone.Lay(new Mine + { + Id = s.Zone.NextBodyId(), Body = new KinematicBody { Position = at + float2(2f, 0f), Velocity = float2.zero }, + ArmingDelay = 0f, FuseDelay = 100f, Lifetime = 0f, BlastRadius = 6f, Damage = 10f, + DamageType = DamageType.Kinetic, Layer = null, LayerFaction = null + }); + + s.Zone.Update(.001f); + + Assert.Empty(s.Zone.Mines); + Assert.Single(absorbs); + Assert.True(s.Zone.ChunkRadius(rock) < undamaged); + } +} diff --git a/tests/Aetheria.Shared.Tests/MiningCut4bTests.cs b/tests/Aetheria.Shared.Tests/MiningCut4bTests.cs new file mode 100644 index 000000000..351e875a2 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/MiningCut4bTests.cs @@ -0,0 +1,458 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using System.Collections.Generic; +using System.Linq; +using CultMath; +using UniRx; +using Xunit; +using static CultMath.math; +using float2 = CultMath.float2; +using float3 = CultMath.float3; + +// Mining Cut 4b (docs/mining-cut-refresh.md, Q12 = A): a shot at a rock goes through FireControl's one fire path +// and wears it; the rock is a disc. The fixture is MiningCut3Tests' belt scene: a shooter at the origin, one rock +// straight ahead (+z, phase .25) at `Distance`, a gun and a targeting system fitted on the shooter. +public sealed class MiningCut4bTests : IDisposable +{ + private const float Distance = 100f; + private readonly MiningCut3Tests _fixtures = new MiningCut3Tests(); + + public void Dispose() => _fixtures.Dispose(); + + private sealed class Rig + { + public MiningCut3Tests.Scene Scene; + public Zone Zone => Scene.Zone; + public Ship Shooter; + public EquippedItem GunItem; + public Weapon Gun; + public ChunkId Rock; + public List<ShotOutcome> Resolved = new List<ShotOutcome>(); + } + + private static InstantWeaponData Behavior(bool launcher, float damage, float velocity, float spread, float effective = float.PositiveInfinity) + { + InstantWeaponData data = launcher ? new LockWeaponData + { + LockSpeed = MiningCut3Tests.Constant(1000), SensorImpact = MiningCut3Tests.Constant(1), LockAngle = MiningCut3Tests.Constant(180), + DirectionImpact = MiningCut3Tests.Constant(1), Decay = MiningCut3Tests.Constant(1) + } : new InstantWeaponData(); + data.Damage = MiningCut3Tests.Constant(damage); + data.Range = MiningCut3Tests.Constant(500f); + data.MinRange = MiningCut3Tests.Constant(0); + data.EffectiveRange = MiningCut3Tests.Constant(effective); + data.DamageAtMaxRange = 0f; + data.Velocity = MiningCut3Tests.Constant(velocity); + data.Spread = MiningCut3Tests.Constant(spread); + data.DamageSpread = MiningCut3Tests.Constant(0); + data.Penetration = MiningCut3Tests.Constant(0); + data.Count = MiningCut3Tests.Constant(1); + data.BurstTime = MiningCut3Tests.Constant(0); + data.Cooldown = MiningCut3Tests.Constant(1000); + return data; + } + + // `precision` 1 gives sigma 1 cell; accuracy 1 and a resolution that asks little of the info make PSensor 1. + private Rig Build(bool sensor = true, bool launcher = false, float damage = 10f, float velocity = 0f, float spread = 0f, + float precision = 1f, float effective = float.PositiveInfinity, WeaponFuse? fuse = null, float blastRadius = 0f, + float rockSize = 0f, float crossSection = 20f, bool target = true, float tracking = 1000000f) + { + var kind = MiningCut3Tests.Kind("Asteroid", crossSection); + var scene = _fixtures.BuildScene(new[] { kind }, MiningCut3Tests.Belt(kind, MiningCut3Tests.Rock(Distance, .25f, rockSize))); + var gear = MiningCut3Tests.Gear("Targeting", new TargetingSystemData + { + Accuracy = MiningCut3Tests.Constant(1f), Resolution = MiningCut3Tests.Constant(1000f), + Precision = MiningCut3Tests.Constant(precision), Tracking = MiningCut3Tests.Constant(tracking) + }); + scene.Cache.Upsert(gear); + var gun = new WeaponItemData + { + Name = "Gun", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 1, + MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000, + Fuse = fuse, BlastRadius = blastRadius, + Behaviors = { Behavior(launcher, damage, velocity, spread, effective) } + }; + scene.Cache.Upsert(gun); + + var shape = new Shape(5, 5); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + var hull = new HullData + { + Name = "Gunship", HullType = HullType.Ship, Shape = shape, Durability = 10, Mass = 1000, + Hardpoints = { new HardpointData { Type = HardpointType.Sensors, Position = new int2(0, 0), Shape = new Shape() } } + }; + scene.Cache.Upsert(hull); + var shooter = new Ship(scene.Items, scene.Zone, MiningCut3Tests.Mint(scene, hull), new EntitySettings()); + if (sensor) Assert.True(shooter.TryEquip(MiningCut3Tests.Mint(scene, scene.Eye)), "eye"); + Assert.True(shooter.TryEquip(MiningCut3Tests.Mint(scene, gear)), "targeting"); + var minted = MiningCut3Tests.Mint(scene, gun); + Assert.True(shooter.TryEquip(minted, new int2(0, 0)), "gun"); + scene.Zone.Admit(shooter, piloted: false); + shooter.Position = float3.zero; + shooter.Direction = float2(0, 1); + shooter.Aim = float3(0, 0, 1); + + shooter.Update(.05f); // the fitted sensor becomes active on its first tick; zone time does not advance + shooter.Position = float3.zero; + shooter.Velocity = float2.zero; + var item = shooter.Equipment.Single(x => x.EquippableItem == minted); + var rig = new Rig + { + Scene = scene, Shooter = shooter, GunItem = item, Gun = (Weapon) item.Behaviors.Single(b => b is Weapon), + Rock = new ChunkId(scene.Belts[0], 0) + }; + scene.Zone.ShotResolved.Subscribe(outcome => rig.Resolved.Add(outcome)); + if (target && sensor) Assert.True(shooter.SetTarget(rig.Rock), "target"); + return rig; + } + + private static float Phi(double z) => (float) (.5 * (1 + erf((float) (z / Math.Sqrt(2))))); + + // The rock's radius in cells is the one the zone reports, sigma the targeting system's (floored at half a cell). + private static float Disc(Rig rig) + { + var sigma = max(1f / FireControl.Precision(rig.Shooter), .5f); + var radius = rig.Zone.ChunkCells(rig.Rock); + return Phi(radius / sigma) - Phi(-radius / sigma); + } + + // PSensor as the rule states it, for a gear that wants only the detection threshold plus a thousandth of the rest. + private static float Sensor(Rig rig, float info) + { + var th = rig.Scene.Items.GameplaySettings.TargetDetectionInfoThreshold; + return saturate(unlerp(th, th + (1f - th) / 1000f, info)); + } + + // ==== one fire path ==== + + // Accuracy, PSensor, PSpread, Sigma and PMount price a rock exactly as a ship at equal range, precision and info: + // a two-cell ship (span 2, centre-aimed) and a rock one cell in radius (span 2) are the same disc to the gun, and + // an unauthored gun follows anything, so the mount is 1 for both. + [Fact] + public void ARockShotUsesTheSameFactors() + { + var rig = Build(spread: 4f, precision: 1f, crossSection: 1f); + var s = rig.Scene; + Assert.Equal(1f, rig.Zone.ChunkCells(rig.Rock), 4); + var info = rig.Shooter.ChunkInfo(rig.Rock); + Assert.True(info > .11f && info < 1f, $"the rock's info {info} should be visible and unsaturated"); + + var hull = new HullData { Name = "Pair", HullType = HullType.Ship, Shape = new Shape(2, 2), Durability = 10, Mass = 1000 }; + foreach (var cell in hull.Shape.AllCoordinates) hull.Shape[cell] = true; + s.Cache.Upsert(hull); + var at = rig.Zone.ChunkPose(rig.Rock.Field, rig.Rock.Index).xy; + var ship = new Ship(s.Items, rig.Zone, MiningCut3Tests.Mint(s, hull), new EntitySettings()); + rig.Zone.Admit(ship, piloted: false); + ship.Position = float3(at.x, 0, at.y); + ship.Direction = float2(0, 1); + rig.Shooter.EntityInfoGathered[ship] = info; + rig.Shooter.VisibleEntities.Add(ship); + + var rock = FireControl.HitProbability(rig.Gun, rig.Shooter, rig.Rock); + var vessel = FireControl.HitProbability(rig.Gun, rig.Shooter, ship); + Assert.InRange(rock, .05f, .99f); + Assert.Equal(vessel, rock, 4); + } + + [Fact] + public void AnUnseenRockCannotBeFiredOn() + { + var blind = Build(sensor: false); + Assert.False(FireControl.Designated(blind.Gun, blind.Shooter, blind.Rock, out var range)); + Assert.Equal(Distance, range, 2); + Assert.Equal(0f, FireControl.HitProbability(blind.Gun, blind.Shooter, blind.Rock)); + Assert.False(FireControl.Solve(blind.Gun, blind.GunItem, blind.Shooter, blind.Rock).Designated); + + var sighted = Build(); + Assert.True(FireControl.Designated(sighted.Gun, sighted.Shooter, sighted.Rock, out _)); + Assert.True(FireControl.HitProbability(sighted.Gun, sighted.Shooter, sighted.Rock) > 0f); + } + + // Q12 = A: a launcher (a LockWeapon) is never designated on a rock, locked or not. + [Fact] + public void LaunchersCannotFireOnARock() + { + var launcher = Build(launcher: true); + Assert.False(FireControl.Designated(launcher.Gun, launcher.Shooter, launcher.Rock, out _)); + Assert.Equal(0f, FireControl.HitProbability(launcher.Gun, launcher.Shooter, launcher.Rock)); + var plain = Build(); + Assert.True(FireControl.Designated(plain.Gun, plain.Shooter, plain.Rock, out _)); + } + + // POnHull is the closed form Phi(R/sigma) - Phi(-R/sigma): a zero-spread gun with a full sensor reading is priced by the + // disc alone. + [Fact] + public void DiscMassIsTheClosedForm() + { + var rig = Build(spread: 0f, precision: 1f, rockSize: .5f); + var info = rig.Shooter.ChunkInfo(rig.Rock); + var expected = Sensor(rig, info) * Disc(rig); + Assert.InRange(Disc(rig), .5f, .99f); + Assert.Equal(expected, FireControl.HitProbability(rig.Gun, rig.Shooter, rig.Rock), 4); + } + + // Commit's price at fire time is the forecast: for a rock still at the instant it is fired at, one price. + [Fact] + public void TheForecastIsTheCommitPriceForARock() + { + var rig = Build(spread: 4f, precision: 1f, velocity: 50f); + var forecast = FireControl.HitProbability(rig.Gun, rig.Shooter, rig.Rock); + var id = FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); + Assert.True(rig.Zone.TryGetShot(id, out var shot)); + Assert.Equal(rig.Rock, shot.Chunk); + Assert.Null(shot.Target); + Assert.Equal(forecast, FireControl.CommitProbability(shot, shot.FireTime, out _), 4); + } + + // ==== resolution ==== + + private static void Run(Rig rig, float seconds) + { + for (var elapsed = 0f; elapsed < seconds; elapsed += .01f) rig.Zone.Update(.01f); + } + + // A rock hit has no lane and no shield. Hits wear the rock by the shot's Damage after the falloff, and each + // publishes one absorb on the zone's ChunkCapabilities at the rock's surface facing the shot. + [Fact] + public void DirectHitsWearTheRock() + { + var rig = Build(damage: 3f, rockSize: .5f, precision: 1000f, effective: 50f); + var absorbs = new List<AbsorbEvent>(); + var surface = new List<float>(); + rig.Zone.ChunkCapabilities.Absorb.Subscribe(e => + { + absorbs.Add(e); + var centre = rig.Zone.ChunkPose(rig.Rock.Field, rig.Rock.Index).xy; + surface.Add(length(float2(e.Position.x, e.Position.z) - centre) - rig.Zone.ChunkRadius(rig.Rock)); + }); + var before = rig.Zone.ChunkRadius(rig.Rock); + var factor = WeaponData.RangeFactor(0f, 50f, 500f, 0f, Distance); + Assert.InRange(factor, .01f, .99f); + + for (var shot = 0; shot < 12; shot++) + { + FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); + Run(rig, .02f); + } + + var hits = rig.Resolved.Count(o => o.Hit); + Assert.InRange(hits, 1, 12); + Assert.Equal(hits, absorbs.Count); + Assert.All(rig.Resolved.Where(o => o.Hit), o => { Assert.Equal(0, o.Cell.x); Assert.Equal(0, o.Cell.y); Assert.False(o.Shielded); }); + Assert.All(absorbs, e => Assert.Equal(3f * factor, e.Magnitude, 2)); + Assert.All(surface, d => Assert.True(abs(d) < 1e-3f, $"absorb was {d} off the rock's surface")); + Assert.All(absorbs, e => Assert.Equal(AbsorbLayer.Hull, e.Layer)); + var hp = MiningCut3Tests.PlanetSettings().AsteroidHitpoints.Evaluate(.5f); + var expected = MiningCut3Tests.PlanetSettings().AsteroidSize.Evaluate((hp - hits * 3f * factor) / hp * .5f); + Assert.Equal(expected, rig.Zone.ChunkRadius(rig.Rock), 3); + Assert.True(rig.Zone.ChunkRadius(rig.Rock) < before); + } + + // A contact round that hits a rock detonates at its centre as it arrives, through Detonate: a bystander beside it + // takes the blast from the rock's centre, not from the muzzle or from a lane. + [Fact] + public void AContactRoundAtARockDetonatesAtItsCentre() + { + var rig = Build(damage: 10f, fuse: WeaponFuse.Contact, blastRadius: 6f, precision: 1000f, rockSize: .5f); + var s = rig.Scene; + var at = rig.Zone.ChunkPose(rig.Rock.Field, rig.Rock.Index).xy; + var bystander = new Ship(s.Items, rig.Zone, MiningCut3Tests.Mint(s, s.Hull), new EntitySettings()); + rig.Zone.Admit(bystander, piloted: false); + bystander.Position = float3(at.x + 3f, 0, at.y); + var burstAt = new List<float>(); + bystander.Capabilities.Absorb.Subscribe(e => + { + var centre = rig.Zone.ChunkPose(rig.Rock.Field, rig.Rock.Index).xy; + burstAt.Add(length(float2(e.Position.x, e.Position.z) - centre)); + }); + + for (var shot = 0; shot < 12; shot++) + { + FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); + Run(rig, .02f); + } + + Assert.InRange(rig.Resolved.Count(o => o.Hit), 1, 12); + Assert.NotEmpty(burstAt); + Assert.All(burstAt, d => Assert.True(d < 1e-2f, $"blast was {d} from the rock's centre")); + } + + // A rock that no longer exists when its round arrives, broken in flight, resolves as a miss, like a target that + // left the zone: nothing is worn and nothing absorbs. + [Fact] + public void ARockThatBreaksMidFlightIsAMiss() + { + var rig = Build(velocity: 50f, precision: 1000f); + var absorbs = 0; + rig.Zone.ChunkCapabilities.Absorb.Subscribe(_ => absorbs++); + FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); + Assert.Empty(rig.Resolved); + + Assert.True(rig.Zone.Wear(rig.Rock, 1e6f)); + Run(rig, 2.5f); + + var outcome = Assert.Single(rig.Resolved); + Assert.Equal(ShotResult.Miss, outcome.Result); + Assert.Equal(0, absorbs); + Assert.False(rig.Zone.ChunkExists(rig.Rock)); + } + + // The shot's own dice: two zones built alike roll the same sequence of outcomes for the same shot ids. + [Fact] + public void RockDiceAreTheShotsOwn() + { + List<ShotResult> Roll() + { + var rig = Build(precision: 1f); + for (var shot = 0; shot < 20; shot++) + { + FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); + Run(rig, .02f); + } + return rig.Resolved.Select(o => o.Result).ToList(); + } + + var first = Roll(); + var second = Roll(); + Assert.Equal(20, first.Count); + Assert.Contains(ShotResult.Hit, first); + Assert.Contains(ShotResult.Miss, first); + Assert.Equal(first, second); + } + + // A rock's velocity is the pose function's derivative, derived on every read. + [Fact] + public void ARockMovesAtItsPoseVelocity() + { + var rig = Build(); + var velocity = rig.Zone.ChunkVelocity(rig.Rock); + var ahead = rig.Zone.ChunkPose(rig.Rock.Field, rig.Rock.Index, rig.Zone.Time + .5).xy; + var now = rig.Zone.ChunkPose(rig.Rock.Field, rig.Rock.Index).xy; + Assert.True(length(velocity) > 1f); + Assert.True(length(velocity * .5f - (ahead - now)) < .05f * length(ahead - now)); + } + + // A rock is not a Ship: its evasion is 0, so Tracking (the metres of deviation a shooter forgives) never + // discounts the price of a rock. The same rock priced by a tight and by a loose tracker reads one price. + [Fact] + public void ARockEvadesNothing() + { + var tight = Build(spread: 4f, precision: 1f, tracking: 10f); + var loose = Build(spread: 4f, precision: 1f, tracking: 1000000f); + var tightPrice = FireControl.HitProbability(tight.Gun, tight.Shooter, tight.Rock); + var loosePrice = FireControl.HitProbability(loose.Gun, loose.Shooter, loose.Rock); + Assert.InRange(loosePrice, .05f, .99f); + Assert.Equal(loosePrice, tightPrice, 5); + } + + // The lead is the intercept of the rock's pose velocity: the point is where the rock will be when a round of the + // gun's velocity gets there, derived here from the time of flight, not from the code under test. + [Fact] + public void AMovingRockIsLeadAtItsPoseVelocity() + { + var rig = Build(velocity: 50f); + var velocity = rig.Zone.ChunkVelocity(rig.Rock); + var now = rig.Zone.ChunkPose(rig.Rock.Field, rig.Rock.Index).xy; + Assert.True(length(velocity) > 1f); + + var point = FireControl.PredictedIntercept(rig.Gun, rig.Shooter, rig.Rock); + + var flight = length(point.xz - rig.Shooter.Position.xz) / 50f; + var there = now + velocity * flight; + Assert.True(length(point.xz - now) > .5f, "the aim leads the rock"); + Assert.Equal(there.x, point.x, 2); + Assert.Equal(there.y, point.z, 2); + } + + // A rock that breaks after its round committed a hit resolves as a miss through Step's gone rule: the frozen + // outcome says Hit, so only that rule stops the round from absorbing on, and wearing, a rock that is gone. + [Fact] + public void ARockThatBreaksAfterCommitIsAMissNotAFrozenHit() + { + var rig = Build(velocity: 50f, precision: 1000f); + var committed = new List<ShotOutcome>(); + rig.Zone.ShotCommitted.Subscribe(committed.Add); + var absorbs = 0; + rig.Zone.ChunkCapabilities.Absorb.Subscribe(_ => absorbs++); + FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); + for (var waited = 0f; committed.Count == 0 && waited < 3f; waited += .01f) rig.Zone.Update(.01f); + var frozen = Assert.Single(committed); + Assert.True(frozen.Hit, "fixture: the commit rolled a hit"); + Assert.Empty(rig.Resolved); + + Assert.True(rig.Zone.Wear(rig.Rock, 1e6f)); + Run(rig, 2.5f); + + var outcome = Assert.Single(rig.Resolved); + Assert.False(outcome.Hit); + Assert.Equal(0, absorbs); + } + + private static void Wear(Rig rig, WeaponFuse fuse, int shots, out int hits, out List<AbsorbEvent> absorbs, out float worn) + { + var seen = new List<AbsorbEvent>(); + rig.Zone.ChunkCapabilities.Absorb.Subscribe(seen.Add); + for (var shot = 0; shot < shots; shot++) + { + FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); + Run(rig, .02f); + } + hits = rig.Resolved.Count(o => o.Hit); + absorbs = seen; + worn = seen.Sum(e => e.Magnitude); + } + + // A contact round that hits a rock wears it exactly once, by the blast's share through Detonate: one absorb per hit, + // and the rock's wear is the sum of those absorbs' magnitudes, with no Damage added on top. + [Fact] + public void AContactRoundWearsARockExactlyOnce() + { + var rig = Build(damage: 10f, fuse: WeaponFuse.Contact, blastRadius: 6f, precision: 1000f, rockSize: .5f); + Wear(rig, WeaponFuse.Contact, 12, out var hits, out var absorbs, out var worn); + + Assert.InRange(hits, 1, 12); + Assert.Equal(hits, absorbs.Count); + var belt = rig.Zone.AsteroidBelts[rig.Rock.Field]; + Assert.True(rig.Zone.ChunkExists(rig.Rock)); + Assert.Equal(belt.DamagedSize(rig.Rock.Index, worn, rig.Zone.Settings), rig.Zone.ChunkRadius(rig.Rock), 3); + } + + // The same for a proximity round, which detonates at its burst point hit or miss: one absorb per resolved round + // that covers the rock, and no wear beyond them. + [Fact] + public void AProximityRoundWearsARockExactlyOnce() + { + var rig = Build(damage: 10f, fuse: WeaponFuse.Proximity, blastRadius: 6f, precision: 1000f, rockSize: .5f); + Wear(rig, WeaponFuse.Proximity, 12, out _, out var absorbs, out var worn); + + Assert.Equal(12, rig.Resolved.Count); + Assert.NotEmpty(absorbs); + var belt = rig.Zone.AsteroidBelts[rig.Rock.Field]; + Assert.True(rig.Zone.ChunkExists(rig.Rock)); + Assert.Equal(belt.DamagedSize(rig.Rock.Index, worn, rig.Zone.Settings), rig.Zone.ChunkRadius(rig.Rock), 3); + } + + // A rock's absorb has one height rule whoever reports it: a direct hit and a blast both publish at height 0, not at + // the shooter's. + [Fact] + public void ARockAbsorbHasOneHeightRule() + { + var rig = Build(damage: 3f, rockSize: .5f, precision: 1000f); + rig.Shooter.Position = float3(0, 7, 0); + var heights = new List<float>(); + rig.Zone.ChunkCapabilities.Absorb.Subscribe(e => heights.Add(e.Position.y)); + for (var shot = 0; shot < 6; shot++) + { + FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); + Run(rig, .02f); + } + var direct = heights.Count; + FireControl.Detonate(rig.Zone, rig.Zone.ChunkPose(rig.Rock.Field, rig.Rock.Index).xy, 5f, 3f, DamageType.Kinetic); + + Assert.True(direct > 0 && heights.Count > direct); + Assert.All(heights, h => Assert.Equal(0f, h)); + } +} From 3ccb9801854d1610c17ff997f25fc84c68bb1e47 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Thu, 12 Nov 2026 23:01:04 +0000 Subject: [PATCH 066/190] Ore sheet: DemoOre batch and tests for the Asteroid ore yields, holdability and prices Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- GameData/Aetheria.cc | 4 +- .../DemoOreSheetTests.cs | 92 +++++++++++++++++++ tools/AetherDb/Economy/DemoOre.cs | 44 +++++++++ 3 files changed, 138 insertions(+), 2 deletions(-) create mode 100644 tests/Aetheria.Shared.Tests/DemoOreSheetTests.cs create mode 100644 tools/AetherDb/Economy/DemoOre.cs diff --git a/GameData/Aetheria.cc b/GameData/Aetheria.cc index f4cfdc4a3..ef463cde8 100644 --- a/GameData/Aetheria.cc +++ b/GameData/Aetheria.cc @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:9edc8434524f43f751c89416479cf07fba03b424f266cb8bfc1870bd46eef6a7 -size 220537 +oid sha256:62a6678e741e296449b6ac8cd8698e071a873ea39bc9c0303abe68887310dceb +size 220731 diff --git a/tests/Aetheria.Shared.Tests/DemoOreSheetTests.cs b/tests/Aetheria.Shared.Tests/DemoOreSheetTests.cs new file mode 100644 index 000000000..24ef521eb --- /dev/null +++ b/tests/Aetheria.Shared.Tests/DemoOreSheetTests.cs @@ -0,0 +1,92 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using CultMath; +using GameCult.Caching; +using Xunit; + +// The interim ore sheet (rulings mining-demo-ore-minimal-yields-now, mining-demo-ore-prices-gear-scale): what the shipped catalog's +// Asteroid belt holds can be carried and sold, so mine, sell, repair closes on the existing stations. +public sealed class DemoOreSheetTests : IDisposable +{ + private static readonly string[] Ores = { "Rock", "New Metals", "Gold" }; + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-demoore-" + Guid.NewGuid().ToString("N")); + + public DemoOreSheetTests() => Directory.CreateDirectory(_root); + public void Dispose() => Directory.Delete(_root, true); + + private CultCache Shipped() + { + var path = Path.Combine(_root, "Aetheria.cc"); + File.Copy(TestCatalog.Repo, path, true); + return AetheriaStores.Open(path, catalogWritable: true, registry: TestCatalog.Registry()); + } + + private static CultRecordRef<FieldKindData> Asteroid(CultCache cache) => + cache.RefOf(cache.GetAll<FieldKindData>().Single(k => k.Name == "Asteroid")); + + [Fact] + public void AsteroidYieldsThreeOresInKeyOrder() + { + using var cache = Shipped(); + var yield = FieldKinds.Yield(Asteroid(cache), default, cache); + var amounts = yield.ToDictionary(y => cache.Get(y.Commodity).Name, y => y.Amount); + Assert.Equal(Ores.OrderBy(n => n).ToArray(), amounts.Keys.OrderBy(n => n).ToArray()); + Assert.Equal(6f, amounts["Rock"]); + Assert.Equal(3f, amounts["New Metals"]); + Assert.Equal(1f, amounts["Gold"]); + Assert.Equal(yield.Select(y => y.Commodity.Key.Value).OrderBy(k => k, StringComparer.Ordinal), yield.Select(y => y.Commodity.Key.Value)); + } + + [Fact] + public void EveryYieldedOreCanBeHeldAndSold() + { + using var cache = Shipped(); + var shape = new Shape(5, 5); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + var bay = new Shape(4, 4); + foreach (var cell in bay.AllCoordinates) bay[cell] = true; + cache.Upsert(new VerseGrammar { Revision = 1 }); + cache.Upsert(new HullData { Name = "OreSkiff", HullType = HullType.Ship, Shape = shape, Price = 1000, Durability = 10, Armor = 10 }); + cache.Upsert(new CargoBayData { Name = "OreBay", Shape = new Shape(), InteriorShape = bay, Price = 20, Durability = 4 }); + cache.FlushAsync().GetAwaiter().GetResult(); + var items = new ItemManager(1u, cache, new ProvenanceLedger(), AuthoredSettings.Load(RestoredHullsTests.FindRepoRoot()).Read<GameplaySettings>("GameplaySettings"), _ => { }); + var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null); + EquippableItem Mint(string design) + { + var data = cache.GetByName<EquippableItemData>(design); + return new EquippableItem + { + Data = cache.RefOf<ItemData>(data), Durability = data.Durability, + Lot = items.Lots.Add(new Lot { Design = cache.RefOf<ItemData>(data), Origin = new Attributed(), Quality = .5f, Roles = new List<RoleFill>() }) + }; + } + var ship = new Ship(items, zone, Mint("OreSkiff"), new EntitySettings()); + Assert.True(ship.TryEquip(Mint("OreBay"), new int2(1, 1))); + + foreach (var (commodity, _) in FieldKinds.Yield(Asteroid(cache), default, cache)) + { + var data = cache.Get(commodity); + Assert.NotNull(data.Shape); + Assert.True(data.Price > 0, data.Name); + Assert.True(data.Mass > 0, data.Name); + Assert.True(ship.CargoBays.Single().TryStore(new SimpleCommodity { Data = cache.RefOf<ItemData>(data), Quantity = 1 }), data.Name); + } + } + + [Fact] + public void TheSheetConverges() + { + var path = Path.Combine(_root, "Converge.cc"); + File.Copy(Path.Combine(RestoredHullsTests.FindRepoRoot(), "GameData", "Aetheria.cc"), path); + var before = File.ReadAllBytes(path); + var output = new StringWriter(); + Assert.Equal(0, EconomyCommand.Author(path, new List<EconomyBatch> { new DemoOre() }, true, output, TestCatalog.Registry(), _root)); + Assert.Equal(before, File.ReadAllBytes(path)); + + using var cache = AetheriaStores.Open(path, registry: TestCatalog.Registry()); + var ids = cache.GetAll<FieldKindData>().Single(k => k.Name == "Asteroid").Yields.Select(y => y.Id).ToArray(); + Assert.Equal(new[] { "a57e0c000001", "a57e0c000002", "a57e0c000003" }, ids); + } +} diff --git a/tools/AetherDb/Economy/DemoOre.cs b/tools/AetherDb/Economy/DemoOre.cs new file mode 100644 index 000000000..df2a2aff2 --- /dev/null +++ b/tools/AetherDb/Economy/DemoOre.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; + +// Interim ore sheet (ruling mining-demo-ore-minimal-yields-now): the Asteroid field kind yields Rock, New Metals and Gold, and those +// three can be held (a 1x1 shape, a mass) and are sold (a price). The economy ores batch may rewrite the yields by element id. +// Prices are ruling mining-demo-ore-prices-gear-scale, gear-scale so the mine, sell, repair loop closes: a retune is an edit here and a rerun. +// Munitions and MunitionsFeed never rewrite these three commodities, so rerunning them does not clobber this sheet. +public sealed class DemoOre : EconomyBatch +{ + private const int RockPrice = 200; + private const int NewMetalsPrice = 1000; + private const int GoldPrice = 5000; + + // Authored element ids (the cache takes a hand-written id only as 12 lowercase hex): asteroid-rock, asteroid-new-metals, asteroid-gold. + private const string RockId = "a57e0c000001"; + private const string NewMetalsId = "a57e0c000002"; + private const string GoldId = "a57e0c000003"; + + public override void Author(EconomyAuthor author) + { + author.Edit<SimpleCommodityData>("Rock", o => { o.Shape = new Shape(); o.Price = RockPrice; }); + author.Edit<SimpleCommodityData>("New Metals", o => { o.Shape = new Shape(); o.Price = NewMetalsPrice; o.Mass = 2; }); + author.Edit<SimpleCommodityData>("Gold", o => { o.Shape = new Shape(); o.Price = GoldPrice; }); + + var kinds = author.Catalog.GetAll<FieldKindData>().Where(k => k.Name == "Asteroid").ToArray(); + if (kinds.Length != 1) throw new InvalidOperationException($"{kinds.Length} field kinds are named 'Asteroid'; the ore sheet needs exactly one."); + var asteroid = kinds[0]; + asteroid.Yields = new List<FieldYield> + { + Yield(author, "Rock", 6, RockId), + Yield(author, "New Metals", 3, NewMetalsId), + Yield(author, "Gold", 1, GoldId) + }; + author.Put(asteroid, author.Catalog.RefOf(asteroid).Key); + } + + private static FieldYield Yield(EconomyAuthor author, string name, float abundance, string id) + { + var item = author.Catalog.GetAll<SimpleCommodityData>().Single(i => i.Name == name); + return new FieldYield { Commodity = new CultRecordRef<SimpleCommodityData>(author.Catalog.RefOf(item).Key), Abundance = abundance, Regional = false, Id = id }; + } +} From f5eeb2e21481db42c78f6762907e4363e9b5a8ac Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Thu, 12 Nov 2026 23:00:16 +0000 Subject: [PATCH 067/190] Zone.Wear returns the damage the rock absorbed; a break is ChunkExists Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/Zone.cs | 15 ++--- tests/Aetheria.Shared.Tests/DrawnPoseTests.cs | 2 +- .../Aetheria.Shared.Tests/MiningCut2Tests.cs | 62 +++++++++++-------- .../Aetheria.Shared.Tests/MiningCut3Tests.cs | 10 +-- .../Aetheria.Shared.Tests/MiningCut4aTests.cs | 2 +- .../Aetheria.Shared.Tests/MiningCut4bTests.cs | 4 +- .../Aetheria.Shared.Tests/MiningIndexTests.cs | 2 +- 7 files changed, 55 insertions(+), 42 deletions(-) diff --git a/Assets/Scripts/ServerShared/Zone.cs b/Assets/Scripts/ServerShared/Zone.cs index d0c5b5330..7cbde82ef 100644 --- a/Assets/Scripts/ServerShared/Zone.cs +++ b/Assets/Scripts/ServerShared/Zone.cs @@ -685,16 +685,17 @@ public class Zone return size.Exponent > 0 ? max(abs(size.Minimum), abs(size.Maximum)) : float.PositiveInfinity; } - // Cut 2: the only writer of chunk wear. Returns whether this hit broke the chunk. The break threshold is + // Cut 2: the only writer of chunk wear. Returns the damage the rock absorbed: the damage, or the hitpoints it had + // left when the hit broke it; 0 on a chunk that is already broken. Whether it broke is ChunkExists. The break threshold is // strictly greater-than, matching the deleted per-tick miner's own comparison against accumulated damage: // damage exactly equal to hitpoints does not yet break the chunk, only damage that exceeds them does. - // A chunk that is currently broken (zone time < BrokenUntil) absorbs nothing: this hit did not break it - // (it was already broken), and its wear stays zeroed until it respawns and starts fresh. - public bool Wear(ChunkId chunk, float damage) + // A chunk that is currently broken (zone time < BrokenUntil) absorbs nothing, and its wear stays zeroed until it + // respawns and starts fresh. + public float Wear(ChunkId chunk, float damage) { _wear.TryGetValue(chunk, out var wear); if (wear.BrokenUntil.HasValue && wear.BrokenUntil.Value > _time) - return false; + return 0f; var beltData = (AsteroidBeltData) Planets[chunk.Field]; var size = beltData.Asteroids[chunk.Index].Size; @@ -706,11 +707,11 @@ public class Zone { var respawnTime = Settings.AsteroidRespawnTime.Evaluate(size); _wear[chunk] = new ChunkWear { Damage = 0f, BrokenUntil = _time + respawnTime }; - return true; + return max(hitpoints - wear.Damage, 0f); } _wear[chunk] = new ChunkWear { Damage = newDamage, BrokenUntil = null }; - return false; + return damage; } // Cut 1 (docs/mining-cut.md): a chunk's pose is a pure function of zone time, computed when asked. No stored diff --git a/tests/Aetheria.Shared.Tests/DrawnPoseTests.cs b/tests/Aetheria.Shared.Tests/DrawnPoseTests.cs index 37111b114..e7254fac6 100644 --- a/tests/Aetheria.Shared.Tests/DrawnPoseTests.cs +++ b/tests/Aetheria.Shared.Tests/DrawnPoseTests.cs @@ -542,7 +542,7 @@ public sealed class DrawnPoseTests : IDisposable var chunk = new ChunkId(w.Belt, 5); var hitpoints = w.Zone.Settings.AsteroidHitpoints.Evaluate(w.Asteroids[5].Size); var unworn = w.Zone.ChunkRadius(chunk); - Assert.False(w.Zone.Wear(chunk, hitpoints * .9f)); + Assert.False(w.Zone.Breaks(chunk, hitpoints * .9f)); Assert.True(w.Zone.ChunkRadius(chunk) < unworn * .5f, "the rock has shrunk to less than half its size"); Assert.Equal(before, Meshes()); } diff --git a/tests/Aetheria.Shared.Tests/MiningCut2Tests.cs b/tests/Aetheria.Shared.Tests/MiningCut2Tests.cs index 54fc99972..7716e3c9a 100644 --- a/tests/Aetheria.Shared.Tests/MiningCut2Tests.cs +++ b/tests/Aetheria.Shared.Tests/MiningCut2Tests.cs @@ -134,9 +134,9 @@ public sealed class MiningCut2Tests : IDisposable var hp = f.Settings.AsteroidHitpoints.Evaluate(f.AsteroidsA[index].Size); // Several partial hits under the threshold: still there, still shrinking. - Assert.False(f.Zone.Wear(chunk, hp * 0.3f)); + Assert.False(f.Zone.Breaks(chunk, hp * 0.3f)); Assert.True(f.Zone.ChunkExists(chunk)); - Assert.False(f.Zone.Wear(chunk, hp * 0.3f)); + Assert.False(f.Zone.Breaks(chunk, hp * 0.3f)); Assert.True(f.Zone.ChunkExists(chunk)); var before = f.Zone.ChunkRadius(chunk); @@ -147,11 +147,11 @@ public sealed class MiningCut2Tests : IDisposable // break condition as strictly greater-than, not greater-or-equal (today's behaviour, kept deliberately // -- see Zone.Wear's own comment). Equal-to-hitpoints must not break the chunk. var remaining = hp - hp * 0.6f; - Assert.False(f.Zone.Wear(chunk, remaining)); + Assert.False(f.Zone.Breaks(chunk, remaining)); Assert.True(f.Zone.ChunkExists(chunk), "damage exactly equal to hitpoints must not break the chunk"); // One more point of damage tips it over. - Assert.True(f.Zone.Wear(chunk, 0.01f)); + Assert.True(f.Zone.Breaks(chunk, 0.01f)); Assert.False(f.Zone.ChunkExists(chunk)); Assert.Equal(0f, f.Zone.ChunkRadius(chunk)); } @@ -165,7 +165,7 @@ public sealed class MiningCut2Tests : IDisposable var hp = f.Settings.AsteroidHitpoints.Evaluate(f.AsteroidsA[index].Size); var respawn = f.Settings.AsteroidRespawnTime.Evaluate(f.AsteroidsA[index].Size); - Assert.True(f.Zone.Wear(chunk, hp + 1f)); + Assert.True(f.Zone.Breaks(chunk, hp + 1f)); Assert.False(f.Zone.ChunkExists(chunk)); // Uneven steps that sum to just under the authored respawn time: still broken. @@ -188,13 +188,13 @@ public sealed class MiningCut2Tests : IDisposable var hp = f.Settings.AsteroidHitpoints.Evaluate(f.AsteroidsB[index].Size); var respawn = f.Settings.AsteroidRespawnTime.Evaluate(f.AsteroidsB[index].Size); - Assert.True(f.Zone.Wear(chunk, hp * 1.5f)); + Assert.True(f.Zone.Breaks(chunk, hp * 1.5f)); f.Zone.Update(respawn + 1f); Assert.True(f.Zone.ChunkExists(chunk)); // A hit well under hitpoints, on the freshly respawned chunk, must not break it -- if the old damage // (or the old broken state) leaked through, this hit alone would already be over any stale threshold. - Assert.False(f.Zone.Wear(chunk, hp * 0.4f)); + Assert.False(f.Zone.Breaks(chunk, hp * 0.4f)); Assert.True(f.Zone.ChunkExists(chunk)); var radius = f.Zone.ChunkRadius(chunk); Assert.True(radius > 0f && radius < f.Zone.AsteroidBelts[f.BeltB].UndamagedSize(index, f.Settings)); @@ -211,7 +211,7 @@ public sealed class MiningCut2Tests : IDisposable var chunkA1 = new ChunkId(f.BeltA, 1); var hpA0 = f.Settings.AsteroidHitpoints.Evaluate(f.AsteroidsA[0].Size); - Assert.True(f.Zone.Wear(chunkA0, hpA0 + 1f)); + Assert.True(f.Zone.Breaks(chunkA0, hpA0 + 1f)); Assert.False(f.Zone.ChunkExists(chunkA0)); Assert.True(f.Zone.ChunkExists(chunkB0), "a different field at the same index must be unaffected"); @@ -230,8 +230,8 @@ public sealed class MiningCut2Tests : IDisposable var hpDamaged = f.Settings.AsteroidHitpoints.Evaluate(f.AsteroidsA[4].Size); var hpBroken = f.Settings.AsteroidHitpoints.Evaluate(f.AsteroidsB[3].Size); - Assert.False(f.Zone.Wear(damaged, hpDamaged * 0.45f)); - Assert.True(f.Zone.Wear(broken, hpBroken + 5f)); + Assert.False(f.Zone.Breaks(damaged, hpDamaged * 0.45f)); + Assert.True(f.Zone.Breaks(broken, hpBroken + 5f)); f.Zone.Update(1.3f); var damagedRadiusBefore = f.Zone.ChunkRadius(damaged); @@ -255,7 +255,7 @@ public sealed class MiningCut2Tests : IDisposable var hp = f.Settings.AsteroidHitpoints.Evaluate(f.AsteroidsA[6].Size); var respawn = f.Settings.AsteroidRespawnTime.Evaluate(f.AsteroidsA[6].Size); - Assert.True(f.Zone.Wear(chunk, hp + 1f)); + Assert.True(f.Zone.Breaks(chunk, hp + 1f)); f.Zone.Update(respawn + 2f); Assert.True(f.Zone.ChunkExists(chunk), "sanity: this chunk must have respawned before packing"); @@ -333,20 +333,20 @@ public sealed class MiningCut2Tests : IDisposable var hp = f.Settings.AsteroidHitpoints.Evaluate(f.AsteroidsA[index].Size); var respawn = f.Settings.AsteroidRespawnTime.Evaluate(f.AsteroidsA[index].Size); - Assert.True(f.Zone.Wear(chunk, hp + 1f)); + Assert.True(f.Zone.Breaks(chunk, hp + 1f)); Assert.False(f.Zone.ChunkExists(chunk)); // A hit well under hitpoints, inside the respawn window: must not break it (it is already broken) and // must not touch BrokenUntil. f.Zone.Update(respawn * 0.2f); - Assert.False(f.Zone.Wear(chunk, hp * 0.1f), "a hit on an already-broken chunk did not break it"); + Assert.False(f.Zone.Breaks(chunk, hp * 0.1f), "a hit on an already-broken chunk did not break it"); Assert.False(f.Zone.ChunkExists(chunk), "must still be absent -- the old bug un-broke it here"); Assert.Equal(0f, f.Zone.ChunkRadius(chunk)); // A second hit, this one alone well over hitpoints, inside the same window: still must not break it // (it is already broken) and must not push BrokenUntil further out. f.Zone.Update(respawn * 0.3f); - Assert.False(f.Zone.Wear(chunk, hp + 50f), "a hit on an already-broken chunk did not break it, even when large"); + Assert.False(f.Zone.Breaks(chunk, hp + 50f), "a hit on an already-broken chunk did not break it, even when large"); Assert.False(f.Zone.ChunkExists(chunk)); // Just under the original respawn time (measured from the original break, not from either re-hit): @@ -360,9 +360,9 @@ public sealed class MiningCut2Tests : IDisposable Assert.Equal(f.Zone.AsteroidBelts[f.BeltA].UndamagedSize(index, f.Settings), f.Zone.ChunkRadius(chunk), 4); // Worn again from fresh: breaks on the normal threshold, not one warped by the earlier no-op hits. - Assert.False(f.Zone.Wear(chunk, hp * 0.9f)); + Assert.False(f.Zone.Breaks(chunk, hp * 0.9f)); Assert.True(f.Zone.ChunkExists(chunk)); - Assert.True(f.Zone.Wear(chunk, hp * 0.2f)); + Assert.True(f.Zone.Breaks(chunk, hp * 0.2f)); Assert.False(f.Zone.ChunkExists(chunk)); } @@ -377,9 +377,9 @@ public sealed class MiningCut2Tests : IDisposable var hp = f.Settings.AsteroidHitpoints.Evaluate(f.AsteroidsB[idx].Size); var respawn = f.Settings.AsteroidRespawnTime.Evaluate(f.AsteroidsB[idx].Size); - Assert.True(f.Zone.Wear(chunk, hp + 1f)); + Assert.True(f.Zone.Breaks(chunk, hp + 1f)); f.Zone.Update(respawn * 0.4f); - Assert.False(f.Zone.Wear(chunk, hp * 0.5f), "re-hit inside the window did not break an already-broken chunk"); + Assert.False(f.Zone.Breaks(chunk, hp * 0.5f), "re-hit inside the window did not break an already-broken chunk"); var pack = f.Zone.PackZone(); var reloaded = new Zone(f.Items, f.Settings, pack, new GalaxyZone { Name = "MiningCut2ReHitReload", Owner = null }, null); @@ -424,7 +424,7 @@ public sealed class MiningCut2Tests : IDisposable var hp = f.Settings.AsteroidHitpoints.Evaluate(f.AsteroidsA[index].Size); var respawn = f.Settings.AsteroidRespawnTime.Evaluate(f.AsteroidsA[index].Size); - Assert.True(f.Zone.Wear(chunk, hp + 1f)); + Assert.True(f.Zone.Breaks(chunk, hp + 1f)); f.Zone.Update(respawn); // zone time now equals BrokenUntil exactly, not "respawn plus a margin". Assert.True(f.Zone.ChunkExists(chunk), "must read as respawned the instant zone time reaches BrokenUntil, not strictly after it"); @@ -458,11 +458,11 @@ public sealed class MiningCut2Tests : IDisposable var hp = f.Settings.AsteroidHitpoints.Evaluate(f.AsteroidsA[index].Size); var respawn = f.Settings.AsteroidRespawnTime.Evaluate(f.AsteroidsA[index].Size); - Assert.True(f.Zone.Wear(chunk, hp + 1f)); + Assert.True(f.Zone.Breaks(chunk, hp + 1f)); f.Zone.Update(respawn); Assert.True(f.Zone.ChunkExists(chunk)); - Assert.True(f.Zone.Wear(chunk, hp + 1f), "a hit on the instant of respawn breaks the respawned chunk again"); + Assert.True(f.Zone.Breaks(chunk, hp + 1f), "a hit on the instant of respawn breaks the respawned chunk again"); Assert.False(f.Zone.ChunkExists(chunk)); } @@ -477,9 +477,9 @@ public sealed class MiningCut2Tests : IDisposable var hp = f.Settings.AsteroidHitpoints.Evaluate(f.AsteroidsA[index].Size); var respawn = f.Settings.AsteroidRespawnTime.Evaluate(f.AsteroidsA[index].Size); - Assert.True(f.Zone.Wear(chunk, hp + 1f)); + Assert.True(f.Zone.Breaks(chunk, hp + 1f)); f.Zone.Update(respawn + 1f); - Assert.False(f.Zone.Wear(chunk, hp * 0.3f)); + Assert.False(f.Zone.Breaks(chunk, hp * 0.3f)); var packed = f.Zone.PackZone().ChunkWear.Find(w => w.Field.Equals(chunk.Field) && w.Index == index); Assert.NotNull(packed); @@ -501,12 +501,12 @@ public sealed class MiningCut2Tests : IDisposable var undamaged = f.Zone.ChunkPose(f.BeltA, index).w; Assert.Equal(f.Zone.AsteroidBelts[f.BeltA].UndamagedSize(index, f.Settings), undamaged, 4); - Assert.False(f.Zone.Wear(chunk, hp * 0.6f)); + Assert.False(f.Zone.Breaks(chunk, hp * 0.6f)); var worn = f.Zone.ChunkPose(f.BeltA, index).w; Assert.Equal(f.Zone.ChunkRadius(chunk), worn, 4); Assert.True(worn < undamaged, "a worn chunk is smaller than an untouched one"); - Assert.True(f.Zone.Wear(chunk, hp)); + Assert.True(f.Zone.Breaks(chunk, hp)); Assert.Equal(0f, f.Zone.ChunkPose(f.BeltA, index).w); } } @@ -520,3 +520,15 @@ internal static class MiningCut2TestExtensions return list; } } + +internal static class ChunkWearTestExtensions +{ + // Wears the chunk and reports whether that hit broke it: Zone.Wear returns the damage absorbed, and a break is + // ChunkExists going from true to false. + public static bool Breaks(this Zone zone, ChunkId chunk, float damage) + { + var there = zone.ChunkExists(chunk); + zone.Wear(chunk, damage); + return there && !zone.ChunkExists(chunk); + } +} diff --git a/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs b/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs index 76a67472a..d020b068e 100644 --- a/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs +++ b/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs @@ -416,7 +416,7 @@ public sealed partial class MiningCut3Tests : IDisposable var whole = s.Zone.ChunkVisibility(chunk); var hitpoints = PlanetSettings().AsteroidHitpoints.Evaluate(.5f); - Assert.False(s.Zone.Wear(chunk, hitpoints * .5f)); + Assert.False(s.Zone.Breaks(chunk, hitpoints * .5f)); var worn = s.Zone.ChunkVisibility(chunk); Assert.InRange(worn, whole * .05f, whole * .95f); Assert.Equal(ExpectedVisibility(s, chunk, kind), worn, 4); @@ -433,7 +433,7 @@ public sealed partial class MiningCut3Tests : IDisposable Tick((observer, eyeAt)); Assert.True(observer.ChunkVisible(chunk)); - Assert.True(s.Zone.Wear(chunk, PlanetSettings().AsteroidHitpoints.Evaluate(.5f) * 2f)); + Assert.True(s.Zone.Breaks(chunk, PlanetSettings().AsteroidHitpoints.Evaluate(.5f) * 2f)); Assert.Equal(0f, s.Zone.ChunkVisibility(chunk)); Assert.Equal(0f, observer.ChunkInfo(chunk)); Assert.False(observer.SetTarget(chunk)); @@ -487,7 +487,7 @@ public sealed partial class MiningCut3Tests : IDisposable var centre = float2(400, -250); // off the origin, so a query that ignored the belt centre would disagree var s = BuildSceneAt(centre, new[] { kind }, Belt(kind, rocks)); var belt = s.Belts[0]; - Assert.True(s.Zone.Wear(new ChunkId(belt, 5), 1e6f)); // broken + Assert.True(s.Zone.Breaks(new ChunkId(belt, 5), 1e6f)); // broken var found = new List<ChunkId>(); var sawSome = false; @@ -555,7 +555,7 @@ public sealed partial class MiningCut3Tests : IDisposable Assert.True(watcher.SetTarget(second)); Tick((watcher, eyeAt)); Assert.False(watcher.Target.Value.IsNone); - Assert.True(s.Zone.Wear(second, 1e6f)); + Assert.True(s.Zone.Breaks(second, 1e6f)); Tick((watcher, eyeAt)); Assert.True(watcher.Target.Value.IsNone); @@ -565,7 +565,7 @@ public sealed partial class MiningCut3Tests : IDisposable var third = new ChunkId(s.Belts[0], 2); Assert.True(docked.SetTarget(third)); docked.Deactivate(); - Assert.True(s.Zone.Wear(third, 1e6f)); + Assert.True(s.Zone.Breaks(third, 1e6f)); docked.Activate(); Assert.True(docked.Target.Value.IsNone); } diff --git a/tests/Aetheria.Shared.Tests/MiningCut4aTests.cs b/tests/Aetheria.Shared.Tests/MiningCut4aTests.cs index 7d43c86d3..49fc75886 100644 --- a/tests/Aetheria.Shared.Tests/MiningCut4aTests.cs +++ b/tests/Aetheria.Shared.Tests/MiningCut4aTests.cs @@ -181,7 +181,7 @@ public sealed partial class MiningCut3Tests { var (s, rock) = OneRock(); var at = At(s, rock); - Assert.True(s.Zone.Wear(rock, 1e6f)); + Assert.True(s.Zone.Breaks(rock, 1e6f)); var subs = new List<IDisposable>(); var absorbs = Absorbs(s, subs); FireControl.Detonate(s.Zone, at, 8f, 10f, DamageType.Kinetic); diff --git a/tests/Aetheria.Shared.Tests/MiningCut4bTests.cs b/tests/Aetheria.Shared.Tests/MiningCut4bTests.cs index 351e875a2..6b263652a 100644 --- a/tests/Aetheria.Shared.Tests/MiningCut4bTests.cs +++ b/tests/Aetheria.Shared.Tests/MiningCut4bTests.cs @@ -291,7 +291,7 @@ public sealed class MiningCut4bTests : IDisposable FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); Assert.Empty(rig.Resolved); - Assert.True(rig.Zone.Wear(rig.Rock, 1e6f)); + Assert.True(rig.Zone.Breaks(rig.Rock, 1e6f)); Run(rig, 2.5f); var outcome = Assert.Single(rig.Resolved); @@ -383,7 +383,7 @@ public sealed class MiningCut4bTests : IDisposable Assert.True(frozen.Hit, "fixture: the commit rolled a hit"); Assert.Empty(rig.Resolved); - Assert.True(rig.Zone.Wear(rig.Rock, 1e6f)); + Assert.True(rig.Zone.Breaks(rig.Rock, 1e6f)); Run(rig, 2.5f); var outcome = Assert.Single(rig.Resolved); diff --git a/tests/Aetheria.Shared.Tests/MiningIndexTests.cs b/tests/Aetheria.Shared.Tests/MiningIndexTests.cs index e47f9a4a1..a90f8343b 100644 --- a/tests/Aetheria.Shared.Tests/MiningIndexTests.cs +++ b/tests/Aetheria.Shared.Tests/MiningIndexTests.cs @@ -70,7 +70,7 @@ public sealed partial class MiningCut3Tests var centre = float2(-300, 820); var s = BuildSceneAt(centre, 5000f, 1234.5, null, new[] { kind }, Belt(kind, Annulus(rng, 3000, 200f, 900f)), Belt(kind, Annulus(rng, 700, 1000f, 1060f))); - for (var i = 0; i < 40; i++) Assert.True(s.Zone.Wear(new ChunkId(s.Belts[0], i * 73), 1e6f)); + for (var i = 0; i < 40; i++) Assert.True(s.Zone.Breaks(new ChunkId(s.Belts[0], i * 73), 1e6f)); var found = new List<ChunkId>(); var nonEmpty = 0; From 8a31099d991b4971467599059012c0e568db25d9 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Thu, 12 Nov 2026 23:05:07 +0000 Subject: [PATCH 068/190] Mining 5a: a worn rock pays the shooter in ore at the wear site from the shot's dice; overflow floats Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Resources/Settings.asset | 4 +- Assets/Scripts/ServerShared/FireControl.cs | 76 +++++- Assets/Scripts/ServerShared/Settings.cs | 5 + Assets/Scripts/ServerShared/SimulationDice.cs | 3 + .../Aetheria.Shared.Tests/MiningCut3Tests.cs | 2 + .../Aetheria.Shared.Tests/MiningCut4bTests.cs | 10 +- .../Aetheria.Shared.Tests/MiningCut5aTests.cs | 245 ++++++++++++++++++ 7 files changed, 332 insertions(+), 13 deletions(-) create mode 100644 tests/Aetheria.Shared.Tests/MiningCut5aTests.cs diff --git a/Assets/Resources/Settings.asset b/Assets/Resources/Settings.asset index 46bee7272..c12d32c99 100644 --- a/Assets/Resources/Settings.asset +++ b/Assets/Resources/Settings.asset @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:7f09c54dfdb87dffd76fa92365d62c53ce333457b89ccf8ead09093ffffedc42 -size 12525 +oid sha256:711ded55b95c512e3803df7682e44f0a9bb83ad36a384432781dc12dc5dadf0a +size 12630 diff --git a/Assets/Scripts/ServerShared/FireControl.cs b/Assets/Scripts/ServerShared/FireControl.cs index 6cd860ab3..3df60cf50 100644 --- a/Assets/Scripts/ServerShared/FireControl.cs +++ b/Assets/Scripts/ServerShared/FireControl.cs @@ -7,6 +7,7 @@ using System.Buffers; using System.Collections.Generic; using System.Linq; using CultMath; +using GameCult.Caching; using static CultMath.math; using float2 = CultMath.float2; using float3 = CultMath.float3; @@ -1234,7 +1235,7 @@ public static class FireControl // Detonate is still the one blast path. if (shot.Outcome.Result == ShotResult.Burst || shot.Fuse == WeaponFuse.Proximity) { - Detonate(zone, shot.Outcome.BurstPoint, shot.BlastRadius, shot.Damage, shot.DamageType); + Detonate(zone, shot.Outcome.BurstPoint, shot.BlastRadius, shot.Damage, shot.DamageType, shot); return; } @@ -1270,11 +1271,12 @@ public static class FireControl var direction = float3(shot.TravelDirection.x, 0, shot.TravelDirection.y); var surface = centre - shot.TravelDirection * zone.ChunkRadius(rock); Publish(zone.ChunkCapabilities, AbsorbLayer.Hull, float3(surface.x, 0f, surface.y), direction, shot.Damage, shot.DamageType); - zone.Wear(rock, shot.Damage); + var absorbed = zone.Wear(rock, shot.Damage); + Extract(zone, rock, absorbed, shot.Source, SimulationDice.For(zone.DropSeed, SimulationDice.OreStream, (uint) shot.ShotId)); return; } var point = Armed(shot.FireOrigin, shot.TravelDirection, shot.BlastRadius, float3(centre.x, shot.FireOrigin.y, centre.y)).xz; - Detonate(zone, point, shot.BlastRadius, shot.Damage, shot.DamageType); + Detonate(zone, point, shot.BlastRadius, shot.Damage, shot.DamageType, shot); } // Cut 12.3 (docs/fire-control-cut.md, "How a direct hit travels"): replaces Entity.ApplyHit's 0.5-step @@ -1413,7 +1415,7 @@ public static class FireControl // the muzzle than the blast radius is detonated on at the radius, along the round's own flight line. var hullPoint = target.ToWorldPoint(schematicPoint); var worldPoint = Armed(shot.FireOrigin, shot.TravelDirection, shot.BlastRadius, float3(hullPoint.x, shot.FireOrigin.y, hullPoint.y)).xz; - Detonate(target.Zone, worldPoint, shot.BlastRadius, shot.Damage, shot.DamageType); + Detonate(target.Zone, worldPoint, shot.BlastRadius, shot.Damage, shot.DamageType, shot); } // Cut 12.4(b) (docs/fire-control-cut.md, "The penetrator", Q12-8): the one penetration-reach owner, moved @@ -1715,7 +1717,7 @@ public static class FireControl // call: doing so would buy no behaviour, per ProbeC in the cut doc). Leftovers -- unoccupied-cell shares, // and whatever an item's pool does not absorb -- join one entity-wide hull total, applied through one // DamageHull call. - public static void Detonate(Zone zone, float2 worldPlanar, float radius, float damage, DamageType damageType) + public static void Detonate(Zone zone, float2 worldPlanar, float radius, float damage, DamageType damageType, PendingShot? shot = null) { // No distance prefilter: RectDiskOverlap is the one decider of whether the disc touches a hull. A // prefilter measured from Position (the centre of mass) with the bounding box's half-diagonal is not a @@ -1804,6 +1806,9 @@ public static class FireControl return byField != 0 ? byField : a.Target.Chunk.Value.Index.CompareTo(b.Target.Chunk.Value.Index); }); var discArea = PI * radius * radius; + // Mining Cut 5a: a shot's blast pays its Source for the rocks it wears, from the shot's own dice, once for the + // blast, drawn in the rock order above. A mine (no shot) wears rocks and yields nothing. + var dice = shot != null ? SimulationDice.For(zone.DropSeed, SimulationDice.OreStream, (uint) shot.Value.ShotId) : default; foreach (var rock in rocks) { var chunk = rock.Target.Chunk.Value; @@ -1812,7 +1817,66 @@ public static class FireControl var share = damage * CircleCircleOverlap(length(centre - worldPlanar), radius, zone.ChunkRadius(chunk)) / discArea; if (!(share > 0f)) continue; PublishBlast(zone.ChunkCapabilities, centre, 0f, worldPlanar, AbsorbLayer.Hull, share, damageType); - zone.Wear(chunk, share); + var absorbed = zone.Wear(chunk, share); + if (shot != null) Extract(zone, chunk, absorbed, shot.Value.Source, dice); + } + } + + // Mining Cut 5a: the one loot owner of a rock. A worn rock pays the shooter at the wear site, at arrival or detonation, + // from the shot's own dice: the damage it absorbed is that fraction of its hitpoints, and the same fraction of the + // units its size authors (AsteroidYield), so a rock pays its whole yield however many hits break it. Whole units, and + // one Bernoulli draw on the fraction. Each unit draws an ore by weight: the belt's yields for this province, scaled by + // exp(variance x g), g a stable hash of (field, index, ore) in [-1, 1) -- a rock's composition, derived here every call + // and never stored. A shot with no Source (a mine) yields nothing. The units go to the shooter's cargo bays in + // stacks; what does not fit, or everything when the shooter has left the zone, floats at the rock (ruling + // mining-overflow-floats). + // Draw order: the Bernoulli, then one draw per unit. + public static void Extract(Zone zone, ChunkId chunk, float absorbed, Entity shooter, Random dice) + { + if (shooter == null || !(absorbed > 0f)) return; + var settings = zone.Settings; + var belt = zone.AsteroidBelts[chunk.Field]; + var catalog = shooter.ItemManager.ItemData; + var ores = FieldKinds.Yield(belt.Data.Kind, zone.GalaxyZone?.Province?.Type ?? default, catalog); + if (ores.Length == 0) return; + + var size = belt.Data.Asteroids[chunk.Index].Size; + var owed = absorbed / settings.AsteroidHitpoints.Evaluate(size) * settings.AsteroidYield.Evaluate(size); + var units = (int) floor(owed); + if (dice.NextFloat() < owed - units) units++; + if (units == 0) return; + + var weights = new float[ores.Length]; + var total = 0f; + for (var i = 0; i < ores.Length; i++) + { + var g = $"{chunk.Field.Value}:{chunk.Index}:{ores[i].Commodity.Key.Value}".StableHash() / 2147483648.0 - 1.0; + total += weights[i] = ores[i].Amount * (float) Math.Exp(settings.ChunkCompositionVariance * g); + } + var counts = new int[ores.Length]; + for (var unit = 0; unit < units; unit++) + { + var pick = dice.NextFloat() * total; + var ore = 0; + while (ore < ores.Length - 1 && pick >= weights[ore]) pick -= weights[ore++]; + counts[ore]++; + } + + var at = zone.ChunkPose(chunk.Field, chunk.Index).xy; + var velocity = zone.ChunkVelocity(chunk); + var present = zone.Entities.Contains(shooter); + for (var i = 0; i < ores.Length; i++) + { + var key = ores[i].Commodity.Key; + var maxStack = Math.Max(1, ((SimpleCommodityData) catalog.Get(ores[i].Commodity)).MaxStack); + for (var left = counts[i]; left > 0; left -= maxStack) + { + var stack = new SimpleCommodity { Data = new CultRecordRef<ItemData>(key), Quantity = Math.Min(left, maxStack) }; + // A partial store leaves the remainder in Quantity and returns false, so the next bay is offered the rest. + var stored = false; + if (present) foreach (var bay in shooter.CargoBays) if (stored = bay.TryStore(stack)) break; + if (!stored) zone.Release(stack, at, velocity); + } } } diff --git a/Assets/Scripts/ServerShared/Settings.cs b/Assets/Scripts/ServerShared/Settings.cs index 8326f76da..1d83bd692 100644 --- a/Assets/Scripts/ServerShared/Settings.cs +++ b/Assets/Scripts/ServerShared/Settings.cs @@ -29,6 +29,11 @@ public class PlanetSettings public ExponentialLerp AsteroidSize; public ExponentialLerp AsteroidHitpoints; public ExponentialLerp AsteroidRespawnTime; + // Units of ore a whole rock of normalized size s gives (FireControl.Extract), however many hits break it. + public ExponentialLerp AsteroidYield; + // How far a rock's mix of its belt's ores strays from the kind's ratio: each ore's weight is scaled by + // exp(variance x g), g in [-1, 1) a stable hash of (rock, ore). Zero reads the kind's ratio. + public float ChunkCompositionVariance; public float SecureAreaRadiusMultiplier = .45f; diff --git a/Assets/Scripts/ServerShared/SimulationDice.cs b/Assets/Scripts/ServerShared/SimulationDice.cs index adc440299..c8cb9e759 100644 --- a/Assets/Scripts/ServerShared/SimulationDice.cs +++ b/Assets/Scripts/ServerShared/SimulationDice.cs @@ -18,6 +18,9 @@ public static class SimulationDice // seed (CombatSeed): the run seed feeds drops and mines only (ruling run-seed-drops-only), and placement never rides // ItemManager.Random. public const uint ScatterStream = 5; + // The ore a shot's wear of rocks pays, ordinal the shot's ShotId, on the zone's DropSeed (mined ore is a drop): + // FireControl.Extract is the one reader. + public const uint OreStream = 6; // 9.1 (docs/fire-control-cut.md): fmix32, MurmurHash3's 32-bit finalizer -- xor-shift, multiply, // xor-shift, multiply, xor-shift. Diffuses a structured seed (a zone seed XORed with a small, diff --git a/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs b/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs index d020b068e..64e371c07 100644 --- a/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs +++ b/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs @@ -56,6 +56,8 @@ public sealed partial class MiningCut3Tests : IDisposable AsteroidSize = new ExponentialLerp { Minimum = 2f, Maximum = 9f, Exponent = 1.7f }, AsteroidHitpoints = new ExponentialLerp { Minimum = 20f, Maximum = 220f, Exponent = 1.6f }, AsteroidRespawnTime = new ExponentialLerp { Minimum = 8f, Maximum = 96f, Exponent = 1.2f }, + AsteroidYield = new ExponentialLerp { Minimum = 2f, Maximum = 6f, Exponent = 1f }, + ChunkCompositionVariance = .5f, BodyRadius = new ExponentialCurve(), LightRadius = new ExponentialCurve { Constant = lightRadius } }; diff --git a/tests/Aetheria.Shared.Tests/MiningCut4bTests.cs b/tests/Aetheria.Shared.Tests/MiningCut4bTests.cs index 6b263652a..8502e7d7d 100644 --- a/tests/Aetheria.Shared.Tests/MiningCut4bTests.cs +++ b/tests/Aetheria.Shared.Tests/MiningCut4bTests.cs @@ -22,7 +22,7 @@ public sealed class MiningCut4bTests : IDisposable public void Dispose() => _fixtures.Dispose(); - private sealed class Rig + internal sealed class Rig { public MiningCut3Tests.Scene Scene; public Zone Zone => Scene.Zone; @@ -56,11 +56,11 @@ public sealed class MiningCut4bTests : IDisposable } // `precision` 1 gives sigma 1 cell; accuracy 1 and a resolution that asks little of the info make PSensor 1. - private Rig Build(bool sensor = true, bool launcher = false, float damage = 10f, float velocity = 0f, float spread = 0f, + internal Rig Build(bool sensor = true, bool launcher = false, float damage = 10f, float velocity = 0f, float spread = 0f, float precision = 1f, float effective = float.PositiveInfinity, WeaponFuse? fuse = null, float blastRadius = 0f, - float rockSize = 0f, float crossSection = 20f, bool target = true, float tracking = 1000000f) + float rockSize = 0f, float crossSection = 20f, bool target = true, float tracking = 1000000f, FieldKindData kind = null) { - var kind = MiningCut3Tests.Kind("Asteroid", crossSection); + kind ??= MiningCut3Tests.Kind("Asteroid", crossSection); var scene = _fixtures.BuildScene(new[] { kind }, MiningCut3Tests.Belt(kind, MiningCut3Tests.Rock(Distance, .25f, rockSize))); var gear = MiningCut3Tests.Gear("Targeting", new TargetingSystemData { @@ -209,7 +209,7 @@ public sealed class MiningCut4bTests : IDisposable // ==== resolution ==== - private static void Run(Rig rig, float seconds) + internal static void Run(Rig rig, float seconds) { for (var elapsed = 0f; elapsed < seconds; elapsed += .01f) rig.Zone.Update(.01f); } diff --git a/tests/Aetheria.Shared.Tests/MiningCut5aTests.cs b/tests/Aetheria.Shared.Tests/MiningCut5aTests.cs new file mode 100644 index 000000000..cd93ca233 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/MiningCut5aTests.cs @@ -0,0 +1,245 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using System.Collections.Generic; +using System.Linq; +using CultMath; +using GameCult.Caching; +using Xunit; +using static CultMath.math; + +// Mining Cut 5a (docs/mining-cut-refresh.md): a worn rock pays the shooter in ore at the wear site, from the shot's own +// dice; what does not fit in the hold floats at the rock. The fixtures are Cut 3's belt scene and Cut 4b's rig. +public sealed class MiningCut5aTests : IDisposable +{ + private readonly MiningCut4bTests _rigs = new MiningCut4bTests(); + private readonly MiningCut3Tests _scenes = new MiningCut3Tests(); + + public void Dispose() + { + _rigs.Dispose(); + _scenes.Dispose(); + } + + private static SimpleCommodityData Commodity(string name, int maxStack = 100) => + new SimpleCommodityData { Name = name, Shape = new Shape(), Price = 5, MaxStack = maxStack }; + + // Registers the ores and the kind's yields in the scene's catalog (the kind refs need the stored commodities). + private static void Stock(MiningCut3Tests.Scene scene, FieldKindData kind, params (SimpleCommodityData Ore, float Abundance)[] yields) + { + kind.Yields.Clear(); + foreach (var (ore, abundance) in yields) + { + scene.Cache.Upsert(ore); + kind.Yields.Add(new FieldYield { Commodity = scene.Cache.RefOf(ore), Abundance = abundance }); + } + scene.Cache.Upsert(kind); + } + + private EquippedCargoBay Bay(MiningCut3Tests.Scene scene, Ship ship, int width, int height, string name) + { + var shape = new Shape(width, height); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + var data = new CargoBayData { Name = name, Shape = new Shape(), InteriorShape = shape, Price = 1, Durability = 4 }; + scene.Cache.Upsert(data); + var bay = new EquippedCargoBay(scene.Items, MiningCut3Tests.Mint(scene, data), new int2(1, 1), ship, name); + ship.CargoBays.Add(bay); + return bay; + } + + private static int Units(IEnumerable<ItemInstance> items, string ore, MiningCut3Tests.Scene scene) => + items.OfType<SimpleCommodity>().Where(c => scene.Items.GetData(c).Name == ore).Sum(c => c.Quantity); + + private static int Units(EquippedCargoBay bay, string ore, MiningCut3Tests.Scene scene) => Units(bay.Cargo.Keys, ore, scene); + + // A rig whose rock (size .5: 4 units, whole) yields `ores`, shooter holding one bay. + private (MiningCut4bTests.Rig Rig, EquippedCargoBay Bay) Mining(int bayWidth = 4, int bayHeight = 4, float damage = 1000f, + WeaponFuse? fuse = null, float velocity = 0f, params (SimpleCommodityData, float)[] ores) + { + var kind = MiningCut3Tests.Kind("Asteroid", 20f); + var rig = _rigs.Build(damage: damage, fuse: fuse, blastRadius: fuse == null ? 0f : 6f, precision: 1000f, rockSize: .5f, velocity: velocity, kind: kind); + Stock(rig.Scene, kind, ores.Length > 0 ? ores : new[] { (Commodity("Rock"), 1f) }); + return (rig, Bay(rig.Scene, rig.Shooter, bayWidth, bayHeight, "Hold")); + } + + private static int Hits(MiningCut4bTests.Rig rig, int cap = 40) + { + for (var shot = 0; shot < cap && !rig.Resolved.Any(o => o.Hit); shot++) + { + // A broken rock cannot be targeted again: the first hit ends the loop. + FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); + MiningCut4bTests.Run(rig, .05f); + } + return rig.Resolved.Count(o => o.Hit); + } + + private static float Hitpoints(MiningCut4bTests.Rig rig) => + rig.Zone.Settings.AsteroidHitpoints.Evaluate(rig.Zone.AsteroidBelts[rig.Rock.Field].Data.Asteroids[rig.Rock.Index].Size); + + [Fact] + public void WearReturnsWhatTheRockAbsorbed() + { + var (rig, _) = Mining(); + var hp = Hitpoints(rig); + Assert.Equal(hp * .3f, rig.Zone.Wear(rig.Rock, hp * .3f), 3); + // The breaking hit absorbs only what the rock had left. + Assert.Equal(hp * .7f, rig.Zone.Wear(rig.Rock, hp * 5f), 3); + Assert.False(rig.Zone.ChunkExists(rig.Rock)); + Assert.Equal(0f, rig.Zone.Wear(rig.Rock, hp)); + } + + // Units owed are absorbed/hitpoints x AsteroidYield(size): a rock pays its whole yield however many hits break it, so + // the mean over many rocks does not depend on how the damage arrives. + [Fact] + public void ARockYieldsItsAuthoredTotalWhateverBreaksIt() + { + const int rocks = 300; + var ore = Commodity("Rock"); + var kind = MiningCut3Tests.Kind("Asteroid", 4f); + var scene = _scenes.BuildScene(new[] { kind }, MiningCut3Tests.Belt(kind, + Enumerable.Range(0, rocks).Select(i => MiningCut3Tests.Rock(150f + i * .1f, i / (float) rocks, .3f)).ToArray())); + Stock(scene, kind, (ore, 1f)); + var ship = new Ship(scene.Items, scene.Zone, MiningCut3Tests.Mint(scene, scene.Hull), new EntitySettings()); + scene.Zone.Admit(ship, piloted: false); + var bay = Bay(scene, ship, 8, 8, "Hold"); + var settings = scene.Zone.Settings; + var hp = settings.AsteroidHitpoints.Evaluate(.3f); + var owed = settings.AsteroidYield.Evaluate(.3f); + + uint ordinal = 0; + void Hit(int rock, float fraction) => + FireControl.Extract(scene.Zone, new ChunkId(scene.Belts[0], rock), scene.Zone.Wear(new ChunkId(scene.Belts[0], rock), hp * fraction), + ship, SimulationDice.For(scene.Zone.DropSeed, SimulationDice.OreStream, ++ordinal)); + + for (var rock = 0; rock < rocks / 2; rock++) Hit(rock, 2f); + var wholeHits = Units(bay.Cargo.Keys.Concat(scene.Zone.FloatingItems.Select(f => f.Item)), "Rock", scene); + for (var rock = rocks / 2; rock < rocks; rock++) for (var part = 0; part < 4; part++) Hit(rock, .25f); + var total = Units(bay.Cargo.Keys.Concat(scene.Zone.FloatingItems.Select(f => f.Item)), "Rock", scene); + var quartered = total - wholeHits; + + // owed = 3.2 per rock; 150 rocks: mean 480, sigma about 4.9 whole, 4.9 quartered. + Assert.InRange(wholeHits, 480 - 30, 480 + 30); + Assert.InRange(quartered, 480 - 30, 480 + 30); + Assert.Equal(3.2f, owed, 3); + } + + [Fact] + public void ADirectHitPaysTheShooter() + { + var (rig, bay) = Mining(ores: new[] { (Commodity("Rock"), 1f), (Commodity("Gold"), 1f) }); + var yields = FieldKinds.Yield(rig.Zone.AsteroidBelts[rig.Rock.Field].Data.Kind, default, rig.Scene.Cache); + Assert.Equal(2, yields.Length); + Assert.Equal(1, Hits(rig)); + Assert.False(rig.Zone.ChunkExists(rig.Rock)); + Assert.Equal(4, Units(bay, "Rock", rig.Scene) + Units(bay, "Gold", rig.Scene)); + Assert.Empty(rig.Zone.FloatingItems); + } + + [Fact] + public void ABlastPaysTheShooter() + { + var (rig, bay) = Mining(fuse: WeaponFuse.Contact, ores: new[] { (Commodity("Rock"), 1f) }); + Hits(rig); + Assert.False(rig.Zone.ChunkExists(rig.Rock)); + Assert.Equal(4, Units(bay, "Rock", rig.Scene)); + } + + [Fact] + public void AMineWearsButYieldsNothing() + { + var (rig, bay) = Mining(); + var at = rig.Zone.ChunkPose(rig.Rock.Field, rig.Rock.Index).xy; + FireControl.Detonate(rig.Zone, at, 6f, 1000f, DamageType.Kinetic); + Assert.False(rig.Zone.ChunkExists(rig.Rock)); + Assert.Empty(bay.Cargo); + Assert.Empty(rig.Zone.FloatingItems); + } + + // Ruling mining-overflow-floats: what the hold cannot take floats at the rock, where another ship can pick it up. + [Fact] + public void AFullHoldReleasesTheOverflow() + { + var grit = Commodity("Grit", maxStack: 2); + var (rig, bay) = Mining(bayWidth: 1, bayHeight: 1, ores: new[] { (grit, 1f) }); + Hits(rig); + + Assert.Equal(2, Units(bay, "Grit", rig.Scene)); + var floating = Assert.Single(rig.Zone.FloatingItems); + Assert.Equal(2, Assert.IsType<SimpleCommodity>(floating.Item).Quantity); + var rock = rig.Zone.ChunkPose(rig.Rock.Field, rig.Rock.Index).xy; + Assert.True(length(floating.Body.Position - rock) < 1f, "the overflow leaves from the rock"); + + var taker = new Ship(rig.Scene.Items, rig.Zone, MiningCut3Tests.Mint(rig.Scene, rig.Scene.Hull), new EntitySettings()); + rig.Zone.Admit(taker, piloted: false); + var takerBay = Bay(rig.Scene, taker, 4, 4, "Taker"); + Assert.True(rig.Zone.TryPickUp(taker, floating.Id)); + Assert.Equal(2, Units(takerBay, "Grit", rig.Scene)); + } + + [Fact] + public void AGoneShooterReleasesEverything() + { + var (rig, bay) = Mining(velocity: 50f); + FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); + rig.Shooter.HeatstrokeDeath.OnNext(UniRx.Unit.Default); + MiningCut4bTests.Run(rig, 3f); + + Assert.Empty(bay.Cargo); + Assert.Equal(4, Units(rig.Zone.FloatingItems.Select(f => f.Item), "Rock", rig.Scene)); + } + + // Two zones of one pack share every key, so the same rocks wear in each: the ore is a function of the dice alone. + private (MiningCut3Tests.Scene Scene, Func<Zone> NewZone, Ship Shooter) Field(int rocks, float size, float variance = .5f, float yield = 4f) + { + var kind = MiningCut3Tests.Kind("Asteroid", 4f); + var scene = _scenes.BuildScene(new[] { kind }, MiningCut3Tests.Belt(kind, + Enumerable.Range(0, rocks).Select(i => MiningCut3Tests.Rock(150f + i, i / (float) rocks, size)).ToArray())); + Stock(scene, kind, (Commodity("Rock"), 1f), (Commodity("Gold"), 1f)); + var ship = new Ship(scene.Items, scene.Zone, MiningCut3Tests.Mint(scene, scene.Hull), new EntitySettings()); + Zone NewZone() + { + var settings = MiningCut3Tests.PlanetSettings(); + settings.ChunkCompositionVariance = variance; + settings.AsteroidYield = new ExponentialLerp { Minimum = yield, Maximum = yield, Exponent = 1f }; + return new Zone(scene.Items, settings, scene.Pack, new GalaxyZone { Name = "MiningCut3", Owner = null }, null); + } + return (scene, NewZone, ship); + } + + // Every rock broken once; the shooter is not in the zone, so everything floats and the floats are the record. + private static (int Rock, int Gold)[] Break(MiningCut3Tests.Scene scene, Zone zone, Ship ship, int rocks, uint seed) => + Enumerable.Range(0, rocks).Select(rock => + { + var chunk = new ChunkId(scene.Belts[0], rock); + var before = zone.FloatingItems.Select(f => f.Item).ToArray(); + FireControl.Extract(zone, chunk, zone.Wear(chunk, 1e6f), ship, SimulationDice.For(seed, SimulationDice.OreStream, (uint) rock)); + var added = zone.FloatingItems.Select(f => f.Item).Except(before).ToArray(); + return (Units(added, "Rock", scene), Units(added, "Gold", scene)); + }).ToArray(); + + [Fact] + public void TheSameShotGivesTheSameOre() + { + var (scene, newZone, ship) = Field(20, .5f); + var first = Break(scene, newZone(), ship, 20, 11); + Assert.Equal(first, Break(scene, newZone(), ship, 20, 11)); + Assert.NotEqual(first, Break(scene, newZone(), ship, 20, 12)); + } + + // Composition is derived from the rock's identity every call: variance 0 reads the kind's ratio, variance above 0 gives + // rocks different mixes, and nothing stores it (a second zone of the pack reads the same mixes from the dice and keys). + [Fact] + public void CompositionVariesByRockAndIsDerived() + { + var (scene, even, ship) = Field(12, 1f, variance: 0f, yield: 600f); + // Equal weights, 600 units a rock: even splits within sampling noise (sigma about 12). + Assert.All(Break(scene, even(), ship, 12, 5), m => Assert.InRange(m.Rock, 240, 360)); + + var (scene2, varied, ship2) = Field(12, 1f, variance: 2f, yield: 600f); + var mixes = Break(scene2, varied(), ship2, 12, 5).Select(m => m.Rock).ToArray(); + Assert.True(mixes.Max() - mixes.Min() > 100, "rocks differ in mix when variance is above zero"); + Assert.Equal(mixes, Break(scene2, varied(), ship2, 12, 5).Select(m => m.Rock)); + } +} From 5a3324d612146e925c1beb2d9a851dc2112846e7 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 02:06:45 +0000 Subject: [PATCH 069/190] Station market absorbs a sold commodity; DemoLoop mine, sell, repair, buy test TrySell: a simple commodity always sells (aetheria-release:ruling:station-market-absorbs-sold-commodity). The station bays take as much of the stack as fits, the market absorbs the rest, full price paid. Crafted items still need a bay. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../Scripts/ServerShared/StationServices.cs | 19 +++-- tests/Aetheria.Shared.Tests/DemoLoopTests.cs | 79 +++++++++++++++++++ .../StationServicesTests.cs | 17 ++++ 3 files changed, 109 insertions(+), 6 deletions(-) create mode 100644 tests/Aetheria.Shared.Tests/DemoLoopTests.cs diff --git a/Assets/Scripts/ServerShared/StationServices.cs b/Assets/Scripts/ServerShared/StationServices.cs index 153fc595d..be15fc74e 100644 --- a/Assets/Scripts/ServerShared/StationServices.cs +++ b/Assets/Scripts/ServerShared/StationServices.cs @@ -94,15 +94,22 @@ public static class StationServices public static int BuyableQuantity(ItemManager items, SimpleCommodity stock, int typed, int credits) => Math.Max(1, Math.Min(Math.Min(typed, credits / BuyPrice(items, stock)), stock.Quantity)); - // The sale: the item leaves the bay for one of the station's cargo bays and the station pays SellPrice. False, - // with the item in its bay and the credits unchanged, when no station bay can take it. + // The sale: the item leaves the bay and the station pays SellPrice. A crafted item goes to one of the station's + // cargo bays; false, with the item in its bay and the credits unchanged, when no bay can take it. A simple + // commodity always sells (aetheria-release:ruling:station-market-absorbs-sold-commodity): the bays take as much of + // the stack as fits and the market absorbs the rest, at the full price. public static bool TrySell(EquippedCargoBay from, Entity station, ItemInstance item, ref int credits) { var price = SellPrice(station.ItemManager, item); - var moved = item is SimpleCommodity commodity - ? station.CargoBays.Any(bay => from.TryTransferItem(bay, commodity, commodity.Quantity)) - : station.CargoBays.Any(bay => from.TryTransferItem(bay, (CraftedItemInstance) item)); - if (!moved) return false; + if (item is SimpleCommodity commodity) + { + if (!from.Cargo.ContainsKey(commodity)) return false; + var offered = commodity.Quantity; + for (var quantity = offered; quantity >= 1; quantity--) + if (station.CargoBays.Any(bay => from.TryTransferItem(bay, commodity, quantity))) break; + if (from.Cargo.ContainsKey(commodity)) from.Remove(commodity, commodity.Quantity); + } + else if (!station.CargoBays.Any(bay => from.TryTransferItem(bay, (CraftedItemInstance) item))) return false; credits += price; return true; } diff --git a/tests/Aetheria.Shared.Tests/DemoLoopTests.cs b/tests/Aetheria.Shared.Tests/DemoLoopTests.cs new file mode 100644 index 000000000..7e765174c --- /dev/null +++ b/tests/Aetheria.Shared.Tests/DemoLoopTests.cs @@ -0,0 +1,79 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System.Linq; +using CultMath; +using Xunit; + +// The demo loop on the shipped catalog (aetheria-release, mining 5a and the ore sheet): the player's own gun breaks a rock +// through the trigger, the ore lands in the hold, the Pirates station Zenith buys it, repairs the hull and sells a unit back. +public sealed partial class RunStartTests +{ + [Fact] + public void DemoLoop_mine_sell_repair_buy() + { + var (galaxy, arena, staged, failures) = Launch(new DemoTerminus(), Inputs(() => 1)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + var player = staged.Player; + var belt = arena.Planets.Single(body => body.Value is AsteroidBeltData); + var rock = new ChunkId(belt.Key, 0); + var laser = player.Equipment.Select(equipped => equipped.Behaviors.OfType<Weapon>().FirstOrDefault()) + .First(weapon => weapon != null && weapon.Item.EquippableItem != null && _items.GetData(weapon.Item.EquippableItem).Name == "Light Laser"); + + // Once the ship's stats have settled. + for (var tick = 0; tick < 50; tick++) arena.Update(.02f); + // The belt drifts and the sun's well pulls, so the ship is held where it was put: forty units off the rock. + void Hold() + { + var at = arena.ChunkPose(rock.Field, rock.Index).xy; + player.Position = new float3(at.x, player.Position.y, at.y - 40f); + player.Velocity = float2.zero; + player.Direction = new float2(0, 1); + player.Aim = new float3(0, 0, 1); + } + Hold(); + arena.Update(.02f); + Hold(); + Assert.True(player.SetTarget(rock), "the rock is a target"); + laser.Activate(); + for (var elapsed = 0f; elapsed < 20f && arena.ChunkExists(rock); elapsed += .02f) { Hold(); arena.Update(.02f); } + var info = player.ChunkInfo(rock); + Assert.False(arena.ChunkExists(rock), $"the laser broke the rock: designated {FireControl.Designated(laser, player, rock, out var range)} range {range} info {info} target {player.Target} pos {player.Position} rockpos {arena.ChunkPose(rock.Field, rock.Index)} hp {arena.Settings.AsteroidHitpoints.Evaluate(arena.AsteroidBelts[rock.Field].Data.Asteroids[0].Size)}"); + + var ores = new[] { "Rock", "New Metals", "Gold" }; + var held = player.CargoBays.SelectMany(bay => bay.Cargo.Keys.OfType<SimpleCommodity>().Select(stack => (bay, stack))) + .Where(h => ores.Contains(_items.GetData(h.stack).Name)).ToArray(); + Assert.NotEmpty(held); + Assert.Empty(arena.FloatingItems); + + var zenith = arena.Entities.Single(entity => entity.HullData.Name == "Zenith"); + var credits = 0; + // Every ore stack goes: the market takes it all, whatever the full hold of Zenith has room for. + foreach (var (from, sold) in held) Assert.True(StationServices.TrySell(from, zenith, sold, ref credits), "the market takes the ore"); + Assert.DoesNotContain(player.CargoBays.SelectMany(bay => bay.Cargo.Keys.OfType<SimpleCommodity>()), c => ores.Contains(_items.GetData(c).Name)); + Assert.True(credits > 0, "the station pays for the ore"); + + var cell = Enumerable.Range(0, player.MaxArmor.GetLength(0)).SelectMany(x => Enumerable.Range(0, player.MaxArmor.GetLength(1)).Select(y => (x, y))) + .First(c => player.MaxArmor[c.x, c.y] > 0); + player.Armor[cell.x, cell.y] = 0; + var cost = StationServices.RepairCost(_items, player); + Assert.True(cost > 0); + var paid = credits; + credits += cost; + Assert.True(StationServices.TryRepair(player, ref credits)); + Assert.Equal(paid, credits); + Assert.Equal(player.MaxArmor[cell.x, cell.y], player.Armor[cell.x, cell.y]); + + // Zenith's whole stock is one 16-cell reactor, which fits only an empty 4x4: the player jettisons what the hold + // still carries, then buys it. + var hold = player.CargoBays[0]; + foreach (var leftover in hold.Cargo.Keys.ToArray()) hold.Remove(leftover); + var stock = zenith.CargoBays.SelectMany(bay => bay.Cargo.Keys.OfType<CraftedItemInstance>().Select(piece => (bay, piece))).Single(); + credits = StationServices.BuyPrice(_items, stock.piece); + Assert.Equal(BuyResult.Bought, StationServices.TryBuy(_items, stock.piece, 1, ref credits, + () => stock.bay.TryTransferItem(hold, stock.piece))); + Assert.Equal(0, credits); + Assert.Contains(stock.piece, hold.Cargo.Keys); + } +} diff --git a/tests/Aetheria.Shared.Tests/StationServicesTests.cs b/tests/Aetheria.Shared.Tests/StationServicesTests.cs index 2bf4d3c2f..173f00069 100644 --- a/tests/Aetheria.Shared.Tests/StationServicesTests.cs +++ b/tests/Aetheria.Shared.Tests/StationServicesTests.cs @@ -175,6 +175,23 @@ public sealed class StationServicesTests : IDisposable Assert.Contains(ore, open.Cargo.Keys); } + // The market absorbs a sold commodity (aetheria-release:ruling:station-market-absorbs-sold-commodity): a full hold + // stores what fits, the rest is taken, and the full price is paid; a hold with no room at all still pays. + [Fact] + public void TrySell_commodity_is_paid_in_full_when_the_station_hold_is_full() + { + var from = Ship().CargoBays.Single(); + var ore = Ore(10); + Assert.True(from.TryStore(ore)); + var station = Station(); + while (station.CargoBays[0].TryStore(Mint("Gun"))) { } + var credits = 0; + Assert.True(StationServices.TrySell(from, station, ore, ref credits)); + Assert.Equal(35, credits); + Assert.Empty(from.Cargo.Keys.OfType<SimpleCommodity>()); + Assert.Empty(station.CargoBays[0].Cargo.Keys.OfType<SimpleCommodity>()); + } + [Fact] public void Repair_restores_and_charges() { From 5663361e940f5df77055ea4bd9ec38dd640fed5f Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 02:57:50 +0000 Subject: [PATCH 070/190] Tests: ore dice keyed by ShotId and DropSeed on both fire paths; TrySell of an unheld commodity pays nothing Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../Aetheria.Shared.Tests/MiningCut3Tests.cs | 6 +- .../Aetheria.Shared.Tests/MiningCut4bTests.cs | 3 +- .../Aetheria.Shared.Tests/MiningCut5aTests.cs | 70 ++++++++++++++++++- .../StationServicesTests.cs | 23 ++++++ 4 files changed, 98 insertions(+), 4 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs b/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs index 64e371c07..95dbacd1f 100644 --- a/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs +++ b/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs @@ -24,6 +24,9 @@ public sealed partial class MiningCut3Tests : IDisposable private readonly List<CultCache> _caches = new List<CultCache>(); private int _fixtureCount; + // A run seed for the scenes built next: nonzero gives the zone a galaxy carrying it (so Zone.DropSeed differs by it). + internal uint GalaxySeed; + public MiningCut3Tests() => Directory.CreateDirectory(_root); public void Dispose() @@ -163,7 +166,8 @@ public sealed partial class MiningCut3Tests : IDisposable pack.Planets.Add(new CultRecordRef<BodyData>(key)); scene.Belts.Add(key); } - scene.Zone = new Zone(items, PlanetSettings(lightRadius), pack, new GalaxyZone { Name = "MiningCut3", Owner = null }, null); + scene.Zone = new Zone(items, PlanetSettings(lightRadius), pack, new GalaxyZone { Name = "MiningCut3", Owner = null }, + GalaxySeed == 0 ? null : RunSeedFixture.Continue(cache, "MiningCut3", GalaxySeed)); return scene; } diff --git a/tests/Aetheria.Shared.Tests/MiningCut4bTests.cs b/tests/Aetheria.Shared.Tests/MiningCut4bTests.cs index 8502e7d7d..abf4f0dc1 100644 --- a/tests/Aetheria.Shared.Tests/MiningCut4bTests.cs +++ b/tests/Aetheria.Shared.Tests/MiningCut4bTests.cs @@ -58,8 +58,9 @@ public sealed class MiningCut4bTests : IDisposable // `precision` 1 gives sigma 1 cell; accuracy 1 and a resolution that asks little of the info make PSensor 1. internal Rig Build(bool sensor = true, bool launcher = false, float damage = 10f, float velocity = 0f, float spread = 0f, float precision = 1f, float effective = float.PositiveInfinity, WeaponFuse? fuse = null, float blastRadius = 0f, - float rockSize = 0f, float crossSection = 20f, bool target = true, float tracking = 1000000f, FieldKindData kind = null) + float rockSize = 0f, float crossSection = 20f, bool target = true, float tracking = 1000000f, FieldKindData kind = null, uint galaxySeed = 0) { + _fixtures.GalaxySeed = galaxySeed; kind ??= MiningCut3Tests.Kind("Asteroid", crossSection); var scene = _fixtures.BuildScene(new[] { kind }, MiningCut3Tests.Belt(kind, MiningCut3Tests.Rock(Distance, .25f, rockSize))); var gear = MiningCut3Tests.Gear("Targeting", new TargetingSystemData diff --git a/tests/Aetheria.Shared.Tests/MiningCut5aTests.cs b/tests/Aetheria.Shared.Tests/MiningCut5aTests.cs index cd93ca233..d71607031 100644 --- a/tests/Aetheria.Shared.Tests/MiningCut5aTests.cs +++ b/tests/Aetheria.Shared.Tests/MiningCut5aTests.cs @@ -56,10 +56,10 @@ public sealed class MiningCut5aTests : IDisposable // A rig whose rock (size .5: 4 units, whole) yields `ores`, shooter holding one bay. private (MiningCut4bTests.Rig Rig, EquippedCargoBay Bay) Mining(int bayWidth = 4, int bayHeight = 4, float damage = 1000f, - WeaponFuse? fuse = null, float velocity = 0f, params (SimpleCommodityData, float)[] ores) + WeaponFuse? fuse = null, float velocity = 0f, uint galaxySeed = 0, float rockSize = .5f, params (SimpleCommodityData, float)[] ores) { var kind = MiningCut3Tests.Kind("Asteroid", 20f); - var rig = _rigs.Build(damage: damage, fuse: fuse, blastRadius: fuse == null ? 0f : 6f, precision: 1000f, rockSize: .5f, velocity: velocity, kind: kind); + var rig = _rigs.Build(damage: damage, fuse: fuse, blastRadius: fuse == null ? 0f : 6f, precision: 1000f, rockSize: rockSize, velocity: velocity, kind: kind, galaxySeed: galaxySeed); Stock(rig.Scene, kind, ores.Length > 0 ? ores : new[] { (Commodity("Rock"), 1f) }); return (rig, Bay(rig.Scene, rig.Shooter, bayWidth, bayHeight, "Hold")); } @@ -242,4 +242,70 @@ public sealed class MiningCut5aTests : IDisposable Assert.True(mixes.Max() - mixes.Min() > 100, "rocks differ in mix when variance is above zero"); Assert.Equal(mixes, Break(scene2, varied(), ship2, 12, 5).Select(m => m.Rock)); } + + // ==== the shot's own dice: ShotId and the zone's DropSeed key the ore ==== + + // A rig whose rock outlives many shots and pays hundreds of units a hit, three ores, so a changed key shows in the mix. The rock is + // wider than the blast, so every blast wears it by the same share and only the dice can tell two shots apart. + private (MiningCut4bTests.Rig Rig, EquippedCargoBay Bay) Rich(WeaponFuse? fuse, float damage, uint galaxySeed = 0) + { + var (rig, bay) = Mining(bayWidth: 8, bayHeight: 8, damage: damage, fuse: fuse, galaxySeed: galaxySeed, rockSize: 1f, + ores: new[] { (Commodity("Rock"), 1f), (Commodity("Gold"), 1f), (Commodity("Ice"), 1f) }); + rig.Zone.Settings.AsteroidYield = new ExponentialLerp { Minimum = 6000f, Maximum = 6000f, Exponent = 1f }; + // Composition hashes the belt's record key, which differs per scene; variance 0 leaves the dice alone to vary the ore. + rig.Zone.Settings.ChunkCompositionVariance = 0f; + return (rig, bay); + } + + // Fires until `hits` shots have landed, returning each landed shot's payout (bay and floats together) as (Rock, Gold, Ice). + private static (int, int, int)[] Payouts(MiningCut4bTests.Rig rig, EquippedCargoBay bay, int hits) + { + IEnumerable<ItemInstance> Held() => bay.Cargo.Keys.Concat(rig.Zone.FloatingItems.Select(f => f.Item)); + var paid = new List<(int, int, int)>(); + var before = (0, 0, 0); + for (var shot = 0; shot < 100 && paid.Count < hits; shot++) + { + var landed = rig.Resolved.Count(o => o.Hit); + FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); + MiningCut4bTests.Run(rig, .05f); + if (rig.Resolved.Count(o => o.Hit) == landed) continue; + Assert.True(rig.Zone.ChunkExists(rig.Rock), "the rock must outlive the shots under test"); + var held = Held().ToArray(); + var now = (Units(held, "Rock", rig.Scene), Units(held, "Gold", rig.Scene), Units(held, "Ice", rig.Scene)); + paid.Add((now.Item1 - before.Item1, now.Item2 - before.Item2, now.Item3 - before.Item3)); + before = now; + } + Assert.Equal(hits, paid.Count); + return paid.ToArray(); + } + + // Which ore lands in which slot follows each scene's catalog keys, so scenes compare by the multiset of counts. + private static int[][] Mix(IEnumerable<(int, int, int)> paid) => paid.Select(p => new[] { p.Item1, p.Item2, p.Item3 }.OrderBy(n => n).ToArray()).ToArray(); + + [Theory] + [InlineData(null, 8f)] + [InlineData(WeaponFuse.Contact, 40f)] + public void TwoShotsInOneZonePayDifferentOre(WeaponFuse? fuse, float damage) + { + var (rig, bay) = Rich(fuse, damage); + var paid = Payouts(rig, bay, 2); + Assert.All(paid, p => Assert.True(p.Item1 + p.Item2 + p.Item3 > 100, "a shot pays hundreds of units")); + Assert.NotEqual(paid[0], paid[1]); + } + + [Theory] + [InlineData(null, 8f)] + [InlineData(WeaponFuse.Contact, 40f)] + public void ADifferentRunSeedPaysDifferentOreForTheSameShot(WeaponFuse? fuse, float damage) + { + var (a, bayA) = Rich(fuse, damage, galaxySeed: 7); + var (b, bayB) = Rich(fuse, damage, galaxySeed: 8); + Assert.NotEqual(a.Zone.DropSeed, b.Zone.DropSeed); + Assert.Equal(a.Zone.CombatSeed, b.Zone.CombatSeed); + Assert.NotEqual(Mix(Payouts(a, bayA, 1)), Mix(Payouts(b, bayB, 1))); + // The same seed repeats it. + var (c, bayC) = Rich(fuse, damage, galaxySeed: 7); + var (d, bayD) = Rich(fuse, damage, galaxySeed: 7); + Assert.Equal(Mix(Payouts(c, bayC, 1)), Mix(Payouts(d, bayD, 1))); + } } diff --git a/tests/Aetheria.Shared.Tests/StationServicesTests.cs b/tests/Aetheria.Shared.Tests/StationServicesTests.cs index 173f00069..824ef7158 100644 --- a/tests/Aetheria.Shared.Tests/StationServicesTests.cs +++ b/tests/Aetheria.Shared.Tests/StationServicesTests.cs @@ -192,6 +192,29 @@ public sealed class StationServicesTests : IDisposable Assert.Empty(station.CargoBays[0].Cargo.Keys.OfType<SimpleCommodity>()); } + // A commodity the seller does not hold sells for nothing: not one never stored, and not a stale copy of a stack the sale + // already took. The held stack is untouched, and no credit is paid. + [Fact] + public void TrySell_commodity_not_in_the_hold_pays_nothing() + { + var from = Ship().CargoBays.Single(); + var held = Ore(10); + Assert.True(from.TryStore(held)); + var station = Station(); + var credits = 500; + + Assert.False(StationServices.TrySell(from, station, Ore(10), ref credits)); + Assert.Equal(500, credits); + Assert.Empty(station.CargoBays.Single().Cargo.Keys.OfType<SimpleCommodity>()); + Assert.Equal(10, Assert.Single(from.Cargo.Keys.OfType<SimpleCommodity>()).Quantity); + + Assert.True(StationServices.TrySell(from, station, held, ref credits)); + var paid = credits; + Assert.False(StationServices.TrySell(from, station, held, ref credits)); + Assert.Equal(paid, credits); + Assert.Equal(10, station.CargoBays.Single().Cargo.Keys.OfType<SimpleCommodity>().Sum(c => c.Quantity)); + } + [Fact] public void Repair_restores_and_charges() { From 00a036427df6ed08c7578567713e59fbd57adff5 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 03:00:44 +0000 Subject: [PATCH 071/190] Lot moves to ItemInstance at key 11; stacks merge, split, restore and root by lot Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/Entity.cs | 6 +++--- Assets/Scripts/ServerShared/EntitySerializer.cs | 6 +++--- Assets/Scripts/ServerShared/ItemInstance.cs | 9 ++++++--- Assets/Scripts/ServerShared/ItemManager.cs | 5 +++-- Assets/Scripts/ServerShared/SavedGame.cs | 2 +- 5 files changed, 16 insertions(+), 12 deletions(-) diff --git a/Assets/Scripts/ServerShared/Entity.cs b/Assets/Scripts/ServerShared/Entity.cs index 43d9729d9..b520db17d 100644 --- a/Assets/Scripts/ServerShared/Entity.cs +++ b/Assets/Scripts/ServerShared/Entity.cs @@ -2465,7 +2465,7 @@ public class EquippedCargoBay : EquippedItem // For simple commodities, search for existing item stacks to add to foreach (var cargoItem in Cargo.Keys) { - if (!item.Data.Key.Equals(cargoItem.Data.Key)) continue; + if (!item.Data.Key.Equals(cargoItem.Data.Key) || item.Lot != cargoItem.Lot) continue; var cargoCommodity = (SimpleCommodity) cargoItem; if (cargoCommodity.Quantity >= itemData.MaxStack) continue; @@ -2563,7 +2563,7 @@ public class EquippedCargoBay : EquippedItem ItemsOfType[item.Data.Key] = new List<ItemInstance>(); ItemsOfType[item.Data.Key].Add(item); } - else if (Occupancy[cargoCoord.x, cargoCoord.y] is SimpleCommodity cargoCommodity && cargoCommodity.Data.Key.Equals(item.Data.Key)) + else if (Occupancy[cargoCoord.x, cargoCoord.y] is SimpleCommodity cargoCommodity && cargoCommodity.Data.Key.Equals(item.Data.Key) && cargoCommodity.Lot == item.Lot) { if (cargoCommodity.Quantity + item.Quantity <= itemData.MaxStack) { @@ -2643,7 +2643,7 @@ public class EquippedCargoBay : EquippedItem item.Quantity -= quantity; Mass -= itemData.Mass * quantity; ThermalMass -= itemData.Mass * itemData.SpecificHeat * quantity; - return new SimpleCommodity{Data = item.Data, Quantity = quantity, Rotation = item.Rotation}; + return new SimpleCommodity{Data = item.Data, Lot = item.Lot, Quantity = quantity, Rotation = item.Rotation}; } public void Remove(CraftedItemInstance item) diff --git a/Assets/Scripts/ServerShared/EntitySerializer.cs b/Assets/Scripts/ServerShared/EntitySerializer.cs index 9aefe5a19..73656b87e 100644 --- a/Assets/Scripts/ServerShared/EntitySerializer.cs +++ b/Assets/Scripts/ServerShared/EntitySerializer.cs @@ -60,8 +60,8 @@ public static class EntitySerializer && itemManager.GetData(commodity).MaxStack >= 1) { var maxStack = itemManager.GetData(commodity).MaxStack; - var first = new SimpleCommodity { Data = commodity.Data, Rotation = commodity.Rotation, Quantity = maxStack }; - var rest = new SimpleCommodity { Data = commodity.Data, Rotation = commodity.Rotation, Quantity = commodity.Quantity - maxStack }; + var first = new SimpleCommodity { Data = commodity.Data, Lot = commodity.Lot, Rotation = commodity.Rotation, Quantity = maxStack }; + var rest = new SimpleCommodity { Data = commodity.Data, Lot = commodity.Lot, Rotation = commodity.Rotation, Quantity = commodity.Quantity - maxStack }; if (!bay.TryStore(first, position)) rest.Quantity += first.Quantity; spill.Add((bay, rest)); return; @@ -82,7 +82,7 @@ public static class EntitySerializer var remaining = rest.Quantity; while (remaining > 0) { - var chunk = new SimpleCommodity { Data = rest.Data, Rotation = rest.Rotation, Quantity = Math.Min(remaining, maxStack) }; + var chunk = new SimpleCommodity { Data = rest.Data, Lot = rest.Lot, Rotation = rest.Rotation, Quantity = Math.Min(remaining, maxStack) }; var placed = home.TryStore(chunk) || bays.Where(b => b != home).Any(b => b.TryStore(chunk)); // A refused store may still have topped up a stack; what is left in the chunk found no room. remaining -= Math.Min(remaining, maxStack) - (placed ? 0 : chunk.Quantity); diff --git a/Assets/Scripts/ServerShared/ItemInstance.cs b/Assets/Scripts/ServerShared/ItemInstance.cs index 80a891666..a16553b9f 100644 --- a/Assets/Scripts/ServerShared/ItemInstance.cs +++ b/Assets/Scripts/ServerShared/ItemInstance.cs @@ -24,6 +24,11 @@ public abstract class ItemInstance { [JsonProperty("data"), Key(0)] public CultRecordRef<ItemData> Data; [JsonProperty("rotation"), Key(1)] public ItemRotation Rotation; + + // The lot this unit was minted or mined from: crafted units' design, provenance, workmanship and role fills all + // live there; a mined SimpleCommodity names its Extracted lot (zone, belt, ore). Lot 0 is no lot: bought, staged + // and loadout commodities, and every save from before the field reached SimpleCommodity. + [JsonProperty("lot"), Key(11)] public int Lot; } [Union(0, typeof(CompoundCommodity)), @@ -33,9 +38,7 @@ public abstract class ItemInstance public abstract class CraftedItemInstance : ItemInstance { // Keys 2 (Quality), 9 (Ingredients) and 10 (Product) belonged to fields moved to Lot; do not reuse them. - - // The lot this unit was minted from: its design, provenance, workmanship and role fills all live there. - [JsonProperty("lot"), Key(11)] public int Lot; + // Key 11 (Lot) lives on ItemInstance. } [MessagePackObject, JsonObject(MemberSerialization.OptIn)] diff --git a/Assets/Scripts/ServerShared/ItemManager.cs b/Assets/Scripts/ServerShared/ItemManager.cs index 090fe1545..774abbe83 100644 --- a/Assets/Scripts/ServerShared/ItemManager.cs +++ b/Assets/Scripts/ServerShared/ItemManager.cs @@ -72,8 +72,9 @@ public class ItemManager }; } - // The one resolution path from a crafted instance to the lot it was minted from. - public Lot GetLot(CraftedItemInstance item) => Lots[item.Lot]; + // The one resolution path from an instance to the lot it was minted or mined from. Lot 0 throws: a bought or + // staged commodity has no lot, and the caller asks Lot != 0 first. + public Lot GetLot(ItemInstance item) => Lots[item.Lot]; // Returns stat when not equipped: a null-entity context with no heat, no power and no modifiers. It says so // in its own name (UnequippedStatContext) rather than being a third quiet dialect of the arithmetic. diff --git a/Assets/Scripts/ServerShared/SavedGame.cs b/Assets/Scripts/ServerShared/SavedGame.cs index 5f42de446..21f3f3b71 100644 --- a/Assets/Scripts/ServerShared/SavedGame.cs +++ b/Assets/Scripts/ServerShared/SavedGame.cs @@ -225,7 +225,7 @@ public static class RunSave var roots = zones .SelectMany(zone => zone.Contents?.Entities ?? new List<EntityPack>()) .SelectMany(EntitySerializer.Items) - .OfType<CraftedItemInstance>() + .Where(item => item.Lot != 0) .Select(item => item.Lot); cache.Commit(batch => { From df67c875e349a85a274018ca80950d5636eacf2e Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 03:03:25 +0000 Subject: [PATCH 072/190] FireControl.Extract stamps every mined stack with the Extracted lot of its zone, belt and ore Extracted gains Body at key 2. ItemManager.ExtractedLot finds or mints the lot; its (zone, belt, ore) index is derived from the ledger at construction and never saved. SavedGame roots skip null items and Lot 0. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/FireControl.cs | 7 ++++-- Assets/Scripts/ServerShared/ItemManager.cs | 26 ++++++++++++++++++++++ Assets/Scripts/ServerShared/Provenance.cs | 2 ++ Assets/Scripts/ServerShared/SavedGame.cs | 2 +- 4 files changed, 34 insertions(+), 3 deletions(-) diff --git a/Assets/Scripts/ServerShared/FireControl.cs b/Assets/Scripts/ServerShared/FireControl.cs index 3df60cf50..bb6d48d6c 100644 --- a/Assets/Scripts/ServerShared/FireControl.cs +++ b/Assets/Scripts/ServerShared/FireControl.cs @@ -1864,14 +1864,17 @@ public static class FireControl var at = zone.ChunkPose(chunk.Field, chunk.Index).xy; var velocity = zone.ChunkVelocity(chunk); + var zoneIndex = zone.Galaxy?.Zones == null ? -1 : Array.IndexOf(zone.Galaxy.Zones, zone.GalaxyZone); var present = zone.Entities.Contains(shooter); for (var i = 0; i < ores.Length; i++) { var key = ores[i].Commodity.Key; - var maxStack = Math.Max(1, ((SimpleCommodityData) catalog.Get(ores[i].Commodity)).MaxStack); + var commodity = (SimpleCommodityData) catalog.Get(ores[i].Commodity); + var maxStack = Math.Max(1, commodity.MaxStack); + var lot = counts[i] > 0 ? shooter.ItemManager.ExtractedLot(zoneIndex, chunk.Field, commodity) : 0; for (var left = counts[i]; left > 0; left -= maxStack) { - var stack = new SimpleCommodity { Data = new CultRecordRef<ItemData>(key), Quantity = Math.Min(left, maxStack) }; + var stack = new SimpleCommodity { Data = new CultRecordRef<ItemData>(key), Lot = lot, Quantity = Math.Min(left, maxStack) }; // A partial store leaves the remainder in Quantity and returns false, so the next bay is offered the rest. var stored = false; if (present) foreach (var bay in shooter.CargoBays) if (stored = bay.TryStore(stack)) break; diff --git a/Assets/Scripts/ServerShared/ItemManager.cs b/Assets/Scripts/ServerShared/ItemManager.cs index 774abbe83..c91568efd 100644 --- a/Assets/Scripts/ServerShared/ItemManager.cs +++ b/Assets/Scripts/ServerShared/ItemManager.cs @@ -25,6 +25,11 @@ public class ItemManager public CultCache ItemData { get; } public ProvenanceLedger Lots { get; } + + // (zone index, belt, commodity) -> the Extracted lot minted for it. Derived from Lots at construction and on mint, + // never persisted: a reload rebuilds it from the ledger, so the same source finds the same lot. + private readonly Dictionary<(int, CultRecordKey, CultRecordKey), int> _extracted = + new Dictionary<(int, CultRecordKey, CultRecordKey), int>(); public GameplaySettings GameplaySettings { get; } public ItemManager(uint seed, CultCache itemData, ProvenanceLedger lots, GameplaySettings settings, Action<string> logger) @@ -33,6 +38,9 @@ public class ItemManager Random = new Random(seed); ItemData = itemData; Lots = lots; + foreach (var (id, lot) in lots.Lots) + if (lot.Origin is Extracted extracted) + _extracted[(extracted.Zone, extracted.Body.Key, extracted.Commodity.Key)] = id; GameplaySettings = settings; _logger = logger; } @@ -181,6 +189,24 @@ public class ItemManager return Lots.Add(lot); } + // Mining Cut 5b: the lot of every unit mined from one commodity in one belt of one zone, found or minted. Unbranded + // (Product unset) and unworked (Quality 1, no roles). FireControl.Extract is the only caller. + public int ExtractedLot(int zone, CultRecordKey belt, SimpleCommodityData commodity) + { + var key = (zone, belt, ItemData.RefOf<ItemData>(commodity).Key); + if (_extracted.TryGetValue(key, out var found)) return found; + var id = Lots.Add(new Lot + { + Design = ItemData.RefOf<ItemData>(commodity), + Origin = new Extracted + { + Zone = zone, Body = new CultRecordRef<BodyData>(belt), Commodity = ItemData.RefOf(commodity) + }, + Quality = 1 + }); + return _extracted[key] = id; + } + // The one writer of a crafted instance's Data: copied from the lot's design, never independently set. public CraftedItemInstance CreateInstance(int lot) { diff --git a/Assets/Scripts/ServerShared/Provenance.cs b/Assets/Scripts/ServerShared/Provenance.cs index 25a4a6175..71c260496 100644 --- a/Assets/Scripts/ServerShared/Provenance.cs +++ b/Assets/Scripts/ServerShared/Provenance.cs @@ -137,6 +137,8 @@ public class Produced : Provenance [MessagePackObject] public class Extracted : Provenance { + // Zone is the zone's index in galaxy.Zones (SavedGame's convention), -1 with no galaxy; Body is the belt. [Key(0)] public int Zone; [Key(1)] public CultRecordRef<SimpleCommodityData> Commodity; + [Key(2)] public CultRecordRef<BodyData> Body; } diff --git a/Assets/Scripts/ServerShared/SavedGame.cs b/Assets/Scripts/ServerShared/SavedGame.cs index 21f3f3b71..7c7952494 100644 --- a/Assets/Scripts/ServerShared/SavedGame.cs +++ b/Assets/Scripts/ServerShared/SavedGame.cs @@ -225,7 +225,7 @@ public static class RunSave var roots = zones .SelectMany(zone => zone.Contents?.Entities ?? new List<EntityPack>()) .SelectMany(EntitySerializer.Items) - .Where(item => item.Lot != 0) + .Where(item => item != null && item.Lot != 0) .Select(item => item.Lot); cache.Commit(batch => { From 7d9c4d4844f7adee237176fadd34360c4b166ca4 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 03:03:25 +0000 Subject: [PATCH 073/190] Tests: mined lots, stack merge and split by lot, save GC roots, rebuilt index, old saves read Lot 0 Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../Aetheria.Shared.Tests/MiningCut5aTests.cs | 10 +- .../Aetheria.Shared.Tests/MiningCut5bTests.cs | 308 ++++++++++++++++++ 2 files changed, 313 insertions(+), 5 deletions(-) create mode 100644 tests/Aetheria.Shared.Tests/MiningCut5bTests.cs diff --git a/tests/Aetheria.Shared.Tests/MiningCut5aTests.cs b/tests/Aetheria.Shared.Tests/MiningCut5aTests.cs index d71607031..04f02164d 100644 --- a/tests/Aetheria.Shared.Tests/MiningCut5aTests.cs +++ b/tests/Aetheria.Shared.Tests/MiningCut5aTests.cs @@ -23,11 +23,11 @@ public sealed class MiningCut5aTests : IDisposable _scenes.Dispose(); } - private static SimpleCommodityData Commodity(string name, int maxStack = 100) => + internal static SimpleCommodityData Commodity(string name, int maxStack = 100) => new SimpleCommodityData { Name = name, Shape = new Shape(), Price = 5, MaxStack = maxStack }; // Registers the ores and the kind's yields in the scene's catalog (the kind refs need the stored commodities). - private static void Stock(MiningCut3Tests.Scene scene, FieldKindData kind, params (SimpleCommodityData Ore, float Abundance)[] yields) + internal static void Stock(MiningCut3Tests.Scene scene, FieldKindData kind, params (SimpleCommodityData Ore, float Abundance)[] yields) { kind.Yields.Clear(); foreach (var (ore, abundance) in yields) @@ -38,7 +38,7 @@ public sealed class MiningCut5aTests : IDisposable scene.Cache.Upsert(kind); } - private EquippedCargoBay Bay(MiningCut3Tests.Scene scene, Ship ship, int width, int height, string name) + internal static EquippedCargoBay Bay(MiningCut3Tests.Scene scene, Ship ship, int width, int height, string name) { var shape = new Shape(width, height); foreach (var cell in shape.AllCoordinates) shape[cell] = true; @@ -49,10 +49,10 @@ public sealed class MiningCut5aTests : IDisposable return bay; } - private static int Units(IEnumerable<ItemInstance> items, string ore, MiningCut3Tests.Scene scene) => + internal static int Units(IEnumerable<ItemInstance> items, string ore, MiningCut3Tests.Scene scene) => items.OfType<SimpleCommodity>().Where(c => scene.Items.GetData(c).Name == ore).Sum(c => c.Quantity); - private static int Units(EquippedCargoBay bay, string ore, MiningCut3Tests.Scene scene) => Units(bay.Cargo.Keys, ore, scene); + internal static int Units(EquippedCargoBay bay, string ore, MiningCut3Tests.Scene scene) => Units(bay.Cargo.Keys, ore, scene); // A rig whose rock (size .5: 4 units, whole) yields `ores`, shooter holding one bay. private (MiningCut4bTests.Rig Rig, EquippedCargoBay Bay) Mining(int bayWidth = 4, int bayHeight = 4, float damage = 1000f, diff --git a/tests/Aetheria.Shared.Tests/MiningCut5bTests.cs b/tests/Aetheria.Shared.Tests/MiningCut5bTests.cs new file mode 100644 index 000000000..45f52c144 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/MiningCut5bTests.cs @@ -0,0 +1,308 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using CultMath; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; +using Xunit; + +// Mining Cut 5b (docs/mining-cut-refresh.md, Cut 5, Q6b = A): a mined unit carries an Extracted lot naming the zone, the belt +// and the ore; stacks merge, split, restore and save by lot. Fixtures are Cut 3's belt scene and Cut 5a's bay and stock helpers. +public sealed class MiningCut5bTests : IDisposable +{ + private readonly MiningCut3Tests _scenes = new MiningCut3Tests(); + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-mining5b-" + Guid.NewGuid().ToString("N")); + private uint _ordinal; + + public MiningCut5bTests() => Directory.CreateDirectory(_root); + + public void Dispose() + { + _scenes.Dispose(); + Directory.Delete(_root, true); + } + + private sealed class Field + { + public MiningCut3Tests.Scene Scene; + public Galaxy Galaxy; + public SimpleCommodityData Ore; + } + + // Two belts of rocks (size .5: 4 whole units a rock), one ore, in a galaxy of three zones. + private Field Build() + { + var ore = MiningCut5aTests.Commodity("Rock"); + var kind = MiningCut3Tests.Kind("Asteroid", 4f); + var scene = _scenes.BuildScene(new[] { kind }, + MiningCut3Tests.Belt(kind, MiningCut3Tests.Rock(150f, 0f), MiningCut3Tests.Rock(155f, .3f)), + MiningCut3Tests.Belt(kind, MiningCut3Tests.Rock(160f, .6f))); + MiningCut5aTests.Stock(scene, kind, (ore, 1f)); + var game = new SavedGame + { + Seed = 5, Factions = new CultRecordRef<Faction>[0], Relationships = new FactionRelationship[0], + HomeZones = new Dictionary<int, int>(), BossZones = new Dictionary<int, int>(), DiscoveredZones = new[] { 0 }, + ActionBarBindings = new SavedActionBarBinding[0], Entrance = 0, Exit = -1 + }; + var zones = Enumerable.Range(0, 3) + .Select(i => new SavedZone { Name = $"Z{i}", AdjacentZones = new int[0], Factions = new int[0], Owner = -1 }).ToArray(); + RunSave.Commit(scene.Cache, game, zones, new ProvenanceLedger()); + return new Field { Scene = scene, Galaxy = new Galaxy(scene.Cache, scene.Cache.GetGlobal<SavedGame>(), _ => { }), Ore = ore }; + } + + private static Zone ZoneOf(Field f, int index) + { + var settings = MiningCut3Tests.PlanetSettings(); + settings.AsteroidYield = new ExponentialLerp { Minimum = 4f, Maximum = 4f, Exponent = 1f }; + return index < 0 + ? new Zone(f.Scene.Items, settings, f.Scene.Pack, new GalaxyZone { Name = "Lone", Owner = null }, null) + : new Zone(f.Scene.Items, settings, f.Scene.Pack, f.Galaxy.Zones[index], f.Galaxy); + } + + private Ship Shooter(Field f, Zone zone) + { + var ship = new Ship(f.Scene.Items, zone, MiningCut3Tests.Mint(f.Scene, f.Scene.Hull), new EntitySettings()); + zone.Admit(ship, piloted: false); + return ship; + } + + private void Mine(Field f, Zone zone, Ship ship, int belt, int rock) + { + var chunk = new ChunkId(f.Scene.Belts[belt], rock); + FireControl.Extract(zone, chunk, zone.Wear(chunk, 1e6f), ship, SimulationDice.For(zone.DropSeed, SimulationDice.OreStream, ++_ordinal)); + } + + private static SimpleCommodity[] Stacks(EquippedCargoBay bay) => bay.Cargo.Keys.OfType<SimpleCommodity>().OrderBy(s => s.Lot).ToArray(); + + [Fact] + public void MinedUnitsCarryAnExtractedLotNamingZoneBeltAndOre() + { + var f = Build(); + var zone = ZoneOf(f, 2); + var ship = Shooter(f, zone); + var bay = MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); + Mine(f, zone, ship, 1, 0); + + var stack = Assert.Single(Stacks(bay)); + Assert.Equal(4, stack.Quantity); + Assert.NotEqual(0, stack.Lot); + var lot = f.Scene.Items.GetLot(stack); + var origin = Assert.IsType<Extracted>(lot.Origin); + Assert.Equal(2, origin.Zone); + Assert.Equal(f.Scene.Belts[1], origin.Body.Key); + Assert.Equal(stack.Data.Key, origin.Commodity.Key); + Assert.Equal(stack.Data.Key, lot.Design.Key); + Assert.Equal(1f, lot.Quality); + Assert.Equal(default, lot.Product); + } + + [Fact] + public void AZoneWithNoGalaxyIsMinus1() + { + var f = Build(); + var zone = ZoneOf(f, -1); + var ship = Shooter(f, zone); + var bay = MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); + Mine(f, zone, ship, 0, 0); + Assert.Equal(-1, Assert.IsType<Extracted>(f.Scene.Items.GetLot(Assert.Single(Stacks(bay))).Origin).Zone); + } + + [Fact] + public void UnitsFromOneSourceStack_UnitsFromTwoSourcesDoNot() + { + var f = Build(); + var zone = ZoneOf(f, 1); + var ship = Shooter(f, zone); + var bay = MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); + Mine(f, zone, ship, 0, 0); + Mine(f, zone, ship, 0, 1); + var one = Assert.Single(Stacks(bay)); + Assert.Equal(8, one.Quantity); + + Mine(f, zone, ship, 1, 0); + var stacks = Stacks(bay); + Assert.Equal(new[] { 8, 4 }, stacks.Select(s => s.Quantity)); + Assert.NotEqual(stacks[0].Lot, stacks[1].Lot); + Assert.Equal(2, f.Scene.Items.Lots.Lots.Values.Count(l => l.Origin is Extracted)); + // Two lots of one ore still total one commodity for the market and the hold. + Assert.Equal(12, MiningCut5aTests.Units(bay, "Rock", f.Scene)); + } + + // TryFindSpace and the at-coordinate store both look for a stack to top up: a stack of another lot is not one. + [Fact] + public void ASearchAndAStoreIgnoreAStackOfAnotherLot() + { + var f = Build(); + var zone = ZoneOf(f, 0); + var ship = Shooter(f, zone); + var bay = MiningCut5aTests.Bay(f.Scene, ship, 1, 1, "Hold"); + var key = new CultRecordRef<ItemData>(f.Scene.Cache.RefOf(f.Ore).Key); + SimpleCommodity Units(int lot, int quantity) => new SimpleCommodity { Data = key, Lot = lot, Quantity = quantity }; + + Assert.True(bay.TryStore(Units(7, 90))); + Assert.False(bay.TryFindSpace(Units(8, 5), out _)); + Assert.True(bay.TryFindSpace(Units(7, 5), out _)); + var other = Units(8, 5); + Assert.False(bay.TryStore(other, new int2(0, 0))); + Assert.Equal(90, Assert.Single(bay.Cargo.Keys.OfType<SimpleCommodity>()).Quantity); + Assert.Equal(5, other.Quantity); + Assert.True(bay.TryStore(Units(7, 5), new int2(0, 0))); + Assert.Equal(95, Assert.Single(bay.Cargo.Keys.OfType<SimpleCommodity>()).Quantity); + } + + [Fact] + public void ASplitStackKeepsItsLot() + { + var f = Build(); + var zone = ZoneOf(f, 0); + var ship = Shooter(f, zone); + var bay = MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); + Mine(f, zone, ship, 0, 0); + var stack = Assert.Single(Stacks(bay)); + + var part = bay.Remove(stack, 3); + Assert.Equal(3, part.Quantity); + Assert.Equal(stack.Lot, part.Lot); + Assert.NotEqual(0, part.Lot); + Assert.Equal(1, stack.Quantity); + } + + // A saved stack above its design's MaxStack comes back as several stacks, every one of the saved lot. + [Fact] + public void ARestoredOversizeStackKeepsItsLot() + { + var f = Build(); + var zone = ZoneOf(f, 0); + var ship = Shooter(f, zone); + var bay = MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); + for (var rock = 0; rock < 2; rock++) Mine(f, zone, ship, 0, rock); + var lot = Assert.Single(Stacks(bay)).Lot; + + var pack = EntitySerializer.Pack(ship); + f.Ore.MaxStack = 3; + var restored = EntitySerializer.Unpack(f.Scene.Items, zone, pack); + + var stacks = restored.CargoBays.SelectMany(Stacks).ToArray(); + Assert.Equal(8, stacks.Sum(s => s.Quantity)); + Assert.True(stacks.Length >= 3); + Assert.All(stacks, s => Assert.Equal(lot, s.Lot)); + } + + private CultCache Open() => AetheriaStores.Open(Path.Combine(_root, "Aetheria.cc"), Path.Combine(_root, "run.cc"), Path.Combine(_root, "player.cc")); + + private static ShipPack PackHolding(params ItemInstance[] stacks) => new ShipPack + { + Name = "ship", Hull = new EquippableItem(), + Equipment = Array.Empty<(int2, EquippableItem)>(), CargoBays = Array.Empty<(int2, EquippableItem)>(), + DockingBays = Array.Empty<(int2, EquippableItem)>(), + CargoContents = new[] { stacks.Select((s, i) => (new int2(i, 0), s)).ToArray() }, + DockingBayContents = Array.Empty<(int2, ItemInstance)[]>(), Children = Array.Empty<EntityPack>(), + Temperature = new float[0, 0], Armor = new float[0, 0], Conductivity = new bool2[0, 0], + DockingBayAssignments = Array.Empty<int>(), Settings = new EntitySettings(), WeaponGroups = Array.Empty<int[]>() + }; + + // The ledger as the run file holds it after a save of ships holding `held`. + private ProvenanceLedger SaveAndReload(ProvenanceLedger live, params ItemInstance[] held) + { + using (var cache = AetheriaStores.Open(Path.Combine(_root, "Aetheria.cc"), catalogWritable: true)) + { + cache.Commit(batch => batch.Upsert(new VerseGrammar { Revision = 1 })); + } + using (var cache = Open()) + { + var game = new SavedGame + { + Factions = new CultRecordRef<Faction>[0], Relationships = new FactionRelationship[0], + HomeZones = new Dictionary<int, int>(), BossZones = new Dictionary<int, int>(), DiscoveredZones = new[] { 0 }, + ActionBarBindings = new SavedActionBarBinding[0], Exit = -1 + }; + var zone = new SavedZone + { + Name = "Zone 0", AdjacentZones = Array.Empty<int>(), Factions = Array.Empty<int>(), Owner = -1, + Contents = new ZonePack { Entities = new List<EntityPack> { PackHolding(held) } } + }; + RunSave.Commit(cache, game, new[] { zone }, live); + } + using (var cache = Open()) return RunSave.Lots(cache); + } + + [Fact] + public void AMinedStackSurvivesSaveGc() + { + var f = Build(); + var zone = ZoneOf(f, 1); + var ship = Shooter(f, zone); + var bay = MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); + Mine(f, zone, ship, 0, 0); + Mine(f, zone, ship, 1, 0); + var held = Stacks(bay); + Assert.Equal(2, held.Length); + // A third lot nobody holds: floated and gone, or never collected. + var orphan = f.Scene.Items.ExtractedLot(1, new CultRecordKey("elsewhere"), f.Ore); + + var saved = SaveAndReload(f.Scene.Items.Lots, held); + + Assert.Equal(held.Select(s => s.Lot).OrderBy(i => i), saved.Lots.Keys.OrderBy(i => i)); + Assert.DoesNotContain(orphan, saved.Lots.Keys); + var origin = Assert.IsType<Extracted>(saved[held[0].Lot].Origin); + Assert.Equal(1, origin.Zone); + Assert.Equal(f.Scene.Belts[0], origin.Body.Key); + } + + [Fact] + public void TheLotIndexIsRebuiltOnContinue() + { + var f = Build(); + var zone = ZoneOf(f, 1); + var ship = Shooter(f, zone); + var bay = MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); + Mine(f, zone, ship, 0, 0); + var held = Assert.Single(Stacks(bay)); + + var saved = SaveAndReload(f.Scene.Items.Lots, held); + var continued = new ItemManager(1u, f.Scene.Cache, saved, RunSaveTests.TestSettings(), _ => { }); + + Assert.Equal(held.Lot, continued.ExtractedLot(1, f.Scene.Belts[0], f.Ore)); + Assert.Single(saved.Lots); + var next = continued.ExtractedLot(1, f.Scene.Belts[1], f.Ore); + Assert.NotEqual(held.Lot, next); + Assert.Equal(2, saved.Lots.Count); + // Zone and ore tell lots apart as the belt does. + Assert.NotEqual(next, continued.ExtractedLot(2, f.Scene.Belts[1], f.Ore)); + } + + // A save from before the field reached SimpleCommodity: Data, Rotation, Quantity and nothing else. + [Fact] + public void OldSavesReadLotZero() + { + var f = Build(); + var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(ItemInstance).Assembly); + var key = new CultRecordRef<ItemData>(f.Scene.Cache.RefOf(f.Ore).Key); + var buffer = new System.Buffers.ArrayBufferWriter<byte>(); + var writer = new MessagePackWriter(buffer); + writer.WriteArrayHeader(2); + writer.Write(0); // Union(0, SimpleCommodity) + writer.WriteArrayHeader(3); + MessagePackSerializer.Serialize(ref writer, key, options); + MessagePackSerializer.Serialize(ref writer, ItemRotation.None, options); + writer.Write(7); + writer.Flush(); + + var old = Assert.IsType<SimpleCommodity>(MessagePackSerializer.Deserialize<ItemInstance>(buffer.WrittenMemory, options)); + Assert.Equal(7, old.Quantity); + Assert.Equal(0, old.Lot); + Assert.Equal(key.Key, old.Data.Key); + + // A lot rides the wire; a Lot-0 stack is no root, so the old stack saves no lot. + var back = MessagePackSerializer.Deserialize<ItemInstance>(MessagePackSerializer.Serialize<ItemInstance>( + new SimpleCommodity { Data = key, Quantity = 2, Lot = 9 }, options), options); + Assert.Equal(9, back.Lot); + Assert.Empty(SaveAndReload(new ProvenanceLedger(), old).Lots); + } +} From d3572c01906653d231310ab7fa625db63a106e9c Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 03:55:32 +0000 Subject: [PATCH 074/190] Save roots: every crafted item roots at Lot 0 too; pin zero-draw mint guard and both root sides Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/SavedGame.cs | 4 +- .../Aetheria.Shared.Tests/MiningCut5bTests.cs | 52 ++++++++++++++++--- 2 files changed, 48 insertions(+), 8 deletions(-) diff --git a/Assets/Scripts/ServerShared/SavedGame.cs b/Assets/Scripts/ServerShared/SavedGame.cs index 7c7952494..cf225ab8b 100644 --- a/Assets/Scripts/ServerShared/SavedGame.cs +++ b/Assets/Scripts/ServerShared/SavedGame.cs @@ -222,10 +222,12 @@ public static class RunSave .Select(stored => stored.Key) .ToArray(); game.Zones = keys.Select(key => new CultRecordRef<SavedZone>(key)).ToArray(); + // Every crafted item roots, Lot 0 included: a crafted item with no lot is corruption and Reachable throws on it. + // A SimpleCommodity roots only when it names a lot; Lot 0 is bought, staged or loadout stock. var roots = zones .SelectMany(zone => zone.Contents?.Entities ?? new List<EntityPack>()) .SelectMany(EntitySerializer.Items) - .Where(item => item != null && item.Lot != 0) + .Where(item => item != null && (item is CraftedItemInstance || item.Lot != 0)) .Select(item => item.Lot); cache.Commit(batch => { diff --git a/tests/Aetheria.Shared.Tests/MiningCut5bTests.cs b/tests/Aetheria.Shared.Tests/MiningCut5bTests.cs index 45f52c144..9ad960a77 100644 --- a/tests/Aetheria.Shared.Tests/MiningCut5bTests.cs +++ b/tests/Aetheria.Shared.Tests/MiningCut5bTests.cs @@ -196,9 +196,9 @@ public sealed class MiningCut5bTests : IDisposable private CultCache Open() => AetheriaStores.Open(Path.Combine(_root, "Aetheria.cc"), Path.Combine(_root, "run.cc"), Path.Combine(_root, "player.cc")); - private static ShipPack PackHolding(params ItemInstance[] stacks) => new ShipPack + private static ShipPack PackHolding(int hullLot, params ItemInstance[] stacks) => new ShipPack { - Name = "ship", Hull = new EquippableItem(), + Name = "ship", Hull = new EquippableItem { Lot = hullLot }, Equipment = Array.Empty<(int2, EquippableItem)>(), CargoBays = Array.Empty<(int2, EquippableItem)>(), DockingBays = Array.Empty<(int2, EquippableItem)>(), CargoContents = new[] { stacks.Select((s, i) => (new int2(i, 0), s)).ToArray() }, @@ -207,9 +207,13 @@ public sealed class MiningCut5bTests : IDisposable DockingBayAssignments = Array.Empty<int>(), Settings = new EntitySettings(), WeaponGroups = Array.Empty<int[]>() }; + // The ship's hull is a crafted item and roots like any other, so the fixture gives it a lot of its own. + private int _hullLot; + // The ledger as the run file holds it after a save of ships holding `held`. private ProvenanceLedger SaveAndReload(ProvenanceLedger live, params ItemInstance[] held) { + _hullLot = live.Add(new Lot { Design = default, Origin = new Attributed(), Quality = 1f, Roles = new List<RoleFill>() }); using (var cache = AetheriaStores.Open(Path.Combine(_root, "Aetheria.cc"), catalogWritable: true)) { cache.Commit(batch => batch.Upsert(new VerseGrammar { Revision = 1 })); @@ -225,13 +229,46 @@ public sealed class MiningCut5bTests : IDisposable var zone = new SavedZone { Name = "Zone 0", AdjacentZones = Array.Empty<int>(), Factions = Array.Empty<int>(), Owner = -1, - Contents = new ZonePack { Entities = new List<EntityPack> { PackHolding(held) } } + Contents = new ZonePack { Entities = new List<EntityPack> { PackHolding(_hullLot, held) } } }; RunSave.Commit(cache, game, new[] { zone }, live); } using (var cache = Open()) return RunSave.Lots(cache); } + // An ore the draw never picks mints no lot: the ledger gains nothing for it, only for the ore that was drawn. + [Fact] + public void AnOreThatDrawsZeroUnitsMintsNoLot() + { + var f = Build(); + var dud = MiningCut5aTests.Commodity("Dud"); + MiningCut5aTests.Stock(f.Scene, f.Scene.Kinds[0], (f.Ore, 1f), (dud, 1e-12f)); + var zone = ZoneOf(f, 0); + var ship = Shooter(f, zone); + var bay = MiningCut5aTests.Bay(f.Scene, ship, 4, 4, "Hold"); + var before = f.Scene.Items.Lots.Lots.Count; + Mine(f, zone, ship, 0, 0); + + Assert.Equal(4, MiningCut5aTests.Units(bay, "Rock", f.Scene)); + Assert.Equal(0, MiningCut5aTests.Units(bay, "Dud", f.Scene)); + Assert.Equal(before + 1, f.Scene.Items.Lots.Lots.Count); + Assert.Equal(1, f.Scene.Items.Lots.Lots.Values.Count(l => l.Origin is Extracted)); + } + + // A crafted item with no lot is corruption and the save says so; a SimpleCommodity at Lot 0 is ordinary stock. + [Fact] + public void ACraftedItemAtLotZeroFailsTheSaveLoudly() + { + var f = Build(); + var crafted = new EquippableItem { Data = f.Scene.Cache.RefOf<ItemData>(f.Scene.Hull), Lot = 0 }; + var thrown = Assert.Throws<InvalidOperationException>(() => SaveAndReload(new ProvenanceLedger(), crafted)); + Assert.Contains("Lot 0 is not in the provenance ledger", thrown.Message); + + var stock = new SimpleCommodity { Data = new CultRecordRef<ItemData>(f.Scene.Cache.RefOf(f.Ore).Key), Quantity = 3, Lot = 0 }; + var savedStock = SaveAndReload(new ProvenanceLedger(), stock); + Assert.Equal(new[] { _hullLot }, savedStock.Lots.Keys); + } + [Fact] public void AMinedStackSurvivesSaveGc() { @@ -248,7 +285,7 @@ public sealed class MiningCut5bTests : IDisposable var saved = SaveAndReload(f.Scene.Items.Lots, held); - Assert.Equal(held.Select(s => s.Lot).OrderBy(i => i), saved.Lots.Keys.OrderBy(i => i)); + Assert.Equal(held.Select(s => s.Lot).Append(_hullLot).OrderBy(i => i), saved.Lots.Keys.OrderBy(i => i)); Assert.DoesNotContain(orphan, saved.Lots.Keys); var origin = Assert.IsType<Extracted>(saved[held[0].Lot].Origin); Assert.Equal(1, origin.Zone); @@ -269,10 +306,10 @@ public sealed class MiningCut5bTests : IDisposable var continued = new ItemManager(1u, f.Scene.Cache, saved, RunSaveTests.TestSettings(), _ => { }); Assert.Equal(held.Lot, continued.ExtractedLot(1, f.Scene.Belts[0], f.Ore)); - Assert.Single(saved.Lots); + Assert.Equal(2, saved.Lots.Count); // the mined lot and the hull var next = continued.ExtractedLot(1, f.Scene.Belts[1], f.Ore); Assert.NotEqual(held.Lot, next); - Assert.Equal(2, saved.Lots.Count); + Assert.Equal(3, saved.Lots.Count); // Zone and ore tell lots apart as the belt does. Assert.NotEqual(next, continued.ExtractedLot(2, f.Scene.Belts[1], f.Ore)); } @@ -303,6 +340,7 @@ public sealed class MiningCut5bTests : IDisposable var back = MessagePackSerializer.Deserialize<ItemInstance>(MessagePackSerializer.Serialize<ItemInstance>( new SimpleCommodity { Data = key, Quantity = 2, Lot = 9 }, options), options); Assert.Equal(9, back.Lot); - Assert.Empty(SaveAndReload(new ProvenanceLedger(), old).Lots); + var savedOld = SaveAndReload(new ProvenanceLedger(), old); + Assert.Equal(new[] { _hullLot }, savedOld.Lots.Keys); // the hull only } } From 149c513269164e6d55c6e1465b13ee1502985ce7 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 05:14:48 +0000 Subject: [PATCH 075/190] Mining 6 C1-C3: Zone.CargoGained, published by Extract and TryPickUp; HaulFeed words and hold fill Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/FireControl.cs | 12 ++++- Assets/Scripts/ServerShared/HaulFeed.cs | 47 ++++++++++++++++++++ Assets/Scripts/ServerShared/HaulFeed.cs.meta | 11 +++++ Assets/Scripts/ServerShared/Zone.cs | 7 +++ 4 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 Assets/Scripts/ServerShared/HaulFeed.cs create mode 100644 Assets/Scripts/ServerShared/HaulFeed.cs.meta diff --git a/Assets/Scripts/ServerShared/FireControl.cs b/Assets/Scripts/ServerShared/FireControl.cs index bb6d48d6c..9102b16eb 100644 --- a/Assets/Scripts/ServerShared/FireControl.cs +++ b/Assets/Scripts/ServerShared/FireControl.cs @@ -1872,14 +1872,24 @@ public static class FireControl var commodity = (SimpleCommodityData) catalog.Get(ores[i].Commodity); var maxStack = Math.Max(1, commodity.MaxStack); var lot = counts[i] > 0 ? shooter.ItemManager.ExtractedLot(zoneIndex, chunk.Field, commodity) : 0; + var adrift = 0; for (var left = counts[i]; left > 0; left -= maxStack) { var stack = new SimpleCommodity { Data = new CultRecordRef<ItemData>(key), Lot = lot, Quantity = Math.Min(left, maxStack) }; // A partial store leaves the remainder in Quantity and returns false, so the next bay is offered the rest. var stored = false; if (present) foreach (var bay in shooter.CargoBays) if (stored = bay.TryStore(stack)) break; - if (!stored) zone.Release(stack, at, velocity); + if (!stored) + { + adrift += stack.Quantity; + zone.Release(stack, at, velocity); + } } + if (counts[i] > 0) + zone.CargoGained.OnNext(new CargoGain + { + Taker = shooter, Design = new CultRecordRef<ItemData>(key), Lot = lot, Stored = counts[i] - adrift, Adrift = adrift, Kind = GainKind.Mined + }); } } diff --git a/Assets/Scripts/ServerShared/HaulFeed.cs b/Assets/Scripts/ServerShared/HaulFeed.cs new file mode 100644 index 000000000..b6f4055c8 --- /dev/null +++ b/Assets/Scripts/ServerShared/HaulFeed.cs @@ -0,0 +1,47 @@ +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; + +public enum GainKind { Mined, Collected } + +// One entry into a hold: what Extract stored (and let float) of one ore, or what a pickup collected. Stored plus Adrift is +// the units; a pickup has Adrift 0. Published on Zone.CargoGained by its two writers and read by presentations only. +public struct CargoGain +{ + public Entity Taker; + public CultRecordRef<ItemData> Design; + public int Lot; + public int Stored; + public int Adrift; + public GainKind Kind; +} + +// The words for a cargo gain, and the taker's hold fill. Nothing here is stored: the line and the fill are derived on +// every call. +public static class HaulFeed +{ + public static string Line(CargoGain gain, ItemManager items) + { + var name = items.ItemData.Get(gain.Design).Name; + var (used, total) = HoldFill(gain.Taker?.CargoBays ?? Enumerable.Empty<EquippedCargoBay>()); + var hold = $"(hold {used}/{total})"; + if (gain.Kind == GainKind.Collected) return $"Collected {gain.Stored} {name} {hold}"; + return gain.Adrift > 0 + ? $"+{gain.Stored} {name}, {gain.Adrift} adrift {hold}" + : $"+{gain.Stored} {name} {hold}"; + } + + // Occupied cells over the bays' interiors, a multi-cell item counted per cell. + public static (int used, int total) HoldFill(IEnumerable<EquippedCargoBay> bays) + { + int used = 0, total = 0; + foreach (var bay in bays) + foreach (var v in bay.Data.InteriorShape.AllCoordinates) + { + if (!bay.Data.InteriorShape[v]) continue; + total++; + if (bay.Occupancy[v.x, v.y] != null) used++; + } + return (used, total); + } +} diff --git a/Assets/Scripts/ServerShared/HaulFeed.cs.meta b/Assets/Scripts/ServerShared/HaulFeed.cs.meta new file mode 100644 index 000000000..b9b4b88b6 --- /dev/null +++ b/Assets/Scripts/ServerShared/HaulFeed.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4d3ef606ec5240119cbb3d7dd51123d9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/Zone.cs b/Assets/Scripts/ServerShared/Zone.cs index 7cbde82ef..0d729d2be 100644 --- a/Assets/Scripts/ServerShared/Zone.cs +++ b/Assets/Scripts/ServerShared/Zone.cs @@ -90,6 +90,8 @@ public class Zone public Subject<ShotOutcome> ShotResolved = new Subject<ShotOutcome>(); // Contacts.Step publishes each hull-on-hull contact it resolves; presentations are the only readers. public Subject<ContactEvent> Contacted = new Subject<ContactEvent>(); + // Published by FireControl.Extract and TryPickUp once ore or an item enters (or is offered to) a hold; read by presentations only. + public Subject<CargoGain> CargoGained = new Subject<CargoGain>(); private int _nextShotId; public int NextShotId() => ++_nextShotId; @@ -443,6 +445,11 @@ public class Zone if (floating == null || (floating.Holder != null && !ReferenceEquals(floating.Holder, taker))) return false; if (!taker.CargoBays.Any(bay => bay.TryStore(floating.Item))) return false; FloatingItems.Remove(floating); + CargoGained.OnNext(new CargoGain + { + Taker = taker, Design = floating.Item.Data, Lot = floating.Item.Lot, Kind = GainKind.Collected, + Stored = floating.Item is SimpleCommodity stack ? stack.Quantity : 1 + }); return true; } From d09850cfce116ed3c61512ab9484171293101a0d Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 05:14:48 +0000 Subject: [PATCH 076/190] Mining 6 C4: StationServices.OreValue and TrySellOre sell mined stacks through TrySell Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../Scripts/ServerShared/StationServices.cs | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/Assets/Scripts/ServerShared/StationServices.cs b/Assets/Scripts/ServerShared/StationServices.cs index be15fc74e..dace9288e 100644 --- a/Assets/Scripts/ServerShared/StationServices.cs +++ b/Assets/Scripts/ServerShared/StationServices.cs @@ -114,6 +114,30 @@ public static class StationServices return true; } + // The mined stacks of the bays: simple commodities with a lot whose origin is Extracted. Ammunition and consumables are + // simple commodities too, and a bought or staged commodity has Lot 0, which GetLot cannot resolve. + private static ItemInstance[] OreStacks(ItemManager items, IEnumerable<EquippedCargoBay> bays) => + bays.SelectMany(bay => bay.Cargo.Keys.OfType<SimpleCommodity>().Where(stack => stack.Lot != 0 && items.GetLot(stack).Origin is Extracted).Select(stack => (ItemInstance) stack)).ToArray(); + + // What the station pays for every mined stack of the bays: the sum of SellPrice over the stacks TrySellOre sells. + public static int OreValue(ItemManager items, IEnumerable<EquippedCargoBay> bays) => + (int) Math.Min(OreStacks(items, bays).Sum(stack => (long) SellPrice(items, stack)), int.MaxValue); + + // Sells every mined stack of the bays, each through TrySell, so the market's absorb rule and the price are the + // single-stack path's. Returns the units sold. + public static int TrySellOre(IEnumerable<EquippedCargoBay> bays, Entity station, ref int credits) + { + var bayList = bays.ToArray(); + var units = 0; + foreach (var stack in OreStacks(station.ItemManager, bayList)) + { + var quantity = ((SimpleCommodity) stack).Quantity; + var from = bayList.First(bay => bay.Cargo.ContainsKey(stack)); + if (TrySell(from, station, stack, ref credits)) units += quantity; + } + return units; + } + // The repair: armour and every durability go back to design and the station charges RepairCost. False, with // nothing restored, when the credits fall short. public static bool TryRepair(Entity entity, ref int credits) From 1662c53b9c0ac38f3b947a6584652d4e26f53b33 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 05:16:35 +0000 Subject: [PATCH 077/190] Mining 6 tests: CargoGained from Extract and TryPickUp, HaulFeed, TrySellOre, DemoLoop sells ore in one step Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- tests/Aetheria.Shared.Tests/DemoLoopTests.cs | 16 +- tests/Aetheria.Shared.Tests/HaulFeedTests.cs | 178 ++++++++++++++++++ .../StationServicesTests.cs | 65 +++++++ 3 files changed, 256 insertions(+), 3 deletions(-) create mode 100644 tests/Aetheria.Shared.Tests/HaulFeedTests.cs diff --git a/tests/Aetheria.Shared.Tests/DemoLoopTests.cs b/tests/Aetheria.Shared.Tests/DemoLoopTests.cs index 7e765174c..a2daf444a 100644 --- a/tests/Aetheria.Shared.Tests/DemoLoopTests.cs +++ b/tests/Aetheria.Shared.Tests/DemoLoopTests.cs @@ -3,7 +3,9 @@ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ using System.Linq; +using System.Collections.Generic; using CultMath; +using UniRx; using Xunit; // The demo loop on the shipped catalog (aetheria-release, mining 5a and the ore sheet): the player's own gun breaks a rock @@ -36,6 +38,8 @@ public sealed partial class RunStartTests arena.Update(.02f); Hold(); Assert.True(player.SetTarget(rock), "the rock is a target"); + var gains = new List<CargoGain>(); + arena.CargoGained.Subscribe(gains.Add); laser.Activate(); for (var elapsed = 0f; elapsed < 20f && arena.ChunkExists(rock); elapsed += .02f) { Hold(); arena.Update(.02f); } var info = player.ChunkInfo(rock); @@ -46,13 +50,19 @@ public sealed partial class RunStartTests .Where(h => ores.Contains(_items.GetData(h.stack).Name)).ToArray(); Assert.NotEmpty(held); Assert.Empty(arena.FloatingItems); + // The feed saw every unit that went into the hold and none float. + Assert.NotEmpty(gains); + Assert.All(gains, gain => Assert.Equal((GainKind.Mined, 0), (gain.Kind, gain.Adrift))); + Assert.Equal(held.Sum(h => h.stack.Quantity), gains.Sum(gain => gain.Stored)); var zenith = arena.Entities.Single(entity => entity.HullData.Name == "Zenith"); var credits = 0; - // Every ore stack goes: the market takes it all, whatever the full hold of Zenith has room for. - foreach (var (from, sold) in held) Assert.True(StationServices.TrySell(from, zenith, sold, ref credits), "the market takes the ore"); + // Every mined stack goes in one sale: the market takes it all, whatever the full hold of Zenith has room for. + var value = StationServices.OreValue(_items, player.CargoBays); + Assert.True(value > 0); + Assert.Equal(gains.Sum(gain => gain.Stored), StationServices.TrySellOre(player.CargoBays, zenith, ref credits)); + Assert.Equal(value, credits); Assert.DoesNotContain(player.CargoBays.SelectMany(bay => bay.Cargo.Keys.OfType<SimpleCommodity>()), c => ores.Contains(_items.GetData(c).Name)); - Assert.True(credits > 0, "the station pays for the ore"); var cell = Enumerable.Range(0, player.MaxArmor.GetLength(0)).SelectMany(x => Enumerable.Range(0, player.MaxArmor.GetLength(1)).Select(y => (x, y))) .First(c => player.MaxArmor[c.x, c.y] > 0); diff --git a/tests/Aetheria.Shared.Tests/HaulFeedTests.cs b/tests/Aetheria.Shared.Tests/HaulFeedTests.cs new file mode 100644 index 000000000..7157020b7 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/HaulFeedTests.cs @@ -0,0 +1,178 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using CultMath; +using GameCult.Caching; +using UniRx; +using Xunit; + +// Zone.CargoGained and HaulFeed (aetheria-release mining 6): Extract and TryPickUp publish what entered a hold, once; the feed +// words it and counts the hold. Fixtures are Mining Cut 5a's rig. +public sealed class HaulFeedTests : IDisposable +{ + private readonly MiningCut5aTests _five = new MiningCut5aTests(); + private readonly MiningCut4bTests _rigs = new MiningCut4bTests(); + + public void Dispose() + { + _five.Dispose(); + _rigs.Dispose(); + } + + // The 5a rig: a rock of 4 units, the shooter holding one bay of the given size; the event log records every gain. + private (MiningCut4bTests.Rig Rig, EquippedCargoBay Bay, List<CargoGain> Gains) Mining(int w, int h, params (SimpleCommodityData, float)[] ores) + { + var kind = MiningCut3Tests.Kind("Asteroid", 20f); + var rig = _rigs.Build(damage: 1000f, fuse: null, blastRadius: 0f, precision: 1000f, rockSize: .5f, velocity: 0f, kind: kind, galaxySeed: 0); + MiningCut5aTests.Stock(rig.Scene, kind, ores); + var bay = MiningCut5aTests.Bay(rig.Scene, rig.Shooter, w, h, "Hold"); + var gains = new List<CargoGain>(); + rig.Zone.CargoGained.Subscribe(gains.Add); + return (rig, bay, gains); + } + + private static CultMath.Random Dice(MiningCut4bTests.Rig rig, uint n) => SimulationDice.For(rig.Zone.DropSeed, SimulationDice.OreStream, n); + + private static void Break(MiningCut4bTests.Rig rig) + { + for (var shot = 0; shot < 40 && rig.Zone.ChunkExists(rig.Rock); shot++) + { + FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); + MiningCut4bTests.Run(rig, .05f); + } + Assert.False(rig.Zone.ChunkExists(rig.Rock)); + } + + [Fact] + public void AnExtractionPublishesWhatWasStoredAndWhatFloated() + { + // Room for everything. + var (rig, bay, gains) = Mining(4, 4, (MiningCut5aTests.Commodity("Rock"), 1f)); + Break(rig); + var gain = Assert.Single(gains); + Assert.Equal((GainKind.Mined, 4, 0), (gain.Kind, gain.Stored, gain.Adrift)); + Assert.Same(rig.Shooter, gain.Taker); + Assert.Equal(4, MiningCut5aTests.Units(bay, "Rock", rig.Scene)); + Assert.NotEqual(0, gain.Lot); + + // A full hold: everything floats. + var (full, fullBay, fullGains) = Mining(1, 1, (MiningCut5aTests.Commodity("Grit", maxStack: 1), 1f)); + Assert.True(fullBay.TryStore(new SimpleCommodity { Data = full.Scene.Cache.RefOf<ItemData>(full.Scene.Cache.GetByName<SimpleCommodityData>("Grit")), Quantity = 1 })); + Break(full); + var overflow = Assert.Single(fullGains); + Assert.Equal((0, 4), (overflow.Stored, overflow.Adrift)); + Assert.Equal(4, MiningCut5aTests.Units(full.Zone.FloatingItems.Select(f => f.Item), "Grit", full.Scene)); + + // A partial store: the hold takes two of four. + var (part, partBay, partGains) = Mining(1, 1, (MiningCut5aTests.Commodity("Grit", maxStack: 2), 1f)); + Break(part); + var split = Assert.Single(partGains); + Assert.Equal((2, 2), (split.Stored, split.Adrift)); + Assert.Equal(2, MiningCut5aTests.Units(partBay, "Grit", part.Scene)); + Assert.Equal(2, MiningCut5aTests.Units(part.Zone.FloatingItems.Select(f => f.Item), "Grit", part.Scene)); + } + + [Fact] + public void AGoneShooterPublishesEverythingAdrift() + { + var (rig, _, gains) = Mining(4, 4, (MiningCut5aTests.Commodity("Rock"), 1f)); + rig.Shooter.HeatstrokeDeath.OnNext(UniRx.Unit.Default); + var at = rig.Zone.ChunkPose(rig.Rock.Field, rig.Rock.Index).xy; + FireControl.Extract(rig.Zone, rig.Rock, rig.Zone.Wear(rig.Rock, 1e6f), rig.Shooter, Dice(rig, 1)); + var gain = Assert.Single(gains); + Assert.Equal((0, 4), (gain.Stored, gain.Adrift)); + } + + [Fact] + public void AMineAndANullShooterPublishNothing() + { + var (rig, _, gains) = Mining(4, 4, (MiningCut5aTests.Commodity("Rock"), 1f)); + FireControl.Extract(rig.Zone, rig.Rock, rig.Zone.Wear(rig.Rock, 1e6f), null, Dice(rig, 1)); + Assert.Empty(gains); + Assert.Empty(rig.Zone.FloatingItems); + } + + [Fact] + public void AMergeIntoAnExistingStackStillPublishes() + { + var (rig, bay, gains) = Mining(4, 4, (MiningCut5aTests.Commodity("Rock"), 1f)); + var chunk = rig.Rock; + FireControl.Extract(rig.Zone, chunk, rig.Zone.Wear(chunk, 1e6f), rig.Shooter, Dice(rig, 1)); + var keys = bay.Cargo.Keys.ToArray(); + // Same rock field and index, same ore, so the same lot: the second extraction merges and writes no Cargo key. + FireControl.Extract(rig.Zone, chunk, 40f, rig.Shooter, Dice(rig, 2)); + Assert.Equal(keys, bay.Cargo.Keys.ToArray()); + Assert.Equal(2, gains.Count); + Assert.Equal(gains[0].Lot, gains[1].Lot); + Assert.True(gains[1].Stored > 0); + } + + [Fact] + public void EveryOreOfOneExtractionPublishesOnce() + { + var (rig, _, gains) = Mining(8, 8, (MiningCut5aTests.Commodity("Rock"), 1f), (MiningCut5aTests.Commodity("Gold"), 1f)); + rig.Zone.Settings.AsteroidYield = new ExponentialLerp { Minimum = 400f, Maximum = 400f, Exponent = 1f }; + FireControl.Extract(rig.Zone, rig.Rock, rig.Zone.Wear(rig.Rock, 1e6f), rig.Shooter, Dice(rig, 3)); + Assert.Equal(2, gains.Count); + Assert.Equal(2, gains.Select(g => g.Lot).Distinct().Count()); + Assert.All(gains, g => Assert.True(g.Stored + g.Adrift > 0)); + } + + [Fact] + public void APickupPublishesCollected() + { + var grit = MiningCut5aTests.Commodity("Grit", maxStack: 2); + var (rig, _, gains) = Mining(1, 1, (grit, 1f)); + Break(rig); + gains.Clear(); + var floating = rig.Zone.FloatingItems.First(); + var quantity = ((SimpleCommodity) floating.Item).Quantity; + + // A taker with no room is refused and publishes nothing. + var packed = new Ship(rig.Scene.Items, rig.Zone, MiningCut3Tests.Mint(rig.Scene, rig.Scene.Hull), new EntitySettings()); + rig.Zone.Admit(packed, piloted: false); + Assert.False(rig.Zone.TryPickUp(packed, floating.Id)); + Assert.Empty(gains); + + var taker = new Ship(rig.Scene.Items, rig.Zone, MiningCut3Tests.Mint(rig.Scene, rig.Scene.Hull), new EntitySettings()); + rig.Zone.Admit(taker, piloted: false); + MiningCut5aTests.Bay(rig.Scene, taker, 4, 4, "Taker"); + Assert.True(rig.Zone.TryPickUp(taker, floating.Id)); + var gain = Assert.Single(gains); + Assert.Equal((GainKind.Collected, quantity, 0), (gain.Kind, gain.Stored, gain.Adrift)); + Assert.Same(taker, gain.Taker); + } + + [Fact] + public void TheLineNamesWhatWasTakenAndWhatFloated() + { + var (rig, bay, _) = Mining(4, 4, (MiningCut5aTests.Commodity("Rock"), 1f)); + var items = rig.Scene.Items; + var design = rig.Scene.Cache.RefOf<ItemData>(rig.Scene.Cache.GetByName<SimpleCommodityData>("Rock")); + var fill = HaulFeed.HoldFill(rig.Shooter.CargoBays); + var hold = $"hold {fill.used}/{fill.total}"; + + var clean = HaulFeed.Line(new CargoGain { Taker = rig.Shooter, Design = design, Stored = 3, Kind = GainKind.Mined }, items); + Assert.Contains("3", clean); + Assert.Contains("Rock", clean); + Assert.Contains(hold, clean); + Assert.DoesNotContain("adrift", clean); + + var spill = HaulFeed.Line(new CargoGain { Taker = rig.Shooter, Design = design, Stored = 1, Adrift = 2, Kind = GainKind.Mined }, items); + Assert.Contains("2 adrift", spill); + Assert.Contains("Rock", spill); + Assert.DoesNotContain("adrift", HaulFeed.Line(new CargoGain { Taker = rig.Shooter, Design = design, Stored = 2, Kind = GainKind.Collected }, items)); + } + + [Fact] + public void HoldFillCountsOccupiedCellsAcrossBays() + { + var (rig, bay, _) = Mining(2, 2, (MiningCut5aTests.Commodity("Rock"), 1f)); + var second = MiningCut5aTests.Bay(rig.Scene, rig.Shooter, 3, 1, "Aft"); + Assert.Equal((0, 7), HaulFeed.HoldFill(new[] { bay, second })); + var rock = rig.Scene.Cache.GetByName<SimpleCommodityData>("Rock"); + Assert.True(bay.TryStore(new SimpleCommodity { Data = rig.Scene.Cache.RefOf<ItemData>(rock), Quantity = 1 })); + Assert.True(second.TryStore(new SimpleCommodity { Data = rig.Scene.Cache.RefOf<ItemData>(rock), Quantity = 1 })); + Assert.Equal((2, 7), HaulFeed.HoldFill(new[] { bay, second })); + } +} diff --git a/tests/Aetheria.Shared.Tests/StationServicesTests.cs b/tests/Aetheria.Shared.Tests/StationServicesTests.cs index 824ef7158..b255ad71b 100644 --- a/tests/Aetheria.Shared.Tests/StationServicesTests.cs +++ b/tests/Aetheria.Shared.Tests/StationServicesTests.cs @@ -505,4 +505,69 @@ public sealed class StationServicesTests : IDisposable Assert.Equal(BuyResult.Bought, StationServices.TryBuy(_items, ore, 10, ref credits, () => true)); Assert.Equal(0, credits); } + + private SimpleCommodity Mined(int quantity) + { + var data = _cache.GetByName<SimpleCommodityData>("Ore"); + return new SimpleCommodity { Data = _cache.RefOf<ItemData>(data), Quantity = quantity, Lot = _items.ExtractedLot(0, default, data) }; + } + + [Fact] + public void SellOreSellsOnlyMinedStacks() + { + var ship = Ship(); + var bay = ship.CargoBays.Single(); + var mined = Mined(10); + var staged = Ore(5); + var gun = Mint("Gun"); + Assert.True(bay.TryStore(mined)); + Assert.True(bay.TryStore(staged)); + Assert.True(bay.TryStore(gun)); + var station = Station(); + var value = StationServices.OreValue(_items, ship.CargoBays); + Assert.Equal(StationServices.SellPrice(_items, mined), value); + Assert.True(value > 0); + + var credits = 100; + Assert.Equal(10, StationServices.TrySellOre(ship.CargoBays, station, ref credits)); + Assert.Equal(100 + value, credits); + Assert.DoesNotContain(mined, bay.Cargo.Keys); + Assert.Contains(staged, bay.Cargo.Keys); + Assert.Contains(gun, bay.Cargo.Keys); + } + + [Fact] + public void SellOreAcrossBaysAndShips() + { + var one = Ship(); + var two = Ship(); + var bays = one.CargoBays.Concat(two.CargoBays).ToArray(); + Assert.True(one.CargoBays.Single().TryStore(Mined(30))); + Assert.True(two.CargoBays.Single().TryStore(Mined(40))); + var station = Station(); + // Fill the station's bay so nothing more fits: the market absorbs the sale at full price all the same. + for (var i = 0; i < 20; i++) station.CargoBays.Single().TryStore(Ore(100)); + var value = StationServices.OreValue(_items, bays); + Assert.Equal(StationServices.SellPrice(_items, Ore(70)), value); + + var credits = 0; + Assert.Equal(70, StationServices.TrySellOre(bays, station, ref credits)); + Assert.Equal(value, credits); + Assert.All(bays, bay => Assert.Empty(bay.Cargo.Keys.OfType<SimpleCommodity>())); + } + + [Fact] + public void SellOreWithNoOreChangesNothing() + { + var ship = Ship(); + var bay = ship.CargoBays.Single(); + Assert.True(bay.TryStore(Ore(5))); + Assert.True(bay.TryStore(Mint("Gun"))); + var held = bay.Cargo.Count; + var credits = 100; + Assert.Equal(0, StationServices.OreValue(_items, ship.CargoBays)); + Assert.Equal(0, StationServices.TrySellOre(ship.CargoBays, Station(), ref credits)); + Assert.Equal(100, credits); + Assert.Equal(held, bay.Cargo.Count); + } } From c131045e7d9c9e19668d5b0a61a93a4d3e241d7d Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 05:32:18 +0000 Subject: [PATCH 078/190] Mining 6 C5: Event Log shows each take (CargoGained), Sell Ore foldout entry; dormant log activated, placeholder text removed Option event-log of question mining-6-feedback-surface (recommended; no ruling). Unity files are not compiled here. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scenes/ARPG.unity | 23 ++------------------ Assets/Scripts/EventLog.cs | 3 ++- Assets/Scripts/Gameplay/ActionGameManager.cs | 6 +++++ Assets/Scripts/UI/Menu/TradeMenu.cs | 13 +++++++++++ 4 files changed, 23 insertions(+), 22 deletions(-) diff --git a/Assets/Scenes/ARPG.unity b/Assets/Scenes/ARPG.unity index 4d5b15473..f583a38ec 100644 --- a/Assets/Scenes/ARPG.unity +++ b/Assets/Scenes/ARPG.unity @@ -21236,7 +21236,7 @@ GameObject: m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 - m_IsActive: 0 + m_IsActive: 1 --- !u!224 &1396909587 RectTransform: m_ObjectHideFlags: 0 @@ -24703,26 +24703,7 @@ MonoBehaviour: m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_text: "What the fuck did you just fucking type about me, you little bitch? I\u2019ll - have you know I graduated top of my class at MIT, and I\u2019ve been involved - in numerous secret raids with Anonymous, and I have over 300 confirmed DDoSes.\n\nI - am trained in online trolling and I\u2019m the top hacker in the entire world. - You are nothing to me but just another virus host. I will wipe you the fuck out - with precision the likes of which has never been seen before on the Internet, - mark my fucking words. You think you can get away with typing that shit to me - over the Internet? Think again, fucker.\n\nAs we chat over IRC I am tracing your - IP with my damn bare hands so you better prepare for the storm, maggot. The storm - that wipes out the pathetic little thing you call your computer. You\u2019re - fucking dead, kid. I can be anywhere, anytime, and I can hack into your files - in over seven hundred ways, and that\u2019s just with my bare hands.\n\nNot only - am I extensively trained in hacking, but I have access to the entire arsenal - of every piece of malware ever created and I will use it to its full extent to - wipe your miserable ass off the face of the world wide web, you little shit. - If only you could have known what unholy retribution your little \u201Cclever\u201D - comment was about to bring down upon you, maybe you would have held your fucking - fingers. But you couldn\u2019t, you didn\u2019t, and now you\u2019re paying the - price, you goddamn idiot. I will shit code all over you and you will drown in - it.\n\nYou\u2019re fucking dead, kiddo." + m_text: "" m_isRightToLeft: 0 m_fontAsset: {fileID: 11400000, guid: 53555f7a2d5e745428813f1b1118734f, type: 2} m_sharedMaterial: {fileID: -2804126062856497447, guid: 53555f7a2d5e745428813f1b1118734f, diff --git a/Assets/Scripts/EventLog.cs b/Assets/Scripts/EventLog.cs index 54db8dd57..967653b1d 100644 --- a/Assets/Scripts/EventLog.cs +++ b/Assets/Scripts/EventLog.cs @@ -13,7 +13,8 @@ public class EventLog : MonoBehaviour private SizedQueue<string> LogMessages; private StringBuilder LogText; - private void Start() + // Awake, not Start: a message can arrive in the frame the parent activates, before Start would run. + private void Awake() { LogMessages = new SizedQueue<string>(LineCount); LogText = new StringBuilder(); diff --git a/Assets/Scripts/Gameplay/ActionGameManager.cs b/Assets/Scripts/Gameplay/ActionGameManager.cs index a0cf3a4c1..8c2b38345 100644 --- a/Assets/Scripts/Gameplay/ActionGameManager.cs +++ b/Assets/Scripts/Gameplay/ActionGameManager.cs @@ -1092,6 +1092,12 @@ public class ActionGameManager : MonoBehaviour _shipSubscriptions.Add(CurrentEntity.Zone.ShotResolved .Where(outcome => outcome.Source == CurrentEntity) .Subscribe(outcome => _debugLastShots[outcome.Weapon] = outcome)); + _shipSubscriptions.Add(CurrentEntity.Zone.CargoGained + .Where(gain => gain.Taker == CurrentEntity) + .Subscribe(gain => + { + if (EventLog != null) EventLog.LogMessage(HaulFeed.Line(gain, ItemManager), gain.Adrift > 0 ? Color.yellow : Color.white); + })); FollowCamera.LookAt = ZoneRenderer.EntityInstances[CurrentEntity].LookAtPoint; FollowCamera.Follow = ZoneRenderer.EntityInstances[CurrentEntity].transform; diff --git a/Assets/Scripts/UI/Menu/TradeMenu.cs b/Assets/Scripts/UI/Menu/TradeMenu.cs index 13345f88a..5f4123ff2 100644 --- a/Assets/Scripts/UI/Menu/TradeMenu.cs +++ b/Assets/Scripts/UI/Menu/TradeMenu.cs @@ -312,6 +312,17 @@ public class TradeMenu : MonoBehaviour Dialog.MoveToCursor(); } + // Sells every mined stack of the player's ships' bays in one step; the station pays through TrySell, so nothing refuses. + private void SellOre() + { + StationServices.TrySellOre(PlayerBays(), GameManager.DockedEntity, ref GameManager.Credits); + UpdateCreditsLabel(); + Populate(); + } + + private IEnumerable<EquippedCargoBay> PlayerBays() => + GameManager.CurrentEntity.Parent.Children.Where(e => e is Ship {IsPlayerShip: true}).SelectMany(s => s.CargoBays); + private void Repair() { if (StationServices.TryRepair(GameManager.CurrentEntity, ref GameManager.Credits)) @@ -398,6 +409,8 @@ public class TradeMenu : MonoBehaviour }); var repairCost = StationServices.RepairCost(GameManager.ItemManager, GameManager.CurrentEntity); if (repairCost > 0) ContextMenu.AddOption($"Repair ({repairCost:N0})", Repair); + var oreValue = StationServices.OreValue(GameManager.ItemManager, PlayerBays()); + if (oreValue > 0) ContextMenu.AddOption($"Sell Ore ({oreValue:N0})", SellOre); ContextMenu.Show(); }); } From b5cfa3cbea7a07b12b45411ef8c3d88d65c9baca Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 05:58:28 +0000 Subject: [PATCH 079/190] Mining 6 fix: pickup reports the whole stack (read Quantity before TryStore); pin sell-ore Origin and Collected hold fill Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/Zone.cs | 5 ++++- tests/Aetheria.Shared.Tests/HaulFeedTests.cs | 22 ++++++++++++++++++- .../StationServicesTests.cs | 17 ++++++++++++++ 3 files changed, 42 insertions(+), 2 deletions(-) diff --git a/Assets/Scripts/ServerShared/Zone.cs b/Assets/Scripts/ServerShared/Zone.cs index 0d729d2be..74d1486c3 100644 --- a/Assets/Scripts/ServerShared/Zone.cs +++ b/Assets/Scripts/ServerShared/Zone.cs @@ -443,12 +443,15 @@ public class Zone { var floating = FloatingItems.FirstOrDefault(f => f.Id.Equals(id)); if (floating == null || (floating.Holder != null && !ReferenceEquals(floating.Holder, taker))) return false; + // The quantity is read before the store: a store that merges into a part-filled stack and spills the rest into a + // new cell rewrites the item's Quantity. + var stored = floating.Item is SimpleCommodity stack ? stack.Quantity : 1; if (!taker.CargoBays.Any(bay => bay.TryStore(floating.Item))) return false; FloatingItems.Remove(floating); CargoGained.OnNext(new CargoGain { Taker = taker, Design = floating.Item.Data, Lot = floating.Item.Lot, Kind = GainKind.Collected, - Stored = floating.Item is SimpleCommodity stack ? stack.Quantity : 1 + Stored = stored }); return true; } diff --git a/tests/Aetheria.Shared.Tests/HaulFeedTests.cs b/tests/Aetheria.Shared.Tests/HaulFeedTests.cs index 7157020b7..34eb8a3db 100644 --- a/tests/Aetheria.Shared.Tests/HaulFeedTests.cs +++ b/tests/Aetheria.Shared.Tests/HaulFeedTests.cs @@ -143,6 +143,23 @@ public sealed class HaulFeedTests : IDisposable Assert.Same(taker, gain.Taker); } + [Fact] + public void APickupThatMergesAndSpillsReportsTheWholeStack() + { + var grit = MiningCut5aTests.Commodity("Grit", maxStack: 4); + var (rig, _, gains) = Mining(1, 1, (grit, 1f)); + var taker = new Ship(rig.Scene.Items, rig.Zone, MiningCut3Tests.Mint(rig.Scene, rig.Scene.Hull), new EntitySettings()); + rig.Zone.Admit(taker, piloted: false); + var bay = MiningCut5aTests.Bay(rig.Scene, taker, 2, 1, "Taker"); + var design = rig.Scene.Cache.RefOf<ItemData>(grit); + Assert.True(bay.TryStore(new SimpleCommodity { Data = design, Lot = 7, Quantity = 3 })); + gains.Clear(); + var floating = rig.Zone.Release(new SimpleCommodity { Data = design, Lot = 7, Quantity = 4 }, new float2(0, 0), new float2(0, 0)); + Assert.True(rig.Zone.TryPickUp(taker, floating.Id)); + Assert.Equal(7, MiningCut5aTests.Units(bay, "Grit", rig.Scene)); + Assert.Equal((GainKind.Collected, 4, 0), (Assert.Single(gains).Kind, gains[0].Stored, gains[0].Adrift)); + } + [Fact] public void TheLineNamesWhatWasTakenAndWhatFloated() { @@ -161,7 +178,10 @@ public sealed class HaulFeedTests : IDisposable var spill = HaulFeed.Line(new CargoGain { Taker = rig.Shooter, Design = design, Stored = 1, Adrift = 2, Kind = GainKind.Mined }, items); Assert.Contains("2 adrift", spill); Assert.Contains("Rock", spill); - Assert.DoesNotContain("adrift", HaulFeed.Line(new CargoGain { Taker = rig.Shooter, Design = design, Stored = 2, Kind = GainKind.Collected }, items)); + var collected = HaulFeed.Line(new CargoGain { Taker = rig.Shooter, Design = design, Stored = 2, Kind = GainKind.Collected }, items); + Assert.DoesNotContain("adrift", collected); + Assert.Contains("Collected 2", collected); + Assert.Contains(hold, collected); } [Fact] diff --git a/tests/Aetheria.Shared.Tests/StationServicesTests.cs b/tests/Aetheria.Shared.Tests/StationServicesTests.cs index b255ad71b..3821a22b4 100644 --- a/tests/Aetheria.Shared.Tests/StationServicesTests.cs +++ b/tests/Aetheria.Shared.Tests/StationServicesTests.cs @@ -536,6 +536,23 @@ public sealed class StationServicesTests : IDisposable Assert.Contains(gun, bay.Cargo.Keys); } + [Fact] + public void SellOreLeavesALottedCommodityThatWasNotExtracted() + { + var ship = Ship(); + var bay = ship.CargoBays.Single(); + var data = _cache.GetByName<SimpleCommodityData>("Ore"); + var lot = _items.Lots.Add(new Lot { Design = _cache.RefOf<ItemData>(data), Origin = new Attributed(), Quality = 1 }); + Assert.NotEqual(0, lot); + var traded = new SimpleCommodity { Data = _cache.RefOf<ItemData>(data), Quantity = 6, Lot = lot }; + Assert.True(bay.TryStore(traded)); + var credits = 100; + Assert.Equal(0, StationServices.OreValue(_items, ship.CargoBays)); + Assert.Equal(0, StationServices.TrySellOre(ship.CargoBays, Station(), ref credits)); + Assert.Equal(100, credits); + Assert.Contains(traded, bay.Cargo.Keys); + } + [Fact] public void SellOreAcrossBaysAndShips() { From 7d5e14a65b1148f13b5e571744690247449378a8 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 06:08:02 +0000 Subject: [PATCH 080/190] Red test: a boot catalog must hold no hull the importer cannot build ABootCatalogHoldsNoHullTheImporterCannotBuild fails at f7fd76857: dangling, POSITION-less, skinned and primitive-less mesh nodes are all composed and included (Excluded is empty). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../ShipModCatalogTests.cs | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs b/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs index f439eecc9..476fde846 100644 --- a/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs @@ -328,6 +328,49 @@ public sealed class ShipModCatalogTests : IDisposable Assert.Contains("GLB", excluded.Reason); } + // Bind is the one verdict on whether a mod hull exists: a package whose GLB names a node mesh the importer cannot build + // (dangling index, no POSITION, skinned node, no primitives) never reaches the boot catalog, so Preload has nothing left to refuse on file facts. + [Fact] + public void ABootCatalogHoldsNoHullTheImporterCannotBuild() + { + WritePackage("mod.good", hullName: "Good"); + var broken = new Dictionary<string, (string From, string To)> + { + ["mod.dangling"] = (@"{""name"":""collider"",""mesh"":0", @"{""name"":""collider"",""mesh"":7"), + ["mod.nopos"] = (@"""attributes"":{""POSITION"":0}", @"""attributes"":{}"), + ["mod.skinned"] = (@"{""name"":""map"",""mesh"":0", @"{""name"":""map"",""mesh"":0,""skin"":0"), + ["mod.noprims"] = (@"""primitives"":[{""attributes"":{""POSITION"":0}}]", @"""primitives"":[]") + }; + foreach (var (package, (from, to)) in broken) + { + WritePackage(package, hullName: package.Substring(4)); + var json = ShipFixture.GlbJson(FixtureNodes); + Assert.Contains(from, json); + File.WriteAllBytes(Path.Combine(Mods, package, "skiff.glb"), ShipFixture.Glb(json.Replace(from, to), ShipFixture.MeshBytes())); + } + + var (catalog, excluded) = ShipModCatalog.ResolveCatalog(Shipped, Derived, Mods); + + Assert.Equal(Derived, catalog); + Assert.Equal(broken.Keys.OrderBy(name => name, StringComparer.Ordinal), excluded.Select(e => e.Package).OrderBy(name => name, StringComparer.Ordinal)); + Assert.All(excluded, e => Assert.Contains("needs a mesh", e.Reason)); + using var cache = AetheriaStores.Open(catalog); + var hulls = cache.GetAll<HullData>().Where(hull => hull.Visual.IsSet()).ToArray(); + Assert.Equal(new[] { "Good" }, hulls.Select(hull => hull.Name)); + var keys = cache.AllStoredDocuments.Select(record => record.Key.Value).ToHashSet(); + foreach (var package in broken.Keys) + { + Assert.DoesNotContain(ShipModCatalog.HullKey(package).Value, keys); + Assert.DoesNotContain(ShipModCatalog.AuthoringKey(package).Value, keys); + } + // Preload's own two steps over file facts, run headlessly: neither may refuse a hull the catalog holds. + foreach (var hull in hulls) + { + var package = ShipModCatalog.PackageOf(cache, hull, Mods); + ShipModPlan.Build(package.Hull, package.Visual); + } + } + // The game's boot: a bad package is named and the rest boot; with none left, the shipped catalog boots. [Fact] public void TheBootCatalogSurvivesBadPackages() From b66d4f89abb8effc34c23815a170e6f43c063501 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 06:08:44 +0000 Subject: [PATCH 081/190] Bind decides every GLB-structure fact of a mod ship once ReadNodeIds' HasMesh is now BuildsMesh: no skin, mesh index inside meshes, at least one primitive, POSITION and triangle mode on each. Assemble's shield-radii throw is deleted (Bind's PositiveScale is the judge). The FBX thruster emitter takes Hide, with a smoke Require. Unity-only edits are not compiled in this Body. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/Editor/ShipPrefabAuthoring.cs | 1 + .../Editor/ShipPrefabAuthoringSmoke.cs | 2 ++ Assets/Scripts/Gameplay/ShipModShips.cs | 11 +++---- Assets/Scripts/ServerShared/ShipModCatalog.cs | 31 ++++++++++++++----- .../ShipModCatalogTests.cs | 5 +-- 5 files changed, 35 insertions(+), 15 deletions(-) diff --git a/Assets/Scripts/Editor/ShipPrefabAuthoring.cs b/Assets/Scripts/Editor/ShipPrefabAuthoring.cs index d2937b79d..45bbc8609 100644 --- a/Assets/Scripts/Editor/ShipPrefabAuthoring.cs +++ b/Assets/Scripts/Editor/ShipPrefabAuthoring.cs @@ -112,6 +112,7 @@ public static class ShipPrefabAuthoring case "Thruster": var emitter = DirectChild(node, "Emitter")?.GetComponent<MeshRenderer>(); if (emitter == null) throw new InvalidOperationException($"{name} needs an Emitter mesh child"); + ShipModShips.Hide(emitter, invisible); AddOrGet<ThrusterHardpoint>(node.gameObject).Emitter = emitter; thrusters.Add(node.GetComponent<ThrusterHardpoint>()); break; diff --git a/Assets/Scripts/Editor/ShipPrefabAuthoringSmoke.cs b/Assets/Scripts/Editor/ShipPrefabAuthoringSmoke.cs index 9f740f557..5342eb352 100644 --- a/Assets/Scripts/Editor/ShipPrefabAuthoringSmoke.cs +++ b/Assets/Scripts/Editor/ShipPrefabAuthoringSmoke.cs @@ -28,6 +28,8 @@ public static class ShipPrefabAuthoringSmoke ShipPrefabAuthoring.Configure(root); var ship = root.GetComponent<ShipInstance>(); Require(ship != null && ship.ThrusterHardpoints.Length == 1 && ship.ThrusterHardpoints[0].Emitter != null, "thruster emitter"); + Require(Array.TrueForAll(ship.ThrusterHardpoints[0].Emitter.sharedMaterials, material => material == ship.InvisibleMaterial), + "thruster emitter drawn with the invisible material only"); Require(ship.WeaponHardpoints.Length == 1 && ship.WeaponHardpoints[0].FiringPoint.Length == 2, "weapon muzzles"); Require(ship.WeaponHardpoints[0].FiringPoint[0].name == "Muzzle.0", "numeric muzzle order"); Require(ship.RadiatorHardpoints.Length == 1 && ship.RadiatorHardpoints[0].Mesh != null, "radiator mesh"); diff --git a/Assets/Scripts/Gameplay/ShipModShips.cs b/Assets/Scripts/Gameplay/ShipModShips.cs index 89106a6b7..33f09f590 100644 --- a/Assets/Scripts/Gameplay/ShipModShips.cs +++ b/Assets/Scripts/Gameplay/ShipModShips.cs @@ -6,9 +6,10 @@ using GameCult.Caching; using UnityEngine; using Object = UnityEngine.Object; -// Mod ships in the running game. Compose decides which mod hulls exist; Preload builds a prototype for each, keyed by the -// hull's record key, into an inactive assembled copy that Instantiate clones synchronously, so LoadEntity never loads async. -// A composed hull Preload cannot build is an import fault: Loading faults with ImportFault, naming every such hull's package. +// Mod ships in the running game. Compose (Bind) is the one verdict on whether a mod hull exists, from the package's files; +// Preload only builds a prototype for each, keyed by the hull's record key, into an inactive assembled copy that Instantiate +// clones synchronously, so LoadEntity never loads async. ImportFault reports what the Unity importer made of a composed hull: +// a composed hull Preload cannot build is an import fault: Loading faults with ImportFault, naming every such hull's package. // The prototypes are cache-only: rebuilt every boot from the catalog, the mod GLBs and the template. public static class ShipModShips { @@ -101,6 +102,7 @@ public static class ShipModShips node.name = id; return node; } + // An importer report, not a verdict: Bind has already judged the file. MeshRenderer Renderer(string id) { var found = Node(id).GetComponentInChildren<MeshRenderer>(true); @@ -130,9 +132,6 @@ public static class ShipModShips var surface = AddOrGet<HullCollider>(hullNode.gameObject); var shieldMarker = Node(plan.Shield); - var scale = shieldMarker.localScale; - if (!(scale.x > 0 && scale.y > 0 && scale.z > 0)) - throw new InvalidOperationException($"{ship.Id}: the shield anchor scale must have three positive radii."); var shield = Object.Instantiate(template.Shield.GetComponent<ShieldManager>(), shieldMarker, false); Reset(shield.transform); AddOrGet<ShieldEnvelope>(shield.gameObject); diff --git a/Assets/Scripts/ServerShared/ShipModCatalog.cs b/Assets/Scripts/ServerShared/ShipModCatalog.cs index e9ed613a2..88dc06b85 100644 --- a/Assets/Scripts/ServerShared/ShipModCatalog.cs +++ b/Assets/Scripts/ServerShared/ShipModCatalog.cs @@ -251,14 +251,15 @@ public static class ShipModCatalog foreach (var anchor in ship.Anchors) if (!modelNodes.ContainsKey(anchor.ModelNodeId)) throw new InvalidOperationException($"{ship.Id}: model has no node with aetheria.id={anchor.ModelNodeId} for anchor {anchor.Id}."); - // Assemble reads a renderer or collider mesh from these anchors' nodes and refuses without one, and reads the shield - // node's scale as three positive radii (ruling thrusters-radiators-are-meshes). These refusals stand in for Assemble's - // throws, so a package Compose includes is one the importer's assembler can build; the exhaust emission surface and - // the glowing radiator are meshes by that same ruling. A weapon mount and a tractor may be empties. + // Assemble reads a renderer or collider mesh from these anchors' nodes, and the shield node's scale as three positive + // radii (ruling thrusters-radiators-are-meshes). These refusals cover everything the package's files say about whether + // the importer can build a node (skin, dangling or empty mesh, not only "names a mesh") and are Assemble's only judge, + // so a package Compose includes is one the importer's assembler can build; the exhaust emission surface and the + // glowing radiator are meshes by that same ruling. A weapon mount and a tractor may be empties. foreach (var anchor in ship.Anchors) if ((anchor.Role == "thruster-emitter" || anchor.Role == "radiator-mesh" || anchor.Role == "map-icon" || anchor.Role == "hull-collider") && !modelNodes[anchor.ModelNodeId].HasMesh) - throw new InvalidOperationException($"{ship.Id}: {anchor.Role} anchor {anchor.Id} needs a mesh, but model node {anchor.ModelNodeId} has none."); + throw new InvalidOperationException($"{ship.Id}: {anchor.Role} anchor {anchor.Id} needs a mesh, but model node {anchor.ModelNodeId} has none the importer can build."); foreach (var anchor in ship.Anchors) if (anchor.Role == "shield" && !modelNodes[anchor.ModelNodeId].PositiveScale) throw new InvalidOperationException($"{ship.Id}: shield anchor {anchor.Id} needs three positive scale radii on model node {anchor.ModelNodeId}, with no matrix."); @@ -309,7 +310,23 @@ public static class ShipModCatalog private static bool PositiveScale(JObject node) => node["matrix"] == null && (node["scale"] == null || node["scale"].Select(component => (double)component).All(component => component > 0)); - // GLB is the xenos asset boundary. Only its node extras, whether each node names a mesh, and its nearest identified ancestor's node index + // A mesh the importer builds as a plain mesh node: no skin (glTFast makes a skinned node a SkinnedMeshRenderer, which + // Assemble's MeshRenderer/MeshFilter reads cannot see), a mesh index inside meshes, at least one primitive, and every + // primitive with POSITION and a mode absent or 4 (triangles). Geometry accessors and buffers are not read. + private static bool BuildsMesh(JObject json, JObject node) + { + if (node["skin"] != null && node["skin"].Type != JTokenType.Null) return false; + var meshes = json["meshes"] as JArray; + if (node["mesh"] == null || node["mesh"].Type != JTokenType.Integer || meshes == null) return false; + var index = (long)node["mesh"]; + if (index < 0 || index >= meshes.Count) return false; + var primitives = (meshes[(int)index] as JObject)?["primitives"] as JArray; + return primitives != null && primitives.Count > 0 && primitives.All(primitive => + primitive is JObject p && p["attributes"]?["POSITION"] != null && + (p["mode"] == null || (p["mode"].Type == JTokenType.Integer && (int)p["mode"] == 4))); + } + + // GLB is the xenos asset boundary. Only its node extras, whether each node carries a mesh the importer builds as a plain mesh node, and its nearest identified ancestor's node index // (-1 for none) are read here, plus whether the node's scale is three positive radii with no matrix; geometry belongs to the runtime importer. public static Dictionary<string, (uint Index, bool HasMesh, int Parent, bool PositiveScale)> ReadNodeIds(string path) { @@ -333,7 +350,7 @@ public static class ShipModCatalog { var id = (string)node["extras"]?["aetheria.id"]; if (string.IsNullOrEmpty(id)) { index++; continue; } - if (!ids.TryAdd(id, (index, node["mesh"] != null && node["mesh"].Type != JTokenType.Null, IdentifiedAncestor(parents, nodes, (int)index), PositiveScale(node)))) + if (!ids.TryAdd(id, (index, BuildsMesh(json, node), IdentifiedAncestor(parents, nodes, (int)index), PositiveScale(node)))) throw new InvalidOperationException($"{path}: duplicate GLB node aetheria.id={id}."); index++; } diff --git a/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs b/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs index 476fde846..877430027 100644 --- a/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs @@ -597,8 +597,9 @@ public sealed class ShipModCatalogTests : IDisposable public void NodeIdsMapToTheirGlbNodeIndexSkippingNodesWithoutOne() { var path = Write("nodes.glb", ShipFixture.Glb(@"{""asset"":{""version"":""2.0""},""nodes"":[ - {""name"":""plain""},{""extras"":{""aetheria.id"":""a""}},{""extras"":{}},{""extras"":{""aetheria.id"":""""}},{""mesh"":0,""extras"":{""aetheria.id"":""b""}}]}")); - Assert.Equal(new Dictionary<string, (uint, bool, int, bool)> { ["a"] = (1, false, -1, true), ["b"] = (4, true, -1, true) }, ShipModCatalog.ReadNodeIds(path)); + {""name"":""plain""},{""extras"":{""aetheria.id"":""a""}},{""extras"":{}},{""extras"":{""aetheria.id"":""""}},{""mesh"":0,""extras"":{""aetheria.id"":""b""}},{""mesh"":7,""extras"":{""aetheria.id"":""c""}}], + ""meshes"":[{""primitives"":[{""attributes"":{""POSITION"":0}}]}]}")); + Assert.Equal(new Dictionary<string, (uint, bool, int, bool)> { ["a"] = (1, false, -1, true), ["b"] = (4, true, -1, true), ["c"] = (5, false, -1, true) }, ShipModCatalog.ReadNodeIds(path)); } [Fact] From 339c617a74a7d6ec88c8242f8dc48d9c9966d09c Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 06:22:33 +0000 Subject: [PATCH 082/190] ShipRigTests fixture: the shared mesh has a POSITION primitive The fixture's empty primitives array is a mesh the importer cannot build, which Bind now refuses. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- tests/Aetheria.Shared.Tests/ShipRigTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Aetheria.Shared.Tests/ShipRigTests.cs b/tests/Aetheria.Shared.Tests/ShipRigTests.cs index 34581f34a..fbad3ec05 100644 --- a/tests/Aetheria.Shared.Tests/ShipRigTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipRigTests.cs @@ -209,7 +209,7 @@ public sealed class ShipRigTests : IDisposable private static string GlbJson(Node[] nodes) { - var text = new StringBuilder(@"{""asset"":{""version"":""2.0""},""meshes"":[{""primitives"":[]}],""nodes"":["); + var text = new StringBuilder(@"{""asset"":{""version"":""2.0""},""meshes"":[{""primitives"":[{""attributes"":{""POSITION"":0}}]}],""nodes"":["); for (var index = 0; index < nodes.Length; index++) { var node = nodes[index]; From ad295acaf3bfc66be1a77d52abf65675167e397b Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 06:45:43 +0000 Subject: [PATCH 083/190] Pin BuildsMesh clauses: points mode, one bad primitive, negative and fractional mesh index, missing meshes array Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs b/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs index 877430027..175a6bd9f 100644 --- a/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs @@ -329,7 +329,7 @@ public sealed class ShipModCatalogTests : IDisposable } // Bind is the one verdict on whether a mod hull exists: a package whose GLB names a node mesh the importer cannot build - // (dangling index, no POSITION, skinned node, no primitives) never reaches the boot catalog, so Preload has nothing left to refuse on file facts. + // (dangling or negative index, no meshes array, non-integer index, no POSITION on any one primitive, non-triangle mode, skinned node, no primitives) never reaches the boot catalog, so Preload has nothing left to refuse on file facts. [Fact] public void ABootCatalogHoldsNoHullTheImporterCannotBuild() { @@ -339,7 +339,12 @@ public sealed class ShipModCatalogTests : IDisposable ["mod.dangling"] = (@"{""name"":""collider"",""mesh"":0", @"{""name"":""collider"",""mesh"":7"), ["mod.nopos"] = (@"""attributes"":{""POSITION"":0}", @"""attributes"":{}"), ["mod.skinned"] = (@"{""name"":""map"",""mesh"":0", @"{""name"":""map"",""mesh"":0,""skin"":0"), - ["mod.noprims"] = (@"""primitives"":[{""attributes"":{""POSITION"":0}}]", @"""primitives"":[]") + ["mod.noprims"] = (@"""primitives"":[{""attributes"":{""POSITION"":0}}]", @"""primitives"":[]"), + ["mod.onebad"] = (@"""primitives"":[{""attributes"":{""POSITION"":0}}]", @"""primitives"":[{""attributes"":{""POSITION"":0}},{""attributes"":{}}]"), + ["mod.points"] = (@"""attributes"":{""POSITION"":0}}", @"""attributes"":{""POSITION"":0},""mode"":0}"), + ["mod.negative"] = (@"""mesh"":0", @"""mesh"":-1"), + ["mod.nomeshes"] = (@"""meshes"":", @"""other"":"), + ["mod.fractional"] = (@"""mesh"":0", @"""mesh"":0.0") }; foreach (var (package, (from, to)) in broken) { From 5c2dd76ceb4c2d7a1f379b948199ef51b8b86573 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 07:38:06 +0000 Subject: [PATCH 084/190] Test: the Substance clean break (red on base) Four headless facts: no .sbsar or .sbsar.meta remains; no surviving Assets/Packages/ ProjectSettings/GameData file names a removed Substance guid (44 tombstones: 41 sbsar metas, 2 folder metas, the importer script guid); the SUBSTANCE_PLUGIN_ENABLED define, LFS rule and manifest entries are gone; every repointed material names only textures that resolve to a .meta outside the removed tree. Fails on b2322c4ce for those reasons. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../SubstanceCleanBreakTests.cs | 174 ++++++++++++++++++ 1 file changed, 174 insertions(+) create mode 100644 tests/Aetheria.Shared.Tests/SubstanceCleanBreakTests.cs diff --git a/tests/Aetheria.Shared.Tests/SubstanceCleanBreakTests.cs b/tests/Aetheria.Shared.Tests/SubstanceCleanBreakTests.cs new file mode 100644 index 000000000..97e2c0b3b --- /dev/null +++ b/tests/Aetheria.Shared.Tests/SubstanceCleanBreakTests.cs @@ -0,0 +1,174 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using Xunit; + +// Substance clean break (aetheria-release:ruling:clean-break-from-substance, cut remove-sbsar-files). The 41 .sbsar +// files, their importer and the SUBSTANCE_PLUGIN_ENABLED define are gone, and nothing that survives may point into +// them. Headless: no Unity is open, so a dangling GUID is caught here instead of rendering pink in the editor. +public sealed class SubstanceCleanBreakTests +{ + // Every guid the removed tree owned, captured from the .meta files before deletion: the 41 .sbsar.meta, the two + // folder metas (Assets/Materials/Substance.meta, Substance/Metal.meta) and the importer script guid + // (43a8bbf6..., the `script:` line of every .sbsar.meta, whose plugin was already absent). + private static readonly string[] Tombstones = + { + "06833951ebae4cc45ad88d58cb5571de", + "06d6a565d43fba5409712ce9a10bfbef", + "07f679eadba9fb14abac26b1e165f7d5", + "092bdd8d243488141aeab5bb0d72429a", + "09aee558716a08d4c9806b9b4273a209", + "0b5dfc86c0681a3459a57d197804191b", + "0be5fb1df83ac8e499a3f6a060041e49", + "130f566ffa0b2424fbb47de2194c136a", + "180b85899b4b1f848b348230339ce984", + "1c858fec5b74c7c46b1712494192b6b5", + "26a894e543f3ed44893b1620707ca62c", + "2b42584452fe0cc4fa4e8a115230b156", + "2be0f689f5b01be4aa1032bc86f15eab", + "2e9a9dbacde66a446852af882f33e9e2", + "43a8bbf65be290d44ba52b94476242b9", + "4e39297ae4fe9ee4b803c04eabb69da7", + "50192727b92e0af4cbe5c773bec3537f", + "504c7bfe0d50ff64a88b8eac2ceb46f8", + "53adf8e53222e6f4791d7bf2110fb70c", + "58e16b7dbc1c31f4585e11544cdce127", + "6b2eb94965ca27542b8627d3521f5b5b", + "7363fcc4a3c41a349b29de7ec34555be", + "7de1c11cf7591ec48bdb53e9818172f5", + "8249e9ffcbd97c84d8ce73343e156c82", + "885e680924fc12c439a842a2142d4b78", + "9458f33b8e7e51a42aa19686b9779d82", + "9aa51bbe4dd46874a906608c34a739e4", + "9d0963470d3545a4e932ed4ea95b9d62", + "9fc901afb8a434e46b9405eaec2df5a4", + "a1d39ea984432bf44b4a0686afe2bf1a", + "a74970be876d3554ea0f279f39314c9c", + "afbd691d0ea2a5a47b5a43b244593a56", + "b2bec4b400153d745b2915f1c43e5c96", + "b7e648471e9dfc44490bd41973711541", + "c00b5a4f1e4743a4ca59b8030251f900", + "c5f2177e1f35daa499f4d7e0b7f3370a", + "ca8f080ab60226e4097841eee2bfa8db", + "cbc61995a46604441ab9de4f1c68e290", + "d15fc45ed0000934d946b5f271f637ef", + "ddc6970cc883b9845bdadc91983130c2", + "deb7e15e5f95294498d18869d9f11302", + "e7758cad28ae98f478940e55222419a6", + "ea7457b9a4f0bcb43becaa33de541cbd", + "ef9a54b8dacea9f44be70da43472f701", + }; + + private static readonly string[] ScannedExtensions = + { + ".mat", ".prefab", ".unity", ".asset", ".meta", ".controller", ".anim", ".overrideController", ".mixer", + ".lighting", ".flare", ".shader", ".json", + }; + + private static readonly string[] ExcludedDirs = { ".git", "node_modules", ".voidbot" }; + + private static readonly string[] RepointedMaterials = + { + "Assets/Materials/Steel.mat", "Assets/Materials/Aluminium brushed.mat", "Assets/Materials/Silver.mat", + "Assets/Materials/Steel parkerized.mat", "Assets/Materials/Cockpit.mat", "Assets/Materials/Metal 003.mat", + "Assets/Materials/Car Paint Red.mat", "Assets/Materials/Car Paint Magenta.mat", + "Assets/Materials/Car Paint White.mat", "Assets/Materials/Car Paint White Small.mat", + "Assets/Materials/Radiators.mat", "Assets/Materials/Station Lights.mat", "Assets/Materials/Mine Glow.mat", + "Assets/Models/Discobolus/Discobolus Marble.mat", "Assets/Materials/Pickup Trim.mat", + }; + + private static IEnumerable<string> Walk(string dir) + { + foreach (var file in Directory.EnumerateFiles(dir)) yield return file; + foreach (var sub in Directory.EnumerateDirectories(dir)) + if (!ExcludedDirs.Contains(Path.GetFileName(sub))) + foreach (var file in Walk(sub)) yield return file; + } + + [Fact] + public void NoSbsarFileOrMetaRemains() + { + var root = RestoredHullsTests.FindRepoRoot(); + var stray = Walk(root).Where(f => f.EndsWith(".sbsar", StringComparison.OrdinalIgnoreCase) + || f.EndsWith(".sbsar.meta", StringComparison.OrdinalIgnoreCase)) + .Select(f => Path.GetRelativePath(root, f)).ToList(); + Assert.True(stray.Count == 0, $"{stray.Count} Substance archive files remain, first: {stray.FirstOrDefault()}"); + Assert.False(Directory.Exists(Path.Combine(root, "Assets", "Materials", "Substance"))); + } + + [Fact] + public void NoSurvivingFileNamesARemovedSubstanceGuid() + { + var root = RestoredHullsTests.FindRepoRoot(); + var files = new[] { "Assets", "Packages", "ProjectSettings" } + .Select(d => Path.Combine(root, d)).Where(Directory.Exists) + .SelectMany(Walk) + .Concat(Directory.Exists(Path.Combine(root, "GameData")) + ? Directory.EnumerateFiles(Path.Combine(root, "GameData"), "*.cc") : Enumerable.Empty<string>()) + .Where(f => f.EndsWith(".cc") || ScannedExtensions.Contains(Path.GetExtension(f), StringComparer.OrdinalIgnoreCase)); + var hits = new List<string>(); + foreach (var file in files) + { + var lines = File.ReadAllText(file, Encoding.Latin1).Split('\n'); + for (var i = 0; i < lines.Length; i++) + foreach (var guid in Tombstones) + if (lines[i].Contains(guid, StringComparison.Ordinal)) + hits.Add($"{Path.GetRelativePath(root, file)}:{i + 1} names {guid}"); + } + Assert.True(hits.Count == 0, $"{hits.Count} references to removed Substance guids:\n" + string.Join("\n", hits.Take(40))); + } + + [Fact] + public void NoSubstanceBuildSurface() + { + var root = RestoredHullsTests.FindRepoRoot(); + Assert.DoesNotContain("SUBSTANCE", File.ReadAllText(Path.Combine(root, "ProjectSettings", "ProjectSettings.asset")), StringComparison.Ordinal); + foreach (var name in new[] { "manifest.json", "packages-lock.json" }) + { + var text = File.ReadAllText(Path.Combine(root, "Packages", name)); + Assert.DoesNotContain("substance", text, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("allegorithmic", text, StringComparison.OrdinalIgnoreCase); + } + Assert.DoesNotContain("sbsar", File.ReadAllText(Path.Combine(root, ".gitattributes")), StringComparison.OrdinalIgnoreCase); + Assert.False(Directory.Exists(Path.Combine(root, "Assets", "Allegorithmic"))); + } + + [Fact] + public void EveryReplacementTextureResolves() + { + var root = RestoredHullsTests.FindRepoRoot(); + var guidToMeta = new Dictionary<string, string>(); + foreach (var meta in Directory.EnumerateFiles(Path.Combine(root, "Assets"), "*.meta", SearchOption.AllDirectories)) + { + var guid = File.ReadLines(meta).FirstOrDefault(l => l.StartsWith("guid: "))?.Substring("guid: ".Length).Trim(); + if (guid != null) guidToMeta[guid] = Path.GetRelativePath(root, meta).Replace('\\', '/'); + } + + var texture = new Regex(@"m_Texture:\s*\{fileID:\s*(-?\d+),\s*guid:\s*([0-9a-f]{32})", RegexOptions.Compiled); + var problems = new List<string>(); + foreach (var rel in RepointedMaterials) + { + var path = Path.Combine(root, rel); + if (!File.Exists(path)) { problems.Add($"{rel} does not exist"); continue; } + var text = File.ReadAllText(path); + var start = text.IndexOf("m_TexEnvs:", StringComparison.Ordinal); + var end = text.IndexOf("m_Ints:", StringComparison.Ordinal); + Assert.True(start >= 0 && end > start, $"{rel} has no m_TexEnvs section"); + foreach (Match m in texture.Matches(text.Substring(start, end - start))) + { + if (m.Groups[1].Value == "0") continue; + var guid = m.Groups[2].Value; + if (!guidToMeta.TryGetValue(guid, out var meta)) problems.Add($"{rel} names {guid}, which has no .meta under Assets/"); + else if (meta.StartsWith("Assets/Materials/Substance", StringComparison.Ordinal)) problems.Add($"{rel} names {guid} inside the removed Substance tree"); + } + } + Assert.True(problems.Count == 0, string.Join("\n", problems)); + } +} From 6222b5c711849625242f958975995d574edc2056 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 07:38:28 +0000 Subject: [PATCH 085/190] Remove the 41 .sbsar files, the Substance define and five unreferenced materials Deletes Assets/Materials/Substance (41 .sbsar + metas, folder metas), the LFS rule for *.sbsar, SUBSTANCE_PLUGIN_ENABLED from the Standalone scripting defines, and five materials with zero GUID referrers (Assets/Steel, Steel brushed, Radiators 1, Thrusters, Discobolus Bronze). Surviving materials and prefabs still name the removed guids until the next commit repoints them. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Materials/Radiators 1.mat | 87 ---- Assets/Materials/Radiators 1.mat.meta | 8 - Assets/Materials/Steel brushed.mat | 83 ---- Assets/Materials/Steel brushed.mat.meta | 8 - Assets/Materials/Substance.meta | 8 - Assets/Materials/Substance/Metal.meta | 8 - .../Substance/Metal/Pickup Base.sbsar | 3 - .../Substance/Metal/Pickup Base.sbsar.meta | 382 ------------------ .../Substance/Metal/Pickup Trim.sbsar | 3 - .../Substance/Metal/Pickup Trim.sbsar.meta | 381 ----------------- .../Substance/Metal/galvanized_001.sbsar | 3 - .../Substance/Metal/galvanized_001.sbsar.meta | 369 ----------------- .../Substance/Metal/iron_damaged.sbsar | 3 - .../Substance/Metal/iron_damaged.sbsar.meta | 293 -------------- .../Substance/Metal/iron_rugged.sbsar | 3 - .../Substance/Metal/iron_rugged.sbsar.meta | 293 -------------- .../Materials/Substance/Metal/metal_002.sbsar | 3 - .../Substance/Metal/metal_002.sbsar.meta | 372 ----------------- .../Materials/Substance/Metal/metal_003.sbsar | 3 - .../Substance/Metal/metal_003.sbsar.meta | 372 ----------------- .../Materials/Substance/Metal/metal_006.sbsar | 3 - .../Substance/Metal/metal_006.sbsar.meta | 369 ----------------- .../Substance/Metal/metal_aluminium.sbsar | 3 - .../Metal/metal_aluminium.sbsar.meta | 373 ----------------- .../Metal/metal_aluminium_brushed.sbsar | 3 - .../Metal/metal_aluminium_brushed.sbsar.meta | 373 ----------------- .../Substance/Metal/metal_brass.sbsar | 3 - .../Substance/Metal/metal_brass.sbsar.meta | 375 ----------------- .../Substance/Metal/metal_car_paint 1.sbsar | 3 - .../Metal/metal_car_paint 1.sbsar.meta | 379 ----------------- .../Metal/metal_car_paint Magenta.sbsar | 3 - .../Metal/metal_car_paint Magenta.sbsar.meta | 381 ----------------- .../Substance/Metal/metal_car_paint red.sbsar | 3 - .../Metal/metal_car_paint red.sbsar.meta | 381 ----------------- .../Metal/metal_car_paint white.sbsar | 3 - .../Metal/metal_car_paint white.sbsar.meta | 382 ------------------ .../Substance/Metal/metal_copper.sbsar | 3 - .../Substance/Metal/metal_copper.sbsar.meta | 369 ----------------- .../Metal/metal_corrugated_002.sbsar | 3 - .../Metal/metal_corrugated_002.sbsar.meta | 369 ----------------- .../Substance/Metal/metal_floor_002.sbsar | 3 - .../Metal/metal_floor_002.sbsar.meta | 369 ----------------- .../Substance/Metal/metal_floor_004.sbsar | 3 - .../Metal/metal_floor_004.sbsar.meta | 369 ----------------- .../Substance/Metal/metal_floor_006.sbsar | 3 - .../Metal/metal_floor_006.sbsar.meta | 369 ----------------- .../Substance/Metal/metal_gold.sbsar | 3 - .../Substance/Metal/metal_gold.sbsar.meta | 373 ----------------- .../Substance/Metal/metal_nickel.sbsar | 3 - .../Substance/Metal/metal_nickel.sbsar.meta | 369 ----------------- .../Substance/Metal/metal_painted_steel.sbsar | 3 - .../Metal/metal_painted_steel.sbsar.meta | 376 ----------------- .../Substance/Metal/metal_panels_001.sbsar | 3 - .../Metal/metal_panels_001.sbsar.meta | 369 ----------------- .../Substance/Metal/metal_panels_002.sbsar | 3 - .../Metal/metal_panels_002.sbsar.meta | 369 ----------------- .../Substance/Metal/metal_plate_001.sbsar | 3 - .../Metal/metal_plate_001.sbsar.meta | 369 ----------------- .../Substance/Metal/metal_plate_004.sbsar | 3 - .../Metal/metal_plate_004.sbsar.meta | 369 ----------------- .../Substance/Metal/metal_plate_011.sbsar | 3 - .../Metal/metal_plate_011.sbsar.meta | 369 ----------------- .../Substance/Metal/metal_platinum.sbsar | 3 - .../Substance/Metal/metal_platinum.sbsar.meta | 372 ----------------- .../Substance/Metal/metal_roll_up.sbsar | 3 - .../Substance/Metal/metal_roll_up.sbsar.meta | 369 ----------------- .../Substance/Metal/metal_silver.sbsar | 3 - .../Substance/Metal/metal_silver.sbsar.meta | 369 ----------------- .../Substance/Metal/metal_steel.sbsar | 3 - .../Substance/Metal/metal_steel.sbsar.meta | 375 ----------------- .../Substance/Metal/metal_steel_brushed.sbsar | 3 - .../Metal/metal_steel_brushed.sbsar.meta | 370 ----------------- .../Substance/Metal/metal_steel_bumped.sbsar | 3 - .../Metal/metal_steel_bumped.sbsar.meta | 369 ----------------- .../Metal/metal_steel_parkerized.sbsar | 3 - .../Metal/metal_steel_parkerized.sbsar.meta | 369 ----------------- .../Substance/Metal/metal_titanium.sbsar | 3 - .../Substance/Metal/metal_titanium.sbsar.meta | 369 ----------------- .../Substance/Metal/metal_used.sbsar | 3 - .../Substance/Metal/metal_used.sbsar.meta | 371 ----------------- .../Substance/Metal/metal_weapon.sbsar | 3 - .../Substance/Metal/metal_weapon.sbsar.meta | 373 ----------------- .../Substance/Metal/metal_woven.sbsar | 3 - .../Substance/Metal/metal_woven.sbsar.meta | 369 ----------------- .../Substance/Metal/snatched_metal.sbsar | 3 - .../Substance/Metal/snatched_metal.sbsar.meta | 311 -------------- Assets/Materials/Substance/marble_002.sbsar | 3 - .../Materials/Substance/marble_002.sbsar.meta | 296 -------------- Assets/Materials/Thrusters.mat | 87 ---- Assets/Materials/Thrusters.mat.meta | 8 - .../Models/Discobolus/Discobolus Bronze.mat | 80 ---- .../Discobolus/Discobolus Bronze.mat.meta | 8 - Assets/Steel.mat | 83 ---- Assets/Steel.mat.meta | 8 - 94 files changed, 15564 deletions(-) delete mode 100644 Assets/Materials/Radiators 1.mat delete mode 100644 Assets/Materials/Radiators 1.mat.meta delete mode 100644 Assets/Materials/Steel brushed.mat delete mode 100644 Assets/Materials/Steel brushed.mat.meta delete mode 100644 Assets/Materials/Substance.meta delete mode 100644 Assets/Materials/Substance/Metal.meta delete mode 100644 Assets/Materials/Substance/Metal/Pickup Base.sbsar delete mode 100644 Assets/Materials/Substance/Metal/Pickup Base.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/Pickup Trim.sbsar delete mode 100644 Assets/Materials/Substance/Metal/Pickup Trim.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/galvanized_001.sbsar delete mode 100644 Assets/Materials/Substance/Metal/galvanized_001.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/iron_damaged.sbsar delete mode 100644 Assets/Materials/Substance/Metal/iron_damaged.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/iron_rugged.sbsar delete mode 100644 Assets/Materials/Substance/Metal/iron_rugged.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_002.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_002.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_003.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_003.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_006.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_006.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_aluminium.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_aluminium.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_aluminium_brushed.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_aluminium_brushed.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_brass.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_brass.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_car_paint 1.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_car_paint 1.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_car_paint Magenta.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_car_paint Magenta.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_car_paint red.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_car_paint red.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_car_paint white.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_car_paint white.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_copper.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_copper.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_corrugated_002.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_corrugated_002.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_floor_002.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_floor_002.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_floor_004.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_floor_004.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_floor_006.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_floor_006.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_gold.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_gold.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_nickel.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_nickel.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_painted_steel.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_painted_steel.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_panels_001.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_panels_001.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_panels_002.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_panels_002.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_plate_001.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_plate_001.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_plate_004.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_plate_004.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_plate_011.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_plate_011.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_platinum.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_platinum.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_roll_up.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_roll_up.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_silver.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_silver.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_steel.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_steel.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_steel_brushed.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_steel_brushed.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_steel_bumped.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_steel_bumped.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_steel_parkerized.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_steel_parkerized.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_titanium.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_titanium.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_used.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_used.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_weapon.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_weapon.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/metal_woven.sbsar delete mode 100644 Assets/Materials/Substance/Metal/metal_woven.sbsar.meta delete mode 100644 Assets/Materials/Substance/Metal/snatched_metal.sbsar delete mode 100644 Assets/Materials/Substance/Metal/snatched_metal.sbsar.meta delete mode 100644 Assets/Materials/Substance/marble_002.sbsar delete mode 100644 Assets/Materials/Substance/marble_002.sbsar.meta delete mode 100644 Assets/Materials/Thrusters.mat delete mode 100644 Assets/Materials/Thrusters.mat.meta delete mode 100644 Assets/Models/Discobolus/Discobolus Bronze.mat delete mode 100644 Assets/Models/Discobolus/Discobolus Bronze.mat.meta delete mode 100644 Assets/Steel.mat delete mode 100644 Assets/Steel.mat.meta diff --git a/Assets/Materials/Radiators 1.mat b/Assets/Materials/Radiators 1.mat deleted file mode 100644 index a6219fe9d..000000000 --- a/Assets/Materials/Radiators 1.mat +++ /dev/null @@ -1,87 +0,0 @@ -%YAML 1.1 -%TAG !u! tag:unity3d.com,2011: ---- !u!21 &2100000 -Material: - serializedVersion: 6 - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_Name: Radiators 1 - m_Shader: {fileID: 4800000, guid: d69ef48273708ef4680762f5cdcfc860, type: 3} - m_ShaderKeywords: - m_LightmapFlags: 4 - m_EnableInstancingVariants: 0 - m_DoubleSidedGI: 0 - m_CustomRenderQueue: -1 - stringTagMap: {} - disabledShaderPasses: [] - m_SavedProperties: - serializedVersion: 3 - m_TexEnvs: - - _BumpMap: - m_Texture: {fileID: -812895718602229137, guid: b7e648471e9dfc44490bd41973711541, - type: 3} - m_Scale: {x: 8, y: 8} - m_Offset: {x: 0, y: 0} - - _DetailAlbedoMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailMask: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailNormalMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _EmissionMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _MainTex: - m_Texture: {fileID: -6057190860509678031, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - m_Scale: {x: 8, y: 8} - m_Offset: {x: 0, y: 0} - - _MetallicGlossMap: - m_Texture: {fileID: -894214952450941493, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _OcclusionMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _ParallaxMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - m_Floats: - - _BumpPower: 2 - - _BumpScale: 1 - - _Cutoff: 0.5 - - _DetailNormalMapScale: 1 - - _DstBlend: 0 - - _Emission: 15 - - _EmissionFresnel: 4 - - _EmissionRoughnessFresnelPower: 0.5 - - _GlossMapScale: 1 - - _Glossiness: 1 - - _GlossyReflections: 1 - - _Metallic: 0 - - _Mode: 0 - - _OcclusionStrength: 1 - - _Parallax: 0.02 - - _ReverseRim: 0 - - _Rotation: 0 - - _SmoothnessTextureChannel: 0 - - _SpecularHighlights: 1 - - _SrcBlend: 1 - - _UVSec: 0 - - _ZWrite: 1 - m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} - - _EmissionColor: {r: 1, g: 0.40135294, b: 0, a: 1} - m_BuildTextureStacks: [] diff --git a/Assets/Materials/Radiators 1.mat.meta b/Assets/Materials/Radiators 1.mat.meta deleted file mode 100644 index c562a84de..000000000 --- a/Assets/Materials/Radiators 1.mat.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: f396635dc77c59c44ac85ae278a2e909 -NativeFormatImporter: - externalObjects: {} - mainObjectFileID: 0 - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Materials/Steel brushed.mat b/Assets/Materials/Steel brushed.mat deleted file mode 100644 index dba1bd074..000000000 --- a/Assets/Materials/Steel brushed.mat +++ /dev/null @@ -1,83 +0,0 @@ -%YAML 1.1 -%TAG !u! tag:unity3d.com,2011: ---- !u!21 &2100000 -Material: - serializedVersion: 6 - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_Name: Steel brushed - m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - m_ShaderKeywords: _MAINTEX _METALLICGLOSSMAP _NORMALMAP _OCCLUSIONMAP _PARALLAXMAP - m_LightmapFlags: 4 - m_EnableInstancingVariants: 0 - m_DoubleSidedGI: 0 - m_CustomRenderQueue: -1 - stringTagMap: {} - disabledShaderPasses: [] - m_SavedProperties: - serializedVersion: 3 - m_TexEnvs: - - _BumpMap: - m_Texture: {fileID: -4471413742775304797, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailAlbedoMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailMask: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailNormalMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _EmissionMap: - m_Texture: {fileID: 0} - m_Scale: {x: 8, y: 8} - m_Offset: {x: 0, y: 0} - - _MainTex: - m_Texture: {fileID: -4638397344074346932, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - m_Scale: {x: 8, y: 8} - m_Offset: {x: 0, y: 0} - - _MetallicGlossMap: - m_Texture: {fileID: 5049811794194361025, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _OcclusionMap: - m_Texture: {fileID: 1753668427856518731, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _ParallaxMap: - m_Texture: {fileID: -3498708498072814504, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - m_Floats: - - _BumpScale: 1 - - _Cutoff: 0.5 - - _DetailNormalMapScale: 1 - - _DstBlend: 0 - - _GlossMapScale: 1 - - _Glossiness: 0.5 - - _GlossyReflections: 1 - - _Metallic: 0 - - _Mode: 0 - - _OcclusionStrength: 1 - - _Parallax: 0.02 - - _SmoothnessTextureChannel: 0 - - _SpecularHighlights: 1 - - _SrcBlend: 1 - - _UVSec: 0 - - _ZWrite: 1 - m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} - - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} - m_BuildTextureStacks: [] diff --git a/Assets/Materials/Steel brushed.mat.meta b/Assets/Materials/Steel brushed.mat.meta deleted file mode 100644 index 73afa8139..000000000 --- a/Assets/Materials/Steel brushed.mat.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: df3e704fc59794a45b8e14a78d96cca3 -NativeFormatImporter: - externalObjects: {} - mainObjectFileID: 0 - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Materials/Substance.meta b/Assets/Materials/Substance.meta deleted file mode 100644 index c6926c786..000000000 --- a/Assets/Materials/Substance.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 7de1c11cf7591ec48bdb53e9818172f5 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Materials/Substance/Metal.meta b/Assets/Materials/Substance/Metal.meta deleted file mode 100644 index e8c0226e7..000000000 --- a/Assets/Materials/Substance/Metal.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 09aee558716a08d4c9806b9b4273a209 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Materials/Substance/Metal/Pickup Base.sbsar b/Assets/Materials/Substance/Metal/Pickup Base.sbsar deleted file mode 100644 index 963310406..000000000 --- a/Assets/Materials/Substance/Metal/Pickup Base.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dbee14b278a03ed59e1df8ecd6ba2b07ab7c2b2089e5e2bc3fad5673694a9f03 -size 14971 diff --git a/Assets/Materials/Substance/Metal/Pickup Base.sbsar.meta b/Assets/Materials/Substance/Metal/Pickup Base.sbsar.meta deleted file mode 100644 index 2966159bc..000000000 --- a/Assets/Materials/Substance/Metal/Pickup Base.sbsar.meta +++ /dev/null @@ -1,382 +0,0 @@ -fileFormatVersion: 2 -guid: 26a894e543f3ed44893b1620707ca62c -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_car_paint/metal_car_paint - - first: - 4: 400000 - second: metal_car_paint/metal_car_paint/Transform - - first: - 21: 2100000 - second: mat.Car paint - - first: - 23: 2300000 - second: metal_car_paint/metal_car_paint/MeshRenderer - - first: - 28: 2800000 - second: Car paint_baseColor - - first: - 28: 2800002 - second: Car paint_normal - - first: - 28: 2800004 - second: Car paint_metallic - - first: - 28: 2800006 - second: Car paint_ambientOcclusion - - first: - 28: 2800008 - second: Car paint_height - - first: - 33: 3300000 - second: metal_car_paint/metal_car_paint/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_car_paint/metal_car_paint/SphereCollider - - first: - 1001: 100100000 - second: metal_car_paint - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Car paint - prototypeName: Car paint - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_car_paint\" label=\"\" >\n <presetinput - identifier=\"$outputsize\" uid=\"2092133592\" type=\"8\" value=\"11,11\" />\n - <presetinput identifier=\"normal_intensity\" uid=\"2045651458\" type=\"0\" - value=\"0.25\" />\n <presetinput identifier=\"age\" uid=\"2038752334\" type=\"0\" - value=\"1\" />\n <presetinput identifier=\"flakes\" uid=\"20245147\" type=\"4\" - value=\"1\" />\n <presetinput identifier=\"flakes_scale\" uid=\"20192266\" - type=\"0\" value=\"0\" />\n <presetinput identifier=\"paint_scratches\" uid=\"22509202\" - type=\"0\" value=\"1\" />\n <presetinput identifier=\"paint_peeling\" uid=\"103560714\" - type=\"0\" value=\"0.151\" />\n <presetinput identifier=\"metal_roughness\" - uid=\"22504787\" type=\"0\" value=\"0.33\" />\n <presetinput identifier=\"paint_color\" - uid=\"105341618\" type=\"2\" value=\"1,0.891509,0.946396\" />\n <presetinput - identifier=\"paint_roughness\" uid=\"22504606\" type=\"0\" value=\"0\" />\n - <presetinput identifier=\"paint_metallic\" uid=\"22503567\" type=\"0\" value=\"0\" - />\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 3068890721646206586, guid: 26a894e543f3ed44893b1620707ca62c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 0.5, y: 0.5} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 5917659159057834157, guid: 26a894e543f3ed44893b1620707ca62c, - type: 3} - scale: {x: 0.5, y: 0.5} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -3552914696322007609, guid: 26a894e543f3ed44893b1620707ca62c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -1242281561028671816, guid: 26a894e543f3ed44893b1620707ca62c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -1652887728991447519, guid: 26a894e543f3ed44893b1620707ca62c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 1 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 1 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Car paint_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 2048 - textureHeight: 2048 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3720744386649352057, guid: 26a894e543f3ed44893b1620707ca62c, - type: 3} - generatedTextures: - - {fileID: 5917659159057834157, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} - - {fileID: 3068890721646206586, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} - - {fileID: -3552914696322007609, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} - - {fileID: -1242281561028671816, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} - - {fileID: -1652887728991447519, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} diff --git a/Assets/Materials/Substance/Metal/Pickup Trim.sbsar b/Assets/Materials/Substance/Metal/Pickup Trim.sbsar deleted file mode 100644 index 963310406..000000000 --- a/Assets/Materials/Substance/Metal/Pickup Trim.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dbee14b278a03ed59e1df8ecd6ba2b07ab7c2b2089e5e2bc3fad5673694a9f03 -size 14971 diff --git a/Assets/Materials/Substance/Metal/Pickup Trim.sbsar.meta b/Assets/Materials/Substance/Metal/Pickup Trim.sbsar.meta deleted file mode 100644 index 302e453b5..000000000 --- a/Assets/Materials/Substance/Metal/Pickup Trim.sbsar.meta +++ /dev/null @@ -1,381 +0,0 @@ -fileFormatVersion: 2 -guid: c00b5a4f1e4743a4ca59b8030251f900 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_car_paint/metal_car_paint - - first: - 4: 400000 - second: metal_car_paint/metal_car_paint/Transform - - first: - 21: 2100000 - second: mat.Car paint - - first: - 23: 2300000 - second: metal_car_paint/metal_car_paint/MeshRenderer - - first: - 28: 2800000 - second: Car paint_baseColor - - first: - 28: 2800002 - second: Car paint_normal - - first: - 28: 2800004 - second: Car paint_metallic - - first: - 28: 2800006 - second: Car paint_ambientOcclusion - - first: - 28: 2800008 - second: Car paint_height - - first: - 33: 3300000 - second: metal_car_paint/metal_car_paint/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_car_paint/metal_car_paint/SphereCollider - - first: - 1001: 100100000 - second: metal_car_paint - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Car paint - prototypeName: Car paint - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_car_paint\" label=\"\" >\n <presetinput - identifier=\"$outputsize\" uid=\"2092133592\" type=\"8\" value=\"11,11\" />\n - <presetinput identifier=\"normal_intensity\" uid=\"2045651458\" type=\"0\" - value=\"0.25\" />\n <presetinput identifier=\"age\" uid=\"2038752334\" type=\"0\" - value=\"1\" />\n <presetinput identifier=\"flakes\" uid=\"20245147\" type=\"4\" - value=\"1\" />\n <presetinput identifier=\"flakes_scale\" uid=\"20192266\" - type=\"0\" value=\"0.425\" />\n <presetinput identifier=\"paint_scratches\" - uid=\"22509202\" type=\"0\" value=\"1\" />\n <presetinput identifier=\"paint_peeling\" - uid=\"103560714\" type=\"0\" value=\"0.405\" />\n <presetinput identifier=\"metal_roughness\" - uid=\"22504787\" type=\"0\" value=\"0.425\" />\n <presetinput identifier=\"paint_color\" - uid=\"105341618\" type=\"2\" value=\"0,0.605881,1\" />\n <presetinput identifier=\"paint_roughness\" - uid=\"22504606\" type=\"0\" value=\"0\" />\n <presetinput identifier=\"paint_metallic\" - uid=\"22503567\" type=\"0\" value=\"1\" />\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 3068890721646206586, guid: c00b5a4f1e4743a4ca59b8030251f900, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 0.5, y: 0.5} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 5917659159057834157, guid: c00b5a4f1e4743a4ca59b8030251f900, - type: 3} - scale: {x: 0.5, y: 0.5} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -3552914696322007609, guid: c00b5a4f1e4743a4ca59b8030251f900, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -1242281561028671816, guid: c00b5a4f1e4743a4ca59b8030251f900, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -1652887728991447519, guid: c00b5a4f1e4743a4ca59b8030251f900, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.005 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Car paint_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 2048 - textureHeight: 2048 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3720744386649352057, guid: c00b5a4f1e4743a4ca59b8030251f900, - type: 3} - generatedTextures: - - {fileID: 5917659159057834157, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: 3068890721646206586, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: -3552914696322007609, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: -1242281561028671816, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: -1652887728991447519, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} diff --git a/Assets/Materials/Substance/Metal/galvanized_001.sbsar b/Assets/Materials/Substance/Metal/galvanized_001.sbsar deleted file mode 100644 index 5d6237210..000000000 --- a/Assets/Materials/Substance/Metal/galvanized_001.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:274db26d631b6cd53024c1366c01322d99b6194b5e211d04c5430bb8174ae8f6 -size 8207 diff --git a/Assets/Materials/Substance/Metal/galvanized_001.sbsar.meta b/Assets/Materials/Substance/Metal/galvanized_001.sbsar.meta deleted file mode 100644 index 9815351c0..000000000 --- a/Assets/Materials/Substance/Metal/galvanized_001.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 2be0f689f5b01be4aa1032bc86f15eab -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: galvanized_001/galvanized_001 - - first: - 4: 400000 - second: galvanized_001/galvanized_001/Transform - - first: - 21: 2100000 - second: mat.Galvanized_001 - - first: - 23: 2300000 - second: galvanized_001/galvanized_001/MeshRenderer - - first: - 28: 2800000 - second: Galvanized_001_baseColor - - first: - 28: 2800002 - second: Galvanized_001_normal - - first: - 28: 2800004 - second: Galvanized_001_metallic - - first: - 28: 2800006 - second: Galvanized_001_ambientOcclusion - - first: - 28: 2800008 - second: Galvanized_001_height - - first: - 33: 3300000 - second: galvanized_001/galvanized_001/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: galvanized_001/galvanized_001/SphereCollider - - first: - 1001: 100100000 - second: galvanized_001 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Galvanized_001 - prototypeName: Galvanized_001 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://galvanized_001\" label=\"\" >\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -2787997366030867252, guid: 2be0f689f5b01be4aa1032bc86f15eab, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 7907137595978400316, guid: 2be0f689f5b01be4aa1032bc86f15eab, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 1034366337303036879, guid: 2be0f689f5b01be4aa1032bc86f15eab, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 4470803051826786927, guid: 2be0f689f5b01be4aa1032bc86f15eab, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -3422293810953865746, guid: 2be0f689f5b01be4aa1032bc86f15eab, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Galvanized_001_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Galvanized_001 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -231086597109407277, guid: 2be0f689f5b01be4aa1032bc86f15eab, - type: 3} - generatedTextures: - - {fileID: 7907137595978400316, guid: 2be0f689f5b01be4aa1032bc86f15eab, type: 3} - - {fileID: -2787997366030867252, guid: 2be0f689f5b01be4aa1032bc86f15eab, type: 3} - - {fileID: 1034366337303036879, guid: 2be0f689f5b01be4aa1032bc86f15eab, type: 3} - - {fileID: 4470803051826786927, guid: 2be0f689f5b01be4aa1032bc86f15eab, type: 3} - - {fileID: -3422293810953865746, guid: 2be0f689f5b01be4aa1032bc86f15eab, type: 3} diff --git a/Assets/Materials/Substance/Metal/iron_damaged.sbsar b/Assets/Materials/Substance/Metal/iron_damaged.sbsar deleted file mode 100644 index cb09572e5..000000000 --- a/Assets/Materials/Substance/Metal/iron_damaged.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4a12de208077d6dfd8e70dfa8a8976bb9e5b2ca2d258bb34aa50c81a58a6451c -size 30808 diff --git a/Assets/Materials/Substance/Metal/iron_damaged.sbsar.meta b/Assets/Materials/Substance/Metal/iron_damaged.sbsar.meta deleted file mode 100644 index d7a4d07d7..000000000 --- a/Assets/Materials/Substance/Metal/iron_damaged.sbsar.meta +++ /dev/null @@ -1,293 +0,0 @@ -fileFormatVersion: 2 -guid: d15fc45ed0000934d946b5f271f637ef -ScriptedImporter: - internalIDToNameTable: [] - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Iron Damaged - prototypeName: Iron Damaged - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://iron_damaged\" label=\"\" >\n <presetinput - identifier=\"$outputsize\" uid=\"1484747668\" type=\"8\" value=\"9,9\" />\n - </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -1855041196637152199, guid: d15fc45ed0000934d946b5f271f637ef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -2789335455068261637, guid: d15fc45ed0000934d946b5f271f637ef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 7922211451800446260, guid: d15fc45ed0000934d946b5f271f637ef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -4424499752615739725, guid: d15fc45ed0000934d946b5f271f637ef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 7474978398744299577, guid: d15fc45ed0000934d946b5f271f637ef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambientocclusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - textureParameters: - - textureName: Iron Damaged - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Damaged - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Damaged - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Damaged - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Damaged - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Damaged - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Damaged - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Damaged - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Damaged - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 512 - textureHeight: 512 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 1736733470071950104, guid: d15fc45ed0000934d946b5f271f637ef, - type: 3} - generatedTextures: - - {fileID: -2789335455068261637, guid: d15fc45ed0000934d946b5f271f637ef, type: 3} - - {fileID: -1855041196637152199, guid: d15fc45ed0000934d946b5f271f637ef, type: 3} - - {fileID: 7922211451800446260, guid: d15fc45ed0000934d946b5f271f637ef, type: 3} - - {fileID: 7474978398744299577, guid: d15fc45ed0000934d946b5f271f637ef, type: 3} - - {fileID: -4424499752615739725, guid: d15fc45ed0000934d946b5f271f637ef, type: 3} diff --git a/Assets/Materials/Substance/Metal/iron_rugged.sbsar b/Assets/Materials/Substance/Metal/iron_rugged.sbsar deleted file mode 100644 index d211f88ad..000000000 --- a/Assets/Materials/Substance/Metal/iron_rugged.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5f2bc787cbb3f6511050a4faddaa07077bf54814131752687ed3717914d77de5 -size 28930 diff --git a/Assets/Materials/Substance/Metal/iron_rugged.sbsar.meta b/Assets/Materials/Substance/Metal/iron_rugged.sbsar.meta deleted file mode 100644 index 4d3540662..000000000 --- a/Assets/Materials/Substance/Metal/iron_rugged.sbsar.meta +++ /dev/null @@ -1,293 +0,0 @@ -fileFormatVersion: 2 -guid: afbd691d0ea2a5a47b5a43b244593a56 -ScriptedImporter: - internalIDToNameTable: [] - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Iron Rugged - prototypeName: Iron Rugged - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://iron_rugged\" label=\"\" >\n <presetinput - identifier=\"$outputsize\" uid=\"780426713\" type=\"8\" value=\"9,9\" />\n - </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -2323688274092838296, guid: afbd691d0ea2a5a47b5a43b244593a56, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -3909611376798458227, guid: afbd691d0ea2a5a47b5a43b244593a56, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -1417795912608492100, guid: afbd691d0ea2a5a47b5a43b244593a56, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -7795300588429949130, guid: afbd691d0ea2a5a47b5a43b244593a56, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 3868076301887189615, guid: afbd691d0ea2a5a47b5a43b244593a56, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambientocclusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - textureParameters: - - textureName: Iron Rugged - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Rugged - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Rugged - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Rugged - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Rugged - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Rugged - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Rugged - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Rugged - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Iron Rugged - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 512 - textureHeight: 512 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -7894845242109240131, guid: afbd691d0ea2a5a47b5a43b244593a56, - type: 3} - generatedTextures: - - {fileID: -3909611376798458227, guid: afbd691d0ea2a5a47b5a43b244593a56, type: 3} - - {fileID: -2323688274092838296, guid: afbd691d0ea2a5a47b5a43b244593a56, type: 3} - - {fileID: -1417795912608492100, guid: afbd691d0ea2a5a47b5a43b244593a56, type: 3} - - {fileID: 3868076301887189615, guid: afbd691d0ea2a5a47b5a43b244593a56, type: 3} - - {fileID: -7795300588429949130, guid: afbd691d0ea2a5a47b5a43b244593a56, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_002.sbsar b/Assets/Materials/Substance/Metal/metal_002.sbsar deleted file mode 100644 index 97dcc5ffe..000000000 --- a/Assets/Materials/Substance/Metal/metal_002.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9282e9326add2015fd2748e98c38062e438b085036eae00825551986e30d002f -size 11670 diff --git a/Assets/Materials/Substance/Metal/metal_002.sbsar.meta b/Assets/Materials/Substance/Metal/metal_002.sbsar.meta deleted file mode 100644 index 725363c0a..000000000 --- a/Assets/Materials/Substance/Metal/metal_002.sbsar.meta +++ /dev/null @@ -1,372 +0,0 @@ -fileFormatVersion: 2 -guid: 2b42584452fe0cc4fa4e8a115230b156 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_002/metal_002 - - first: - 4: 400000 - second: metal_002/metal_002/Transform - - first: - 21: 2100000 - second: mat.Metal 002 - - first: - 23: 2300000 - second: metal_002/metal_002/MeshRenderer - - first: - 28: 2800000 - second: Metal 002_baseColor - - first: - 28: 2800002 - second: Metal 002_normal - - first: - 28: 2800004 - second: Metal 002_metallic - - first: - 28: 2800006 - second: Metal 002_ambientOcclusion - - first: - 28: 2800008 - second: Metal 002_height - - first: - 33: 3300000 - second: metal_002/metal_002/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_002/metal_002/SphereCollider - - first: - 1001: 100100000 - second: metal_002 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal 002 - prototypeName: Metal 002 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_002\" label=\"\" >\n <presetinput - identifier=\"deep_rust\" uid=\"428347714\" type=\"0\" value=\"0.49\" />\n - <presetinput identifier=\"rust\" uid=\"428349112\" type=\"0\" value=\"0.83\" - />\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 1550000119726971649, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -6057190860509678031, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -894214952450941493, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -6882973941229436791, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 6347190432477724635, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal 002_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 002 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3766318789785789000, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - generatedTextures: - - {fileID: -6057190860509678031, guid: 2b42584452fe0cc4fa4e8a115230b156, type: 3} - - {fileID: 1550000119726971649, guid: 2b42584452fe0cc4fa4e8a115230b156, type: 3} - - {fileID: -894214952450941493, guid: 2b42584452fe0cc4fa4e8a115230b156, type: 3} - - {fileID: -6882973941229436791, guid: 2b42584452fe0cc4fa4e8a115230b156, type: 3} - - {fileID: 6347190432477724635, guid: 2b42584452fe0cc4fa4e8a115230b156, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_003.sbsar b/Assets/Materials/Substance/Metal/metal_003.sbsar deleted file mode 100644 index bbc118a2d..000000000 --- a/Assets/Materials/Substance/Metal/metal_003.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4ef8ee0ce61d17b7c84433ea0f780f32609c81f580f2c7d3a9c78303b9051a47 -size 7739 diff --git a/Assets/Materials/Substance/Metal/metal_003.sbsar.meta b/Assets/Materials/Substance/Metal/metal_003.sbsar.meta deleted file mode 100644 index f3ab67932..000000000 --- a/Assets/Materials/Substance/Metal/metal_003.sbsar.meta +++ /dev/null @@ -1,372 +0,0 @@ -fileFormatVersion: 2 -guid: 885e680924fc12c439a842a2142d4b78 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_003/metal_003 - - first: - 4: 400000 - second: metal_003/metal_003/Transform - - first: - 21: 2100000 - second: mat.Metal 003 - - first: - 23: 2300000 - second: metal_003/metal_003/MeshRenderer - - first: - 28: 2800000 - second: Metal 003_baseColor - - first: - 28: 2800002 - second: Metal 003_normal - - first: - 28: 2800004 - second: Metal 003_metallic - - first: - 28: 2800006 - second: Metal 003_height - - first: - 28: 2800008 - second: Metal 003_ambientOcclusion - - first: - 33: 3300000 - second: metal_003/metal_003/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_003/metal_003/SphereCollider - - first: - 1001: 100100000 - second: metal_003 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal 003 - prototypeName: Metal 003 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_003\" label=\"\" >\n <presetinput - identifier=\"$outputsize\" uid=\"1810375239\" type=\"8\" value=\"10,10\" />\n - <presetinput identifier=\"age\" uid=\"288263018\" type=\"0\" value=\"0.592\" - />\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -2508943184622041221, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 8, y: 8} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -1236254257114565538, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} - scale: {x: 8, y: 8} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 4019402794555593307, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -1475328947160444094, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 7523010977671448217, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - textureParameters: - - textureName: Metal 003_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 003 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 1024 - textureHeight: 1024 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -741235592913766832, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} - generatedTextures: - - {fileID: -1236254257114565538, guid: 885e680924fc12c439a842a2142d4b78, type: 3} - - {fileID: -2508943184622041221, guid: 885e680924fc12c439a842a2142d4b78, type: 3} - - {fileID: 4019402794555593307, guid: 885e680924fc12c439a842a2142d4b78, type: 3} - - {fileID: 7523010977671448217, guid: 885e680924fc12c439a842a2142d4b78, type: 3} - - {fileID: -1475328947160444094, guid: 885e680924fc12c439a842a2142d4b78, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_006.sbsar b/Assets/Materials/Substance/Metal/metal_006.sbsar deleted file mode 100644 index ac614998f..000000000 --- a/Assets/Materials/Substance/Metal/metal_006.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c7cdd662d4c7ee3124366ac316fe6aa5dd247c279bba053a9084916e0510d8df -size 12109 diff --git a/Assets/Materials/Substance/Metal/metal_006.sbsar.meta b/Assets/Materials/Substance/Metal/metal_006.sbsar.meta deleted file mode 100644 index f304dd2c0..000000000 --- a/Assets/Materials/Substance/Metal/metal_006.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 53adf8e53222e6f4791d7bf2110fb70c -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_006/metal_006 - - first: - 4: 400000 - second: metal_006/metal_006/Transform - - first: - 21: 2100000 - second: mat.Metal 006 - - first: - 23: 2300000 - second: metal_006/metal_006/MeshRenderer - - first: - 28: 2800000 - second: Metal 006_baseColor - - first: - 28: 2800002 - second: Metal 006_normal - - first: - 28: 2800004 - second: Metal 006_metallic - - first: - 28: 2800006 - second: Metal 006_height - - first: - 28: 2800008 - second: Metal 006_ambientOcclusion - - first: - 33: 3300000 - second: metal_006/metal_006/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_006/metal_006/SphereCollider - - first: - 1001: 100100000 - second: metal_006 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal 006 - prototypeName: Metal 006 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_006\" label=\"\" >\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -9145106948908842110, guid: 53adf8e53222e6f4791d7bf2110fb70c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 8714526317094329886, guid: 53adf8e53222e6f4791d7bf2110fb70c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 8283496261199770474, guid: 53adf8e53222e6f4791d7bf2110fb70c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -247870979206812949, guid: 53adf8e53222e6f4791d7bf2110fb70c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 4895182546727821380, guid: 53adf8e53222e6f4791d7bf2110fb70c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - textureParameters: - - textureName: Metal 006_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal 006 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3954565982357225544, guid: 53adf8e53222e6f4791d7bf2110fb70c, - type: 3} - generatedTextures: - - {fileID: 8714526317094329886, guid: 53adf8e53222e6f4791d7bf2110fb70c, type: 3} - - {fileID: -9145106948908842110, guid: 53adf8e53222e6f4791d7bf2110fb70c, type: 3} - - {fileID: 8283496261199770474, guid: 53adf8e53222e6f4791d7bf2110fb70c, type: 3} - - {fileID: 4895182546727821380, guid: 53adf8e53222e6f4791d7bf2110fb70c, type: 3} - - {fileID: -247870979206812949, guid: 53adf8e53222e6f4791d7bf2110fb70c, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_aluminium.sbsar b/Assets/Materials/Substance/Metal/metal_aluminium.sbsar deleted file mode 100644 index 088b73bee..000000000 --- a/Assets/Materials/Substance/Metal/metal_aluminium.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b19246651deb85c3c0a8d424507e0711ccce8c9eae241da396a36cd210f38f20 -size 10491 diff --git a/Assets/Materials/Substance/Metal/metal_aluminium.sbsar.meta b/Assets/Materials/Substance/Metal/metal_aluminium.sbsar.meta deleted file mode 100644 index 95addd8d7..000000000 --- a/Assets/Materials/Substance/Metal/metal_aluminium.sbsar.meta +++ /dev/null @@ -1,373 +0,0 @@ -fileFormatVersion: 2 -guid: 6b2eb94965ca27542b8627d3521f5b5b -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_aluminium/metal_aluminium - - first: - 4: 400000 - second: metal_aluminium/metal_aluminium/Transform - - first: - 21: 2100000 - second: mat.Aluminium - - first: - 23: 2300000 - second: metal_aluminium/metal_aluminium/MeshRenderer - - first: - 28: 2800000 - second: Aluminium_baseColor - - first: - 28: 2800002 - second: Aluminium_normal - - first: - 28: 2800004 - second: Aluminium_metallic - - first: - 28: 2800006 - second: Aluminium_ambientOcclusion - - first: - 28: 2800008 - second: Aluminium_height - - first: - 33: 3300000 - second: metal_aluminium/metal_aluminium/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_aluminium/metal_aluminium/SphereCollider - - first: - 1001: 100100000 - second: metal_aluminium - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Aluminium - prototypeName: Aluminium - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_aluminium\" label=\"\" >\n <presetinput - identifier=\"$outputsize\" uid=\"3181072216\" type=\"8\" value=\"9,9\" />\n - <presetinput identifier=\"dirt\" uid=\"3098331086\" type=\"0\" value=\"0.47\" - />\n <presetinput identifier=\"scratches\" uid=\"3338933642\" type=\"0\" value=\"1\" - />\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -7227111979962756822, guid: 6b2eb94965ca27542b8627d3521f5b5b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 5122202571912407749, guid: 6b2eb94965ca27542b8627d3521f5b5b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -5067940305606501900, guid: 6b2eb94965ca27542b8627d3521f5b5b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 9049458111962441826, guid: 6b2eb94965ca27542b8627d3521f5b5b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -7751791800289965735, guid: 6b2eb94965ca27542b8627d3521f5b5b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Aluminium_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 512 - textureHeight: 512 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 2717629391965333470, guid: 6b2eb94965ca27542b8627d3521f5b5b, - type: 3} - generatedTextures: - - {fileID: 5122202571912407749, guid: 6b2eb94965ca27542b8627d3521f5b5b, type: 3} - - {fileID: -7227111979962756822, guid: 6b2eb94965ca27542b8627d3521f5b5b, type: 3} - - {fileID: -5067940305606501900, guid: 6b2eb94965ca27542b8627d3521f5b5b, type: 3} - - {fileID: 9049458111962441826, guid: 6b2eb94965ca27542b8627d3521f5b5b, type: 3} - - {fileID: -7751791800289965735, guid: 6b2eb94965ca27542b8627d3521f5b5b, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_aluminium_brushed.sbsar b/Assets/Materials/Substance/Metal/metal_aluminium_brushed.sbsar deleted file mode 100644 index 7f2ec6e98..000000000 --- a/Assets/Materials/Substance/Metal/metal_aluminium_brushed.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:41bfd12f87e8255f00383022aa8a1d0c83273a8a23e21233db9f8f08eb89738f -size 12223 diff --git a/Assets/Materials/Substance/Metal/metal_aluminium_brushed.sbsar.meta b/Assets/Materials/Substance/Metal/metal_aluminium_brushed.sbsar.meta deleted file mode 100644 index cafdf3d25..000000000 --- a/Assets/Materials/Substance/Metal/metal_aluminium_brushed.sbsar.meta +++ /dev/null @@ -1,373 +0,0 @@ -fileFormatVersion: 2 -guid: 06d6a565d43fba5409712ce9a10bfbef -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_aluminium_brushed/metal_aluminium_brushed - - first: - 4: 400000 - second: metal_aluminium_brushed/metal_aluminium_brushed/Transform - - first: - 21: 2100000 - second: mat.Aluminium brushed - - first: - 23: 2300000 - second: metal_aluminium_brushed/metal_aluminium_brushed/MeshRenderer - - first: - 28: 2800000 - second: Aluminium brushed_baseColor - - first: - 28: 2800002 - second: Aluminium brushed_normal - - first: - 28: 2800004 - second: Aluminium brushed_metallic - - first: - 28: 2800006 - second: Aluminium brushed_ambientOcclusion - - first: - 28: 2800008 - second: Aluminium brushed_height - - first: - 33: 3300000 - second: metal_aluminium_brushed/metal_aluminium_brushed/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_aluminium_brushed/metal_aluminium_brushed/SphereCollider - - first: - 1001: 100100000 - second: metal_aluminium_brushed - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Aluminium brushed - prototypeName: Aluminium brushed - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_aluminium_brushed\" label=\"\" >\n - <presetinput identifier=\"$outputsize\" uid=\"2569318558\" type=\"8\" value=\"9,9\" - />\n <presetinput identifier=\"scratches\" uid=\"3820743244\" type=\"0\" value=\"1\" - />\n <presetinput identifier=\"aluminium_color\" uid=\"3822108404\" type=\"2\" - value=\"0.951,0.951,0.951\" />\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 4730978449518085612, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 7556082237344091230, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 6373266012617290493, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 342959783478273704, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -9132138291289375396, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Aluminium brushed_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Aluminium brushed - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 512 - textureHeight: 512 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -5899741495057040748, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} - generatedTextures: - - {fileID: 7556082237344091230, guid: 06d6a565d43fba5409712ce9a10bfbef, type: 3} - - {fileID: 4730978449518085612, guid: 06d6a565d43fba5409712ce9a10bfbef, type: 3} - - {fileID: 6373266012617290493, guid: 06d6a565d43fba5409712ce9a10bfbef, type: 3} - - {fileID: 342959783478273704, guid: 06d6a565d43fba5409712ce9a10bfbef, type: 3} - - {fileID: -9132138291289375396, guid: 06d6a565d43fba5409712ce9a10bfbef, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_brass.sbsar b/Assets/Materials/Substance/Metal/metal_brass.sbsar deleted file mode 100644 index 8db7e53b4..000000000 --- a/Assets/Materials/Substance/Metal/metal_brass.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:26e440c8cc91202789c408e82dfa3caca98938014aaf63baade897fade94f212 -size 12658 diff --git a/Assets/Materials/Substance/Metal/metal_brass.sbsar.meta b/Assets/Materials/Substance/Metal/metal_brass.sbsar.meta deleted file mode 100644 index dad220291..000000000 --- a/Assets/Materials/Substance/Metal/metal_brass.sbsar.meta +++ /dev/null @@ -1,375 +0,0 @@ -fileFormatVersion: 2 -guid: 9fc901afb8a434e46b9405eaec2df5a4 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_brass/metal_brass - - first: - 4: 400000 - second: metal_brass/metal_brass/Transform - - first: - 21: 2100000 - second: mat.Brass - - first: - 23: 2300000 - second: metal_brass/metal_brass/MeshRenderer - - first: - 28: 2800000 - second: Brass_baseColor - - first: - 28: 2800002 - second: Brass_normal - - first: - 28: 2800004 - second: Brass_metallic - - first: - 28: 2800006 - second: Brass_ambientOcclusion - - first: - 28: 2800008 - second: Brass_height - - first: - 33: 3300000 - second: metal_brass/metal_brass/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_brass/metal_brass/SphereCollider - - first: - 1001: 100100000 - second: metal_brass - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Brass - prototypeName: Brass - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_brass\" label=\"\" >\n <presetinput - identifier=\"$outputsize\" uid=\"2699195248\" type=\"8\" value=\"10,10\" />\n - <presetinput identifier=\"dirt\" uid=\"3700793424\" type=\"0\" value=\"1\" - />\n <presetinput identifier=\"scratches\" uid=\"2782264294\" type=\"0\" value=\"1\" - />\n <presetinput identifier=\"oxidation\" uid=\"3665635746\" type=\"0\" value=\"0.226\" - />\n <presetinput identifier=\"brass_roughness\" uid=\"3708655714\" type=\"0\" - value=\"0.092\" />\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -3419035557588562233, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -1863473678134789185, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 6214616473909614744, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -3436886866959827803, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 7009887839391554354, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Brass_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Brass - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 1024 - textureHeight: 1024 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -4907982557009795279, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} - generatedTextures: - - {fileID: -1863473678134789185, guid: 9fc901afb8a434e46b9405eaec2df5a4, type: 3} - - {fileID: -3419035557588562233, guid: 9fc901afb8a434e46b9405eaec2df5a4, type: 3} - - {fileID: 6214616473909614744, guid: 9fc901afb8a434e46b9405eaec2df5a4, type: 3} - - {fileID: -3436886866959827803, guid: 9fc901afb8a434e46b9405eaec2df5a4, type: 3} - - {fileID: 7009887839391554354, guid: 9fc901afb8a434e46b9405eaec2df5a4, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_car_paint 1.sbsar b/Assets/Materials/Substance/Metal/metal_car_paint 1.sbsar deleted file mode 100644 index 963310406..000000000 --- a/Assets/Materials/Substance/Metal/metal_car_paint 1.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dbee14b278a03ed59e1df8ecd6ba2b07ab7c2b2089e5e2bc3fad5673694a9f03 -size 14971 diff --git a/Assets/Materials/Substance/Metal/metal_car_paint 1.sbsar.meta b/Assets/Materials/Substance/Metal/metal_car_paint 1.sbsar.meta deleted file mode 100644 index d6786ba5e..000000000 --- a/Assets/Materials/Substance/Metal/metal_car_paint 1.sbsar.meta +++ /dev/null @@ -1,379 +0,0 @@ -fileFormatVersion: 2 -guid: 1c858fec5b74c7c46b1712494192b6b5 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_car_paint/metal_car_paint - - first: - 4: 400000 - second: metal_car_paint/metal_car_paint/Transform - - first: - 21: 2100000 - second: mat.Car paint - - first: - 23: 2300000 - second: metal_car_paint/metal_car_paint/MeshRenderer - - first: - 28: 2800000 - second: Car paint_baseColor - - first: - 28: 2800002 - second: Car paint_normal - - first: - 28: 2800004 - second: Car paint_metallic - - first: - 28: 2800006 - second: Car paint_ambientOcclusion - - first: - 28: 2800008 - second: Car paint_height - - first: - 33: 3300000 - second: metal_car_paint/metal_car_paint/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_car_paint/metal_car_paint/SphereCollider - - first: - 1001: 100100000 - second: metal_car_paint - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Car paint - prototypeName: Car paint - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_car_paint\" label=\"\" >\n <presetinput - identifier=\"$outputsize\" uid=\"2092133592\" type=\"8\" value=\"10,10\" />\n - <presetinput identifier=\"age\" uid=\"2038752334\" type=\"0\" value=\"0.66\" - />\n <presetinput identifier=\"flakes\" uid=\"20245147\" type=\"4\" value=\"1\" - />\n <presetinput identifier=\"flakes_scale\" uid=\"20192266\" type=\"0\" - value=\"0.225\" />\n <presetinput identifier=\"paint_scratches\" uid=\"22509202\" - type=\"0\" value=\"1\" />\n <presetinput identifier=\"paint_peeling\" uid=\"103560714\" - type=\"0\" value=\"0.14\" />\n <presetinput identifier=\"paint_color\" uid=\"105341618\" - type=\"2\" value=\"1,0.891509,0.946396\" />\n <presetinput identifier=\"paint_roughness\" - uid=\"22504606\" type=\"0\" value=\"0.15\" />\n <presetinput identifier=\"paint_metallic\" - uid=\"22503567\" type=\"0\" value=\"0\" />\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 3068890721646206586, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 16, y: 16} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 5917659159057834157, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} - scale: {x: 16, y: 16} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -3552914696322007609, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -1242281561028671816, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -1652887728991447519, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.005 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Car paint_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 1024 - textureHeight: 1024 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3720744386649352057, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} - generatedTextures: - - {fileID: 5917659159057834157, guid: 1c858fec5b74c7c46b1712494192b6b5, type: 3} - - {fileID: 3068890721646206586, guid: 1c858fec5b74c7c46b1712494192b6b5, type: 3} - - {fileID: -3552914696322007609, guid: 1c858fec5b74c7c46b1712494192b6b5, type: 3} - - {fileID: -1242281561028671816, guid: 1c858fec5b74c7c46b1712494192b6b5, type: 3} - - {fileID: -1652887728991447519, guid: 1c858fec5b74c7c46b1712494192b6b5, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_car_paint Magenta.sbsar b/Assets/Materials/Substance/Metal/metal_car_paint Magenta.sbsar deleted file mode 100644 index 963310406..000000000 --- a/Assets/Materials/Substance/Metal/metal_car_paint Magenta.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dbee14b278a03ed59e1df8ecd6ba2b07ab7c2b2089e5e2bc3fad5673694a9f03 -size 14971 diff --git a/Assets/Materials/Substance/Metal/metal_car_paint Magenta.sbsar.meta b/Assets/Materials/Substance/Metal/metal_car_paint Magenta.sbsar.meta deleted file mode 100644 index c839a27b8..000000000 --- a/Assets/Materials/Substance/Metal/metal_car_paint Magenta.sbsar.meta +++ /dev/null @@ -1,381 +0,0 @@ -fileFormatVersion: 2 -guid: a1d39ea984432bf44b4a0686afe2bf1a -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_car_paint/metal_car_paint - - first: - 4: 400000 - second: metal_car_paint/metal_car_paint/Transform - - first: - 21: 2100000 - second: mat.Car paint - - first: - 23: 2300000 - second: metal_car_paint/metal_car_paint/MeshRenderer - - first: - 28: 2800000 - second: Car paint_baseColor - - first: - 28: 2800002 - second: Car paint_normal - - first: - 28: 2800004 - second: Car paint_metallic - - first: - 28: 2800006 - second: Car paint_ambientOcclusion - - first: - 28: 2800008 - second: Car paint_height - - first: - 33: 3300000 - second: metal_car_paint/metal_car_paint/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_car_paint/metal_car_paint/SphereCollider - - first: - 1001: 100100000 - second: metal_car_paint - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Car paint - prototypeName: Car paint - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_car_paint\" label=\"\" >\n <presetinput - identifier=\"$outputsize\" uid=\"2092133592\" type=\"8\" value=\"11,11\" />\n - <presetinput identifier=\"normal_intensity\" uid=\"2045651458\" type=\"0\" - value=\"0.25\" />\n <presetinput identifier=\"age\" uid=\"2038752334\" type=\"0\" - value=\"1\" />\n <presetinput identifier=\"flakes\" uid=\"20245147\" type=\"4\" - value=\"1\" />\n <presetinput identifier=\"flakes_scale\" uid=\"20192266\" - type=\"0\" value=\"1\" />\n <presetinput identifier=\"paint_scratches\" uid=\"22509202\" - type=\"0\" value=\"1\" />\n <presetinput identifier=\"paint_peeling\" uid=\"103560714\" - type=\"0\" value=\"0.246\" />\n <presetinput identifier=\"metal_roughness\" - uid=\"22504787\" type=\"0\" value=\"0.39\" />\n <presetinput identifier=\"paint_color\" - uid=\"105341618\" type=\"2\" value=\"0.5,0,0.228113\" />\n <presetinput identifier=\"paint_roughness\" - uid=\"22504606\" type=\"0\" value=\"0\" />\n <presetinput identifier=\"paint_metallic\" - uid=\"22503567\" type=\"0\" value=\"1\" />\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 3068890721646206586, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 5917659159057834157, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} - scale: {x: 2, y: 2} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -3552914696322007609, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -1242281561028671816, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -1652887728991447519, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 1 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 1 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Car paint_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 2048 - textureHeight: 2048 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3720744386649352057, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} - generatedTextures: - - {fileID: 5917659159057834157, guid: a1d39ea984432bf44b4a0686afe2bf1a, type: 3} - - {fileID: 3068890721646206586, guid: a1d39ea984432bf44b4a0686afe2bf1a, type: 3} - - {fileID: -3552914696322007609, guid: a1d39ea984432bf44b4a0686afe2bf1a, type: 3} - - {fileID: -1242281561028671816, guid: a1d39ea984432bf44b4a0686afe2bf1a, type: 3} - - {fileID: -1652887728991447519, guid: a1d39ea984432bf44b4a0686afe2bf1a, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_car_paint red.sbsar b/Assets/Materials/Substance/Metal/metal_car_paint red.sbsar deleted file mode 100644 index 963310406..000000000 --- a/Assets/Materials/Substance/Metal/metal_car_paint red.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dbee14b278a03ed59e1df8ecd6ba2b07ab7c2b2089e5e2bc3fad5673694a9f03 -size 14971 diff --git a/Assets/Materials/Substance/Metal/metal_car_paint red.sbsar.meta b/Assets/Materials/Substance/Metal/metal_car_paint red.sbsar.meta deleted file mode 100644 index ded098ca6..000000000 --- a/Assets/Materials/Substance/Metal/metal_car_paint red.sbsar.meta +++ /dev/null @@ -1,381 +0,0 @@ -fileFormatVersion: 2 -guid: 504c7bfe0d50ff64a88b8eac2ceb46f8 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_car_paint/metal_car_paint - - first: - 4: 400000 - second: metal_car_paint/metal_car_paint/Transform - - first: - 21: 2100000 - second: mat.Car paint - - first: - 23: 2300000 - second: metal_car_paint/metal_car_paint/MeshRenderer - - first: - 28: 2800000 - second: Car paint_baseColor - - first: - 28: 2800002 - second: Car paint_normal - - first: - 28: 2800004 - second: Car paint_metallic - - first: - 28: 2800006 - second: Car paint_ambientOcclusion - - first: - 28: 2800008 - second: Car paint_height - - first: - 33: 3300000 - second: metal_car_paint/metal_car_paint/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_car_paint/metal_car_paint/SphereCollider - - first: - 1001: 100100000 - second: metal_car_paint - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Car paint - prototypeName: Car paint - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_car_paint\" label=\"\" >\n <presetinput - identifier=\"$outputsize\" uid=\"2092133592\" type=\"8\" value=\"11,11\" />\n - <presetinput identifier=\"normal_intensity\" uid=\"2045651458\" type=\"0\" - value=\"0.25\" />\n <presetinput identifier=\"age\" uid=\"2038752334\" type=\"0\" - value=\"1\" />\n <presetinput identifier=\"flakes\" uid=\"20245147\" type=\"4\" - value=\"1\" />\n <presetinput identifier=\"flakes_scale\" uid=\"20192266\" - type=\"0\" value=\"1\" />\n <presetinput identifier=\"paint_scratches\" uid=\"22509202\" - type=\"0\" value=\"1\" />\n <presetinput identifier=\"paint_peeling\" uid=\"103560714\" - type=\"0\" value=\"0.246\" />\n <presetinput identifier=\"metal_roughness\" - uid=\"22504787\" type=\"0\" value=\"0.39\" />\n <presetinput identifier=\"paint_color\" - uid=\"105341618\" type=\"2\" value=\"1,0.15685,0\" />\n <presetinput identifier=\"paint_roughness\" - uid=\"22504606\" type=\"0\" value=\"0\" />\n <presetinput identifier=\"paint_metallic\" - uid=\"22503567\" type=\"0\" value=\"1\" />\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 3068890721646206586, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 5917659159057834157, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -3552914696322007609, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -1242281561028671816, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -1652887728991447519, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.005 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Car paint_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 2048 - textureHeight: 2048 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3720744386649352057, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} - generatedTextures: - - {fileID: 5917659159057834157, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, type: 3} - - {fileID: 3068890721646206586, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, type: 3} - - {fileID: -3552914696322007609, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, type: 3} - - {fileID: -1242281561028671816, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, type: 3} - - {fileID: -1652887728991447519, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_car_paint white.sbsar b/Assets/Materials/Substance/Metal/metal_car_paint white.sbsar deleted file mode 100644 index 963310406..000000000 --- a/Assets/Materials/Substance/Metal/metal_car_paint white.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dbee14b278a03ed59e1df8ecd6ba2b07ab7c2b2089e5e2bc3fad5673694a9f03 -size 14971 diff --git a/Assets/Materials/Substance/Metal/metal_car_paint white.sbsar.meta b/Assets/Materials/Substance/Metal/metal_car_paint white.sbsar.meta deleted file mode 100644 index 98f20f5ea..000000000 --- a/Assets/Materials/Substance/Metal/metal_car_paint white.sbsar.meta +++ /dev/null @@ -1,382 +0,0 @@ -fileFormatVersion: 2 -guid: b2bec4b400153d745b2915f1c43e5c96 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_car_paint/metal_car_paint - - first: - 4: 400000 - second: metal_car_paint/metal_car_paint/Transform - - first: - 21: 2100000 - second: mat.Car paint - - first: - 23: 2300000 - second: metal_car_paint/metal_car_paint/MeshRenderer - - first: - 28: 2800000 - second: Car paint_baseColor - - first: - 28: 2800002 - second: Car paint_normal - - first: - 28: 2800004 - second: Car paint_metallic - - first: - 28: 2800006 - second: Car paint_ambientOcclusion - - first: - 28: 2800008 - second: Car paint_height - - first: - 33: 3300000 - second: metal_car_paint/metal_car_paint/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_car_paint/metal_car_paint/SphereCollider - - first: - 1001: 100100000 - second: metal_car_paint - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Car paint - prototypeName: Car paint - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_car_paint\" label=\"\" >\n <presetinput - identifier=\"$outputsize\" uid=\"2092133592\" type=\"8\" value=\"11,11\" />\n - <presetinput identifier=\"normal_intensity\" uid=\"2045651458\" type=\"0\" - value=\"0.25\" />\n <presetinput identifier=\"age\" uid=\"2038752334\" type=\"0\" - value=\"1\" />\n <presetinput identifier=\"flakes\" uid=\"20245147\" type=\"4\" - value=\"1\" />\n <presetinput identifier=\"flakes_scale\" uid=\"20192266\" - type=\"0\" value=\"0\" />\n <presetinput identifier=\"paint_scratches\" uid=\"22509202\" - type=\"0\" value=\"1\" />\n <presetinput identifier=\"paint_peeling\" uid=\"103560714\" - type=\"0\" value=\"0.095\" />\n <presetinput identifier=\"metal_roughness\" - uid=\"22504787\" type=\"0\" value=\"0.33\" />\n <presetinput identifier=\"paint_color\" - uid=\"105341618\" type=\"2\" value=\"1,0.891509,0.946396\" />\n <presetinput - identifier=\"paint_roughness\" uid=\"22504606\" type=\"0\" value=\"0\" />\n - <presetinput identifier=\"paint_metallic\" uid=\"22503567\" type=\"0\" value=\"0\" - />\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 3068890721646206586, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 0.5, y: 0.5} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 5917659159057834157, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} - scale: {x: 0.5, y: 0.5} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -3552914696322007609, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -1242281561028671816, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -1652887728991447519, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 1 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 1 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Car paint_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Car paint - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 2048 - textureHeight: 2048 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3720744386649352057, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} - generatedTextures: - - {fileID: 5917659159057834157, guid: b2bec4b400153d745b2915f1c43e5c96, type: 3} - - {fileID: 3068890721646206586, guid: b2bec4b400153d745b2915f1c43e5c96, type: 3} - - {fileID: -3552914696322007609, guid: b2bec4b400153d745b2915f1c43e5c96, type: 3} - - {fileID: -1242281561028671816, guid: b2bec4b400153d745b2915f1c43e5c96, type: 3} - - {fileID: -1652887728991447519, guid: b2bec4b400153d745b2915f1c43e5c96, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_copper.sbsar b/Assets/Materials/Substance/Metal/metal_copper.sbsar deleted file mode 100644 index b9eaa9f10..000000000 --- a/Assets/Materials/Substance/Metal/metal_copper.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7e0b38479a336f09f0f273488c666a1eb025ddd9a65366da00c80179ca0a64ee -size 7413 diff --git a/Assets/Materials/Substance/Metal/metal_copper.sbsar.meta b/Assets/Materials/Substance/Metal/metal_copper.sbsar.meta deleted file mode 100644 index d1afb9abd..000000000 --- a/Assets/Materials/Substance/Metal/metal_copper.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 8249e9ffcbd97c84d8ce73343e156c82 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_copper/metal_copper - - first: - 4: 400000 - second: metal_copper/metal_copper/Transform - - first: - 21: 2100000 - second: mat.Copper - - first: - 23: 2300000 - second: metal_copper/metal_copper/MeshRenderer - - first: - 28: 2800000 - second: Copper_baseColor - - first: - 28: 2800002 - second: Copper_normal - - first: - 28: 2800004 - second: Copper_metallic - - first: - 28: 2800006 - second: Copper_ambientOcclusion - - first: - 28: 2800008 - second: Copper_height - - first: - 33: 3300000 - second: metal_copper/metal_copper/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_copper/metal_copper/SphereCollider - - first: - 1001: 100100000 - second: metal_copper - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Copper - prototypeName: Copper - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_copper\" label=\"\" >\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -3792452219542522299, guid: 8249e9ffcbd97c84d8ce73343e156c82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -595311359069952391, guid: 8249e9ffcbd97c84d8ce73343e156c82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -1397886531756242709, guid: 8249e9ffcbd97c84d8ce73343e156c82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 2236529815293478155, guid: 8249e9ffcbd97c84d8ce73343e156c82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -1739956823984805281, guid: 8249e9ffcbd97c84d8ce73343e156c82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Copper_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Copper - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 9219180724257492359, guid: 8249e9ffcbd97c84d8ce73343e156c82, - type: 3} - generatedTextures: - - {fileID: -595311359069952391, guid: 8249e9ffcbd97c84d8ce73343e156c82, type: 3} - - {fileID: -3792452219542522299, guid: 8249e9ffcbd97c84d8ce73343e156c82, type: 3} - - {fileID: -1397886531756242709, guid: 8249e9ffcbd97c84d8ce73343e156c82, type: 3} - - {fileID: 2236529815293478155, guid: 8249e9ffcbd97c84d8ce73343e156c82, type: 3} - - {fileID: -1739956823984805281, guid: 8249e9ffcbd97c84d8ce73343e156c82, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_corrugated_002.sbsar b/Assets/Materials/Substance/Metal/metal_corrugated_002.sbsar deleted file mode 100644 index 24237719c..000000000 --- a/Assets/Materials/Substance/Metal/metal_corrugated_002.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5b798bdf0e774a7d826b7080b18c91ac8000cf6ac617dc395d8cf105aba8d7da -size 12826 diff --git a/Assets/Materials/Substance/Metal/metal_corrugated_002.sbsar.meta b/Assets/Materials/Substance/Metal/metal_corrugated_002.sbsar.meta deleted file mode 100644 index 3de9c9e1e..000000000 --- a/Assets/Materials/Substance/Metal/metal_corrugated_002.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 9d0963470d3545a4e932ed4ea95b9d62 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_corrugated_002/metal_corrugated_002 - - first: - 4: 400000 - second: metal_corrugated_002/metal_corrugated_002/Transform - - first: - 21: 2100000 - second: mat.Metal Corrugated 002 - - first: - 23: 2300000 - second: metal_corrugated_002/metal_corrugated_002/MeshRenderer - - first: - 28: 2800000 - second: Metal Corrugated 002_baseColor - - first: - 28: 2800002 - second: Metal Corrugated 002_normal - - first: - 28: 2800004 - second: Metal Corrugated 002_metallic - - first: - 28: 2800006 - second: Metal Corrugated 002_ambientOcclusion - - first: - 28: 2800008 - second: Metal Corrugated 002_height - - first: - 33: 3300000 - second: metal_corrugated_002/metal_corrugated_002/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_corrugated_002/metal_corrugated_002/SphereCollider - - first: - 1001: 100100000 - second: metal_corrugated_002 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal Corrugated 002 - prototypeName: Metal Corrugated 002 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_corrugated_002\" label=\"\" >\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -3654691528969531916, guid: 9d0963470d3545a4e932ed4ea95b9d62, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 4818317370781631303, guid: 9d0963470d3545a4e932ed4ea95b9d62, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 5859956115695178477, guid: 9d0963470d3545a4e932ed4ea95b9d62, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -8111981235355854162, guid: 9d0963470d3545a4e932ed4ea95b9d62, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -5667621616349238808, guid: 9d0963470d3545a4e932ed4ea95b9d62, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal Corrugated 002_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Corrugated 002 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -1355354389579744761, guid: 9d0963470d3545a4e932ed4ea95b9d62, - type: 3} - generatedTextures: - - {fileID: 4818317370781631303, guid: 9d0963470d3545a4e932ed4ea95b9d62, type: 3} - - {fileID: -3654691528969531916, guid: 9d0963470d3545a4e932ed4ea95b9d62, type: 3} - - {fileID: 5859956115695178477, guid: 9d0963470d3545a4e932ed4ea95b9d62, type: 3} - - {fileID: -8111981235355854162, guid: 9d0963470d3545a4e932ed4ea95b9d62, type: 3} - - {fileID: -5667621616349238808, guid: 9d0963470d3545a4e932ed4ea95b9d62, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_floor_002.sbsar b/Assets/Materials/Substance/Metal/metal_floor_002.sbsar deleted file mode 100644 index af4adc50c..000000000 --- a/Assets/Materials/Substance/Metal/metal_floor_002.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5815e5257550f8315dd80831c4cab398a3ae7b234b25e716ecca18c9facbd9be -size 11140 diff --git a/Assets/Materials/Substance/Metal/metal_floor_002.sbsar.meta b/Assets/Materials/Substance/Metal/metal_floor_002.sbsar.meta deleted file mode 100644 index c100570af..000000000 --- a/Assets/Materials/Substance/Metal/metal_floor_002.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: ddc6970cc883b9845bdadc91983130c2 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_floor_002/metal_floor_002 - - first: - 4: 400000 - second: metal_floor_002/metal_floor_002/Transform - - first: - 21: 2100000 - second: mat.Metal Floor 002 - - first: - 23: 2300000 - second: metal_floor_002/metal_floor_002/MeshRenderer - - first: - 28: 2800000 - second: Metal Floor 002_baseColor - - first: - 28: 2800002 - second: Metal Floor 002_normal - - first: - 28: 2800004 - second: Metal Floor 002_metallic - - first: - 28: 2800006 - second: Metal Floor 002_ambientOcclusion - - first: - 28: 2800008 - second: Metal Floor 002_height - - first: - 33: 3300000 - second: metal_floor_002/metal_floor_002/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_floor_002/metal_floor_002/SphereCollider - - first: - 1001: 100100000 - second: metal_floor_002 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal Floor 002 - prototypeName: Metal Floor 002 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_floor_002\" label=\"\" >\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 351554284034007472, guid: ddc6970cc883b9845bdadc91983130c2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -7508666898770042810, guid: ddc6970cc883b9845bdadc91983130c2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -4403901252400104909, guid: ddc6970cc883b9845bdadc91983130c2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -4356325417559842052, guid: ddc6970cc883b9845bdadc91983130c2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -3247329771169464856, guid: ddc6970cc883b9845bdadc91983130c2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal Floor 002_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 002 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3616699503892477274, guid: ddc6970cc883b9845bdadc91983130c2, - type: 3} - generatedTextures: - - {fileID: -7508666898770042810, guid: ddc6970cc883b9845bdadc91983130c2, type: 3} - - {fileID: 351554284034007472, guid: ddc6970cc883b9845bdadc91983130c2, type: 3} - - {fileID: -4403901252400104909, guid: ddc6970cc883b9845bdadc91983130c2, type: 3} - - {fileID: -4356325417559842052, guid: ddc6970cc883b9845bdadc91983130c2, type: 3} - - {fileID: -3247329771169464856, guid: ddc6970cc883b9845bdadc91983130c2, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_floor_004.sbsar b/Assets/Materials/Substance/Metal/metal_floor_004.sbsar deleted file mode 100644 index f7136c15b..000000000 --- a/Assets/Materials/Substance/Metal/metal_floor_004.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:3d30688944fced2d854f8375ebecd8ad7a6a8021cee07e89710b44ad8272addd -size 8634 diff --git a/Assets/Materials/Substance/Metal/metal_floor_004.sbsar.meta b/Assets/Materials/Substance/Metal/metal_floor_004.sbsar.meta deleted file mode 100644 index 031cbe6c4..000000000 --- a/Assets/Materials/Substance/Metal/metal_floor_004.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 50192727b92e0af4cbe5c773bec3537f -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_floor_004/metal_floor_004 - - first: - 4: 400000 - second: metal_floor_004/metal_floor_004/Transform - - first: - 21: 2100000 - second: mat.Metal Floor 004 - - first: - 23: 2300000 - second: metal_floor_004/metal_floor_004/MeshRenderer - - first: - 28: 2800000 - second: Metal Floor 004_baseColor - - first: - 28: 2800002 - second: Metal Floor 004_normal - - first: - 28: 2800004 - second: Metal Floor 004_metallic - - first: - 28: 2800006 - second: Metal Floor 004_ambientOcclusion - - first: - 28: 2800008 - second: Metal Floor 004_height - - first: - 33: 3300000 - second: metal_floor_004/metal_floor_004/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_floor_004/metal_floor_004/SphereCollider - - first: - 1001: 100100000 - second: metal_floor_004 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal Floor 004 - prototypeName: Metal Floor 004 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_floor_004\" label=\"\" >\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 5886398526092406922, guid: 50192727b92e0af4cbe5c773bec3537f, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 1550179426837470591, guid: 50192727b92e0af4cbe5c773bec3537f, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 4385304290797446058, guid: 50192727b92e0af4cbe5c773bec3537f, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -3130265262045919237, guid: 50192727b92e0af4cbe5c773bec3537f, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 4866469902769357514, guid: 50192727b92e0af4cbe5c773bec3537f, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal Floor 004_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 004 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -1891697860355797410, guid: 50192727b92e0af4cbe5c773bec3537f, - type: 3} - generatedTextures: - - {fileID: 1550179426837470591, guid: 50192727b92e0af4cbe5c773bec3537f, type: 3} - - {fileID: 5886398526092406922, guid: 50192727b92e0af4cbe5c773bec3537f, type: 3} - - {fileID: 4385304290797446058, guid: 50192727b92e0af4cbe5c773bec3537f, type: 3} - - {fileID: -3130265262045919237, guid: 50192727b92e0af4cbe5c773bec3537f, type: 3} - - {fileID: 4866469902769357514, guid: 50192727b92e0af4cbe5c773bec3537f, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_floor_006.sbsar b/Assets/Materials/Substance/Metal/metal_floor_006.sbsar deleted file mode 100644 index 81ce60800..000000000 --- a/Assets/Materials/Substance/Metal/metal_floor_006.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9604a8c7814d09f90d8bc64061cdc39c733d9f96de43143717f9a951b1f08a0e -size 10884 diff --git a/Assets/Materials/Substance/Metal/metal_floor_006.sbsar.meta b/Assets/Materials/Substance/Metal/metal_floor_006.sbsar.meta deleted file mode 100644 index 91f291c9d..000000000 --- a/Assets/Materials/Substance/Metal/metal_floor_006.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 06833951ebae4cc45ad88d58cb5571de -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_floor_006/metal_floor_006 - - first: - 4: 400000 - second: metal_floor_006/metal_floor_006/Transform - - first: - 21: 2100000 - second: mat.Metal Floor 006 - - first: - 23: 2300000 - second: metal_floor_006/metal_floor_006/MeshRenderer - - first: - 28: 2800000 - second: Metal Floor 006_baseColor - - first: - 28: 2800002 - second: Metal Floor 006_normal - - first: - 28: 2800004 - second: Metal Floor 006_metallic - - first: - 28: 2800006 - second: Metal Floor 006_ambientOcclusion - - first: - 28: 2800008 - second: Metal Floor 006_height - - first: - 33: 3300000 - second: metal_floor_006/metal_floor_006/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_floor_006/metal_floor_006/SphereCollider - - first: - 1001: 100100000 - second: metal_floor_006 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal Floor 006 - prototypeName: Metal Floor 006 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_floor_006\" label=\"\" >\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -2252411089510067877, guid: 06833951ebae4cc45ad88d58cb5571de, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -446378320346000722, guid: 06833951ebae4cc45ad88d58cb5571de, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 877764506763962143, guid: 06833951ebae4cc45ad88d58cb5571de, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -4232129871321120126, guid: 06833951ebae4cc45ad88d58cb5571de, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 3318615130639472310, guid: 06833951ebae4cc45ad88d58cb5571de, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal Floor 006_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Floor 006 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -6975397259061671394, guid: 06833951ebae4cc45ad88d58cb5571de, - type: 3} - generatedTextures: - - {fileID: -446378320346000722, guid: 06833951ebae4cc45ad88d58cb5571de, type: 3} - - {fileID: -2252411089510067877, guid: 06833951ebae4cc45ad88d58cb5571de, type: 3} - - {fileID: 877764506763962143, guid: 06833951ebae4cc45ad88d58cb5571de, type: 3} - - {fileID: -4232129871321120126, guid: 06833951ebae4cc45ad88d58cb5571de, type: 3} - - {fileID: 3318615130639472310, guid: 06833951ebae4cc45ad88d58cb5571de, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_gold.sbsar b/Assets/Materials/Substance/Metal/metal_gold.sbsar deleted file mode 100644 index 5aa377680..000000000 --- a/Assets/Materials/Substance/Metal/metal_gold.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:29ef1a459ab7d090b32ee563d729038527c4d031595abef2a49398543d11343c -size 7428 diff --git a/Assets/Materials/Substance/Metal/metal_gold.sbsar.meta b/Assets/Materials/Substance/Metal/metal_gold.sbsar.meta deleted file mode 100644 index c4e7f4644..000000000 --- a/Assets/Materials/Substance/Metal/metal_gold.sbsar.meta +++ /dev/null @@ -1,373 +0,0 @@ -fileFormatVersion: 2 -guid: a74970be876d3554ea0f279f39314c9c -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_gold/metal_gold - - first: - 4: 400000 - second: metal_gold/metal_gold/Transform - - first: - 21: 2100000 - second: mat.Gold - - first: - 23: 2300000 - second: metal_gold/metal_gold/MeshRenderer - - first: - 28: 2800000 - second: Gold_baseColor - - first: - 28: 2800002 - second: Gold_normal - - first: - 28: 2800004 - second: Gold_metallic - - first: - 28: 2800006 - second: Gold_ambientOcclusion - - first: - 28: 2800008 - second: Gold_height - - first: - 33: 3300000 - second: metal_gold/metal_gold/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_gold/metal_gold/SphereCollider - - first: - 1001: 100100000 - second: metal_gold - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Gold - prototypeName: Gold - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_gold\" label=\"\" >\n <presetinput - identifier=\"$outputsize\" uid=\"2862216590\" type=\"8\" value=\"9,9\" />\n - <presetinput identifier=\"dirt\" uid=\"2947448088\" type=\"0\" value=\"0.766\" - />\n <presetinput identifier=\"scratches\" uid=\"3615194042\" type=\"0\" value=\"1\" - />\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -6248678595456566848, guid: a74970be876d3554ea0f279f39314c9c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 4, y: 4} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 2039085267362074300, guid: a74970be876d3554ea0f279f39314c9c, - type: 3} - scale: {x: 4, y: 4} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -8783136193678078058, guid: a74970be876d3554ea0f279f39314c9c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 7384525862955468029, guid: a74970be876d3554ea0f279f39314c9c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -8934633548313413119, guid: a74970be876d3554ea0f279f39314c9c, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Gold_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Gold - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 512 - textureHeight: 512 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -905690159841262435, guid: a74970be876d3554ea0f279f39314c9c, - type: 3} - generatedTextures: - - {fileID: 2039085267362074300, guid: a74970be876d3554ea0f279f39314c9c, type: 3} - - {fileID: -6248678595456566848, guid: a74970be876d3554ea0f279f39314c9c, type: 3} - - {fileID: -8783136193678078058, guid: a74970be876d3554ea0f279f39314c9c, type: 3} - - {fileID: 7384525862955468029, guid: a74970be876d3554ea0f279f39314c9c, type: 3} - - {fileID: -8934633548313413119, guid: a74970be876d3554ea0f279f39314c9c, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_nickel.sbsar b/Assets/Materials/Substance/Metal/metal_nickel.sbsar deleted file mode 100644 index e7cf69c6b..000000000 --- a/Assets/Materials/Substance/Metal/metal_nickel.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a0395691305bc49406088b12b65ea186d65d5101bc230a2e91b4ddbf2c7b65ea -size 8935 diff --git a/Assets/Materials/Substance/Metal/metal_nickel.sbsar.meta b/Assets/Materials/Substance/Metal/metal_nickel.sbsar.meta deleted file mode 100644 index 65531754c..000000000 --- a/Assets/Materials/Substance/Metal/metal_nickel.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: c5f2177e1f35daa499f4d7e0b7f3370a -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_nickel/metal_nickel - - first: - 4: 400000 - second: metal_nickel/metal_nickel/Transform - - first: - 21: 2100000 - second: mat.Nickel - - first: - 23: 2300000 - second: metal_nickel/metal_nickel/MeshRenderer - - first: - 28: 2800000 - second: Nickel_baseColor - - first: - 28: 2800002 - second: Nickel_normal - - first: - 28: 2800004 - second: Nickel_metallic - - first: - 28: 2800006 - second: Nickel_ambientOcclusion - - first: - 28: 2800008 - second: Nickel_height - - first: - 33: 3300000 - second: metal_nickel/metal_nickel/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_nickel/metal_nickel/SphereCollider - - first: - 1001: 100100000 - second: metal_nickel - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Nickel - prototypeName: Nickel - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_nickel\" label=\"\" >\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 1040180909335529060, guid: c5f2177e1f35daa499f4d7e0b7f3370a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -3896990606402278735, guid: c5f2177e1f35daa499f4d7e0b7f3370a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -8156577797594723071, guid: c5f2177e1f35daa499f4d7e0b7f3370a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -7935365347593253955, guid: c5f2177e1f35daa499f4d7e0b7f3370a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -4922792887777872198, guid: c5f2177e1f35daa499f4d7e0b7f3370a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Nickel_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Nickel - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -443055228576417237, guid: c5f2177e1f35daa499f4d7e0b7f3370a, - type: 3} - generatedTextures: - - {fileID: -3896990606402278735, guid: c5f2177e1f35daa499f4d7e0b7f3370a, type: 3} - - {fileID: 1040180909335529060, guid: c5f2177e1f35daa499f4d7e0b7f3370a, type: 3} - - {fileID: -8156577797594723071, guid: c5f2177e1f35daa499f4d7e0b7f3370a, type: 3} - - {fileID: -7935365347593253955, guid: c5f2177e1f35daa499f4d7e0b7f3370a, type: 3} - - {fileID: -4922792887777872198, guid: c5f2177e1f35daa499f4d7e0b7f3370a, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_painted_steel.sbsar b/Assets/Materials/Substance/Metal/metal_painted_steel.sbsar deleted file mode 100644 index d764cd35f..000000000 --- a/Assets/Materials/Substance/Metal/metal_painted_steel.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:bc8dcd55f0619c028037c7225720acb4eea87b28cc7c120125fa2b38d02f775a -size 13628 diff --git a/Assets/Materials/Substance/Metal/metal_painted_steel.sbsar.meta b/Assets/Materials/Substance/Metal/metal_painted_steel.sbsar.meta deleted file mode 100644 index 467fa07bd..000000000 --- a/Assets/Materials/Substance/Metal/metal_painted_steel.sbsar.meta +++ /dev/null @@ -1,376 +0,0 @@ -fileFormatVersion: 2 -guid: b7e648471e9dfc44490bd41973711541 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_painted_steel/metal_painted_steel - - first: - 4: 400000 - second: metal_painted_steel/metal_painted_steel/Transform - - first: - 21: 2100000 - second: mat.Painted steel - - first: - 23: 2300000 - second: metal_painted_steel/metal_painted_steel/MeshRenderer - - first: - 28: 2800000 - second: Painted steel_baseColor - - first: - 28: 2800002 - second: Painted steel_normal - - first: - 28: 2800004 - second: Painted steel_metallic - - first: - 28: 2800006 - second: Painted steel_ambientOcclusion - - first: - 28: 2800008 - second: Painted steel_height - - first: - 33: 3300000 - second: metal_painted_steel/metal_painted_steel/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_painted_steel/metal_painted_steel/SphereCollider - - first: - 1001: 100100000 - second: metal_painted_steel - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Painted steel - prototypeName: Painted steel - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_painted_steel\" label=\"\" >\n <presetinput - identifier=\"$outputsize\" uid=\"326965559\" type=\"8\" value=\"10,10\" />\n - <presetinput identifier=\"$randomseed\" uid=\"1141837669\" type=\"4\" value=\"6025\" - />\n <presetinput identifier=\"scratches\" uid=\"1855038369\" type=\"0\" value=\"1\" - />\n <presetinput identifier=\"rust\" uid=\"1776436197\" type=\"0\" value=\"0.29\" - />\n <presetinput identifier=\"paint_color\" uid=\"1770592093\" type=\"2\" - value=\"1,0.583333,0\" />\n <presetinput identifier=\"paint_roughness\" uid=\"1855031964\" - type=\"0\" value=\"0.18\" />\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -812895718602229137, guid: b7e648471e9dfc44490bd41973711541, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 4387638379454744182, guid: b7e648471e9dfc44490bd41973711541, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 5280895355680202213, guid: b7e648471e9dfc44490bd41973711541, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 1053975553097811288, guid: b7e648471e9dfc44490bd41973711541, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -5932748352949090903, guid: b7e648471e9dfc44490bd41973711541, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Painted steel_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Painted steel - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 1024 - textureHeight: 1024 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -4658142721435264040, guid: b7e648471e9dfc44490bd41973711541, - type: 3} - generatedTextures: - - {fileID: 4387638379454744182, guid: b7e648471e9dfc44490bd41973711541, type: 3} - - {fileID: -812895718602229137, guid: b7e648471e9dfc44490bd41973711541, type: 3} - - {fileID: 5280895355680202213, guid: b7e648471e9dfc44490bd41973711541, type: 3} - - {fileID: 1053975553097811288, guid: b7e648471e9dfc44490bd41973711541, type: 3} - - {fileID: -5932748352949090903, guid: b7e648471e9dfc44490bd41973711541, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_panels_001.sbsar b/Assets/Materials/Substance/Metal/metal_panels_001.sbsar deleted file mode 100644 index 2ee3b87ea..000000000 --- a/Assets/Materials/Substance/Metal/metal_panels_001.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e868f72fde8e3c55a2d8c097ebb39c05157670897d14eeb86932021feec16158 -size 11295 diff --git a/Assets/Materials/Substance/Metal/metal_panels_001.sbsar.meta b/Assets/Materials/Substance/Metal/metal_panels_001.sbsar.meta deleted file mode 100644 index a423b3b51..000000000 --- a/Assets/Materials/Substance/Metal/metal_panels_001.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 7363fcc4a3c41a349b29de7ec34555be -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_panels_001/metal_panels_001 - - first: - 4: 400000 - second: metal_panels_001/metal_panels_001/Transform - - first: - 21: 2100000 - second: mat.Metal Panels 001 - - first: - 23: 2300000 - second: metal_panels_001/metal_panels_001/MeshRenderer - - first: - 28: 2800000 - second: Metal Panels 001_baseColor - - first: - 28: 2800002 - second: Metal Panels 001_normal - - first: - 28: 2800004 - second: Metal Panels 001_metallic - - first: - 28: 2800006 - second: Metal Panels 001_ambientOcclusion - - first: - 28: 2800008 - second: Metal Panels 001_height - - first: - 33: 3300000 - second: metal_panels_001/metal_panels_001/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_panels_001/metal_panels_001/SphereCollider - - first: - 1001: 100100000 - second: metal_panels_001 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal Panels 001 - prototypeName: Metal Panels 001 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_panels_001\" label=\"\" >\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 2945532018097518028, guid: 7363fcc4a3c41a349b29de7ec34555be, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 6344665451385196243, guid: 7363fcc4a3c41a349b29de7ec34555be, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -103584793617860315, guid: 7363fcc4a3c41a349b29de7ec34555be, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -2941359408041138506, guid: 7363fcc4a3c41a349b29de7ec34555be, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 1361220934952870948, guid: 7363fcc4a3c41a349b29de7ec34555be, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal Panels 001_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 001 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 1523472303362493764, guid: 7363fcc4a3c41a349b29de7ec34555be, - type: 3} - generatedTextures: - - {fileID: 6344665451385196243, guid: 7363fcc4a3c41a349b29de7ec34555be, type: 3} - - {fileID: 2945532018097518028, guid: 7363fcc4a3c41a349b29de7ec34555be, type: 3} - - {fileID: -103584793617860315, guid: 7363fcc4a3c41a349b29de7ec34555be, type: 3} - - {fileID: -2941359408041138506, guid: 7363fcc4a3c41a349b29de7ec34555be, type: 3} - - {fileID: 1361220934952870948, guid: 7363fcc4a3c41a349b29de7ec34555be, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_panels_002.sbsar b/Assets/Materials/Substance/Metal/metal_panels_002.sbsar deleted file mode 100644 index 2cf3cd0b5..000000000 --- a/Assets/Materials/Substance/Metal/metal_panels_002.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b16e09a1b06ae6b857d9f9478af0838a31ba554a2455b9e65e9db43a125ce633 -size 7592 diff --git a/Assets/Materials/Substance/Metal/metal_panels_002.sbsar.meta b/Assets/Materials/Substance/Metal/metal_panels_002.sbsar.meta deleted file mode 100644 index fe8ecd2b6..000000000 --- a/Assets/Materials/Substance/Metal/metal_panels_002.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 2e9a9dbacde66a446852af882f33e9e2 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_panels_002/metal_panels_002 - - first: - 4: 400000 - second: metal_panels_002/metal_panels_002/Transform - - first: - 21: 2100000 - second: mat.Metal Panels 002 - - first: - 23: 2300000 - second: metal_panels_002/metal_panels_002/MeshRenderer - - first: - 28: 2800000 - second: Metal Panels 002_baseColor - - first: - 28: 2800002 - second: Metal Panels 002_normal - - first: - 28: 2800004 - second: Metal Panels 002_metallic - - first: - 28: 2800006 - second: Metal Panels 002_ambientOcclusion - - first: - 28: 2800008 - second: Metal Panels 002_height - - first: - 33: 3300000 - second: metal_panels_002/metal_panels_002/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_panels_002/metal_panels_002/SphereCollider - - first: - 1001: 100100000 - second: metal_panels_002 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal Panels 002 - prototypeName: Metal Panels 002 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_panels_002\" label=\"\" >\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -7157783387845257801, guid: 2e9a9dbacde66a446852af882f33e9e2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 6030008930922367719, guid: 2e9a9dbacde66a446852af882f33e9e2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -5177487458041023939, guid: 2e9a9dbacde66a446852af882f33e9e2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -6221273311826804186, guid: 2e9a9dbacde66a446852af882f33e9e2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -2755774738339798629, guid: 2e9a9dbacde66a446852af882f33e9e2, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal Panels 002_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Panels 002 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 3282252981698000714, guid: 2e9a9dbacde66a446852af882f33e9e2, - type: 3} - generatedTextures: - - {fileID: 6030008930922367719, guid: 2e9a9dbacde66a446852af882f33e9e2, type: 3} - - {fileID: -7157783387845257801, guid: 2e9a9dbacde66a446852af882f33e9e2, type: 3} - - {fileID: -5177487458041023939, guid: 2e9a9dbacde66a446852af882f33e9e2, type: 3} - - {fileID: -6221273311826804186, guid: 2e9a9dbacde66a446852af882f33e9e2, type: 3} - - {fileID: -2755774738339798629, guid: 2e9a9dbacde66a446852af882f33e9e2, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_plate_001.sbsar b/Assets/Materials/Substance/Metal/metal_plate_001.sbsar deleted file mode 100644 index 3d06effb9..000000000 --- a/Assets/Materials/Substance/Metal/metal_plate_001.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7c9aea022bbc0138be51bb7b89314a569ad359390a0b8d1b6b2c717d317acd8b -size 10171 diff --git a/Assets/Materials/Substance/Metal/metal_plate_001.sbsar.meta b/Assets/Materials/Substance/Metal/metal_plate_001.sbsar.meta deleted file mode 100644 index 9a0327632..000000000 --- a/Assets/Materials/Substance/Metal/metal_plate_001.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 180b85899b4b1f848b348230339ce984 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_plate_001/metal_plate_001 - - first: - 4: 400000 - second: metal_plate_001/metal_plate_001/Transform - - first: - 21: 2100000 - second: mat.Metal plate 001 - - first: - 23: 2300000 - second: metal_plate_001/metal_plate_001/MeshRenderer - - first: - 28: 2800000 - second: Metal plate 001_baseColor - - first: - 28: 2800002 - second: Metal plate 001_normal - - first: - 28: 2800004 - second: Metal plate 001_metallic - - first: - 28: 2800006 - second: Metal plate 001_ambientOcclusion - - first: - 28: 2800008 - second: Metal plate 001_height - - first: - 33: 3300000 - second: metal_plate_001/metal_plate_001/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_plate_001/metal_plate_001/SphereCollider - - first: - 1001: 100100000 - second: metal_plate_001 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal plate 001 - prototypeName: Metal plate 001 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_plate_001\" label=\"\" >\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 6805374924820727666, guid: 180b85899b4b1f848b348230339ce984, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 443512894100413061, guid: 180b85899b4b1f848b348230339ce984, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -3656363544911682969, guid: 180b85899b4b1f848b348230339ce984, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 6012193567810889268, guid: 180b85899b4b1f848b348230339ce984, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 1247009903862830065, guid: 180b85899b4b1f848b348230339ce984, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal plate 001_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 001 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -1468868417959000437, guid: 180b85899b4b1f848b348230339ce984, - type: 3} - generatedTextures: - - {fileID: 443512894100413061, guid: 180b85899b4b1f848b348230339ce984, type: 3} - - {fileID: 6805374924820727666, guid: 180b85899b4b1f848b348230339ce984, type: 3} - - {fileID: -3656363544911682969, guid: 180b85899b4b1f848b348230339ce984, type: 3} - - {fileID: 6012193567810889268, guid: 180b85899b4b1f848b348230339ce984, type: 3} - - {fileID: 1247009903862830065, guid: 180b85899b4b1f848b348230339ce984, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_plate_004.sbsar b/Assets/Materials/Substance/Metal/metal_plate_004.sbsar deleted file mode 100644 index dc0474e13..000000000 --- a/Assets/Materials/Substance/Metal/metal_plate_004.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:65295627150c30fc70fe138aee16c2266bffdd0a5b1fbcbe7fe040a3d0309d39 -size 14216 diff --git a/Assets/Materials/Substance/Metal/metal_plate_004.sbsar.meta b/Assets/Materials/Substance/Metal/metal_plate_004.sbsar.meta deleted file mode 100644 index fd4373932..000000000 --- a/Assets/Materials/Substance/Metal/metal_plate_004.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 0b5dfc86c0681a3459a57d197804191b -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_plate_004/metal_plate_004 - - first: - 4: 400000 - second: metal_plate_004/metal_plate_004/Transform - - first: - 21: 2100000 - second: mat.Metal plate 004 - - first: - 23: 2300000 - second: metal_plate_004/metal_plate_004/MeshRenderer - - first: - 28: 2800000 - second: Metal plate 004_baseColor - - first: - 28: 2800002 - second: Metal plate 004_normal - - first: - 28: 2800004 - second: Metal plate 004_metallic - - first: - 28: 2800006 - second: Metal plate 004_ambientOcclusion - - first: - 28: 2800008 - second: Metal plate 004_height - - first: - 33: 3300000 - second: metal_plate_004/metal_plate_004/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_plate_004/metal_plate_004/SphereCollider - - first: - 1001: 100100000 - second: metal_plate_004 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal plate 004 - prototypeName: Metal plate 004 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_plate_004\" label=\"\" >\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -7484568915117973449, guid: 0b5dfc86c0681a3459a57d197804191b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 1309396409266656355, guid: 0b5dfc86c0681a3459a57d197804191b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -5781884682247363129, guid: 0b5dfc86c0681a3459a57d197804191b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 5620992320681838871, guid: 0b5dfc86c0681a3459a57d197804191b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 6570316561944570698, guid: 0b5dfc86c0681a3459a57d197804191b, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal plate 004_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 004 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -5894754650268316995, guid: 0b5dfc86c0681a3459a57d197804191b, - type: 3} - generatedTextures: - - {fileID: 1309396409266656355, guid: 0b5dfc86c0681a3459a57d197804191b, type: 3} - - {fileID: -7484568915117973449, guid: 0b5dfc86c0681a3459a57d197804191b, type: 3} - - {fileID: -5781884682247363129, guid: 0b5dfc86c0681a3459a57d197804191b, type: 3} - - {fileID: 5620992320681838871, guid: 0b5dfc86c0681a3459a57d197804191b, type: 3} - - {fileID: 6570316561944570698, guid: 0b5dfc86c0681a3459a57d197804191b, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_plate_011.sbsar b/Assets/Materials/Substance/Metal/metal_plate_011.sbsar deleted file mode 100644 index c1e0a3922..000000000 --- a/Assets/Materials/Substance/Metal/metal_plate_011.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:829bc422cbe5b984103972cd7cf36d207fe0a6b561a2619301dec3e684009784 -size 9674 diff --git a/Assets/Materials/Substance/Metal/metal_plate_011.sbsar.meta b/Assets/Materials/Substance/Metal/metal_plate_011.sbsar.meta deleted file mode 100644 index 55c1cd50c..000000000 --- a/Assets/Materials/Substance/Metal/metal_plate_011.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: ca8f080ab60226e4097841eee2bfa8db -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_plate_011/metal_plate_011 - - first: - 4: 400000 - second: metal_plate_011/metal_plate_011/Transform - - first: - 21: 2100000 - second: mat.Metal plate 011 - - first: - 23: 2300000 - second: metal_plate_011/metal_plate_011/MeshRenderer - - first: - 28: 2800000 - second: Metal plate 011_baseColor - - first: - 28: 2800002 - second: Metal plate 011_normal - - first: - 28: 2800004 - second: Metal plate 011_metallic - - first: - 28: 2800006 - second: Metal plate 011_ambientOcclusion - - first: - 28: 2800008 - second: Metal plate 011_height - - first: - 33: 3300000 - second: metal_plate_011/metal_plate_011/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_plate_011/metal_plate_011/SphereCollider - - first: - 1001: 100100000 - second: metal_plate_011 - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal plate 011 - prototypeName: Metal plate 011 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_plate_011\" label=\"\" >\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 1206901763152500494, guid: ca8f080ab60226e4097841eee2bfa8db, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -562402163750398719, guid: ca8f080ab60226e4097841eee2bfa8db, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -8211546087015286653, guid: ca8f080ab60226e4097841eee2bfa8db, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 7355910353852850503, guid: ca8f080ab60226e4097841eee2bfa8db, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -2794334530799708578, guid: ca8f080ab60226e4097841eee2bfa8db, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal plate 011_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal plate 011 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 5028268363422298589, guid: ca8f080ab60226e4097841eee2bfa8db, - type: 3} - generatedTextures: - - {fileID: -562402163750398719, guid: ca8f080ab60226e4097841eee2bfa8db, type: 3} - - {fileID: 1206901763152500494, guid: ca8f080ab60226e4097841eee2bfa8db, type: 3} - - {fileID: -8211546087015286653, guid: ca8f080ab60226e4097841eee2bfa8db, type: 3} - - {fileID: 7355910353852850503, guid: ca8f080ab60226e4097841eee2bfa8db, type: 3} - - {fileID: -2794334530799708578, guid: ca8f080ab60226e4097841eee2bfa8db, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_platinum.sbsar b/Assets/Materials/Substance/Metal/metal_platinum.sbsar deleted file mode 100644 index ffaec19de..000000000 --- a/Assets/Materials/Substance/Metal/metal_platinum.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b880030baaf5ccc272c780265fc4b1570a55a63a8b804223ccbdc54a576b9be7 -size 5196 diff --git a/Assets/Materials/Substance/Metal/metal_platinum.sbsar.meta b/Assets/Materials/Substance/Metal/metal_platinum.sbsar.meta deleted file mode 100644 index f39efaf0d..000000000 --- a/Assets/Materials/Substance/Metal/metal_platinum.sbsar.meta +++ /dev/null @@ -1,372 +0,0 @@ -fileFormatVersion: 2 -guid: 9458f33b8e7e51a42aa19686b9779d82 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_platinum/metal_platinum - - first: - 4: 400000 - second: metal_platinum/metal_platinum/Transform - - first: - 21: 2100000 - second: mat.Platinum - - first: - 23: 2300000 - second: metal_platinum/metal_platinum/MeshRenderer - - first: - 28: 2800000 - second: Platinum_baseColor - - first: - 28: 2800002 - second: Platinum_normal - - first: - 28: 2800004 - second: Platinum_metallic - - first: - 28: 2800006 - second: Platinum_ambientOcclusion - - first: - 28: 2800008 - second: Platinum_height - - first: - 33: 3300000 - second: metal_platinum/metal_platinum/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_platinum/metal_platinum/SphereCollider - - first: - 1001: 100100000 - second: metal_platinum - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Platinum - prototypeName: Platinum - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_platinum\" label=\"\" >\n <presetinput - identifier=\"dirt\" uid=\"3294776141\" type=\"0\" value=\"0.43\" />\n <presetinput - identifier=\"surface_imperfections\" uid=\"3166060376\" type=\"0\" value=\"1\" - />\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 3498638986299907941, guid: 9458f33b8e7e51a42aa19686b9779d82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -8172963137857357993, guid: 9458f33b8e7e51a42aa19686b9779d82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -8040379993892829019, guid: 9458f33b8e7e51a42aa19686b9779d82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 225164955126363719, guid: 9458f33b8e7e51a42aa19686b9779d82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -130007606447889175, guid: 9458f33b8e7e51a42aa19686b9779d82, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Platinum_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Platinum - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 8636029498071112704, guid: 9458f33b8e7e51a42aa19686b9779d82, - type: 3} - generatedTextures: - - {fileID: -8172963137857357993, guid: 9458f33b8e7e51a42aa19686b9779d82, type: 3} - - {fileID: 3498638986299907941, guid: 9458f33b8e7e51a42aa19686b9779d82, type: 3} - - {fileID: -8040379993892829019, guid: 9458f33b8e7e51a42aa19686b9779d82, type: 3} - - {fileID: 225164955126363719, guid: 9458f33b8e7e51a42aa19686b9779d82, type: 3} - - {fileID: -130007606447889175, guid: 9458f33b8e7e51a42aa19686b9779d82, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_roll_up.sbsar b/Assets/Materials/Substance/Metal/metal_roll_up.sbsar deleted file mode 100644 index db99f183e..000000000 --- a/Assets/Materials/Substance/Metal/metal_roll_up.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1a2036e21cdd2d392fdcb755d2faf982335fc4deaa8c7b913110db234fa04f3a -size 11017 diff --git a/Assets/Materials/Substance/Metal/metal_roll_up.sbsar.meta b/Assets/Materials/Substance/Metal/metal_roll_up.sbsar.meta deleted file mode 100644 index 3d93351e8..000000000 --- a/Assets/Materials/Substance/Metal/metal_roll_up.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 4e39297ae4fe9ee4b803c04eabb69da7 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_roll_up/metal_roll_up - - first: - 4: 400000 - second: metal_roll_up/metal_roll_up/Transform - - first: - 21: 2100000 - second: mat.Metal roll up - - first: - 23: 2300000 - second: metal_roll_up/metal_roll_up/MeshRenderer - - first: - 28: 2800000 - second: Metal roll up_baseColor - - first: - 28: 2800002 - second: Metal roll up_normal - - first: - 28: 2800004 - second: Metal roll up_metallic - - first: - 28: 2800006 - second: Metal roll up_ambientOcclusion - - first: - 28: 2800008 - second: Metal roll up_height - - first: - 33: 3300000 - second: metal_roll_up/metal_roll_up/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_roll_up/metal_roll_up/SphereCollider - - first: - 1001: 100100000 - second: metal_roll_up - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal roll up - prototypeName: Metal roll up - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_roll_up\" label=\"\" >\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 1258325809611119299, guid: 4e39297ae4fe9ee4b803c04eabb69da7, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -5250987364813910665, guid: 4e39297ae4fe9ee4b803c04eabb69da7, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -1897870436205287166, guid: 4e39297ae4fe9ee4b803c04eabb69da7, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 7199963334284863655, guid: 4e39297ae4fe9ee4b803c04eabb69da7, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 1153539711168243343, guid: 4e39297ae4fe9ee4b803c04eabb69da7, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal roll up_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal roll up - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 7440086527666654772, guid: 4e39297ae4fe9ee4b803c04eabb69da7, - type: 3} - generatedTextures: - - {fileID: -5250987364813910665, guid: 4e39297ae4fe9ee4b803c04eabb69da7, type: 3} - - {fileID: 1258325809611119299, guid: 4e39297ae4fe9ee4b803c04eabb69da7, type: 3} - - {fileID: -1897870436205287166, guid: 4e39297ae4fe9ee4b803c04eabb69da7, type: 3} - - {fileID: 7199963334284863655, guid: 4e39297ae4fe9ee4b803c04eabb69da7, type: 3} - - {fileID: 1153539711168243343, guid: 4e39297ae4fe9ee4b803c04eabb69da7, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_silver.sbsar b/Assets/Materials/Substance/Metal/metal_silver.sbsar deleted file mode 100644 index 08b0ac146..000000000 --- a/Assets/Materials/Substance/Metal/metal_silver.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4b18ce39a69d5e25641d53fcbe04f281c92ca7e01936e6a9b279476be8ff3255 -size 6898 diff --git a/Assets/Materials/Substance/Metal/metal_silver.sbsar.meta b/Assets/Materials/Substance/Metal/metal_silver.sbsar.meta deleted file mode 100644 index 326559316..000000000 --- a/Assets/Materials/Substance/Metal/metal_silver.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 0be5fb1df83ac8e499a3f6a060041e49 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_silver/metal_silver - - first: - 4: 400000 - second: metal_silver/metal_silver/Transform - - first: - 21: 2100000 - second: mat.Silver - - first: - 23: 2300000 - second: metal_silver/metal_silver/MeshRenderer - - first: - 28: 2800000 - second: Silver_baseColor - - first: - 28: 2800002 - second: Silver_normal - - first: - 28: 2800004 - second: Silver_metallic - - first: - 28: 2800006 - second: Silver_ambientOcclusion - - first: - 28: 2800008 - second: Silver_height - - first: - 33: 3300000 - second: metal_silver/metal_silver/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_silver/metal_silver/SphereCollider - - first: - 1001: 100100000 - second: metal_silver - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Silver - prototypeName: Silver - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_silver\" label=\"\" >\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 8947980237086559854, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -1383037052668628532, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 6429125567479694453, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -9097439929179392311, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 425190381137097012, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Silver_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Silver - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 7490952440742008943, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} - generatedTextures: - - {fileID: -1383037052668628532, guid: 0be5fb1df83ac8e499a3f6a060041e49, type: 3} - - {fileID: 8947980237086559854, guid: 0be5fb1df83ac8e499a3f6a060041e49, type: 3} - - {fileID: 6429125567479694453, guid: 0be5fb1df83ac8e499a3f6a060041e49, type: 3} - - {fileID: -9097439929179392311, guid: 0be5fb1df83ac8e499a3f6a060041e49, type: 3} - - {fileID: 425190381137097012, guid: 0be5fb1df83ac8e499a3f6a060041e49, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_steel.sbsar b/Assets/Materials/Substance/Metal/metal_steel.sbsar deleted file mode 100644 index 31ec34fd3..000000000 --- a/Assets/Materials/Substance/Metal/metal_steel.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d559edac51ad4c529c197d7c9a813fe8c2fa1bcb0963cd0f8bad8ab1403b3821 -size 10697 diff --git a/Assets/Materials/Substance/Metal/metal_steel.sbsar.meta b/Assets/Materials/Substance/Metal/metal_steel.sbsar.meta deleted file mode 100644 index 172d4668b..000000000 --- a/Assets/Materials/Substance/Metal/metal_steel.sbsar.meta +++ /dev/null @@ -1,375 +0,0 @@ -fileFormatVersion: 2 -guid: cbc61995a46604441ab9de4f1c68e290 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_steel/metal_steel - - first: - 4: 400000 - second: metal_steel/metal_steel/Transform - - first: - 21: 2100000 - second: mat.Steel - - first: - 23: 2300000 - second: metal_steel/metal_steel/MeshRenderer - - first: - 28: 2800000 - second: Steel_baseColor - - first: - 28: 2800002 - second: Steel_normal - - first: - 28: 2800004 - second: Steel_metallic - - first: - 28: 2800006 - second: Steel_ambientOcclusion - - first: - 28: 2800008 - second: Steel_height - - first: - 33: 3300000 - second: metal_steel/metal_steel/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_steel/metal_steel/SphereCollider - - first: - 1001: 100100000 - second: metal_steel - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Steel - prototypeName: Steel - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_steel\" label=\"\" >\n <presetinput - identifier=\"$outputsize\" uid=\"1318093408\" type=\"8\" value=\"9,9\" />\n - <presetinput identifier=\"dirt\" uid=\"854373931\" type=\"0\" value=\"0.903\" - />\n <presetinput identifier=\"rust\" uid=\"854346221\" type=\"0\" value=\"0\" - />\n <presetinput identifier=\"surface_imperfections\" uid=\"863227179\" type=\"0\" - value=\"0.413\" />\n <presetinput identifier=\"steel_roughness\" uid=\"863268384\" - type=\"0\" value=\"0.292\" />\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -3888315358723833787, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 4, y: 4} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 108215966750249586, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - scale: {x: 4, y: 4} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 4793252353645218242, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -4384182597330533215, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 4600200897981803784, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Steel_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 512 - textureHeight: 512 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -3155047780354543793, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - generatedTextures: - - {fileID: 108215966750249586, guid: cbc61995a46604441ab9de4f1c68e290, type: 3} - - {fileID: -3888315358723833787, guid: cbc61995a46604441ab9de4f1c68e290, type: 3} - - {fileID: 4793252353645218242, guid: cbc61995a46604441ab9de4f1c68e290, type: 3} - - {fileID: -4384182597330533215, guid: cbc61995a46604441ab9de4f1c68e290, type: 3} - - {fileID: 4600200897981803784, guid: cbc61995a46604441ab9de4f1c68e290, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_steel_brushed.sbsar b/Assets/Materials/Substance/Metal/metal_steel_brushed.sbsar deleted file mode 100644 index 45c0b10b3..000000000 --- a/Assets/Materials/Substance/Metal/metal_steel_brushed.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:bf6b40453b42e050b2ce05478f1c1964d9489cdf02413f12b40f4ce1e49b4432 -size 12832 diff --git a/Assets/Materials/Substance/Metal/metal_steel_brushed.sbsar.meta b/Assets/Materials/Substance/Metal/metal_steel_brushed.sbsar.meta deleted file mode 100644 index d08c0d290..000000000 --- a/Assets/Materials/Substance/Metal/metal_steel_brushed.sbsar.meta +++ /dev/null @@ -1,370 +0,0 @@ -fileFormatVersion: 2 -guid: ea7457b9a4f0bcb43becaa33de541cbd -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_steel_brushed/metal_steel_brushed - - first: - 4: 400000 - second: metal_steel_brushed/metal_steel_brushed/Transform - - first: - 21: 2100000 - second: mat.Steel brushed - - first: - 23: 2300000 - second: metal_steel_brushed/metal_steel_brushed/MeshRenderer - - first: - 28: 2800000 - second: Steel brushed_baseColor - - first: - 28: 2800002 - second: Steel brushed_normal - - first: - 28: 2800004 - second: Steel brushed_metallic - - first: - 28: 2800006 - second: Steel brushed_ambientOcclusion - - first: - 28: 2800008 - second: Steel brushed_height - - first: - 33: 3300000 - second: metal_steel_brushed/metal_steel_brushed/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_steel_brushed/metal_steel_brushed/SphereCollider - - first: - 1001: 100100000 - second: metal_steel_brushed - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Steel brushed - prototypeName: Steel brushed - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_steel_brushed\" label=\"\" >\n <presetinput - identifier=\"oxidation\" uid=\"44192965\" type=\"0\" value=\"0.8\" />\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -4471413742775304797, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -4638397344074346932, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 5049811794194361025, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 1753668427856518731, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -3498708498072814504, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Steel brushed_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel brushed - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 7852708265981260911, guid: ea7457b9a4f0bcb43becaa33de541cbd, - type: 3} - generatedTextures: - - {fileID: -4638397344074346932, guid: ea7457b9a4f0bcb43becaa33de541cbd, type: 3} - - {fileID: -4471413742775304797, guid: ea7457b9a4f0bcb43becaa33de541cbd, type: 3} - - {fileID: 5049811794194361025, guid: ea7457b9a4f0bcb43becaa33de541cbd, type: 3} - - {fileID: 1753668427856518731, guid: ea7457b9a4f0bcb43becaa33de541cbd, type: 3} - - {fileID: -3498708498072814504, guid: ea7457b9a4f0bcb43becaa33de541cbd, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_steel_bumped.sbsar b/Assets/Materials/Substance/Metal/metal_steel_bumped.sbsar deleted file mode 100644 index 6580295bb..000000000 --- a/Assets/Materials/Substance/Metal/metal_steel_bumped.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a9ae449451a55abd8466e8af67685a45d86fd39ea2070294dde7f2a07776bea5 -size 17275 diff --git a/Assets/Materials/Substance/Metal/metal_steel_bumped.sbsar.meta b/Assets/Materials/Substance/Metal/metal_steel_bumped.sbsar.meta deleted file mode 100644 index 1dd652796..000000000 --- a/Assets/Materials/Substance/Metal/metal_steel_bumped.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 092bdd8d243488141aeab5bb0d72429a -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_steel_bumped/metal_steel_bumped - - first: - 4: 400000 - second: metal_steel_bumped/metal_steel_bumped/Transform - - first: - 21: 2100000 - second: mat.Steel bumped - - first: - 23: 2300000 - second: metal_steel_bumped/metal_steel_bumped/MeshRenderer - - first: - 28: 2800000 - second: Steel bumped_baseColor - - first: - 28: 2800002 - second: Steel bumped_normal - - first: - 28: 2800004 - second: Steel bumped_metallic - - first: - 28: 2800006 - second: Steel bumped_ambientOcclusion - - first: - 28: 2800008 - second: Steel bumped_height - - first: - 33: 3300000 - second: metal_steel_bumped/metal_steel_bumped/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_steel_bumped/metal_steel_bumped/SphereCollider - - first: - 1001: 100100000 - second: metal_steel_bumped - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Steel bumped - prototypeName: Steel bumped - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_steel_bumped\" label=\"\" >\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 3586080781697202320, guid: 092bdd8d243488141aeab5bb0d72429a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 86365302875955127, guid: 092bdd8d243488141aeab5bb0d72429a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 9208498935135840223, guid: 092bdd8d243488141aeab5bb0d72429a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 7740971908710523460, guid: 092bdd8d243488141aeab5bb0d72429a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 6493472383464308858, guid: 092bdd8d243488141aeab5bb0d72429a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Steel bumped_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel bumped - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -864409875390858066, guid: 092bdd8d243488141aeab5bb0d72429a, - type: 3} - generatedTextures: - - {fileID: 86365302875955127, guid: 092bdd8d243488141aeab5bb0d72429a, type: 3} - - {fileID: 3586080781697202320, guid: 092bdd8d243488141aeab5bb0d72429a, type: 3} - - {fileID: 9208498935135840223, guid: 092bdd8d243488141aeab5bb0d72429a, type: 3} - - {fileID: 7740971908710523460, guid: 092bdd8d243488141aeab5bb0d72429a, type: 3} - - {fileID: 6493472383464308858, guid: 092bdd8d243488141aeab5bb0d72429a, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_steel_parkerized.sbsar b/Assets/Materials/Substance/Metal/metal_steel_parkerized.sbsar deleted file mode 100644 index 92bee293c..000000000 --- a/Assets/Materials/Substance/Metal/metal_steel_parkerized.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:54993a1aae47acf7e1aba24812f215e1787969016dd1f420899ab363342a7b6d -size 9206 diff --git a/Assets/Materials/Substance/Metal/metal_steel_parkerized.sbsar.meta b/Assets/Materials/Substance/Metal/metal_steel_parkerized.sbsar.meta deleted file mode 100644 index a7cabf9ff..000000000 --- a/Assets/Materials/Substance/Metal/metal_steel_parkerized.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: e7758cad28ae98f478940e55222419a6 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_steel_parkerized/metal_steel_parkerized - - first: - 4: 400000 - second: metal_steel_parkerized/metal_steel_parkerized/Transform - - first: - 21: 2100000 - second: mat.Steel parkerized - - first: - 23: 2300000 - second: metal_steel_parkerized/metal_steel_parkerized/MeshRenderer - - first: - 28: 2800000 - second: Steel parkerized_baseColor - - first: - 28: 2800002 - second: Steel parkerized_normal - - first: - 28: 2800004 - second: Steel parkerized_metallic - - first: - 28: 2800006 - second: Steel parkerized_ambientOcclusion - - first: - 28: 2800008 - second: Steel parkerized_height - - first: - 33: 3300000 - second: metal_steel_parkerized/metal_steel_parkerized/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_steel_parkerized/metal_steel_parkerized/SphereCollider - - first: - 1001: 100100000 - second: metal_steel_parkerized - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Steel parkerized - prototypeName: Steel parkerized - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_steel_parkerized\" label=\"\" >\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 885599758852769373, guid: e7758cad28ae98f478940e55222419a6, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -4474525002722929857, guid: e7758cad28ae98f478940e55222419a6, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -2334804936223627746, guid: e7758cad28ae98f478940e55222419a6, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: -8380876848358870972, guid: e7758cad28ae98f478940e55222419a6, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 172713863077875830, guid: e7758cad28ae98f478940e55222419a6, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Steel parkerized_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Steel parkerized - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -6026401407715332296, guid: e7758cad28ae98f478940e55222419a6, - type: 3} - generatedTextures: - - {fileID: -4474525002722929857, guid: e7758cad28ae98f478940e55222419a6, type: 3} - - {fileID: 885599758852769373, guid: e7758cad28ae98f478940e55222419a6, type: 3} - - {fileID: -2334804936223627746, guid: e7758cad28ae98f478940e55222419a6, type: 3} - - {fileID: -8380876848358870972, guid: e7758cad28ae98f478940e55222419a6, type: 3} - - {fileID: 172713863077875830, guid: e7758cad28ae98f478940e55222419a6, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_titanium.sbsar b/Assets/Materials/Substance/Metal/metal_titanium.sbsar deleted file mode 100644 index ede9cde4d..000000000 --- a/Assets/Materials/Substance/Metal/metal_titanium.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e3aabfbcb813fef9ef20793d54c93bf5c37255573bb8ad043620f60041acd6d1 -size 5206 diff --git a/Assets/Materials/Substance/Metal/metal_titanium.sbsar.meta b/Assets/Materials/Substance/Metal/metal_titanium.sbsar.meta deleted file mode 100644 index e4ece6915..000000000 --- a/Assets/Materials/Substance/Metal/metal_titanium.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: 58e16b7dbc1c31f4585e11544cdce127 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_titanium/metal_titanium - - first: - 4: 400000 - second: metal_titanium/metal_titanium/Transform - - first: - 21: 2100000 - second: mat.Titanium - - first: - 23: 2300000 - second: metal_titanium/metal_titanium/MeshRenderer - - first: - 28: 2800000 - second: Titanium_baseColor - - first: - 28: 2800002 - second: Titanium_normal - - first: - 28: 2800004 - second: Titanium_metallic - - first: - 28: 2800006 - second: Titanium_ambientOcclusion - - first: - 28: 2800008 - second: Titanium_height - - first: - 33: 3300000 - second: metal_titanium/metal_titanium/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_titanium/metal_titanium/SphereCollider - - first: - 1001: 100100000 - second: metal_titanium - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Titanium - prototypeName: Titanium - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_titanium\" label=\"\" >\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -5074057273227030627, guid: 58e16b7dbc1c31f4585e11544cdce127, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 3009319823116150993, guid: 58e16b7dbc1c31f4585e11544cdce127, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 3613456606582262254, guid: 58e16b7dbc1c31f4585e11544cdce127, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 7558371940554398246, guid: 58e16b7dbc1c31f4585e11544cdce127, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -3774795931012705877, guid: 58e16b7dbc1c31f4585e11544cdce127, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Titanium_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Titanium - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: 9178725544925813344, guid: 58e16b7dbc1c31f4585e11544cdce127, - type: 3} - generatedTextures: - - {fileID: 3009319823116150993, guid: 58e16b7dbc1c31f4585e11544cdce127, type: 3} - - {fileID: -5074057273227030627, guid: 58e16b7dbc1c31f4585e11544cdce127, type: 3} - - {fileID: 3613456606582262254, guid: 58e16b7dbc1c31f4585e11544cdce127, type: 3} - - {fileID: 7558371940554398246, guid: 58e16b7dbc1c31f4585e11544cdce127, type: 3} - - {fileID: -3774795931012705877, guid: 58e16b7dbc1c31f4585e11544cdce127, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_used.sbsar b/Assets/Materials/Substance/Metal/metal_used.sbsar deleted file mode 100644 index 5a8b87d9c..000000000 --- a/Assets/Materials/Substance/Metal/metal_used.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:03b72a9708206dd2c10aba185b507def52bbbcb713666711ed5d67926fbedd68 -size 14332 diff --git a/Assets/Materials/Substance/Metal/metal_used.sbsar.meta b/Assets/Materials/Substance/Metal/metal_used.sbsar.meta deleted file mode 100644 index 37fcc6a20..000000000 --- a/Assets/Materials/Substance/Metal/metal_used.sbsar.meta +++ /dev/null @@ -1,371 +0,0 @@ -fileFormatVersion: 2 -guid: 130f566ffa0b2424fbb47de2194c136a -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_used/metal_used - - first: - 4: 400000 - second: metal_used/metal_used/Transform - - first: - 21: 2100000 - second: mat.Metal used - - first: - 23: 2300000 - second: metal_used/metal_used/MeshRenderer - - first: - 28: 2800000 - second: Metal used_baseColor - - first: - 28: 2800002 - second: Metal used_normal - - first: - 28: 2800004 - second: Metal used_metallic - - first: - 28: 2800006 - second: Metal used_ambientOcclusion - - first: - 28: 2800008 - second: Metal used_height - - first: - 33: 3300000 - second: metal_used/metal_used/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_used/metal_used/SphereCollider - - first: - 1001: 100100000 - second: metal_used - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal used - prototypeName: Metal used - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_used\" label=\"\" >\n <presetinput - identifier=\"$outputsize\" uid=\"2490862535\" type=\"8\" value=\"9,9\" />\n - </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 8398852885706109728, guid: 130f566ffa0b2424fbb47de2194c136a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 8357651109123355072, guid: 130f566ffa0b2424fbb47de2194c136a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -435054815742279573, guid: 130f566ffa0b2424fbb47de2194c136a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 6248133906606842143, guid: 130f566ffa0b2424fbb47de2194c136a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 2780512161145013460, guid: 130f566ffa0b2424fbb47de2194c136a, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal used_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal used - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 512 - textureHeight: 512 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -890370705972978167, guid: 130f566ffa0b2424fbb47de2194c136a, - type: 3} - generatedTextures: - - {fileID: 8357651109123355072, guid: 130f566ffa0b2424fbb47de2194c136a, type: 3} - - {fileID: 8398852885706109728, guid: 130f566ffa0b2424fbb47de2194c136a, type: 3} - - {fileID: -435054815742279573, guid: 130f566ffa0b2424fbb47de2194c136a, type: 3} - - {fileID: 6248133906606842143, guid: 130f566ffa0b2424fbb47de2194c136a, type: 3} - - {fileID: 2780512161145013460, guid: 130f566ffa0b2424fbb47de2194c136a, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_weapon.sbsar b/Assets/Materials/Substance/Metal/metal_weapon.sbsar deleted file mode 100644 index d96236940..000000000 --- a/Assets/Materials/Substance/Metal/metal_weapon.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8e9033843201f75f1b86df82b69fd89ee6b9aa317df18f9105d0f8904d56be8f -size 10547 diff --git a/Assets/Materials/Substance/Metal/metal_weapon.sbsar.meta b/Assets/Materials/Substance/Metal/metal_weapon.sbsar.meta deleted file mode 100644 index 05d1fcf4b..000000000 --- a/Assets/Materials/Substance/Metal/metal_weapon.sbsar.meta +++ /dev/null @@ -1,373 +0,0 @@ -fileFormatVersion: 2 -guid: 07f679eadba9fb14abac26b1e165f7d5 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_weapon/metal_weapon - - first: - 4: 400000 - second: metal_weapon/metal_weapon/Transform - - first: - 21: 2100000 - second: mat.Metal Weapon - - first: - 23: 2300000 - second: metal_weapon/metal_weapon/MeshRenderer - - first: - 28: 2800000 - second: Metal Weapon_baseColor - - first: - 28: 2800002 - second: Metal Weapon_normal - - first: - 28: 2800004 - second: Metal Weapon_metallic - - first: - 28: 2800006 - second: Metal Weapon_ambientOcclusion - - first: - 28: 2800008 - second: Metal Weapon_height - - first: - 33: 3300000 - second: metal_weapon/metal_weapon/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_weapon/metal_weapon/SphereCollider - - first: - 1001: 100100000 - second: metal_weapon - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal Weapon - prototypeName: Metal Weapon - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_weapon\" label=\"\" >\n <presetinput - identifier=\"dirt\" uid=\"2667454443\" type=\"0\" value=\"0.46\" />\n <presetinput - identifier=\"scratches\" uid=\"3780562351\" type=\"0\" value=\"1\" />\n <presetinput - identifier=\"metal_roughness\" uid=\"3861636079\" type=\"0\" value=\"0.4\" - />\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: -6635831357954291190, guid: 07f679eadba9fb14abac26b1e165f7d5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -6402586014670071135, guid: 07f679eadba9fb14abac26b1e165f7d5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: 854616604008364032, guid: 07f679eadba9fb14abac26b1e165f7d5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 4606406952830974004, guid: 07f679eadba9fb14abac26b1e165f7d5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -5822151887330517421, guid: 07f679eadba9fb14abac26b1e165f7d5, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal Weapon_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal Weapon - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -6659110875122461561, guid: 07f679eadba9fb14abac26b1e165f7d5, - type: 3} - generatedTextures: - - {fileID: -6402586014670071135, guid: 07f679eadba9fb14abac26b1e165f7d5, type: 3} - - {fileID: -6635831357954291190, guid: 07f679eadba9fb14abac26b1e165f7d5, type: 3} - - {fileID: 854616604008364032, guid: 07f679eadba9fb14abac26b1e165f7d5, type: 3} - - {fileID: 4606406952830974004, guid: 07f679eadba9fb14abac26b1e165f7d5, type: 3} - - {fileID: -5822151887330517421, guid: 07f679eadba9fb14abac26b1e165f7d5, type: 3} diff --git a/Assets/Materials/Substance/Metal/metal_woven.sbsar b/Assets/Materials/Substance/Metal/metal_woven.sbsar deleted file mode 100644 index 576f8c4a5..000000000 --- a/Assets/Materials/Substance/Metal/metal_woven.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6c50e25516df1c3d2cb879d4e3e78491462296d92f05ac5774b6aa1290a777ee -size 9445 diff --git a/Assets/Materials/Substance/Metal/metal_woven.sbsar.meta b/Assets/Materials/Substance/Metal/metal_woven.sbsar.meta deleted file mode 100644 index 27d8bfafe..000000000 --- a/Assets/Materials/Substance/Metal/metal_woven.sbsar.meta +++ /dev/null @@ -1,369 +0,0 @@ -fileFormatVersion: 2 -guid: deb7e15e5f95294498d18869d9f11302 -ScriptedImporter: - internalIDToNameTable: - - first: - 1: 100000 - second: metal_woven/metal_woven - - first: - 4: 400000 - second: metal_woven/metal_woven/Transform - - first: - 21: 2100000 - second: mat.Metal woven - - first: - 23: 2300000 - second: metal_woven/metal_woven/MeshRenderer - - first: - 28: 2800000 - second: Metal woven_baseColor - - first: - 28: 2800002 - second: Metal woven_normal - - first: - 28: 2800004 - second: Metal woven_metallic - - first: - 28: 2800006 - second: Metal woven_ambientOcclusion - - first: - 28: 2800008 - second: Metal woven_height - - first: - 33: 3300000 - second: metal_woven/metal_woven/MeshFilter - - first: - 114: 11400000 - second: sbsar - - first: - 114: 11400002 - second: graph0 - - first: - 135: 13500000 - second: metal_woven/metal_woven/SphereCollider - - first: - 1001: 100100000 - second: metal_woven - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Metal woven - prototypeName: Metal woven - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://metal_woven\" label=\"\" >\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 549858149917880910, guid: deb7e15e5f95294498d18869d9f11302, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -5021036940690714266, guid: deb7e15e5f95294498d18869d9f11302, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -4741193760961545063, guid: deb7e15e5f95294498d18869d9f11302, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 4441773978818050154, guid: deb7e15e5f95294498d18869d9f11302, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: -8782013540898460330, guid: deb7e15e5f95294498d18869d9f11302, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Metal woven_glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven_diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven_baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven_normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven_specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven_roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven_metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven_ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven_height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Metal woven - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 256 - textureHeight: 256 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -1778075352807424672, guid: deb7e15e5f95294498d18869d9f11302, - type: 3} - generatedTextures: - - {fileID: -5021036940690714266, guid: deb7e15e5f95294498d18869d9f11302, type: 3} - - {fileID: 549858149917880910, guid: deb7e15e5f95294498d18869d9f11302, type: 3} - - {fileID: -4741193760961545063, guid: deb7e15e5f95294498d18869d9f11302, type: 3} - - {fileID: 4441773978818050154, guid: deb7e15e5f95294498d18869d9f11302, type: 3} - - {fileID: -8782013540898460330, guid: deb7e15e5f95294498d18869d9f11302, type: 3} diff --git a/Assets/Materials/Substance/Metal/snatched_metal.sbsar b/Assets/Materials/Substance/Metal/snatched_metal.sbsar deleted file mode 100644 index 35980ce5c..000000000 --- a/Assets/Materials/Substance/Metal/snatched_metal.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:556e67022b660530d0afc8296e37706b09e9ef08db46b5421edbd80f0c8993f2 -size 28573 diff --git a/Assets/Materials/Substance/Metal/snatched_metal.sbsar.meta b/Assets/Materials/Substance/Metal/snatched_metal.sbsar.meta deleted file mode 100644 index 3da7ab6e7..000000000 --- a/Assets/Materials/Substance/Metal/snatched_metal.sbsar.meta +++ /dev/null @@ -1,311 +0,0 @@ -fileFormatVersion: 2 -guid: 9aa51bbe4dd46874a906608c34a739e4 -ScriptedImporter: - internalIDToNameTable: [] - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Snatched Metal - prototypeName: Snatched Metal - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://snatched_metal\" label=\"\" >\n <presetinput - identifier=\"$outputsize\" uid=\"755928508\" type=\"8\" value=\"9,9\" />\n - </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 8651868829797956950, guid: 9aa51bbe4dd46874a906608c34a739e4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: 3043754869544600785, guid: 9aa51bbe4dd46874a906608c34a739e4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -8730703347107057792, guid: 9aa51bbe4dd46874a906608c34a739e4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 8639218750153593357, guid: 9aa51bbe4dd46874a906608c34a739e4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 8363912540366899318, guid: 9aa51bbe4dd46874a906608c34a739e4, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambientocclusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: opacity - identifier: opacity - usageName: opacity - channelStr: opacity - label: Opacity - usage: 2 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: opacity - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: opacity - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: opacity - components: - - sourceName: opacity - from: 0 - to: 3 - textureParameters: - - textureName: Snatched Metal - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Snatched Metal - opacity - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 512 - textureHeight: 512 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -2363654054484809406, guid: 9aa51bbe4dd46874a906608c34a739e4, - type: 3} - generatedTextures: - - {fileID: 3043754869544600785, guid: 9aa51bbe4dd46874a906608c34a739e4, type: 3} - - {fileID: 8651868829797956950, guid: 9aa51bbe4dd46874a906608c34a739e4, type: 3} - - {fileID: -8730703347107057792, guid: 9aa51bbe4dd46874a906608c34a739e4, type: 3} - - {fileID: 8363912540366899318, guid: 9aa51bbe4dd46874a906608c34a739e4, type: 3} - - {fileID: 8639218750153593357, guid: 9aa51bbe4dd46874a906608c34a739e4, type: 3} diff --git a/Assets/Materials/Substance/marble_002.sbsar b/Assets/Materials/Substance/marble_002.sbsar deleted file mode 100644 index 728270967..000000000 --- a/Assets/Materials/Substance/marble_002.sbsar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2859e24557bccbe309d8946052849b828cabd34b8e45b933faee212eeffd462e -size 8113 diff --git a/Assets/Materials/Substance/marble_002.sbsar.meta b/Assets/Materials/Substance/marble_002.sbsar.meta deleted file mode 100644 index 624e0d1a6..000000000 --- a/Assets/Materials/Substance/marble_002.sbsar.meta +++ /dev/null @@ -1,296 +0,0 @@ -fileFormatVersion: 2 -guid: ef9a54b8dacea9f44be70da43472f701 -ScriptedImporter: - internalIDToNameTable: [] - externalObjects: {} - serializedVersion: 2 - userData: - assetBundleName: - assetBundleVariant: - script: {fileID: 232528478, guid: 43a8bbf65be290d44ba52b94476242b9, type: 3} - version: 29 - projectContext: 0 - mGraphInstanceData: - - graphLabel: Marble 002 - prototypeName: Marble 002 - graphDescIndex: 0 - generateAllOutputs: 0 - generateMipMaps: 1 - preset: " <sbspreset pkgurl=\"pkg://marble_002\" label=\"\" >\n <presetinput - identifier=\"$outputsize\" uid=\"756697317\" type=\"8\" value=\"12,12\" />\n - <presetinput identifier=\"cracks_scale\" uid=\"1472628123\" type=\"4\" value=\"13\" - />\n <presetinput identifier=\"cracks_disorder\" uid=\"1472534721\" type=\"0\" - value=\"1\" />\n <presetinput identifier=\"marble_color\" uid=\"1472505596\" - type=\"2\" value=\"0.7,0.654348,0.525\" />\n </sbspreset>\n" - shaderName: Standard - materialProperties: - shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - shaderKeywords: - lightmapFlags: 4 - enableInstancingVariants: 0 - doubleSidedGI: 0 - customRenderQueue: -1 - texEnvs: - - name: _BumpMap - texture: {fileID: 5777664804669422655, guid: ef9a54b8dacea9f44be70da43472f701, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailAlbedoMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailMask - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _DetailNormalMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _EmissionMap - texture: {instanceID: 0} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MainTex - texture: {fileID: -5564000130503291907, guid: ef9a54b8dacea9f44be70da43472f701, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _MetallicGlossMap - texture: {fileID: -3258750942226492355, guid: ef9a54b8dacea9f44be70da43472f701, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _OcclusionMap - texture: {fileID: 4985089394248351555, guid: ef9a54b8dacea9f44be70da43472f701, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - - name: _ParallaxMap - texture: {fileID: 7116303992264550, guid: ef9a54b8dacea9f44be70da43472f701, - type: 3} - scale: {x: 1, y: 1} - offset: {x: 0, y: 0} - floats: - - name: _BumpScale - float: 1 - - name: _Cutoff - float: 0.5 - - name: _DetailNormalMapScale - float: 1 - - name: _DstBlend - float: 0 - - name: _GlossMapScale - float: 1 - - name: _Glossiness - float: 0.5 - - name: _GlossyReflections - float: 1 - - name: _Metallic - float: 0 - - name: _Mode - float: 0 - - name: _OcclusionStrength - float: 1 - - name: _Parallax - float: 0.02 - - name: _SmoothnessTextureChannel - float: 0 - - name: _SpecularHighlights - float: 1 - - name: _SrcBlend - float: 1 - - name: _UVSec - float: 0 - - name: _ZWrite - float: 1 - colors: - - name: _Color - color: {r: 1, g: 1, b: 1, a: 1} - - name: _EmissionColor - color: {r: 0, g: 0, b: 0, a: 1} - outputDescList: - - outputName: diffuse - identifier: diffuse - usageName: diffuse - channelStr: diffuse - label: Diffuse - usage: 0 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: baseColor - identifier: basecolor - usageName: baseColor - channelStr: baseColor - label: Base Color - usage: 1 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: normal - identifier: normal - usageName: normal - channelStr: normal - label: Normal - usage: 7 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: specular - identifier: specular - usageName: specular - channelStr: specular - label: Specular - usage: 11 - bImage: 1 - bNumerical: 0 - bLinear: 0 - - outputName: glossiness - identifier: glossiness - usageName: glossiness - channelStr: glossiness - label: Glossiness - usage: 14 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: roughness - identifier: roughness - usageName: roughness - channelStr: roughness - label: Roughness - usage: 15 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: metallic - identifier: metallic - usageName: metallic - channelStr: metallic - label: Metallic - usage: 34 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: ambientOcclusion - identifier: ambient_occlusion - usageName: ambientOcclusion - channelStr: ambientOcclusion - label: Ambient Occlusion - usage: 5 - bImage: 1 - bNumerical: 0 - bLinear: 1 - - outputName: height - identifier: height - usageName: height - channelStr: height - label: Height - usage: 9 - bImage: 1 - bNumerical: 0 - bLinear: 1 - texturePackingList: - - targetName: diffuse - components: - - sourceName: diffuse - from: 0 - to: 3 - - targetName: baseColor - components: - - sourceName: baseColor - from: 0 - to: 3 - - targetName: normal - components: - - sourceName: normal - from: 0 - to: 3 - - targetName: specular - components: - - sourceName: specular - from: 0 - to: 3 - - targetName: glossiness - components: - - sourceName: glossiness - from: 0 - to: 3 - - targetName: roughness - components: - - sourceName: roughness - from: 0 - to: 3 - - targetName: metallic - components: - - sourceName: smoothness - from: 0 - to: 3 - - targetName: ambientOcclusion - components: - - sourceName: ambientOcclusion - from: 0 - to: 3 - - targetName: height - components: - - sourceName: height - from: 0 - to: 3 - textureParameters: - - textureName: Marble 002 - diffuse - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Marble 002 - baseColor - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Marble 002 - normal - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Marble 002 - specular - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Marble 002 - glossiness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Marble 002 - roughness - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Marble 002 - metallic - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Marble 002 - ambientOcclusion - wrapMode: 0 - filterMode: 1 - aniso: 1 - - textureName: Marble 002 - height - wrapMode: 0 - filterMode: 1 - aniso: 1 - colorSpaceList: [] - inputTextureMap: [] - targetSettingList: - - label: Default - bOverride: 0 - bLockRatio: 1 - textureWidth: 4096 - textureHeight: 4096 - textureFormatMode: 0 - normalCompressed: 0 - bGenerateOnLoad: 1 - material: {fileID: -4681939019719023292, guid: ef9a54b8dacea9f44be70da43472f701, - type: 3} - generatedTextures: - - {fileID: -5564000130503291907, guid: ef9a54b8dacea9f44be70da43472f701, type: 3} - - {fileID: 5777664804669422655, guid: ef9a54b8dacea9f44be70da43472f701, type: 3} - - {fileID: -3258750942226492355, guid: ef9a54b8dacea9f44be70da43472f701, type: 3} - - {fileID: 4985089394248351555, guid: ef9a54b8dacea9f44be70da43472f701, type: 3} - - {fileID: 7116303992264550, guid: ef9a54b8dacea9f44be70da43472f701, type: 3} diff --git a/Assets/Materials/Thrusters.mat b/Assets/Materials/Thrusters.mat deleted file mode 100644 index f9b21ae83..000000000 --- a/Assets/Materials/Thrusters.mat +++ /dev/null @@ -1,87 +0,0 @@ -%YAML 1.1 -%TAG !u! tag:unity3d.com,2011: ---- !u!21 &2100000 -Material: - serializedVersion: 6 - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_Name: Thrusters - m_Shader: {fileID: 4800000, guid: d69ef48273708ef4680762f5cdcfc860, type: 3} - m_ShaderKeywords: - m_LightmapFlags: 4 - m_EnableInstancingVariants: 0 - m_DoubleSidedGI: 0 - m_CustomRenderQueue: -1 - stringTagMap: {} - disabledShaderPasses: [] - m_SavedProperties: - serializedVersion: 3 - m_TexEnvs: - - _BumpMap: - m_Texture: {fileID: -812895718602229137, guid: b7e648471e9dfc44490bd41973711541, - type: 3} - m_Scale: {x: 8, y: 8} - m_Offset: {x: 0, y: 0} - - _DetailAlbedoMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailMask: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailNormalMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _EmissionMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _MainTex: - m_Texture: {fileID: -6057190860509678031, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - m_Scale: {x: 8, y: 8} - m_Offset: {x: 0, y: 0} - - _MetallicGlossMap: - m_Texture: {fileID: -894214952450941493, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _OcclusionMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _ParallaxMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - m_Floats: - - _BumpPower: 2 - - _BumpScale: 1 - - _Cutoff: 0.5 - - _DetailNormalMapScale: 1 - - _DstBlend: 0 - - _Emission: 0 - - _EmissionFresnel: 1 - - _EmissionRoughnessFresnelPower: 0.5 - - _GlossMapScale: 1 - - _Glossiness: 1 - - _GlossyReflections: 1 - - _Metallic: 0 - - _Mode: 0 - - _OcclusionStrength: 1 - - _Parallax: 0.02 - - _ReverseRim: 0 - - _Rotation: 0 - - _SmoothnessTextureChannel: 0 - - _SpecularHighlights: 1 - - _SrcBlend: 1 - - _UVSec: 0 - - _ZWrite: 1 - m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} - - _EmissionColor: {r: 0.7112653, g: 0.4292453, b: 1, a: 1} - m_BuildTextureStacks: [] diff --git a/Assets/Materials/Thrusters.mat.meta b/Assets/Materials/Thrusters.mat.meta deleted file mode 100644 index 5fd79a1be..000000000 --- a/Assets/Materials/Thrusters.mat.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 616adaf59c64a444f8249cc7cf13c527 -NativeFormatImporter: - externalObjects: {} - mainObjectFileID: 0 - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Models/Discobolus/Discobolus Bronze.mat b/Assets/Models/Discobolus/Discobolus Bronze.mat deleted file mode 100644 index 30697d42a..000000000 --- a/Assets/Models/Discobolus/Discobolus Bronze.mat +++ /dev/null @@ -1,80 +0,0 @@ -%YAML 1.1 -%TAG !u! tag:unity3d.com,2011: ---- !u!21 &2100000 -Material: - serializedVersion: 6 - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_Name: Discobolus Bronze - m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - m_ShaderKeywords: _METALLICGLOSSMAP _NORMALMAP - m_LightmapFlags: 4 - m_EnableInstancingVariants: 0 - m_DoubleSidedGI: 0 - m_CustomRenderQueue: -1 - stringTagMap: {} - disabledShaderPasses: [] - m_SavedProperties: - serializedVersion: 3 - m_TexEnvs: - - _BumpMap: - m_Texture: {fileID: 2800000, guid: 9863db663524d9a4eab030a666b1f2da, type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailAlbedoMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailMask: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailNormalMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _EmissionMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _MainTex: - m_Texture: {fileID: -1863473678134789185, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _MetallicGlossMap: - m_Texture: {fileID: 6214616473909614744, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _OcclusionMap: - m_Texture: {fileID: 2800000, guid: d60207b632e464d4b884dded41db5b9b, type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _ParallaxMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - m_Floats: - - _BumpScale: 1 - - _Cutoff: 0.5 - - _DetailNormalMapScale: 1 - - _DstBlend: 0 - - _GlossMapScale: 1 - - _Glossiness: 0.5 - - _GlossyReflections: 1 - - _Metallic: 0 - - _Mode: 0 - - _OcclusionStrength: 1 - - _Parallax: 0.005 - - _SmoothnessTextureChannel: 0 - - _SpecularHighlights: 1 - - _SrcBlend: 1 - - _UVSec: 0 - - _ZWrite: 1 - m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} - - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} - m_BuildTextureStacks: [] diff --git a/Assets/Models/Discobolus/Discobolus Bronze.mat.meta b/Assets/Models/Discobolus/Discobolus Bronze.mat.meta deleted file mode 100644 index 4ca3a3b46..000000000 --- a/Assets/Models/Discobolus/Discobolus Bronze.mat.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 45f1ac126982c314a8471da3d264210b -NativeFormatImporter: - externalObjects: {} - mainObjectFileID: 2100000 - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Steel.mat b/Assets/Steel.mat deleted file mode 100644 index fc4d8d0ca..000000000 --- a/Assets/Steel.mat +++ /dev/null @@ -1,83 +0,0 @@ -%YAML 1.1 -%TAG !u! tag:unity3d.com,2011: ---- !u!21 &2100000 -Material: - serializedVersion: 6 - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_Name: Steel - m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0} - m_ShaderKeywords: _MAINTEX _METALLICGLOSSMAP _NORMALMAP _OCCLUSIONMAP _PARALLAXMAP - m_LightmapFlags: 4 - m_EnableInstancingVariants: 0 - m_DoubleSidedGI: 0 - m_CustomRenderQueue: -1 - stringTagMap: {} - disabledShaderPasses: [] - m_SavedProperties: - serializedVersion: 3 - m_TexEnvs: - - _BumpMap: - m_Texture: {fileID: -3888315358723833787, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailAlbedoMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailMask: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _DetailNormalMap: - m_Texture: {fileID: 0} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _EmissionMap: - m_Texture: {fileID: 0} - m_Scale: {x: 4, y: 4} - m_Offset: {x: 0, y: 0} - - _MainTex: - m_Texture: {fileID: 108215966750249586, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - m_Scale: {x: 4, y: 4} - m_Offset: {x: 0, y: 0} - - _MetallicGlossMap: - m_Texture: {fileID: 4793252353645218242, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _OcclusionMap: - m_Texture: {fileID: -4384182597330533215, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - - _ParallaxMap: - m_Texture: {fileID: 4600200897981803784, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} - m_Scale: {x: 1, y: 1} - m_Offset: {x: 0, y: 0} - m_Floats: - - _BumpScale: 1 - - _Cutoff: 0.5 - - _DetailNormalMapScale: 1 - - _DstBlend: 0 - - _GlossMapScale: 1 - - _Glossiness: 0.5 - - _GlossyReflections: 1 - - _Metallic: 0 - - _Mode: 0 - - _OcclusionStrength: 1 - - _Parallax: 0.02 - - _SmoothnessTextureChannel: 0 - - _SpecularHighlights: 1 - - _SrcBlend: 1 - - _UVSec: 0 - - _ZWrite: 1 - m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} - - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} - m_BuildTextureStacks: [] diff --git a/Assets/Steel.mat.meta b/Assets/Steel.mat.meta deleted file mode 100644 index d645ba6a4..000000000 --- a/Assets/Steel.mat.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 4c998decce894b4458e1bc667975aeea -NativeFormatImporter: - externalObjects: {} - mainObjectFileID: 2100000 - userData: - assetBundleName: - assetBundleVariant: From 3f2f637e6386dfee27c093569bddffcbad01d714 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 07:39:07 +0000 Subject: [PATCH 086/190] Drop the *.sbsar LFS rule and SUBSTANCE_PLUGIN_ENABLED define Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .gitattributes | 1 - ProjectSettings/ProjectSettings.asset | 4 ++-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/.gitattributes b/.gitattributes index d530ed421..9d4b872b4 100644 --- a/.gitattributes +++ b/.gitattributes @@ -51,7 +51,6 @@ *.dylib filter=lfs diff=lfs merge=lfs -text *.bundle filter=lfs diff=lfs merge=lfs -text *.engine filter=lfs diff=lfs merge=lfs -text -*.sbsar filter=lfs diff=lfs merge=lfs -text *.msgpack filter=lfs diff=lfs merge=lfs -text GameData/*.cc filter=lfs diff=lfs merge=lfs -text GameData/Mods/**/*.cc filter=lfs diff=lfs merge=lfs -text diff --git a/ProjectSettings/ProjectSettings.asset b/ProjectSettings/ProjectSettings.asset index 1b000cd89..76b6938ad 100644 --- a/ProjectSettings/ProjectSettings.asset +++ b/ProjectSettings/ProjectSettings.asset @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:1f95917a4ca95a4f6977be90d80185648b012099467fa2275b31b868aca88b6f -size 24058 +oid sha256:900f257853e7bf436c28cb323c323f2ef43e8d0659253ca7545cd23255d8ea57 +size 24033 From d144a2ccc203deda3d6d4a46c74683796dc41eab Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 07:39:47 +0000 Subject: [PATCH 087/190] Repoint the Substance materials to the owned ambientCG PBR sets Rewrites 14 materials from the removed sbsar sub-assets to Assets/Materials/PBR textures (Steel_Brushed, Gunmetal_Dark, Metal_Scratched, Paint_Worn_Light, Plates_Panels), keeping each sbsar preset colour as _Color where it differed; flat colour for Discobolus Marble (no marble set ships). Adds Pickup Trim.mat (copy of Car Paint White Small, flat trim colour). Turret, the five pickup prefabs and the Zenith_Blender externalObjects now name file materials instead of the ProceduralMaterial sub-asset. Own commit so it reverts alone (question sbsar-fallback-fidelity, built on its recommended option; no ruling yet). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Content/Prefabs/Turrets/Turret.prefab | 4 +- Assets/Materials/Aluminium brushed.mat | 17 ++-- Assets/Materials/Car Paint Magenta.mat | 14 +-- Assets/Materials/Car Paint Red.mat | 17 ++-- Assets/Materials/Car Paint White Small.mat | 17 ++-- Assets/Materials/Car Paint White.mat | 14 +-- Assets/Materials/Cockpit.mat | 17 ++-- Assets/Materials/Metal 003.mat | 15 +-- Assets/Materials/Mine Glow.mat | 9 +- Assets/Materials/Pickup Trim.mat | 97 +++++++++++++++++++ Assets/Materials/Pickup Trim.mat.meta | 8 ++ Assets/Materials/Radiators.mat | 9 +- Assets/Materials/Silver.mat | 15 +-- Assets/Materials/Station Lights.mat | 9 +- Assets/Materials/Steel parkerized.mat | 15 +-- Assets/Materials/Steel.mat | 15 +-- .../Models/Discobolus/Discobolus Marble.mat | 10 +- Assets/Models/Zenith_Blender.fbx.meta | 6 +- .../Prefabs/RPG/Pickups/Dodecahedron.prefab | 4 +- Assets/Prefabs/RPG/Pickups/Hexahedron.prefab | 4 +- Assets/Prefabs/RPG/Pickups/Icosahedron.prefab | 4 +- Assets/Prefabs/RPG/Pickups/Octahedron.prefab | 4 +- Assets/Prefabs/RPG/Pickups/Tetrahedron.prefab | 4 +- 23 files changed, 186 insertions(+), 142 deletions(-) create mode 100644 Assets/Materials/Pickup Trim.mat create mode 100644 Assets/Materials/Pickup Trim.mat.meta diff --git a/Assets/Content/Prefabs/Turrets/Turret.prefab b/Assets/Content/Prefabs/Turrets/Turret.prefab index 748ca8a29..2df968941 100644 --- a/Assets/Content/Prefabs/Turrets/Turret.prefab +++ b/Assets/Content/Prefabs/Turrets/Turret.prefab @@ -998,8 +998,8 @@ MeshRenderer: m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - - {fileID: 3720744386649352057, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, type: 3} - - {fileID: 3720744386649352057, guid: b2bec4b400153d745b2915f1c43e5c96, type: 3} + - {fileID: 2100000, guid: 38f8ba6b169127249b6532be2b3926ee, type: 2} + - {fileID: 2100000, guid: 5e43f48908cce2949a41677ec48affe5, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 diff --git a/Assets/Materials/Aluminium brushed.mat b/Assets/Materials/Aluminium brushed.mat index b8ade999f..a624f95e1 100644 --- a/Assets/Materials/Aluminium brushed.mat +++ b/Assets/Materials/Aluminium brushed.mat @@ -20,8 +20,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: 4730978449518085612, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} + m_Texture: {fileID: 2800000, guid: c3ef09438e3e46d18a4c267810aeb285, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -45,23 +44,19 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: 7556082237344091230, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} + m_Texture: {fileID: 2800000, guid: f70b6df0395b4752b4ec80cb7bfd8f42, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: 6373266012617290493, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} + m_Texture: {fileID: 2800000, guid: 40f5e915d2734d43bc01f984772e9d29, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: 342959783478273704, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: - m_Texture: {fileID: -9132138291289375396, guid: 06d6a565d43fba5409712ce9a10bfbef, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Floats: @@ -85,7 +80,7 @@ Material: - _UVSec: 0 - _ZWrite: 1 m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} + - _Color: {r: 0.951, g: 0.951, b: 0.951, a: 1} - _EdgeColor: {r: 3.0117648, g: 3.0117648, b: 11.984314, a: 1} - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} m_BuildTextureStacks: [] diff --git a/Assets/Materials/Car Paint Magenta.mat b/Assets/Materials/Car Paint Magenta.mat index dbe95bd62..bff25331a 100644 --- a/Assets/Materials/Car Paint Magenta.mat +++ b/Assets/Materials/Car Paint Magenta.mat @@ -26,8 +26,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: 3068890721646206586, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} + m_Texture: {fileID: 2800000, guid: 4ce3c2cc69304068b4a2ddc833b748b9, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _FadeTex: @@ -35,18 +34,15 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: 5917659159057834157, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} + m_Texture: {fileID: 2800000, guid: 73568a0c02bd4184bcb398c9e3dd7ab6, type: 3} m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -3552914696322007609, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} + m_Texture: {fileID: 2800000, guid: d9cd336372c244e398532512e3f8f3be, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -1242281561028671816, guid: a1d39ea984432bf44b4a0686afe2bf1a, - type: 3} + m_Texture: {fileID: 2800000, guid: 73e117729c3447e5aa0eb1a30fad7c75, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Ints: [] @@ -59,6 +55,6 @@ Material: - _Metallic: 1 - _OcclusionStrength: 1 m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} + - _Color: {r: 0.5, g: 0, b: 0.228113, a: 1} - _EdgeColor: {r: 3.0117648, g: 3.0117648, b: 11.984314, a: 1} m_BuildTextureStacks: [] diff --git a/Assets/Materials/Car Paint Red.mat b/Assets/Materials/Car Paint Red.mat index 8a7ffa46f..063e9367c 100644 --- a/Assets/Materials/Car Paint Red.mat +++ b/Assets/Materials/Car Paint Red.mat @@ -20,8 +20,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: 3068890721646206586, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} + m_Texture: {fileID: 2800000, guid: 4ce3c2cc69304068b4a2ddc833b748b9, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -45,23 +44,19 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: 5917659159057834157, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} + m_Texture: {fileID: 2800000, guid: 73568a0c02bd4184bcb398c9e3dd7ab6, type: 3} m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -3552914696322007609, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} + m_Texture: {fileID: 2800000, guid: d9cd336372c244e398532512e3f8f3be, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -1242281561028671816, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} + m_Texture: {fileID: 2800000, guid: 73e117729c3447e5aa0eb1a30fad7c75, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: - m_Texture: {fileID: -1652887728991447519, guid: 504c7bfe0d50ff64a88b8eac2ceb46f8, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Floats: @@ -85,7 +80,7 @@ Material: - _UVSec: 0 - _ZWrite: 1 m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} + - _Color: {r: 1, g: 0.15685, b: 0, a: 1} - _EdgeColor: {r: 6.0235295, g: 6.0235295, b: 24.094118, a: 1} - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} m_BuildTextureStacks: [] diff --git a/Assets/Materials/Car Paint White Small.mat b/Assets/Materials/Car Paint White Small.mat index aab8a3663..cca6010f3 100644 --- a/Assets/Materials/Car Paint White Small.mat +++ b/Assets/Materials/Car Paint White Small.mat @@ -29,8 +29,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: 3068890721646206586, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} + m_Texture: {fileID: 2800000, guid: 4ce3c2cc69304068b4a2ddc833b748b9, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -54,23 +53,19 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: 5917659159057834157, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} + m_Texture: {fileID: 2800000, guid: 73568a0c02bd4184bcb398c9e3dd7ab6, type: 3} m_Scale: {x: 16, y: 16} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -3552914696322007609, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} + m_Texture: {fileID: 2800000, guid: d9cd336372c244e398532512e3f8f3be, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -1242281561028671816, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} + m_Texture: {fileID: 2800000, guid: 73e117729c3447e5aa0eb1a30fad7c75, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: - m_Texture: {fileID: -1652887728991447519, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Ints: [] @@ -95,7 +90,7 @@ Material: - _UVSec: 0 - _ZWrite: 1 m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} + - _Color: {r: 1, g: 0.891509, b: 0.946396, a: 1} - _EdgeColor: {r: 6.0235295, g: 6.0235295, b: 24.094118, a: 1} - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} m_BuildTextureStacks: [] diff --git a/Assets/Materials/Car Paint White.mat b/Assets/Materials/Car Paint White.mat index ba32280af..ad0af17d2 100644 --- a/Assets/Materials/Car Paint White.mat +++ b/Assets/Materials/Car Paint White.mat @@ -26,8 +26,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: 3068890721646206586, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} + m_Texture: {fileID: 2800000, guid: 4ce3c2cc69304068b4a2ddc833b748b9, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _FadeTex: @@ -35,18 +34,15 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: 5917659159057834157, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} + m_Texture: {fileID: 2800000, guid: 73568a0c02bd4184bcb398c9e3dd7ab6, type: 3} m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -3552914696322007609, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} + m_Texture: {fileID: 2800000, guid: d9cd336372c244e398532512e3f8f3be, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -1242281561028671816, guid: b2bec4b400153d745b2915f1c43e5c96, - type: 3} + m_Texture: {fileID: 2800000, guid: 73e117729c3447e5aa0eb1a30fad7c75, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Ints: [] @@ -59,6 +55,6 @@ Material: - _Metallic: 1 - _OcclusionStrength: 1 m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} + - _Color: {r: 1, g: 0.891509, b: 0.946396, a: 1} - _EdgeColor: {r: 3.0117648, g: 3.0117648, b: 11.984314, a: 1} m_BuildTextureStacks: [] diff --git a/Assets/Materials/Cockpit.mat b/Assets/Materials/Cockpit.mat index 543d0d608..fb19e541a 100644 --- a/Assets/Materials/Cockpit.mat +++ b/Assets/Materials/Cockpit.mat @@ -26,8 +26,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: -3419035557588562233, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} + m_Texture: {fileID: 2800000, guid: 3a10044baac4438f9fc0930783eccdf7, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -51,23 +50,19 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: -1863473678134789185, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} + m_Texture: {fileID: 2800000, guid: 5a9cee903a2d48718aaf6b224126f279, type: 3} m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: 6214616473909614744, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} + m_Texture: {fileID: 2800000, guid: 8b24d7ea11c341408a146fa39f59b7b0, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -3436886866959827803, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: - m_Texture: {fileID: 7009887839391554354, guid: 9fc901afb8a434e46b9405eaec2df5a4, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Ints: [] @@ -92,7 +87,7 @@ Material: - _UVSec: 0 - _ZWrite: 1 m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} + - _Color: {r: 0.85, g: 0.65, b: 0.30, a: 1} - _EdgeColor: {r: 3.0117648, g: 3.0117648, b: 11.984314, a: 1} - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} m_BuildTextureStacks: [] diff --git a/Assets/Materials/Metal 003.mat b/Assets/Materials/Metal 003.mat index 4d07d4c1a..09330e338 100644 --- a/Assets/Materials/Metal 003.mat +++ b/Assets/Materials/Metal 003.mat @@ -20,8 +20,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: -2508943184622041221, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} + m_Texture: {fileID: 2800000, guid: 3a10044baac4438f9fc0930783eccdf7, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -41,23 +40,19 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: -1236254257114565538, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} + m_Texture: {fileID: 2800000, guid: 5a9cee903a2d48718aaf6b224126f279, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: 4019402794555593307, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} + m_Texture: {fileID: 2800000, guid: 8b24d7ea11c341408a146fa39f59b7b0, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -1475328947160444094, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: - m_Texture: {fileID: 7523010977671448217, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Floats: diff --git a/Assets/Materials/Mine Glow.mat b/Assets/Materials/Mine Glow.mat index e1627f2d9..7d6d630e7 100644 --- a/Assets/Materials/Mine Glow.mat +++ b/Assets/Materials/Mine Glow.mat @@ -20,8 +20,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: -812895718602229137, guid: b7e648471e9dfc44490bd41973711541, - type: 3} + m_Texture: {fileID: 2800000, guid: 8bc10cfce8a64defaf9f67d156003f09, type: 3} m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -41,13 +40,11 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: -6057190860509678031, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} + m_Texture: {fileID: 2800000, guid: 2195885db9e846999fd10aa7f5c629b1, type: 3} m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -894214952450941493, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} + m_Texture: {fileID: 2800000, guid: d91bff887b764847a484d0a9bedce9e9, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: diff --git a/Assets/Materials/Pickup Trim.mat b/Assets/Materials/Pickup Trim.mat new file mode 100644 index 000000000..0cea43f4f --- /dev/null +++ b/Assets/Materials/Pickup Trim.mat @@ -0,0 +1,97 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 8 + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: Pickup Trim + m_Shader: {fileID: 4800000, guid: ddff0b48b92c991499817d2a0f5d5059, type: 3} + m_Parent: {fileID: 0} + m_ModifiedSerializedProperties: 0 + m_ValidKeywords: [] + m_InvalidKeywords: + - _MAINTEX + - _METALLICGLOSSMAP + - _NORMALMAP + - _OCCLUSIONMAP + - _PARALLAXMAP + m_LightmapFlags: 4 + m_EnableInstancingVariants: 0 + m_DoubleSidedGI: 0 + m_CustomRenderQueue: -1 + stringTagMap: {} + disabledShaderPasses: [] + m_LockedProperties: + m_SavedProperties: + serializedVersion: 3 + m_TexEnvs: + - _BumpMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _DetailAlbedoMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _DetailMask: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _DetailNormalMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _EmissionMap: + m_Texture: {fileID: 0} + m_Scale: {x: 16, y: 16} + m_Offset: {x: 0, y: 0} + - _FadeTex: + m_Texture: {fileID: 2800000, guid: df0632a08c5f1a1498fa325c755dc459, type: 3} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _MainTex: + m_Texture: {fileID: 0} + m_Scale: {x: 16, y: 16} + m_Offset: {x: 0, y: 0} + - _MetallicGlossMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _OcclusionMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _ParallaxMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + m_Ints: [] + m_Floats: + - _BumpScale: 1 + - _Cutoff: 0.5 + - _DetailNormalMapScale: 1 + - _DstBlend: 0 + - _Fade: 1 + - _FadeEdge: 0.1 + - _FadeSharpness: 16 + - _GlossMapScale: 1 + - _Glossiness: 0.7 + - _GlossyReflections: 1 + - _Metallic: 0.6 + - _Mode: 0 + - _OcclusionStrength: 1 + - _Parallax: 0.005 + - _SmoothnessTextureChannel: 0 + - _SpecularHighlights: 1 + - _SrcBlend: 1 + - _UVSec: 0 + - _ZWrite: 1 + m_Colors: + - _Color: {r: 0, g: 0.605881, b: 1, a: 1} + - _EdgeColor: {r: 6.0235295, g: 6.0235295, b: 24.094118, a: 1} + - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} + m_BuildTextureStacks: [] + m_AllowLocking: 1 diff --git a/Assets/Materials/Pickup Trim.mat.meta b/Assets/Materials/Pickup Trim.mat.meta new file mode 100644 index 000000000..d57d829c2 --- /dev/null +++ b/Assets/Materials/Pickup Trim.mat.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: bebc82079e5d4e578a73c3ab48d2c2da +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 2100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Materials/Radiators.mat b/Assets/Materials/Radiators.mat index aa7eaf0fb..1e5c52a54 100644 --- a/Assets/Materials/Radiators.mat +++ b/Assets/Materials/Radiators.mat @@ -21,8 +21,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: -812895718602229137, guid: b7e648471e9dfc44490bd41973711541, - type: 3} + m_Texture: {fileID: 2800000, guid: 8bc10cfce8a64defaf9f67d156003f09, type: 3} m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -46,13 +45,11 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: -6057190860509678031, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} + m_Texture: {fileID: 2800000, guid: 2195885db9e846999fd10aa7f5c629b1, type: 3} m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -894214952450941493, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} + m_Texture: {fileID: 2800000, guid: d91bff887b764847a484d0a9bedce9e9, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: diff --git a/Assets/Materials/Silver.mat b/Assets/Materials/Silver.mat index e02d24f97..0bb79d6a1 100644 --- a/Assets/Materials/Silver.mat +++ b/Assets/Materials/Silver.mat @@ -26,8 +26,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: 8947980237086559854, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} + m_Texture: {fileID: 2800000, guid: c3ef09438e3e46d18a4c267810aeb285, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -51,23 +50,19 @@ Material: m_Scale: {x: 2, y: 2} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: -1383037052668628532, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} + m_Texture: {fileID: 2800000, guid: f70b6df0395b4752b4ec80cb7bfd8f42, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: 6429125567479694453, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} + m_Texture: {fileID: 2800000, guid: 40f5e915d2734d43bc01f984772e9d29, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -9097439929179392311, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: - m_Texture: {fileID: 425190381137097012, guid: 0be5fb1df83ac8e499a3f6a060041e49, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Ints: [] diff --git a/Assets/Materials/Station Lights.mat b/Assets/Materials/Station Lights.mat index f863306a1..2aac54ac7 100644 --- a/Assets/Materials/Station Lights.mat +++ b/Assets/Materials/Station Lights.mat @@ -24,8 +24,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: -812895718602229137, guid: b7e648471e9dfc44490bd41973711541, - type: 3} + m_Texture: {fileID: 2800000, guid: 8bc10cfce8a64defaf9f67d156003f09, type: 3} m_Scale: {x: 8, y: 8} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -49,13 +48,11 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: -6057190860509678031, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} + m_Texture: {fileID: 2800000, guid: 2195885db9e846999fd10aa7f5c629b1, type: 3} m_Scale: {x: 16, y: 16} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -894214952450941493, guid: 2b42584452fe0cc4fa4e8a115230b156, - type: 3} + m_Texture: {fileID: 2800000, guid: d91bff887b764847a484d0a9bedce9e9, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: diff --git a/Assets/Materials/Steel parkerized.mat b/Assets/Materials/Steel parkerized.mat index b4194ab66..ba47afb87 100644 --- a/Assets/Materials/Steel parkerized.mat +++ b/Assets/Materials/Steel parkerized.mat @@ -29,8 +29,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: 885599758852769373, guid: e7758cad28ae98f478940e55222419a6, - type: 3} + m_Texture: {fileID: 2800000, guid: dc71e34b4a1f4de7aa826d18b67b5852, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -54,23 +53,19 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: -4474525002722929857, guid: e7758cad28ae98f478940e55222419a6, - type: 3} + m_Texture: {fileID: 2800000, guid: 1ed06708491744fe944217d19e450157, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -2334804936223627746, guid: e7758cad28ae98f478940e55222419a6, - type: 3} + m_Texture: {fileID: 2800000, guid: 31e7d642ff8a49a28390c82626c4b6b9, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -8380876848358870972, guid: e7758cad28ae98f478940e55222419a6, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: - m_Texture: {fileID: 172713863077875830, guid: e7758cad28ae98f478940e55222419a6, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Ints: [] diff --git a/Assets/Materials/Steel.mat b/Assets/Materials/Steel.mat index 37420bfd4..6eeb29385 100644 --- a/Assets/Materials/Steel.mat +++ b/Assets/Materials/Steel.mat @@ -26,8 +26,7 @@ Material: serializedVersion: 3 m_TexEnvs: - _BumpMap: - m_Texture: {fileID: -3888315358723833787, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} + m_Texture: {fileID: 2800000, guid: c3ef09438e3e46d18a4c267810aeb285, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _DetailAlbedoMap: @@ -51,23 +50,19 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: 108215966750249586, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} + m_Texture: {fileID: 2800000, guid: f70b6df0395b4752b4ec80cb7bfd8f42, type: 3} m_Scale: {x: 4, y: 4} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: 4793252353645218242, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} + m_Texture: {fileID: 2800000, guid: 40f5e915d2734d43bc01f984772e9d29, type: 3} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: - m_Texture: {fileID: -4384182597330533215, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _ParallaxMap: - m_Texture: {fileID: 4600200897981803784, guid: cbc61995a46604441ab9de4f1c68e290, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} m_Ints: [] diff --git a/Assets/Models/Discobolus/Discobolus Marble.mat b/Assets/Models/Discobolus/Discobolus Marble.mat index 3c862a22c..f4331ed09 100644 --- a/Assets/Models/Discobolus/Discobolus Marble.mat +++ b/Assets/Models/Discobolus/Discobolus Marble.mat @@ -40,13 +40,11 @@ Material: m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MainTex: - m_Texture: {fileID: -5564000130503291907, guid: ef9a54b8dacea9f44be70da43472f701, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _MetallicGlossMap: - m_Texture: {fileID: -3258750942226492355, guid: ef9a54b8dacea9f44be70da43472f701, - type: 3} + m_Texture: {fileID: 0} m_Scale: {x: 1, y: 1} m_Offset: {x: 0, y: 0} - _OcclusionMap: @@ -63,7 +61,7 @@ Material: - _DetailNormalMapScale: 1 - _DstBlend: 0 - _GlossMapScale: 1 - - _Glossiness: 0.5 + - _Glossiness: 0.45 - _GlossyReflections: 1 - _Metallic: 0 - _Mode: 0 @@ -75,6 +73,6 @@ Material: - _UVSec: 0 - _ZWrite: 1 m_Colors: - - _Color: {r: 1, g: 1, b: 1, a: 1} + - _Color: {r: 0.7, g: 0.654348, b: 0.525, a: 1} - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} m_BuildTextureStacks: [] diff --git a/Assets/Models/Zenith_Blender.fbx.meta b/Assets/Models/Zenith_Blender.fbx.meta index 2094752dc..6f719ce83 100644 --- a/Assets/Models/Zenith_Blender.fbx.meta +++ b/Assets/Models/Zenith_Blender.fbx.meta @@ -8,8 +8,7 @@ ModelImporter: type: UnityEngine:Material assembly: UnityEngine.CoreModule name: Black - second: {fileID: 3720744386649352057, guid: 1c858fec5b74c7c46b1712494192b6b5, - type: 3} + second: {fileID: 2100000, guid: b9f65861b71050b4a84fe0007bedbba9, type: 2} - first: type: UnityEngine:Material assembly: UnityEngine.CoreModule @@ -19,8 +18,7 @@ ModelImporter: type: UnityEngine:Material assembly: UnityEngine.CoreModule name: White - second: {fileID: -741235592913766832, guid: 885e680924fc12c439a842a2142d4b78, - type: 3} + second: {fileID: 2100000, guid: 39af4e3978df92f40a55e2a114aa242a, type: 2} materials: materialImportMode: 1 materialName: 0 diff --git a/Assets/Prefabs/RPG/Pickups/Dodecahedron.prefab b/Assets/Prefabs/RPG/Pickups/Dodecahedron.prefab index 7a65a0864..7be70840f 100644 --- a/Assets/Prefabs/RPG/Pickups/Dodecahedron.prefab +++ b/Assets/Prefabs/RPG/Pickups/Dodecahedron.prefab @@ -103,8 +103,8 @@ MeshRenderer: m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - - {fileID: 3720744386649352057, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: 3720744386649352057, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} + - {fileID: 2100000, guid: bebc82079e5d4e578a73c3ab48d2c2da, type: 2} + - {fileID: 2100000, guid: b9f65861b71050b4a84fe0007bedbba9, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 diff --git a/Assets/Prefabs/RPG/Pickups/Hexahedron.prefab b/Assets/Prefabs/RPG/Pickups/Hexahedron.prefab index f9a477cda..4a8609c7c 100644 --- a/Assets/Prefabs/RPG/Pickups/Hexahedron.prefab +++ b/Assets/Prefabs/RPG/Pickups/Hexahedron.prefab @@ -103,8 +103,8 @@ MeshRenderer: m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - - {fileID: 3720744386649352057, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: 3720744386649352057, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} + - {fileID: 2100000, guid: bebc82079e5d4e578a73c3ab48d2c2da, type: 2} + - {fileID: 2100000, guid: b9f65861b71050b4a84fe0007bedbba9, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 diff --git a/Assets/Prefabs/RPG/Pickups/Icosahedron.prefab b/Assets/Prefabs/RPG/Pickups/Icosahedron.prefab index 4252e74cc..b80967c41 100644 --- a/Assets/Prefabs/RPG/Pickups/Icosahedron.prefab +++ b/Assets/Prefabs/RPG/Pickups/Icosahedron.prefab @@ -103,8 +103,8 @@ MeshRenderer: m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - - {fileID: 3720744386649352057, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: 3720744386649352057, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} + - {fileID: 2100000, guid: bebc82079e5d4e578a73c3ab48d2c2da, type: 2} + - {fileID: 2100000, guid: b9f65861b71050b4a84fe0007bedbba9, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 diff --git a/Assets/Prefabs/RPG/Pickups/Octahedron.prefab b/Assets/Prefabs/RPG/Pickups/Octahedron.prefab index 099083195..9cabd7b79 100644 --- a/Assets/Prefabs/RPG/Pickups/Octahedron.prefab +++ b/Assets/Prefabs/RPG/Pickups/Octahedron.prefab @@ -103,8 +103,8 @@ MeshRenderer: m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - - {fileID: 3720744386649352057, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: 3720744386649352057, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} + - {fileID: 2100000, guid: bebc82079e5d4e578a73c3ab48d2c2da, type: 2} + - {fileID: 2100000, guid: b9f65861b71050b4a84fe0007bedbba9, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 diff --git a/Assets/Prefabs/RPG/Pickups/Tetrahedron.prefab b/Assets/Prefabs/RPG/Pickups/Tetrahedron.prefab index 6dad19967..20f8073a7 100644 --- a/Assets/Prefabs/RPG/Pickups/Tetrahedron.prefab +++ b/Assets/Prefabs/RPG/Pickups/Tetrahedron.prefab @@ -103,8 +103,8 @@ MeshRenderer: m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - - {fileID: 3720744386649352057, guid: c00b5a4f1e4743a4ca59b8030251f900, type: 3} - - {fileID: 3720744386649352057, guid: 26a894e543f3ed44893b1620707ca62c, type: 3} + - {fileID: 2100000, guid: bebc82079e5d4e578a73c3ab48d2c2da, type: 2} + - {fileID: 2100000, guid: b9f65861b71050b4a84fe0007bedbba9, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 From 0bcf8f818793323f1e6d84cc33e79a1351ff9087 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 07:39:54 +0000 Subject: [PATCH 088/190] Docs: record the sbsar removal Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- docs/aetheria-release-map.md | 3 +-- docs/cultcache-migration-cut.md | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/docs/aetheria-release-map.md b/docs/aetheria-release-map.md index 72e96f22e..c270c297c 100644 --- a/docs/aetheria-release-map.md +++ b/docs/aetheria-release-map.md @@ -502,7 +502,6 @@ record. | follow-up | `hull-damage-wear` | demo | Damage visible on the hull (line 6). | | follow-up | `mod-ship-single-existence-gate` | demo | A skipped package throws on spawn; demo hulls are packages. | | follow-up | `ambiguous-hardpoint-origin` | demo | Save correctness for package hulls. | -| follow-up | `remove-sbsar-files` | demo | Clean break from Substance before a public build. | | follow-up | `delaunay-exact-predicates` | demo | Galaxy links; a silently unlinked zone could strand a demo run. | | follow-up | `failed-start-scene-halts` | demo | The New Game failure path the demo's missing-cast refusal uses. | | follow-up | `stale-docs-after-scenarios-menu` | demo | Docs that describe the old New Game path. | @@ -2188,7 +2187,7 @@ wear comes from baked maps. Grunge is baked into `ship.maps.png` A. - r2's region tint (`_PaintStrength`, `RegionLuminance`, a tiling `_WearNoise`) and its `Livery` of three colours are never built. - Revision 1's vertex mask is gone. - - The 41 `.sbsar` files go with follow-up `remove-sbsar-files`. + - The 41 `.sbsar` files are removed (follow-up `remove-sbsar-files`). #### Parity diff --git a/docs/cultcache-migration-cut.md b/docs/cultcache-migration-cut.md index 16e885490..967f4b6b7 100644 --- a/docs/cultcache-migration-cut.md +++ b/docs/cultcache-migration-cut.md @@ -151,7 +151,7 @@ death clearing the run across relaunch, stance toggle, `FieldShieldTest`. It fou migration defect: CultMath types are not Unity-serializable, so Unity-serialized CultMath fields load as zero. Mouse sensitivity (lost look control) moved to `PlayerSettings` in `00ebe46a`; the rest, including the black rarity colours, is `docs/settings-globals-cut.md`. -Scene materials are broken by the dead Substance plugin, not by this migration. +The Substance maps are removed and the materials repointed to Assets/Materials/PBR. History, before the smoke: - nothing else from agents. The preset rework's Soul findings were fixed in From b2a272d1abab8947fa17c13d09c723ce4f85c732 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 07:41:17 +0000 Subject: [PATCH 089/190] Test: scan m_TexEnvs up to m_Floats (some materials have no m_Ints) Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- tests/Aetheria.Shared.Tests/SubstanceCleanBreakTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Aetheria.Shared.Tests/SubstanceCleanBreakTests.cs b/tests/Aetheria.Shared.Tests/SubstanceCleanBreakTests.cs index 97e2c0b3b..db3606ecd 100644 --- a/tests/Aetheria.Shared.Tests/SubstanceCleanBreakTests.cs +++ b/tests/Aetheria.Shared.Tests/SubstanceCleanBreakTests.cs @@ -159,7 +159,7 @@ public sealed class SubstanceCleanBreakTests if (!File.Exists(path)) { problems.Add($"{rel} does not exist"); continue; } var text = File.ReadAllText(path); var start = text.IndexOf("m_TexEnvs:", StringComparison.Ordinal); - var end = text.IndexOf("m_Ints:", StringComparison.Ordinal); + var end = text.IndexOf("m_Floats:", StringComparison.Ordinal); Assert.True(start >= 0 && end > start, $"{rel} has no m_TexEnvs section"); foreach (Match m in texture.Matches(text.Substring(start, end - start))) { From 6905726ba35c752004f263cdac0f6711c5255fcd Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 08:21:54 +0000 Subject: [PATCH 090/190] Test: guard repointed prefab/fbx.meta material guids, LFS pointers, all text assets, texture importer type Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../SubstanceCleanBreakTests.cs | 99 ++++++++++++++++--- 1 file changed, 87 insertions(+), 12 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/SubstanceCleanBreakTests.cs b/tests/Aetheria.Shared.Tests/SubstanceCleanBreakTests.cs index db3606ecd..ae3e0bddf 100644 --- a/tests/Aetheria.Shared.Tests/SubstanceCleanBreakTests.cs +++ b/tests/Aetheria.Shared.Tests/SubstanceCleanBreakTests.cs @@ -66,12 +66,18 @@ public sealed class SubstanceCleanBreakTests "ef9a54b8dacea9f44be70da43472f701", }; - private static readonly string[] ScannedExtensions = + private static readonly string[] PrefabsAndMetasEditedByTheCut = { - ".mat", ".prefab", ".unity", ".asset", ".meta", ".controller", ".anim", ".overrideController", ".mixer", - ".lighting", ".flare", ".shader", ".json", + "Assets/Content/Prefabs/Turrets/Turret.prefab", "Assets/Prefabs/RPG/Pickups/Dodecahedron.prefab", + "Assets/Prefabs/RPG/Pickups/Hexahedron.prefab", "Assets/Prefabs/RPG/Pickups/Icosahedron.prefab", + "Assets/Prefabs/RPG/Pickups/Octahedron.prefab", "Assets/Prefabs/RPG/Pickups/Tetrahedron.prefab", + "Assets/Models/Zenith_Blender.fbx.meta", }; + // A material reference (main object fileID 2100000). Script guids in the same files resolve to Unity packages, + // which have no .meta under Assets/, so only material slots are checked. + private static readonly Regex MaterialRef = new(@"fileID:\s*2100000,\s*guid:\s*([0-9a-f]{32})", RegexOptions.Compiled); + private static readonly string[] ExcludedDirs = { ".git", "node_modules", ".voidbot" }; private static readonly string[] RepointedMaterials = @@ -92,6 +98,51 @@ public sealed class SubstanceCleanBreakTests foreach (var file in Walk(sub)) yield return file; } + // A checkout that holds Git LFS pointers instead of content cannot be scanned. The guards that read LFS-tracked + // files fail loudly here: skipping would pass vacuously, and a failure says "smudge the LFS objects first". + private static bool IsLfsPointer(string path) + { + using var stream = File.OpenRead(path); + var head = new byte[48]; + var n = stream.Read(head, 0, head.Length); + return Encoding.ASCII.GetString(head, 0, n).StartsWith("version https://git-lfs", StringComparison.Ordinal); + } + + private static string ReadTextOrFailOnPointer(string path) + { + Assert.False(IsLfsPointer(path), $"{path} is an LFS pointer, not content: this guard cannot see inside it. Run `git lfs pull`."); + return File.ReadAllText(path, Encoding.Latin1); + } + + // Everything is scanned except known binary media (a denylist, so an unlisted serialized type is still read) and, + // for unlisted extensions, files with a NUL byte in the first 8 KiB. The extension check comes first because an + // LFS pointer for a texture is itself text and says nothing about what the object holds. + private static readonly string[] BinaryExtensions = + { + ".png", ".jpg", ".jpeg", ".tga", ".tif", ".tiff", ".psd", ".bmp", ".gif", ".exr", ".hdr", ".dds", ".wav", ".mp3", + ".ogg", ".mp4", ".fbx", ".glb", ".blend", ".ttf", ".otf", ".dll", ".so", ".pdb", ".msgpack", ".zip", ".bank", + }; + + private static bool LooksBinary(string path) + { + if (BinaryExtensions.Contains(Path.GetExtension(path), StringComparer.OrdinalIgnoreCase)) return true; + using var stream = File.OpenRead(path); + var buf = new byte[8192]; + var n = stream.Read(buf, 0, buf.Length); + return Array.IndexOf(buf, (byte)0, 0, n) >= 0; + } + + private static Dictionary<string, string> GuidToMeta(string root) + { + var map = new Dictionary<string, string>(); + foreach (var meta in Directory.EnumerateFiles(Path.Combine(root, "Assets"), "*.meta", SearchOption.AllDirectories)) + { + var guid = File.ReadLines(meta).FirstOrDefault(l => l.StartsWith("guid: "))?.Substring("guid: ".Length).Trim(); + if (guid != null) map[guid] = Path.GetRelativePath(root, meta).Replace('\\', '/'); + } + return map; + } + [Fact] public void NoSbsarFileOrMetaRemains() { @@ -112,7 +163,11 @@ public sealed class SubstanceCleanBreakTests .SelectMany(Walk) .Concat(Directory.Exists(Path.Combine(root, "GameData")) ? Directory.EnumerateFiles(Path.Combine(root, "GameData"), "*.cc") : Enumerable.Empty<string>()) - .Where(f => f.EndsWith(".cc") || ScannedExtensions.Contains(Path.GetExtension(f), StringComparer.OrdinalIgnoreCase)); + .Where(f => f.EndsWith(".cc") || !LooksBinary(f)) + .ToList(); + var pointers = files.Where(IsLfsPointer).Select(f => Path.GetRelativePath(root, f)).ToList(); + Assert.True(pointers.Count == 0, + $"{pointers.Count} scanned files are LFS pointers, not content (first: {pointers.FirstOrDefault()}); run `git lfs pull`."); var hits = new List<string>(); foreach (var file in files) { @@ -129,7 +184,7 @@ public sealed class SubstanceCleanBreakTests public void NoSubstanceBuildSurface() { var root = RestoredHullsTests.FindRepoRoot(); - Assert.DoesNotContain("SUBSTANCE", File.ReadAllText(Path.Combine(root, "ProjectSettings", "ProjectSettings.asset")), StringComparison.Ordinal); + Assert.DoesNotContain("SUBSTANCE", ReadTextOrFailOnPointer(Path.Combine(root, "ProjectSettings", "ProjectSettings.asset")), StringComparison.Ordinal); foreach (var name in new[] { "manifest.json", "packages-lock.json" }) { var text = File.ReadAllText(Path.Combine(root, "Packages", name)); @@ -144,14 +199,9 @@ public sealed class SubstanceCleanBreakTests public void EveryReplacementTextureResolves() { var root = RestoredHullsTests.FindRepoRoot(); - var guidToMeta = new Dictionary<string, string>(); - foreach (var meta in Directory.EnumerateFiles(Path.Combine(root, "Assets"), "*.meta", SearchOption.AllDirectories)) - { - var guid = File.ReadLines(meta).FirstOrDefault(l => l.StartsWith("guid: "))?.Substring("guid: ".Length).Trim(); - if (guid != null) guidToMeta[guid] = Path.GetRelativePath(root, meta).Replace('\\', '/'); - } + var guidToMeta = GuidToMeta(root); - var texture = new Regex(@"m_Texture:\s*\{fileID:\s*(-?\d+),\s*guid:\s*([0-9a-f]{32})", RegexOptions.Compiled); + var texture = new Regex(@"m_Texture:\s*\{fileID:\s*(-?\d+)(?:,\s*guid:\s*([0-9a-f]{32}))?", RegexOptions.Compiled); var problems = new List<string>(); foreach (var rel in RepointedMaterials) { @@ -164,11 +214,36 @@ public sealed class SubstanceCleanBreakTests foreach (Match m in texture.Matches(text.Substring(start, end - start))) { if (m.Groups[1].Value == "0") continue; + if (!m.Groups[2].Success) { problems.Add($"{rel} has a nonzero texture fileID with no guid: {m.Value}"); continue; } var guid = m.Groups[2].Value; if (!guidToMeta.TryGetValue(guid, out var meta)) problems.Add($"{rel} names {guid}, which has no .meta under Assets/"); else if (meta.StartsWith("Assets/Materials/Substance", StringComparison.Ordinal)) problems.Add($"{rel} names {guid} inside the removed Substance tree"); + else if (!File.ReadLines(Path.Combine(root, meta)).Any(l => l.StartsWith("TextureImporter:", StringComparison.Ordinal))) + problems.Add($"{rel} texture slot names {guid} ({meta}), which is not a TextureImporter asset"); } } Assert.True(problems.Count == 0, string.Join("\n", problems)); } + + [Fact] + public void EveryRepointedPrefabAndFbxSlotResolves() + { + var root = RestoredHullsTests.FindRepoRoot(); + var guidToMeta = GuidToMeta(root); + var problems = new List<string>(); + foreach (var rel in PrefabsAndMetasEditedByTheCut) + { + var path = Path.Combine(root, rel); + if (!File.Exists(path)) { problems.Add($"{rel} does not exist"); continue; } + var lines = ReadTextOrFailOnPointer(path).Split('\n'); + for (var i = 0; i < lines.Length; i++) + foreach (Match m in MaterialRef.Matches(lines[i])) + { + var guid = m.Groups[1].Value; + if (!guidToMeta.TryGetValue(guid, out var meta)) problems.Add($"{rel}:{i + 1} names {guid}, which has no .meta under Assets/"); + else if (!meta.EndsWith(".mat.meta", StringComparison.Ordinal)) problems.Add($"{rel}:{i + 1} material slot names {guid} ({meta}), which is not a .mat"); + } + } + Assert.True(problems.Count == 0, string.Join("\n", problems.Take(40))); + } } From e326f5a8fab71f02d109916e11a07c88b747a8b4 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 08:41:38 +0000 Subject: [PATCH 091/190] Docs: ygg-verify recipe stages every LFS file the sbsar guards read Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- docs/mining-cut-refresh.md | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/docs/mining-cut-refresh.md b/docs/mining-cut-refresh.md index a96d10b40..b14a5c942 100644 --- a/docs/mining-cut-refresh.md +++ b/docs/mining-cut-refresh.md @@ -63,8 +63,9 @@ rows are kept for the combined test count. The three file sets are disjoint. I checked with `git diff --name-only` over each branch's own range, and none of the three pairs shares a file. So each anchored line is byte-identical in the merged tree. - **Tests ran on Yggdrasil, against synthetic merges** (section 0). CultLib `45c2f40` and CultMath `6d5e209` are - the pins in `Directory.Build.props`. The two LFS files the tests read (`GameData/Aetheria.cc`, - `Assets/Resources/Settings.asset`) were staged beside the job, because the verify mirror carries no LFS. + the pins in `Directory.Build.props`. The LFS files the tests read were staged beside the job, because the verify mirror carries no LFS. The Mining + cut tests needed `GameData/Aetheria.cc` and `Assets/Resources/Settings.asset`; `SubstanceCleanBreakTests` needs 99 + (see the LFS staging set under Verification). - **Catalog facts** come from a probe that opens the merged tree's `GameData/Aetheria.cc` through `AetheriaStores.Open` (section 0). @@ -289,7 +290,7 @@ Every mining question is ruled. - Mark the `:396-412` table as history, anchored at `8bd25f6f`. - **Verification:** - Yggdrasil, the same job that section 0 ran: - `ygg-verify.sh <aetheria clone> <merge sha> dotnet '<clone CultLib 45c2f40 to /CultLib and 6d5e209 to /CultMath; restore the two LFS files; dotnet test tests/Aetheria.Shared.Tests -p:CultLibRoot=/CultLib -p:CultMathRoot=/CultMath>'`. + `ygg-verify.sh <aetheria clone> <merge sha> dotnet '<clone CultLib 45c2f40 to /CultLib and 6d5e209 to /CultMath; restore the LFS staging set below; dotnet test tests/Aetheria.Shared.Tests -p:CultLibRoot=/CultLib -p:CultMathRoot=/CultMath>'`. Both roots are mandatory (shared precondition). - The job mounts the Yggdrasil mirrors read-only with `DOCKER_ARGS="-v /home/gamecultadmin/eureka-verify/repos:/repos:ro -v /home/gamecultadmin/eureka-verify/lfs-aetheria:/lfs:ro"`. @@ -298,8 +299,16 @@ Every mining question is ruled. Rule pinned: fire control and mining compose without a behaviour change on either side. Every pre-existing test passes unchanged. - The verify mirror has no LFS (the push from `F:\Projects\Aetheria` fails in the LFS pre-push hook on an - `ssh:` remote). Push from a `--shared --no-checkout` clone, and mount the two LFS blobs. This is recorded + `ssh:` remote). Push from a `--shared --no-checkout` clone, and mount the LFS blobs. This is recorded so the next Hands does not rediscover it. + - LFS staging set. `SubstanceCleanBreakTests` fails loudly on any LFS pointer it scans, so the job must restore + every LFS-tracked file under `Assets/`, `Packages/`, `ProjectSettings/` and `GameData/*.cc` that is not a + binary-media extension (the test's `BinaryExtensions` denylist): 99 files at `6905726ba`, 96 `*.asset` and 3 + `*.cc` (`GameData/Aetheria.cc`, `GameData/Mods/aetheria.nakovalnya/ship.cc`, `GameData/Mods/aetheria.wren/ship.cc`), + which includes `ProjectSettings/ProjectSettings.asset` and `Assets/Resources/Settings.asset`. Derive the list from + the merged tree instead of hand-copying it: + `git ls-files Assets Packages ProjectSettings 'GameData/*.cc' | git check-attr --stdin filter | grep 'lfs$' | sed 's/: filter: lfs//' | grep -viE '\.(png|jpg|jpeg|tga|tif|tiff|psd|bmp|gif|exr|hdr|dds|wav|mp3|ogg|mp4|fbx|glb|blend|ttf|otf|dll|so|pdb|msgpack|zip|bank)$'`, + then copy each path from the `/lfs` mount over the checkout. Staging only two files turns the suite red. - Unity batchmode compile of the merged tree (Self, in a worktree, never with the operator's editor open on the main tree). This is the Cut 1 renderer compile the map still owes. - Operator: fly through a belt (the Cut 1 check the map still owes). Rocks orbit smoothly, and the minimap From 83e6957de07b4da8e9035d8f40aadb013aed09c3 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 08:41:38 +0000 Subject: [PATCH 092/190] Test: guid resolution requires the asset beside the .meta Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../Aetheria.Shared.Tests/SubstanceCleanBreakTests.cs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/SubstanceCleanBreakTests.cs b/tests/Aetheria.Shared.Tests/SubstanceCleanBreakTests.cs index ae3e0bddf..39842e4f0 100644 --- a/tests/Aetheria.Shared.Tests/SubstanceCleanBreakTests.cs +++ b/tests/Aetheria.Shared.Tests/SubstanceCleanBreakTests.cs @@ -138,7 +138,11 @@ public sealed class SubstanceCleanBreakTests foreach (var meta in Directory.EnumerateFiles(Path.Combine(root, "Assets"), "*.meta", SearchOption.AllDirectories)) { var guid = File.ReadLines(meta).FirstOrDefault(l => l.StartsWith("guid: "))?.Substring("guid: ".Length).Trim(); - if (guid != null) map[guid] = Path.GetRelativePath(root, meta).Replace('\\', '/'); + if (guid == null) continue; + // A .meta whose asset is gone still carries the guid, so resolution must look beside it: the asset is the + // .meta path minus ".meta". Directory metas resolve to a folder. + var asset = meta.Substring(0, meta.Length - ".meta".Length); + if (File.Exists(asset) || Directory.Exists(asset)) map[guid] = Path.GetRelativePath(root, meta).Replace('\\', '/'); } return map; } @@ -216,7 +220,7 @@ public sealed class SubstanceCleanBreakTests if (m.Groups[1].Value == "0") continue; if (!m.Groups[2].Success) { problems.Add($"{rel} has a nonzero texture fileID with no guid: {m.Value}"); continue; } var guid = m.Groups[2].Value; - if (!guidToMeta.TryGetValue(guid, out var meta)) problems.Add($"{rel} names {guid}, which has no .meta under Assets/"); + if (!guidToMeta.TryGetValue(guid, out var meta)) problems.Add($"{rel} names {guid}, which has no .meta and asset under Assets/"); else if (meta.StartsWith("Assets/Materials/Substance", StringComparison.Ordinal)) problems.Add($"{rel} names {guid} inside the removed Substance tree"); else if (!File.ReadLines(Path.Combine(root, meta)).Any(l => l.StartsWith("TextureImporter:", StringComparison.Ordinal))) problems.Add($"{rel} texture slot names {guid} ({meta}), which is not a TextureImporter asset"); @@ -240,7 +244,7 @@ public sealed class SubstanceCleanBreakTests foreach (Match m in MaterialRef.Matches(lines[i])) { var guid = m.Groups[1].Value; - if (!guidToMeta.TryGetValue(guid, out var meta)) problems.Add($"{rel}:{i + 1} names {guid}, which has no .meta under Assets/"); + if (!guidToMeta.TryGetValue(guid, out var meta)) problems.Add($"{rel}:{i + 1} names {guid}, which has no .meta and asset under Assets/"); else if (!meta.EndsWith(".mat.meta", StringComparison.Ordinal)) problems.Add($"{rel}:{i + 1} material slot names {guid} ({meta}), which is not a .mat"); } } From ea6b5115b4bf105f637a187a37e10b94ef9942b8 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 09:19:27 +0000 Subject: [PATCH 093/190] Docs: the LFS staging set greens the sbsar guards only; name what else a green suite needs Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- docs/mining-cut-refresh.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/mining-cut-refresh.md b/docs/mining-cut-refresh.md index b14a5c942..7adb1e951 100644 --- a/docs/mining-cut-refresh.md +++ b/docs/mining-cut-refresh.md @@ -64,7 +64,7 @@ rows are kept for the combined test count. of the three pairs shares a file. So each anchored line is byte-identical in the merged tree. - **Tests ran on Yggdrasil, against synthetic merges** (section 0). CultLib `45c2f40` and CultMath `6d5e209` are the pins in `Directory.Build.props`. The LFS files the tests read were staged beside the job, because the verify mirror carries no LFS. The Mining - cut tests needed `GameData/Aetheria.cc` and `Assets/Resources/Settings.asset`; `SubstanceCleanBreakTests` needs 99 + cut tests needed `GameData/Aetheria.cc` and `Assets/Resources/Settings.asset`; `SubstanceCleanBreakTests` needs 97 and the whole suite needs more (see the LFS staging set under Verification). - **Catalog facts** come from a probe that opens the merged tree's `GameData/Aetheria.cc` through `AetheriaStores.Open` (section 0). @@ -303,12 +303,12 @@ Every mining question is ruled. so the next Hands does not rediscover it. - LFS staging set. `SubstanceCleanBreakTests` fails loudly on any LFS pointer it scans, so the job must restore every LFS-tracked file under `Assets/`, `Packages/`, `ProjectSettings/` and `GameData/*.cc` that is not a - binary-media extension (the test's `BinaryExtensions` denylist): 99 files at `6905726ba`, 96 `*.asset` and 3 + binary-media extension (the test's `BinaryExtensions` denylist): 99 files at `83e6957de`, 96 `*.asset` and 3 `*.cc` (`GameData/Aetheria.cc`, `GameData/Mods/aetheria.nakovalnya/ship.cc`, `GameData/Mods/aetheria.wren/ship.cc`), which includes `ProjectSettings/ProjectSettings.asset` and `Assets/Resources/Settings.asset`. Derive the list from the merged tree instead of hand-copying it: `git ls-files Assets Packages ProjectSettings 'GameData/*.cc' | git check-attr --stdin filter | grep 'lfs$' | sed 's/: filter: lfs//' | grep -viE '\.(png|jpg|jpeg|tga|tif|tiff|psd|bmp|gif|exr|hdr|dds|wav|mp3|ogg|mp4|fbx|glb|blend|ttf|otf|dll|so|pdb|msgpack|zip|bank)$'`, - then copy each path from the `/lfs` mount over the checkout. Staging only two files turns the suite red. + then copy each path from the `/lfs` mount over the checkout. That set (99: the 97 the sbsar guards read plus the two mod `ship.cc` files the Nakovalnya and Wren tests open) makes `SubstanceCleanBreakTests` green and nothing more: staging only two files turns it red. For a fully green suite also stage `GameData/Mods/*/ship.glb` (the catalog excludes a package with an invalid GLB header, failing about 520 tests) and the LFS `.ttf`/`.otf` fonts `CreditsTests.FontCreditsShowWhatTheFontsThemselvesEmbed` reads. - Unity batchmode compile of the merged tree (Self, in a worktree, never with the operator's editor open on the main tree). This is the Cut 1 renderer compile the map still owes. - Operator: fly through a belt (the Cut 1 check the map still owes). Rocks orbit smoothly, and the minimap From f38862aabc55744d9736511c48aa780a2e78f2a8 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 09:33:16 +0000 Subject: [PATCH 094/190] Test: reload keeps the hardpoint an origin two hardpoints accept (fails at base) Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../HardpointOriginTests.cs | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 tests/Aetheria.Shared.Tests/HardpointOriginTests.cs diff --git a/tests/Aetheria.Shared.Tests/HardpointOriginTests.cs b/tests/Aetheria.Shared.Tests/HardpointOriginTests.cs new file mode 100644 index 000000000..7087f3090 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/HardpointOriginTests.cs @@ -0,0 +1,67 @@ +using System.Linq; +using CultMath; +using Xunit; +using static CultMath.math; + +// Hardpoint gear holds the hardpoint it was seated in across save and reload: an origin two hardpoints accept is +// resolved by the item's saved Rotation (HardpointData.Rotation), not by hardpoint declaration order. +public sealed partial class RunStartTests +{ + // Two disjoint ballistic hardpoints, A (None, cell (6,5)) and B (Reversed, cell (5,5)). The edge gun's single cell is + // (1,0): origin (5,5) puts it at (6,5) unturned and at (5,5) turned 180 degrees, so both hardpoints take it there. + private (HullData hull, HardpointData a, HardpointData b) TwinMountHull(string name) + { + var a = Mount(HardpointType.Ballistic, 6, 5, rotation: ItemRotation.None); + var b = Mount(HardpointType.Ballistic, 5, 5, rotation: ItemRotation.Reversed); + return (ScratchHull(name, 12, a, b), a, b); + } + + [Fact] + public void AnOriginTwoHardpointsAcceptReloadsIntoTheHardpointItHeld() + { + var (hull, _, b) = TwinMountHull("Origin Twin Mounts"); + var filler = ScratchGear("Origin Filler", HardpointType.Ballistic, 1, 1); + var edge = ScratchGear("Origin Edge Gun", HardpointType.Ballistic, EdgeShape()); + var entity = BareHull(hull); + Assert.True(entity.TryEquip(Instance(filler), int2(6, 5))); + Assert.True(entity.TryEquip(Instance(edge), int2(5, 5))); + var held = entity.Equipment.Single(i => i.Data == edge); + Assert.Same(b, held.Hardpoint); + Assert.Equal(ItemRotation.Reversed, held.EquippableItem.Rotation); + // Un-equip the filler as a player would, then save and reload. + entity.TryUnequip(entity.Equipment.Single(i => i.Data == filler)); + + var reloaded = EntitySerializer.Unpack(_items, null, EntitySerializer.Pack(entity)); + var after = reloaded.Equipment.Single(i => i.Data == edge); + Assert.Equal(1, reloaded.HullData.Hardpoints.IndexOf(after.Hardpoint)); + } + + [Fact] + public void ReloadKeepsTheFirstHardpointToo() + { + var (hull, _, _) = TwinMountHull("Origin Twin Mounts First"); + var edge = ScratchGear("Origin Edge Gun First", HardpointType.Ballistic, EdgeShape()); + var entity = BareHull(hull); + Assert.True(entity.TryEquip(Instance(edge), int2(5, 5))); + Assert.Equal(ItemRotation.None, entity.Equipment.Single(i => i.Data == edge).EquippableItem.Rotation); + + var reloaded = EntitySerializer.Unpack(_items, null, EntitySerializer.Pack(entity)); + var after = reloaded.Equipment.Single(i => i.Data == edge); + Assert.Equal(0, reloaded.HullData.Hardpoints.IndexOf(after.Hardpoint)); + } + + [Fact] + public void AnItemWhoseRotationNamesNoAcceptingHardpointStillSeats() + { + var (hull, a, _) = TwinMountHull("Origin Twin Mounts Stray"); + var edge = ScratchGear("Origin Edge Gun Stray", HardpointType.Ballistic, EdgeShape()); + var entity = BareHull(hull); + var item = Instance(edge); + item.Rotation = ItemRotation.Clockwise; + Assert.True(entity.ItemFits(item, int2(5, 5))); + Assert.True(entity.TryEquip(item, int2(5, 5))); + var held = entity.Equipment.Single(i => i.Data == edge); + Assert.Same(a, held.Hardpoint); + Assert.Equal(ItemRotation.None, held.EquippableItem.Rotation); + } +} From eea98d44140b2484923727063f30d44632dc31a3 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 09:33:23 +0000 Subject: [PATCH 095/190] HardpointAt prefers the hardpoint matching the item's Rotation Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/Entity.cs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Assets/Scripts/ServerShared/Entity.cs b/Assets/Scripts/ServerShared/Entity.cs index b520db17d..6f7683822 100644 --- a/Assets/Scripts/ServerShared/Entity.cs +++ b/Assets/Scripts/ServerShared/Entity.cs @@ -1545,7 +1545,7 @@ public abstract class Entity } else { - hardpoint = HardpointAt(itemData, hullData, hullCoord, moving); + hardpoint = HardpointAt(itemData, hullData, hullCoord, item.Rotation, moving); if (hardpoint == null) return false; item.Rotation = hardpoint.Rotation; } @@ -1560,10 +1560,12 @@ public abstract class Entity // The one placement rule for hardpoint gear. At this origin the item lies within a hardpoint of its type, turned to // that hardpoint's rotation (HardpointData.TakesAt, the fit rule); its own cells are free, since a hardpoint's // leftover cells may hold general gear (operator, 2026-09-30: "saving slots in a hardpoint can be a valid tradeoff - // for crowded ships"); and that hardpoint holds no other hardpoint item, since it holds one at most. - private HardpointData HardpointAt(EquippableItemData itemData, HullData hullData, int2 hullCoord, EquippedItem moving) + // for crowded ships"); and that hardpoint holds no other hardpoint item, since it holds one at most. Where several hardpoints accept the origin, the + // one whose rotation equals the item's own (saved) rotation is preferred, so reload seats gear where it was; an item whose + // rotation names none of them takes the first (stable order). + private HardpointData HardpointAt(EquippableItemData itemData, HullData hullData, int2 hullCoord, ItemRotation seated, EquippedItem moving) { - foreach (var hardpoint in hullData.Hardpoints) + foreach (var hardpoint in hullData.Hardpoints.OrderBy(h => h.Rotation == seated ? 0 : 1)) { if (!hardpoint.TakesAt(itemData, hullCoord - hardpoint.Position)) continue; var ownCellsFree = itemData.Shape.Coordinates From 2d91a5b13b82f23e13300630d5d5e574c6a472cb Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 11:19:09 +0000 Subject: [PATCH 096/190] Probes never write item.Rotation: TryEquip seats the hardpoint's rotation; ItemFits reports it via out Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/Entity.cs | 17 +++++++++++++---- Assets/Scripts/UI/Menu/InventoryPanel.cs | 4 ++-- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/Assets/Scripts/ServerShared/Entity.cs b/Assets/Scripts/ServerShared/Entity.cs index 6f7683822..2f3062ff2 100644 --- a/Assets/Scripts/ServerShared/Entity.cs +++ b/Assets/Scripts/ServerShared/Entity.cs @@ -1547,7 +1547,6 @@ public abstract class Entity { hardpoint = HardpointAt(itemData, hullData, hullCoord, item.Rotation, moving); if (hardpoint == null) return false; - item.Rotation = hardpoint.Rotation; } return true; @@ -1582,14 +1581,22 @@ public abstract class Entity // Check whether the given item will fit when its origin is placed at the given coordinate on the hull. An item that // is already equipped here is judged without its own cells, so a gun can be moved within its own hardpoint; // TryEquip stays strict (it never sees an item as its own occupant), so equipping an equipped item twice is refused. - public bool ItemFits(EquippableItem item, int2 hullCoord) + public bool ItemFits(EquippableItem item, int2 hullCoord) => ItemFits(item, hullCoord, out _); + + // As above, and reports the rotation TryEquip would seat the item at: its hardpoint's for hardpoint gear, otherwise + // its own. A probe never writes item.Rotation; TryEquip is the only seat. + public bool ItemFits(EquippableItem item, int2 hullCoord, out ItemRotation seated) { + seated = item.Rotation; // Don't allow equipping while deployed if (_active) return false; var itemData = ItemManager.GetData(item); var hullData = ItemManager.GetData(Hull) as HullData; - return ItemFits(itemData, hullData, item, hullCoord, out _, Equipment.FirstOrDefault(e => e.EquippableItem == item)); + if (!ItemFits(itemData, hullData, item, hullCoord, out var hardpoint, Equipment.FirstOrDefault(e => e.EquippableItem == item))) + return false; + seated = hardpoint?.Rotation ?? item.Rotation; + return true; } public bool TryFindSpace(EquippableItem item, out int2 hullCoord) @@ -1662,7 +1669,9 @@ public abstract class Entity var hullData = ItemManager.GetData(Hull) as HullData; if (!ItemFits(itemData, hullData, item, hullCoord, out var hardpoint)) return false; - + // The one seat of hardpoint gear's rotation, before EquippedItem's ctor reads it. + if (hardpoint != null) item.Rotation = hardpoint.Rotation; + EquippedItem equippedItem; if (itemData.HardpointType == HardpointType.Tool) { diff --git a/Assets/Scripts/UI/Menu/InventoryPanel.cs b/Assets/Scripts/UI/Menu/InventoryPanel.cs index 2087a3870..eaa6212ac 100644 --- a/Assets/Scripts/UI/Menu/InventoryPanel.cs +++ b/Assets/Scripts/UI/Menu/InventoryPanel.cs @@ -386,11 +386,11 @@ public class InventoryPanel : MonoBehaviour, IPointerClickHandler var itemData = GameManager.ItemManager.GetData(item); if (!(item is EquippableItem equippableItem)) return; var placementPosition = v + itemDragObject.OriginCellOffset; - if (entity.ItemFits(equippableItem, placementPosition)) + if (entity.ItemFits(equippableItem, placementPosition, out var seated)) { //foreach (var cell in _dragCells) cell.gameObject.SetActive(false); FakeItem = item; - FakeOccupancy = hullData.Shape.Inset(itemData.Shape, placementPosition, item.Rotation); + FakeOccupancy = hullData.Shape.Inset(itemData.Shape, placementPosition, seated); RefreshCells(); GameManager.RegisterDragTarget(drag => { From d9ccac62963e56fb39c37b78099610ceca21c647 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 11:19:26 +0000 Subject: [PATCH 097/190] Pin probe purity and the shipped catalog's hardpoint origins Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../HardpointOriginTests.cs | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/tests/Aetheria.Shared.Tests/HardpointOriginTests.cs b/tests/Aetheria.Shared.Tests/HardpointOriginTests.cs index 7087f3090..e675e3646 100644 --- a/tests/Aetheria.Shared.Tests/HardpointOriginTests.cs +++ b/tests/Aetheria.Shared.Tests/HardpointOriginTests.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using System.Linq; using CultMath; using Xunit; @@ -64,4 +65,74 @@ public sealed partial class RunStartTests Assert.Same(a, held.Hardpoint); Assert.Equal(ItemRotation.None, held.EquippableItem.Rotation); } + + // A probe reports; only TryEquip seats. The probe used to turn the item to the hardpoint it found, so the same item + // probed twice could resolve differently, and a failed or merely previewed placement left it turned. + [Fact] + public void AProbeLeavesTheItemsRotationAlone() + { + var (hull, a, b) = TwinMountHull("Origin Twin Mounts Probe"); + var edge = ScratchGear("Origin Edge Gun Probe", HardpointType.Ballistic, EdgeShape()); + var entity = BareHull(hull); + var item = Instance(edge); + item.Rotation = ItemRotation.Clockwise; + + Assert.True(entity.ItemFits(item, int2(5, 5))); + Assert.Equal(ItemRotation.Clockwise, item.Rotation); + Assert.True(entity.ItemFits(item, int2(5, 5), out var seated)); + Assert.Equal(ItemRotation.None, seated); + Assert.Equal(ItemRotation.Clockwise, item.Rotation); + Assert.True(entity.TryFindSpace(item, out _)); + Assert.Equal(ItemRotation.Clockwise, item.Rotation); + Assert.False(entity.ItemFits(item, int2(0, 0), out var unseated)); + Assert.Equal(ItemRotation.Clockwise, unseated); + Assert.Equal(ItemRotation.Clockwise, item.Rotation); + + Assert.True(entity.TryEquip(item, int2(5, 5))); + var held = entity.Equipment.Single(i => i.Data == edge); + Assert.Same(a, held.Hardpoint); + Assert.Equal(ItemRotation.None, held.EquippableItem.Rotation); + + var reversed = Instance(edge); + reversed.Rotation = ItemRotation.Reversed; + var fresh = BareHull(hull); + Assert.True(fresh.ItemFits(reversed, int2(5, 5), out var first)); + Assert.True(fresh.ItemFits(reversed, int2(5, 5), out var second)); + Assert.Equal(ItemRotation.Reversed, first); + Assert.Equal(first, second); + Assert.Equal(b.Rotation, first); + } +} + +// The shipped catalog authors no origin that two differently turned hardpoints of one type both take. The fit rule alone +// over-approximates what Entity.HardpointAt sees (occupancy only removes candidates), so zero here is stricter than needed. +public sealed class ShippedHardpointOriginTests +{ + [Fact] + public void TheShippedCatalogHasNoAmbiguousOrigin() + { + using var cache = RestoredHullsTests.OpenCatalog(); + var designs = cache.GetAll<EquippableItemData>().Where(d => !(d is HullData) && d.HardpointType != HardpointType.Tool).ToArray(); + var ambiguous = new List<string>(); + var pairs = 0; + foreach (var hull in cache.GetAll<HullData>()) + for (var i = 0; i < hull.Hardpoints.Count; i++) + for (var j = i + 1; j < hull.Hardpoints.Count; j++) + { + var a = hull.Hardpoints[i]; + var b = hull.Hardpoints[j]; + if (a.Type != b.Type || a.Rotation == b.Rotation) continue; + pairs++; + foreach (var design in designs.Where(d => d.HardpointType == a.Type)) + for (var x = -20; x < hull.Shape.Width; x++) + for (var y = -20; y < hull.Shape.Height; y++) + { + var origin = int2(x, y); + if (a.TakesAt(design, origin - a.Position) && b.TakesAt(design, origin - b.Position)) + ambiguous.Add($"{hull.Name} {design.Name} at ({x},{y}): hardpoints {i} and {j}"); + } + } + System.Console.WriteLine($"ShippedHardpointOriginTests visited {pairs} same-type different-rotation pairs"); + Assert.True(ambiguous.Count == 0, $"{ambiguous.Count} ambiguous origins: " + string.Join("; ", ambiguous.Take(10))); + } } From cc20ce93ac8b7073003aae00bc641351a459ab0d Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 13:28:37 +0000 Subject: [PATCH 098/190] Catalog origin pin fails if its scan visits nothing Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- tests/Aetheria.Shared.Tests/HardpointOriginTests.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/Aetheria.Shared.Tests/HardpointOriginTests.cs b/tests/Aetheria.Shared.Tests/HardpointOriginTests.cs index e675e3646..7c635bb58 100644 --- a/tests/Aetheria.Shared.Tests/HardpointOriginTests.cs +++ b/tests/Aetheria.Shared.Tests/HardpointOriginTests.cs @@ -115,6 +115,7 @@ public sealed class ShippedHardpointOriginTests var designs = cache.GetAll<EquippableItemData>().Where(d => !(d is HullData) && d.HardpointType != HardpointType.Tool).ToArray(); var ambiguous = new List<string>(); var pairs = 0; + var probes = 0; foreach (var hull in cache.GetAll<HullData>()) for (var i = 0; i < hull.Hardpoints.Count; i++) for (var j = i + 1; j < hull.Hardpoints.Count; j++) @@ -128,11 +129,14 @@ public sealed class ShippedHardpointOriginTests for (var y = -20; y < hull.Shape.Height; y++) { var origin = int2(x, y); + probes++; if (a.TakesAt(design, origin - a.Position) && b.TakesAt(design, origin - b.Position)) ambiguous.Add($"{hull.Name} {design.Name} at ({x},{y}): hardpoints {i} and {j}"); } } System.Console.WriteLine($"ShippedHardpointOriginTests visited {pairs} same-type different-rotation pairs"); + // A scan that visits nothing would pass; the catalog has such pairs today, so losing them must fail loudly. + Assert.True(pairs > 0 && probes > 0, $"the scan visited {pairs} pairs and {probes} origins"); Assert.True(ambiguous.Count == 0, $"{ambiguous.Count} ambiguous origins: " + string.Join("; ", ambiguous.Take(10))); } } From f7d5a7d2a81e2ee8ac1381e6340f2fbf87e1379d Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 13:32:34 +0000 Subject: [PATCH 099/190] A failed start is decided in RunStart.Launch; the scene steps nothing without a live run Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/Gameplay/ActionGameManager.cs | 21 +++------ Assets/Scripts/ServerShared/RunStart.cs | 15 ++++++ tests/Aetheria.Shared.Tests/RunLaunchTests.cs | 46 +++++++++++++++++++ 3 files changed, 68 insertions(+), 14 deletions(-) create mode 100644 tests/Aetheria.Shared.Tests/RunLaunchTests.cs diff --git a/Assets/Scripts/Gameplay/ActionGameManager.cs b/Assets/Scripts/Gameplay/ActionGameManager.cs index 8c2b38345..74f495afb 100644 --- a/Assets/Scripts/Gameplay/ActionGameManager.cs +++ b/Assets/Scripts/Gameplay/ActionGameManager.cs @@ -854,21 +854,12 @@ public class ActionGameManager : MonoBehaviour var scenario = PendingScenario; PendingScenario = null; var failures = new List<string>(); - RunStart.Staged staged = null; - try + var staged = RunStart.Launch(() => RunSave.Replace(CultCache, () => { - staged = RunSave.Replace(CultCache, () => - { - RunStart.GenerateArena(ItemManager, Settings.ZoneSettings, Settings.PlanetSettings, CurrentGalaxy, scenario); - PopulateLevel(CurrentGalaxy.Entrance); - return RunStart.Stage(ItemManager, Zone, scenario, Settings.StartingHullName, Settings.TutorialGenerationSettings, failures); - }); - } - catch (Exception exception) - { - Debug.LogException(exception); - failures.Add(exception.Message); - } + RunStart.GenerateArena(ItemManager, Settings.ZoneSettings, Settings.PlanetSettings, CurrentGalaxy, scenario); + PopulateLevel(CurrentGalaxy.Entrance); + return RunStart.Stage(ItemManager, Zone, scenario, Settings.StartingHullName, Settings.TutorialGenerationSettings, failures); + }), failures, Debug.LogException); if (staged == null) { @@ -1348,6 +1339,8 @@ public class ActionGameManager : MonoBehaviour void Update() { + // No live run (a start that failed, a run that ended): the main menu is up, and nothing steps a zone or reads a player. + if (CurrentGalaxy == null) return; if(!_paused) { _time += Time.deltaTime; diff --git a/Assets/Scripts/ServerShared/RunStart.cs b/Assets/Scripts/ServerShared/RunStart.cs index cadd66bcc..4e6808859 100644 --- a/Assets/Scripts/ServerShared/RunStart.cs +++ b/Assets/Scripts/ServerShared/RunStart.cs @@ -30,6 +30,21 @@ public static class RunStart itemManager, zoneSettings, planetSettings, galaxy, galaxy.Entrance, galaxy.IsPrelude, scenario.Ambient); } + // Runs a start and answers whether it produced a run: null, with the reason in `failures`, when `start` throws or + // returns nothing. The caller shows the failure and clears its run; nothing past a null may run the game. + public static Staged Launch(Func<Staged> start, List<string> failures, Action<Exception> log = null) + { + Staged staged = null; + try { staged = start(); } + catch (Exception exception) + { + log?.Invoke(exception); + failures.Add(exception.Message); + } + if (staged == null && failures.Count == 0) failures.Add("the start produced no run"); + return staged; + } + // Runs the scenario's Stage, then admits its player and everything it placed: each entity's stance set both ways // with the player, a pilot for each piloted one. Returns null, with every failure listed and the arena unchanged, // unless the whole scenario staged. diff --git a/tests/Aetheria.Shared.Tests/RunLaunchTests.cs b/tests/Aetheria.Shared.Tests/RunLaunchTests.cs new file mode 100644 index 000000000..1c8b0e380 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/RunLaunchTests.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using Xunit; + +// RunStart.Launch decides whether a start produced a run; the game scene halts on its answer (a failed start clears the +// galaxy, and a scene with no galaxy steps nothing). Kills: a start that throws or returns nothing reading as a run, a +// failure with no reason to show on the menu, a thrown exception that is neither logged nor listed, and a start that +// worked being reported failed. +public sealed class RunLaunchTests +{ + [Fact] + public void AStartThatThrowsIsNoRunAndSaysWhy() + { + var failures = new List<string>(); + var logged = new List<Exception>(); + var staged = RunStart.Launch(() => throw new InvalidOperationException("the arena would not generate"), failures, logged.Add); + Assert.Null(staged); + Assert.Equal(new[] { "the arena would not generate" }, failures); + Assert.Single(logged); + } + + [Fact] + public void AStartThatReturnsNothingIsNoRunAndKeepsItsOwnReasons() + { + var failures = new List<string>(); + Assert.Null(RunStart.Launch(() => { failures.Add("player: the scenario places no player"); return null; }, failures)); + Assert.Equal(new[] { "player: the scenario places no player" }, failures); + } + + [Fact] + public void AStartThatReturnsNothingAndSaysNothingStillGivesAReason() + { + var failures = new List<string>(); + Assert.Null(RunStart.Launch(() => null, failures)); + Assert.Single(failures); + } + + [Fact] + public void AStartThatStagedIsARunWithNoFailures() + { + var failures = new List<string>(); + var made = new RunStart.Staged(); + Assert.Same(made, RunStart.Launch(() => made, failures)); + Assert.Empty(failures); + } +} From 95568140e2c78d21e440272d956dafc339eae5b2 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 13:35:15 +0000 Subject: [PATCH 100/190] Pin the deployed guard of the out ItemFits overload Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../HardpointOriginTests.cs | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tests/Aetheria.Shared.Tests/HardpointOriginTests.cs b/tests/Aetheria.Shared.Tests/HardpointOriginTests.cs index 7c635bb58..6d5341ae9 100644 --- a/tests/Aetheria.Shared.Tests/HardpointOriginTests.cs +++ b/tests/Aetheria.Shared.Tests/HardpointOriginTests.cs @@ -102,6 +102,27 @@ public sealed partial class RunStartTests Assert.Equal(first, second); Assert.Equal(b.Rotation, first); } + + // A deployed entity takes no gear, so no probe reports a fit or a seat on one (the out overload's own guard). + // Kills: a probe that ignores the deployed state and offers a placement TryEquip would then refuse. + [Fact] + public void ADeployedEntityTakesNoProbe() + { + var (hull, _, _) = TwinMountHull("Origin Twin Mounts Deployed"); + var edge = ScratchGear("Origin Edge Gun Deployed", HardpointType.Ballistic, EdgeShape()); + var entity = BareHull(hull); + var item = Instance(edge); + item.Rotation = ItemRotation.Clockwise; + Assert.True(entity.ItemFits(item, int2(5, 5), out _)); + + var zone = Arena(false); + entity.Zone = zone; + zone.Admit(entity, piloted: false); + Assert.False(entity.ItemFits(item, int2(5, 5), out var seated)); + Assert.Equal(ItemRotation.Clockwise, seated); + Assert.False(entity.ItemFits(item, int2(5, 5))); + Assert.False(entity.TryEquip(item, int2(5, 5))); + } } // The shipped catalog authors no origin that two differently turned hardpoints of one type both take. The fit rule alone From 796a7af9efc605cca831731b57f30603bf95d77a Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 13:56:16 +0000 Subject: [PATCH 101/190] ActionGameManager.RunLive gates the renderer's Update paths too Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/Gameplay/ActionGameManager.cs | 6 ++++-- Assets/Scripts/Zone Display/ZoneRenderer.cs | 2 ++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/Assets/Scripts/Gameplay/ActionGameManager.cs b/Assets/Scripts/Gameplay/ActionGameManager.cs index 74f495afb..a47577d38 100644 --- a/Assets/Scripts/Gameplay/ActionGameManager.cs +++ b/Assets/Scripts/Gameplay/ActionGameManager.cs @@ -106,6 +106,9 @@ public class ActionGameManager : MonoBehaviour } public static Galaxy CurrentGalaxy; + // Whether a run is live: a failed start and a finished run both clear the galaxy, and the scene's update paths (this + // manager's, the renderer's) step and draw nothing without one. + public static bool RunLive => CurrentGalaxy != null; // The scenario a new run starts from: MainMenu.Launch sets it, and StartGame's new-run branch consumes it once. public static Scenario PendingScenario; @@ -1339,8 +1342,7 @@ public class ActionGameManager : MonoBehaviour void Update() { - // No live run (a start that failed, a run that ended): the main menu is up, and nothing steps a zone or reads a player. - if (CurrentGalaxy == null) return; + if (!RunLive) return; if(!_paused) { _time += Time.deltaTime; diff --git a/Assets/Scripts/Zone Display/ZoneRenderer.cs b/Assets/Scripts/Zone Display/ZoneRenderer.cs index f63f746bd..24ce8a494 100644 --- a/Assets/Scripts/Zone Display/ZoneRenderer.cs +++ b/Assets/Scripts/Zone Display/ZoneRenderer.cs @@ -508,6 +508,7 @@ public class ZoneRenderer : MonoBehaviour void LateUpdate() { + if (!ActionGameManager.RunLive) return; Map.Draw(Zone, ActionGameManager.Clock.Lead); } @@ -550,6 +551,7 @@ public class ZoneRenderer : MonoBehaviour void Update() { + if (!ActionGameManager.RunLive) return; var lead = ActionGameManager.Clock.Lead; GravityLowering.Lower(Zone, lead, ref _gravityWells); foreach (var loot in _floatingItems.Values) From 6a5ee8ee1c6e363ed5f0f8860c92520bb1f21547 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 14:00:37 +0000 Subject: [PATCH 102/190] Pin the boss gate's exit-zone check and the refused-boss path Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- tests/Aetheria.Shared.Tests/RunGoalTests.cs | 48 +++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/tests/Aetheria.Shared.Tests/RunGoalTests.cs b/tests/Aetheria.Shared.Tests/RunGoalTests.cs index cfdbdb158..c01927ecb 100644 --- a/tests/Aetheria.Shared.Tests/RunGoalTests.cs +++ b/tests/Aetheria.Shared.Tests/RunGoalTests.cs @@ -414,6 +414,54 @@ public sealed partial class RunStartTests Assert.False(RunGoal.ExitOpen(ZoneOf(galaxy, zone))); } + // The gate belongs to the exit zone alone. A boss zone that is not the exit spawns its boss and loses it, and that zone's gate + // stays sealed: the exit check, not the boss mark, decides where a gate can open (a MainGalaxy choke-point boss zone is such a zone). + [Fact] + public void Exit_stays_sealed_in_a_non_exit_zone_whose_boss_died() + { + var galaxy = DemoGalaxy(1); + GiveAntagonistABoss(galaxy); + var other = galaxy.Zones.First(zone => zone != galaxy.Exit); + galaxy.BossZones[Zhestokost(galaxy)] = other; + + var zone = ZoneOf(galaxy, other); + Assert.True(zone.Pack.BossSpawned, "the fixture must spawn a boss outside the exit"); + var boss = Assert.Single(zone.Entities, entity => entity.IsBoss); + Assert.False(RunGoal.ExitOpen(zone)); + boss.HeatstrokeDeath.OnNext(Unit.Default); + Assert.False(RunGoal.BossAlive(zone)); + Assert.False(RunGoal.ExitOpen(zone), "a dead boss outside the exit zone opens no gate"); + } + + // The null-boss path through the real spawn loop: the boss zone is the exit, the faction's Loadout resolves, and + // Materialize cannot build it, so no boss is produced and the gate must not read as open. + // Both refusals (no Loadout, unbuildable Loadout) leave BossSpawned false. + [Fact] + public void A_refused_boss_leaves_the_exit_sealed_through_the_spawn_loop() + { + var galaxy = DemoGalaxy(1); + var loadout = GiveAntagonistABoss(galaxy); + var antagonist = Zhestokost(galaxy); + var exitZone = galaxy.Exit; + Assert.Equal(exitZone, galaxy.BossZones[antagonist]); + + // Unbuildable: the Loadout resolves and the entity is null. + loadout.Slots[0].Position = new int2(999, 999); + loadout.Slots[1].Position = new int2(998, 998); + StoreLoadout(loadout); + var unbuildable = ZoneOf(galaxy, exitZone); + Assert.False(unbuildable.Pack.BossSpawned); + Assert.DoesNotContain(unbuildable.Entities, entity => entity.IsBoss); + Assert.False(RunGoal.ExitOpen(unbuildable)); + + // Unresolved: the faction's Loadout is gone, so BossOf returns null. + antagonist.BossLoadout = new CultRecordRef<Loadout>(Loadouts.KeyOf("No Such Loadout")); + var unresolved = ZoneOf(galaxy, exitZone); + Assert.False(unresolved.Pack.BossSpawned); + Assert.DoesNotContain(unresolved.Entities, entity => entity.IsBoss); + Assert.False(RunGoal.ExitOpen(unresolved)); + } + // Continue: the mark is saved with the zone and restored, so a boss alive when the run was saved is alive after. [Fact] public void Boss_mark_survives_continue() From 1411629983ac1bf6bc3ccde629880744faefa5ea Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 14:02:19 +0000 Subject: [PATCH 103/190] Pin ship order past 1000 units and undetected ships at every distance Two sweep fixtures close mining-target-pin-gaps: ships on both sides of 1000 and out to 4000 ordered both ways, and undetected ships from 2 to 8000 units on every bearing never picked by any press. Tests only. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../MiningTargetQueriesTests.cs | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/tests/Aetheria.Shared.Tests/MiningTargetQueriesTests.cs b/tests/Aetheria.Shared.Tests/MiningTargetQueriesTests.cs index 374f9292e..9cd8ec025 100644 --- a/tests/Aetheria.Shared.Tests/MiningTargetQueriesTests.cs +++ b/tests/Aetheria.Shared.Tests/MiningTargetQueriesTests.cs @@ -546,4 +546,82 @@ public sealed partial class MiningCut3Tests Assert.Equal(order[i % order.Count], observer.Target.Value); } } + + private static float2 Polar(float2 at, float distance, float angle) => at + distance * float2(cos(angle), sin(angle)); + + // Both presses, from nothing and from every target, visit `order` and wrap. + private static void AssertPressesWalk(Ship observer, List<TargetRef> order) + { + observer.SetTarget(TargetRef.None); + for (var i = 0; i <= order.Count; i++) + { + Assert.True(observer.TargetNext()); + Assert.Equal(order[i % order.Count], observer.Target.Value); + } + observer.SetTarget(TargetRef.None); + for (var i = 0; i <= order.Count; i++) + { + Assert.True(observer.TargetPrevious()); + Assert.Equal(order[order.Count - 1 - i % order.Count], observer.Target.Value); + } + for (var i = 0; i < order.Count; i++) + { + observer.SetTarget(order[i]); + Assert.True(observer.TargetNext()); + Assert.Equal(order[(i + 1) % order.Count], observer.Target.Value); + observer.SetTarget(order[i]); + Assert.True(observer.TargetPrevious()); + Assert.Equal(order[(i + order.Count - 1) % order.Count], observer.Target.Value); + } + } + + // Ships keep their distance order for both presses at every range: the key is the distance itself past 1000 too, + // not a function that clamps or bends there. Ships stand on both sides of 1000, many thousand units out, each a + // distinct distance and admitted in an order unlike the distance order, so a key that ties or inverts any two + // falls back on zone order and shows. + [Fact] + public void ShipsPastAThousandUnitsAreOrderedByDistanceBothWays() + { + var at = float2(500, 0); + var (s, observer) = TargetScene(7, at); + var distances = new[] { 1800f, 700f, 2400f, 1200f, 400f, 4000f, 999f, 1500f, 1001f, 150f, 3100f, 1100f }; + for (var i = 0; i < distances.Length; i++) Sight(s, observer, Polar(at, distances[i], i * 1.9f)); + var order = ByDistance(s, observer, 120f); + Assert.True(order.Count(t => t.Chunk.HasValue) >= 8 && order.Count(t => t.Entity != null) == distances.Length, $"degenerate: {order.Count} candidates"); + var ships = order.Where(t => t.Entity != null).Select(t => length(t.Entity.Position.xz - at)).ToList(); + Assert.Equal(ships.OrderBy(d => d).ToList(), ships); + Assert.Equal(ships.Distinct().Count(), ships.Count); + AssertPressesWalk(observer, order); + } + + // The pilot's instruments bound the pick at every range: undetected ships stand from a few units out to well + // past the farthest seen one, on every bearing, among the seen ships, so a press that offers undetected ships + // within any window of distance (or only once the zone is crowded) offers one here. Every press walks the + // detected order, and the reticle aimed straight at each hidden ship still takes a detected target. + [Fact] + public void ShipsTheObserverHasNotDetectedAreNeverPickedAtAnyDistance() + { + var at = float2(500, 0); + var (s, observer) = TargetScene(7, at); + foreach (var (distance, i) in new[] { 60f, 300f, 800f, 1300f, 2000f }.Select((d, i) => (d, i))) Sight(s, observer, Polar(at, distance, i * 1.3f + .4f)); + var hidden = new List<TargetRef>(); + for (var i = 0; i < 48; i++) + hidden.Add(Unseen(s, Polar(at, 2f * MathF.Pow(1.18f, i), i * 2.4f))); + var order = ByDistance(s, observer, 120f); + Assert.True(order.Count > 5 && order.Count(t => t.Entity != null) == 5, $"degenerate: {order.Count} candidates"); + Assert.All(hidden, h => Assert.DoesNotContain(h, order)); + var farthest = hidden.Max(h => length(h.Entity.Position.xz - at)); + Assert.True(farthest > 4000f && hidden.Count(h => length(h.Entity.Position.xz - at) is > 100f and < 2500f) > 10, "the hidden ships do not sweep the window"); + + AssertPressesWalk(observer, order); + foreach (var h in hidden) + { + var to = h.Entity.Position.xz - at; + observer.Aim = float3(to.x, 0, to.y); + observer.SetTarget(TargetRef.None); + Assert.True(observer.TargetUnderReticle()); + Assert.DoesNotContain(observer.Target.Value, hidden); + Assert.Contains(observer.Target.Value, order); + } + } } From 6c13605adba0f608d939455cdb8e9a1e42b6fa42 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 14:52:07 +0000 Subject: [PATCH 104/190] Docs: bring the new-run passages true to the scenarios menu New Game opens the scenario picker; RunSave.Replace swaps the saved run after staging; Galaxy.IsPrelude is the one tutorial owner; MIConvexHull and the IsTutorial static are gone; item streams are seeded from the galaxy seed. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- docs/cultcache-migration-cut.md | 58 ++++++++++++++++--------------- docs/headless-playground-cut.md | 56 +++++++++++++++-------------- docs/item-provenance-cut.md | 16 +++++---- docs/item-provenance-substrate.md | 23 ++++++------ docs/merge-to-master-checklist.md | 2 +- docs/tutorial-script-sketch.md | 2 +- 6 files changed, 84 insertions(+), 73 deletions(-) diff --git a/docs/cultcache-migration-cut.md b/docs/cultcache-migration-cut.md index 967f4b6b7..f27bde97d 100644 --- a/docs/cultcache-migration-cut.md +++ b/docs/cultcache-migration-cut.md @@ -95,7 +95,7 @@ recorded, none blocking: `WeaponData.AmmoType` refs. - One cache holds all three stores for the process. - `RunSave` commits a save atomically with stable zone keys and clears the run - on New Game or death. + on death or victory (`RunSave.Replace` drops the old run once a new one has staged). - `SavedRun`, the msgpack settings and layout I/O, `.loadout`, `SaveState`, `SaveZone` and the importer are deleted. - **Loadouts are authored ship presets in the catalog.** This was reworked @@ -138,9 +138,6 @@ The first Soul pass found untested all-or-nothing, availability and price rules, weapon-group corruption, dictionary-ordered product choice, and a premature "done". All are fixed. -Recorded, not fixed: New Game clears the previous run before generation, as the -spec says, so a generation fault loses that run. - `GameData/PlayerSettings.msgpack` entered history through `5c5c3d5e`. It holds defaults and the username, and about 65 earlier versions are already in LFS history, so history is left alone. @@ -651,7 +648,9 @@ After Cut 10, every runtime write is a single-store `Commit` on one cache that holds catalog, run and player stores from first access: - `RunSave.Commit` saves the run at wormhole arrival and quit, with stable `SavedZone` keys. -- `RunSave.Clear` deletes every run record at New Game and at death. +- `RunSave.Clear` deletes every run record at death and victory (`ActionGameManager.EndRun`). +- `RunSave.Replace` swaps the saved run for a new one only after the new run has + staged; a start that fails leaves the saved run in place. - The settings getter creates `PlayerSettings` on first launch, and `SavePlayerSettings` commits it. - `Loadouts.Save` writes loadouts to the player store, and @@ -849,7 +848,7 @@ reads a global back (Q4). | Global | Store | Read by | Existence owned by | Missing at main menu | Missing at resume | Missing at new game | |---|---|---|---|---|---|---| | `PlayerSettings` | Player | `MainMenu` (name, tutorial flag), `ActionGameManager` (credits) | boot: `ActionGameManager.Awake` after `AetheriaStores.Open`, when `GetGlobal<PlayerSettings>()` is null, upserts one and flushes (Cut 10) | cannot happen after boot | same | same | -| `SavedGame` | Run | `MainMenu` (resume), `Galaxy(CultCache, SavedGame, ...)` | new game: `ActionGameManager.BeginRun()` creates the run store and writes it; `Die()` deletes the run store (Cut 10) | no run file: Resume hidden; run file without `SavedGame`: refuse to resume, log the key, New Game only | as main menu | new game deletes any run store first | +| `SavedGame` | Run | `MainMenu` (resume), `Galaxy(CultCache, SavedGame, ...)` | new run: `RunSave.Replace` writes the new run's records and removes the old run's once the scenario has staged; `EndRun` calls `RunSave.Clear` at death and victory | no run file: Continue disabled; run file without `SavedGame`: Continue disabled, log the key | as main menu | a new run keeps the saved run until it has staged | | catalog globals | Catalog | none exist | authored data; catalog is read-only | `AetheriaStores.Open` throws naming every `[CultGlobal]` type routed to the catalog with no record | same | same | **CultLib's role.** `[CultGlobal]` means exactly: at most one record of the @@ -1772,8 +1771,8 @@ Probes behind 8a (scratch copies; nothing committed): Math audit: - **Not used:** `float4x4`, `transpose`, `determinant`, `_11` names. The - `determinant` hits (`AetheriaMath.cs:98-112`, `NIH\MIConvexHull`) are locals - and comments; the `half` hits are locals. `float2x2`/`float3x3`, `int3`/`int4`, + `determinant` hits were locals and comments (in `AetheriaMath.cs` and the + vendored `NIH\MIConvexHull`, both since deleted); the `half` hits are locals. `float2x2`/`float3x3`, `int3`/`int4`, `double2`/`double3`, `quaternion.LookRotation`, `Random` and `snoise` all compile against CultMath. - **Accepted by Cut 6b:** `hash`, `normalize`, `Random`, `snoise` and NaN @@ -2596,28 +2595,31 @@ AetherDb and test edits made by Cut 9 (landed `70fbaca1`, recorded `e3af23fa`). - `SavedGame` global and `savedzone-{i}` records in `run.cc`. - `PlayerSettings` global in `player.cc`. - Orbit and body records in `run.cc`, written by zone generation and landed by the next save. - - **Run begins:** New Game calls `RunSave.Clear(CultCache)` as its first - statement (the `MainMenu.cs:110` handler), before the `Task.Run` at `:127` - or `:154`. - - Galaxy generation writes nothing. - - Zone generation (`PopulateLevel` `:615`, then `ZoneGenerator.cs:99, 108, - 200-201, 239, 253`) upserts orbits and bodies into the attached run store. - They stay staged until the next `RunSave.Commit`. + - **Run begins:** a scenario launch (`MainMenu.Launch`) generates the galaxy on a + background task and writes nothing to the run store. `StartGame` then calls + `StartScenario`, which runs arena generation, `PopulateLevel` and staging + inside `RunSave.Replace(CultCache, ...)`. The saved run's records are removed + only when staging succeeds; on failure the records the start wrote are removed + and the saved run stays. + - Zone generation (`PopulateLevel`, then `ZoneGenerator`) upserts orbits and + bodies into the attached run store. They stay staged until the next + `RunSave.Commit`, or are removed by `Replace` on a failed start. - **Run saves:** `ActionGameManager.SaveRun()`: - - It is `if (CurrentGalaxy != null) { var (game, zones) = RunSave.Capture(CultCache, CurrentGalaxy, Zone, DockedEntity ?? CurrentEntity, IsTutorial, _actionBarSlots.Select(s => s.Save()).ToArray()); RunSave.Commit(CultCache, game, zones); }`. + - It captures the live run (`RunSave.Capture`, which writes `SavedGame.IsTutorial` from `galaxy.IsPrelude`) and commits it with `RunSave.Commit` (`ActionGameManager.SaveRun`, `:284`). - Callers: wormhole arrival (`:605`) and `OnApplicationQuit() { SaveRun(); SavePlayerSettings(); }`. - - **Run ends:** `Die` replaces `SavePlayerSettings()` at `:1059` with - `RunSave.Clear(CultCache); SavePlayerSettings();`. - - `CurrentGalaxy` is already null (`:1058`), so a quit afterwards does not save a run. + - **Run ends:** `EndRun` (death and victory) nulls `CurrentGalaxy`, then calls + `RunSave.Clear(CultCache); SavePlayerSettings();` (`ActionGameManager.cs:1224-1232`). + - `CurrentGalaxy` is already null, so a quit afterwards does not save a run. - **Run exists:** derived only as `CultCache.GetGlobal<SavedGame>() != null`. - `MainMenu.ShowMain` enables Continue from it. Continue sets - `IsTutorial = saved.IsTutorial` and - `CurrentGalaxy = new Galaxy(CultCache, saved, Debug.Log)`. - - `StartGame` (`:695-741`) reads it once at the top: `null` takes the - new-run branch; otherwise it resumes from `CurrentZone`, - `CurrentZoneEntity` and `ActionBarBindings` (`:722, 723, 737`). + `CurrentGalaxy = new Galaxy(CultCache, saved, Debug.Log)`, whose `IsPrelude` + comes from `saved.IsTutorial`. + - `StartGame` (`ActionGameManager.cs:820`) branches on `PendingScenario`: set + means a new run (`StartScenario`); otherwise it resumes from `CurrentZone`, + `CurrentZoneEntity` and `ActionBarBindings` of the saved run. - A run store that holds records but no `SavedGame` logs - `run store has no SavedGame; Continue disabled`. New Game clears it. + `run store has no SavedGame; Continue disabled`. The next scenario launch + replaces those records once it has staged. - **Player settings:** - The `ActionGameManager.PlayerSettings` getter returns `CultCache.GetGlobal<PlayerSettings>()`. - When that is absent (first launch), the getter commits @@ -2651,7 +2653,7 @@ AetherDb and test edits made by Cut 9 (landed `70fbaca1`, recorded `e3af23fa`). - The cache never creates either. `AetheriaStores.Open` keeps its missing-global check catalog-only (`AetheriaStores.cs:24-29`). - **Derived state:** - "Run exists" is derived from the `SavedGame` global. - - `IsTutorial` is set from it on Continue and written back by `Capture`. + - `Galaxy.IsPrelude` is set from `SavedGame.IsTutorial` on Continue; `Capture` writes it back from `galaxy.IsPrelude`. No static copy exists. - `PlayerSettings.SavedRun` is deleted, not demoted. - **Forbidden writers:** - `File.*` I/O for game state anywhere in `Assets\Scripts`. @@ -2660,10 +2662,10 @@ AetherDb and test edits made by Cut 9 (landed `70fbaca1`, recorded `e3af23fa`). - A second `AetheriaStores.Open` in `Assets\Scripts`. - Any upsert of `SavedGame` or `SavedZone` outside `RunSave.Commit`. - **Shared paths:** - - Normal and tutorial New Game both call `Clear`. + - Every scenario launch goes through `RunSave.Replace`. - Continue and a new run's `StartGame` read the same global. - Wormhole and quit call `SaveRun`. - - Death calls `Clear`. + - Death and victory call `Clear` through `EndRun`. - **Deletion line:** `SavedRun`, `SaveState`, the msgpack settings and layout I/O, `SaveLoadout`, `SaveZone` and the `SavedGame` constructor go before `RunSave` lands. diff --git a/docs/headless-playground-cut.md b/docs/headless-playground-cut.md index bea30aa46..51c3f1bb5 100644 --- a/docs/headless-playground-cut.md +++ b/docs/headless-playground-cut.md @@ -10,6 +10,13 @@ probe was built with `--artifacts-path` in scratch, so this tree got no `bin`/`o writes. CultLib was a temporary detached worktree at `a0813c6`, since removed. The probe source is not kept; §2.8 records what it did. +Since this map, the new-run path moved: `MainMenu.Launch` starts a `Scenario` and +`ActionGameManager.StartScenario` replaces the saved run through `RunSave.Replace` +after `RunStart` stages it (`docs/scenarios-cut.md` R.9); the `IsTutorial` static is +gone (`Galaxy.IsPrelude` is the one owner) and `ItemManager` takes its seed in its +constructor. Passages below that name the old `MainMenu` new-game anchors or those +statics are rewritten to that path; the `Run` owner itself is still unbuilt. + ## 0. Target Operator, 2026-09-17: player inputs "map directly to the same entity inputs the AI @@ -107,11 +114,11 @@ All of this is Unity code: | Concern | Anchor | Unity dependencies | |---|---|---| | Store composition | `ActionGameManager.cs:43-63` (static, `Application.dataPath`) | path only | -| Handoff across scene load | statics `CurrentGalaxy`, `IsTutorial` (`:96-97`), written by `MainMenu.cs:104-105,126,138,152,166`, read by `SectorMap.cs:114-310` | `SceneManager.LoadScene` (`MainMenu.cs:106,139,167`) | -| New game: clear | `MainMenu.cs:112` | none | -| New game: galaxy | `MainMenu.cs:125,148` (`UnityEngine.Random.value` background noise), `:127-141,153-169` (`Task.Run`, then `Observable.NextFrame`) | Random, UniRx main-thread scheduler | -| ItemManager | `ActionGameManager.cs:264`; RNG clock-seeded at `ItemManager.cs:20` | `Debug.Log` | -| Start / Continue | `StartGame` `:725-770`: spawn player ship `:733-744`; Continue resolves the docked child `:751-762`; action bar restore `:764-767` | renderer binding, `SectorMap` reveal | +| Handoff across scene load | statics `CurrentGalaxy` and `PendingScenario` (`ActionGameManager.cs:108,113`), written by `MainMenu.Launch` and Continue, read by `SectorMap` | `SceneManager.LoadScene` (`MainMenu.EnterGame`, `MainMenu.cs:287`) | +| New game: replace | `ActionGameManager.StartScenario` (`:855-876`): `RunSave.Replace` drops the saved run only after the scenario stages; `MainMenu` clears nothing | none | +| New game: galaxy | `MainMenu.Launch` builds a `GalaxyStage` and runs `Task.Run(() => RunStart.Generate(scenario, stage))`, then `Observable.NextFrame`; background noise and galaxy draw from `GalaxyStage.Seed`, not `UnityEngine.Random` | UniRx main-thread scheduler | +| ItemManager | `ActionGameManager.cs:309`; seed is a constructor argument, `RunStart.ItemSeed(galaxy, step)` (`RunStart.cs:99`), reseeded by `RunStart.SeedItems` | `Debug.Log` | +| Start / Continue | `StartGame` (`:820`): `PendingScenario` set runs `StartScenario` (new run, player staged by `RunStart.Stage`); otherwise Continue resolves the saved zone and docked child and restores the action bar | renderer binding, `SectorMap` reveal | | Zone entry | `PopulateLevel` `:639-675`: generate/unpack `:643-654`; move pilot `:659-666` | `ZoneRenderer.LoadZone`, `Debug.Log` | | Wormhole placement (a game rule) | `ZoneRenderer.cs:222-231` (`dir * Pack.Radius * GameSettings.WormholeDistanceRatio`) | lives in a MonoBehaviour | | Warp | detect `ActionGameManager.cs:312-316`; `EnterWormhole` `:615-637`, which saves on arrival (`:635`) | `ZoneRenderer.WormholeInstances` as the wormhole list | @@ -146,7 +153,7 @@ All of this is Unity code: (`GameSettings.cs:17`, authored `LonginusX`) and `WormholeDistanceRatio` (`:23`, authored 0.75). - Randomness: - - `ItemManager.Random` is clock-seeded (`ItemManager.cs:20`). + - `ItemManager.Random` is seeded by the constructor argument (`ItemManager.cs:35`); a new run's seed is `RunStart.ItemSeed(galaxy, step)`, from `Galaxy.Seed`. - `Galaxy` is clock-seeded only when `seed == 0` (`Galaxy.cs:108,158`). - `Zone` seeds from the zone name (`Zone.cs:54`). - `Zone.Update` runs belt updates on `Task.Run` (`Zone.cs:144`). It is still @@ -243,7 +250,7 @@ Continue and death. There is one instance per run. It holds no Unity type. - `GameplaySettings`, `ZoneGenerationSettings`, `PlanetSettings`; - a `uint seed` for `ItemManager`; - `Action<string> log`; - - for a new run, a caller-built `Galaxy` and `isTutorial`; + - for a new run, a caller-built `Galaxy` (`Galaxy.IsPrelude` says whether it is the prelude) and the staged start (`RunStart.Stage`); - `dt` per step; - commands from either lowering; - `SavedActionBarBinding[]` at save, owned by the Unity action bar (the playground @@ -305,10 +312,8 @@ Continue and death. There is one instance per run. It holds no Unity type. - `ActionGameManager`: bodies of `SaveRun`, `EnterWormhole`, `PopulateLevel`'s simulation half, `StartGame`, `Dock`, `DoDock`'s state half, `Undock`'s checks, `TowShip`, `Die`'s clear, and `IntroCutscene` (entirely); - - statics `CurrentGalaxy` and `IsTutorial`; - - `MainMenu.cs:104-105,112`; - - `ZoneRenderer.cs:222-231`'s wormhole construction; - - `ItemManager.cs:20`'s clock seed. + - statics `CurrentGalaxy` and `PendingScenario`; + - `ZoneRenderer.cs:222-231`'s wormhole construction. All of these go in the same cut that adds `Run`. None survives as a fallback. @@ -318,12 +323,12 @@ Unity dependencies, each injected or cut: |---|---|---| | `Time.deltaTime` | `:1218` | injected: `Run.Step(float dt)` | | `Time.time` | `IntroCutscene`, `Die` post-fx | cutscene deleted; post-fx stays in Unity, on `Died` | -| `UnityEngine.Random` | `MainMenu.cs:125,148` (background noise), `EntityInstance.cs:413-428` (loot) | noise stays in the menu as a galaxy-generation input; loot roll moves to `Zone` on `ItemManager.Random` (Cut 2); effect spread jitter (`ProjectileManager.cs:20-26`) stays visual | -| Clock RNG | `ItemManager.cs:20` | cut; the seed is a constructor argument, and Unity passes a clock-derived one | +| `UnityEngine.Random` | `EntityInstance.cs:413-428` (loot) | galaxy noise already draws from `GalaxyStage.Seed`; loot roll moves to `Zone` on `ItemManager.Random` (Cut 2); effect spread jitter (`ProjectileManager.cs:20-26`) stays visual | +| Clock RNG | `Scenario.Seed` of 0 (`GalaxyStage.SeedFrom`) | the clock seeds only the galaxy seed; every item stream derives from it through `RunStart.ItemSeed` | | Coroutines | `IntroCutscene` | deleted (dead) | | UniRx | `Observable.NextFrame` in the menu, `EveryUpdate` in `Die` | stay in Unity; `Run` uses C# events, and `Entity.Death` (UniRx, headless-compiled) is what `Run` subscribes to | | `Debug.Log` | `:264`, `:657`, `MainMenu` | injected `Action<string>` | -| Scene load | `MainMenu` | stays; the handoff static becomes `ActionGameManager.NewRun : (Galaxy, bool)?`, command-only, consumed once in `Start`; null means Continue | +| Scene load | `MainMenu` | stays; the handoff static is `ActionGameManager.PendingScenario`, command-only, consumed once by `StartGame`; null means Continue | | MonoBehaviour state | `_currentEntity`, `DockedEntity`, `DockingBay`, `TowingStation`, `Zone`, `ItemManager` | projections of `Run` | | Barrel transforms | `EntityInstance.cs:516` -> `HardpointTransforms` | `HardpointTransforms` deleted (Cut 2); the arc is item rotation plus `FiringArc` (fork A); barrels and `ArticulationPoint` are presentation only, `GetBarrel` | | `Physics.*` hit queries | `Projectile`, `GuidedProjectile`, `Laser`, `Lightning`, `HullCollider` subjects | deleted from damage paths; `FireControl` rolls (Cut 2) | @@ -374,7 +379,7 @@ This is subtraction first, then one new file. - Deletes and moves: - `ActionGameManager.cs`: - `IntroCutscene` `:772-799` (dead). - - Statics `CurrentGalaxy` and `IsTutorial` (`:96-97`). + - Statics `CurrentGalaxy` and `PendingScenario` (`:108,113`). - `SaveRun` body `:243-248` becomes `Run?.Save(actionBar)`. Quit (`:236`) calls it. - `EnterWormhole` `:615-637` and the detect loop `:312-316` become `Run.TryEnterWormhole()`. `WarpArrived` drives `SectorMap.QueueZoneReveal`. @@ -393,14 +398,13 @@ This is subtraction first, then one new file. `Run.Died`. - `:264` constructs no `ItemManager`. - `Update` `:1218` becomes `Run.Step(Time.deltaTime)`. - - `MainMenu.cs`: - - Continue (`:102-107`) sets `ActionGameManager.NewRun = null` and loads the scene. - - New Game drops `:112` and sets `NewRun = (sector, tutorial)` at `:138,166`. + - `MainMenu`: already built. Continue (`ShowMain`) loads the scene with no + `PendingScenario`; `MainMenu.Launch` sets `PendingScenario` and clears nothing. - `SectorMap.cs:114-310` reads `ActionGameManager.Instance.Run.Galaxy`. - `InventoryPanel.cs:117-118` becomes `GameManager.Run.Board(ship)`. - `ZoneRenderer.cs:222-231` iterates `zone.Wormholes`. - - `ItemManager.cs:20`: the seed becomes a constructor argument. Call sites: 11 in - tests, 1 in `AetherDb`, and `Run`. + - `ItemManager`: the seed is already a constructor argument (`ItemManager.cs:35`); + `Run` supplies `RunStart.ItemSeed(galaxy, step)`. - Settings (fork S (a)): - `StartingHullName` and `WormholeDistanceRatio` move from `GameSettings.cs:17,23` to `GameplaySettings` (`Settings.cs:155`). @@ -412,8 +416,8 @@ This is subtraction first, then one new file. `GalaxyZone.AdjacentZones` with the rule from `ZoneRenderer.cs:226-230`. Null galaxy zone gives an empty array. - New `Run.cs`: types and rules, no bodies here. - - `static Run New(CultCache, GameplaySettings, ZoneGenerationSettings, PlanetSettings, Galaxy, bool isTutorial, uint seed, Action<string> log)` - 1. `RunSave.Clear`. + - `static Run New(CultCache, GameplaySettings, ZoneGenerationSettings, PlanetSettings, Galaxy, Scenario, Action<string> log)` + 1. `RunSave.Replace` around steps 2-5 (the saved run goes only once the scenario has staged). 2. `ItemManager` over `RunSave.Lots`, seeded. 3. `EnterZone(Entrance)`. 4. Spawn the player ship per `:734-743`. @@ -446,7 +450,7 @@ This is subtraction first, then one new file. child; updates `Bay.DockedShip`. - `void Tow()`: the rule from `:891-911`. - `void Save(SavedActionBarBinding[] actionBar)` - - `RunSave.Capture(cache, Galaxy, Zone, Station ?? Pilot, isTutorial, actionBar)`, + - `RunSave.Capture(cache, Galaxy, Zone, Station ?? Pilot, actionBar, credits)`, then `Commit(…, ItemManager.Lots)`. - No-op when `Ended`. - Remembers `actionBar` for warp saves. @@ -461,7 +465,7 @@ This is subtraction first, then one new file. | Test | Asserts | Mutation that must kill it | |---|---|---| -| `NewRunSpawnsPilotInEntrance` | pilot is a `Ship` with `IsPlayerShip`, in `Zone.Entities`, `Zone.GalaxyZone == Galaxy.Entrance`; the run store is cleared of a prior `SavedGame` | `New` skips `RunSave.Clear`; spawn omits `Zones.Entities.Add` | +| `NewRunSpawnsPilotInEntrance` | pilot is a `Ship` with `IsPlayerShip`, in `Zone.Entities`, `Zone.GalaxyZone == Galaxy.Entrance`; the run store holds no prior `SavedGame` once the run has staged | `New` skips `RunSave.Replace`; spawn omits `Zones.Entities.Add` | | `WarpMovesPilotAndSaves` | stepping after `TryEnterWormhole` lands the pilot in the target zone, out of the old zone's entities, with `SavedGame.CurrentZone` equal to the target index after reopen | arrival skips `Save`; `EnterZone` leaves the pilot in the old zone | | `ContinueLandsDocked` | save while docked, reopen, `Continue`: `Station` is the saved orbital, `Pilot` is its player child | `Land` binds to the orbital itself | | `DeathEndsAndClears` | hull death clears every run record; `Step` throws; `Save` writes nothing | `Died` handler omits `Clear`; `Ended` not set | @@ -473,7 +477,7 @@ This is subtraction first, then one new file. - Unity batchmode has no `error CS`. - Negative greps: - `rg -n "RunSave\.(Clear|Commit|Capture)" Assets/Scripts --glob '!ServerShared/**'` is empty. - - `rg -n "CurrentGalaxy|IsTutorial\s*=" Assets/Scripts` is empty. + - `rg -n "CurrentGalaxy|PendingScenario" Assets/Scripts` matches only the `Run` lowering in `ActionGameManager` and `MainMenu`. - `rg -n "new Wormhole" Assets/Scripts` matches only `Zone.cs`. - `rg -n "new ItemManager\(" Assets/Scripts` matches only `Run.cs`. - `rg -n "ZoneGenerator\.GenerateZone|new Zone\(" Assets/Scripts --glob '!ServerShared/**'` is empty. @@ -1161,7 +1165,7 @@ Options as mapped before the ruling: - **Recommend (a).** **N. Is the scene handoff static acceptable?** Low-blocking. -- (a) `ActionGameManager.NewRun : (Galaxy, bool)?`, consumed once by `Start`. +- (a) `ActionGameManager.PendingScenario : Scenario`, consumed once by `StartGame` (built this way). - (b) `MainMenu` builds the whole `Run` on its generation thread. That moves zone generation's run-store upserts off the main thread, and the `CultCache` threading contract is not checked here. diff --git a/docs/item-provenance-cut.md b/docs/item-provenance-cut.md index 473ec76c2..a0ccd947f 100644 --- a/docs/item-provenance-cut.md +++ b/docs/item-provenance-cut.md @@ -166,9 +166,9 @@ Contradictions and corrections found in the Body: `LoadoutTests` fixture is not: `FirstAvailableProductInKeyOrderBuildsTheSlot` (`LoadoutTests.cs:289-312`) adds two same-maker Lamp products and reads `.Product`. 6. **`ItemManager` lives one scene load, and every run starts with a scene load.** It is - constructed in `ActionGameManager.Start` (`:264`). There is one scene, `ARPG`. New Game - and Continue both end in `SceneManager.LoadScene("ARPG")` (`MainMenu.cs:106,139,167`), and - no `DontDestroyOnLoad` exists. So a ledger held by `ItemManager` spans exactly one run. + constructed in `ActionGameManager.Start` (`:309`). There is one scene, `ARPG`. A scenario + launch and Continue both end in `SceneManager.LoadScene("ARPG")` (`MainMenu.EnterGame`, + `:287`), and no `DontDestroyOnLoad` guards the `ItemManager`. So a ledger held by `ItemManager` spans exactly one run. 7. **Aside, not this cut:** `CreateInstance(CraftedItemData, float)` mints a `CompoundCommodity` for a `ConsumableItemData` design (`ItemManager.cs:136-141`), while `TryActivateConsumable` casts to `ConsumableItem` (`Entity.cs:336`). This map keeps @@ -252,9 +252,11 @@ Not probed: CultCache Studio's rendering of the ledger (operator check); Unity c `ZoneGenerator`'s staged-upsert pattern (`ZoneGenerator.cs:99-108`) is not used for lots: the ledger is live simulation state, captured at commit like entities. - Lifecycle: the run begins with a scene load (§1.6), whose `Start` reads - `RunSave.Lots(CultCache)`. New Game has already cleared the run store (`MainMenu.cs:112`), - so it gets an empty ledger. Continue gets the stored one. Death clears the run store - (`ActionGameManager.cs:1090`); the next run reloads the scene. + `RunSave.Lots(CultCache)`. A scenario launch has `PendingScenario` set, so `Start` builds an + empty `ProvenanceLedger` instead (`ActionGameManager.cs:312`); the saved run's records stay + in the store until `RunSave.Replace` drops them once the new run has staged + (`SavedGame.cs:247`). Continue reads the stored ledger. Death and victory end in `EndRun`, + which calls `RunSave.Clear` (`ActionGameManager.cs:1224-1231`); the next run reloads the scene. **Branding.** - Owner: `ItemManager.Brand(CraftedItemInstance)` -> `(Faction Maker, FactionProductData Product)`. @@ -526,7 +528,7 @@ Subtraction, plus a data rewrite. worktrees. Operator-only checks after Cut C: -- New Game and fly through one zone. The starting ship's items show tier colour, and the +- New Game, pick a scenario, and fly through one zone. The starting ship's items show tier colour, and the properties panel shows Manufacturer, product name and flavour text for branded gear. - Dock and buy an item: its brand still shows in your cargo. - Kill an NPC and pick up loot: brand shown. diff --git a/docs/item-provenance-substrate.md b/docs/item-provenance-substrate.md index 0bc310942..956d79138 100644 --- a/docs/item-provenance-substrate.md +++ b/docs/item-provenance-substrate.md @@ -68,8 +68,7 @@ catalog, built a 196-zone sector galaxy from the authored `Settings.asset`, and `47189c8a`). The commented `HaulingControllerData` union (`Behaviors.cs:179`) is the same kind of residue. - **No recipe, blueprint or ingredient model exists.** "Factory", "fabricat", - "assembler", "blueprint", "recipe" and "refiner" appear in no live C# outside - `NIH/MIConvexHull`. + "assembler", "blueprint", "recipe" and "refiner" appear in no live C#. `ItemData.Manufacturer` readers: `PropertiesPanel.cs:371-372` (shows "Manufacturer", falling back to "GameCult"), `tools/AetherDb/Program.cs:54` (census), and the @@ -83,7 +82,7 @@ All crafted instances come from three `ItemManager` overloads: - `CreateInstance(CraftedItemData, float quality)` (`ItemManager.cs:126-142`) sets Quality and Durability, with no product and no ingredients. - `CreateInstance(CraftedItemData)` (`:144-160`) rolls a rarity tier with the - **time-seeded** `ItemManager.Random` (`:20`) and stores the tier's *discrete* + `ItemManager.Random` (`:22`; seeded per run from the galaxy seed by `RunStart.ItemSeed`) and stores the tier's *discrete* Quality. - `CreateInstance(FactionProductData)` (`:164-187`) calls the previous overload, sets `Product`, and draws a gaussian `RoleFill` per design role. Since no role is @@ -130,9 +129,12 @@ unexecuted stubs. `TradeMenu.Inventory = entity.CargoBays.First()` (`ActionGameManager.cs:827-829`). - **Zones generate lazily on first entry** (`ActionGameManager.cs:643-652`, `PackedContents ??=`) from a deterministic zone seed - (`ZoneGenerator.cs:47`: name hash xor position hash). Item *selection* follows that - seed, but item *quality* comes from the time-seeded `ItemManager.Random`. A zone is - never regenerated within a run. New Game clears the run store (`MainMenu.cs:111`). + (`ZoneGenerator.cs:52`: name hash xor position hash). Item *selection* follows that + seed, but item *quality* comes from `ItemManager.Random`, a stream seeded per run from + the galaxy seed (`RunStart.SeedItems`, steps `ArenaStep`, `StageStep`, `ContinueStep`) + and drawn in the order zones are entered. A zone is never regenerated within a run. A + new run does not clear the run store up front: `RunSave.Replace` drops the old run's + records once the new run has staged (`SavedGame.cs:247`). - Each station carries hull, hardpoint gear, one docking bay, cargo bay, capacitor and stock, all embedded by value. No station equips a factory; none can, because factory designs have no product (§1). @@ -150,8 +152,9 @@ unexecuted stubs. `FactionProductData`, `PersonalityAttribute`, `NameFile`, `InputLayout`, `Loadout`. - Run (`:10`): `OrbitData`, `BodyData`, `SavedZone`, `SavedGame`. Written only by `RunSave.Commit`, which does one commit, keys zones `savedzone-{i}` and removes stale - zones (`SavedGame.cs:96-111`). `RunSave.Clear` removes every run-typed record - (`:114-124`). The single-file store writes its whole view on commit. + zones (`SavedGame.cs:216`). `RunSave.Clear` removes every run-typed + record (`:242`); `RunSave.Replace` (`:247`) does the same for a new run, but only once + the new run has staged. The single-file store writes its whole view on commit. - Player (`:11`): `PlayerSettings`. - **Every item instance is a value** embedded in `EntityPack` (hull, equipment, bays, cargo contents; `EntitySerializer.cs:179-196`), inside `SavedZone.Contents`. No @@ -237,7 +240,7 @@ Every stat and wear reader goes through the instance: "F" marks a fork (§9). "D" marks a recorded default. -| Kind | Named by | Mint | Transfer / loot / sell | Consume | Zone unload / save | New Game / death | Decides | +| Kind | Named by | Mint | Transfer / loot / sell | Consume | Zone unload / save | New run / death | Decides | |---|---|---|---|---|---|---|---| | **Lot** (provenance node) | run-scoped `LotId` (F1) | synthesis, at the mint site's call (F3) | never moves; instances point at it (D) | synthesized inputs are consumed at synthesis and have no instance (D) | kept while reachable from any instance, route or station; GC on `RunSave.Commit` (D, from the orphan-SavedZone scar) | cleared with the run store (D) | the synthesizer, one function in `ServerShared` | | **Lot properties** (mocked quality per role) | on the lot (F4) | rolled once at synthesis from factory quality and input qualities, seeded by lot id (F4) | immutable | n/a | with the lot | with the lot | synthesizer; stat readers only read | @@ -301,7 +304,7 @@ synthesized?** Blocks station identity, routes, stock and loot provenance. pirated freighter's cargo should come from a station the player can fly to. The skeleton is about 200 stations, small next to 16k instances. It demotes `ZoneGenerator`'s station count and faction choice to reading the roster. It also - moves item quality from the time-seeded `ItemManager.Random` to seeded synthesis, + moves item quality from the per-run `ItemManager.Random` stream, which depends on the order zones are entered, to lot-seeded synthesis, which makes the chain regenerable. - Sub-default: stations keep no identity outside a run. Zones never regenerate within one. diff --git a/docs/merge-to-master-checklist.md b/docs/merge-to-master-checklist.md index d5d70e17b..270b5625b 100644 --- a/docs/merge-to-master-checklist.md +++ b/docs/merge-to-master-checklist.md @@ -33,7 +33,7 @@ Compiled 2026-09-29 by Eyes from the maps on the branch. Pointers are `doc:line` ### 2b. Fresh launch (no `run.cc`, no `player.cc`) 3. **Launch to main menu.** Expect no Addressables errors, and the Groups window shows `Assets/Content` under `Default Local Group` (`addressables-cut.md:301`). `player.cc` appears and Continue is disabled (`cultcache-migration-cut.md:2746`). Proves: Addressables Cut 1, CultCache cutover. The 09-17 smoke covered the last two on the old tree; this is a cheap recheck on the new schema. -4. **New Game (tutorial).** Expect the galaxy generates and the start ship is the Longinus (`settings-globals-cut.md:498`, an expectation, not a recorded check for this stack). Expect a Zenith station with a docking bay in the entrance zone every time (`locomotion-cut.md:375`). Proves: locomotion Cut 1 station rule. +4. **New Game, then a scenario.** New Game opens the scenario picker (`MainMenu.ShowScenarios`); a development build lists modes (Terminus (Demo)), development (Tutorial Galaxy, Main Galaxy) and test arenas, a release build lists only the modes. Pick Tutorial Galaxy or Terminus (Demo). Expect the galaxy generates and the start ship is the Longinus (`settings-globals-cut.md:498`, an expectation, not a recorded check for this stack). Expect a Zenith station with a docking bay in the entrance zone every time (`locomotion-cut.md:375`). Proves: locomotion Cut 1 station rule. 5. **Addressables, "Use Asset Database".** Ships, turret and Zenith spawn; thruster and aether-drive particles show; fire an instant weapon (Autocannon) and a charged one (ChargeBlast SG); action bar icons show (`addressables-cut.md:362-366`). Proves: Addressables Cut 2. ### 2c. Flight, power and economy diff --git a/docs/tutorial-script-sketch.md b/docs/tutorial-script-sketch.md index 7e9233988..3fcbbebb6 100644 --- a/docs/tutorial-script-sketch.md +++ b/docs/tutorial-script-sketch.md @@ -16,7 +16,7 @@ Status: sketch for the operator to react to. Nothing here is built or canon. ## Shape -One contained tutorial run in a small prelude galaxy (`IsTutorial`, +One contained tutorial run in a small prelude galaxy (`Galaxy.IsPrelude`, `TutorialGenerationSettings`). The player is a newly incorporated subsidiary of the protagonist faction. Threefra, a debt-born assessor with opinions, walks them through a "qualification module" whose checklist is theatre. The real test is how the player From 4a3e5394ebf846686595424525143bfd9920103e Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 14:59:48 +0000 Subject: [PATCH 105/190] Pin mining ship order out to 8000 units and the hidden-ship pick in a crowded zone Closes the far-window edges the 141162998 pins left: ships out to 7990 units admitted farthest first, and a zone of 100+ entities with undetected ships out to 8000. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../MiningTargetQueriesTests.cs | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/tests/Aetheria.Shared.Tests/MiningTargetQueriesTests.cs b/tests/Aetheria.Shared.Tests/MiningTargetQueriesTests.cs index 9cd8ec025..e492b5835 100644 --- a/tests/Aetheria.Shared.Tests/MiningTargetQueriesTests.cs +++ b/tests/Aetheria.Shared.Tests/MiningTargetQueriesTests.cs @@ -624,4 +624,52 @@ public sealed partial class MiningCut3Tests Assert.Contains(observer.Target.Value, order); } } + + // The distance key stays the distance far beyond the clamps a fixture reaching 4000 can see: ships stand out to + // 8000 units, several within any one quantum or round-number cap (4600 and 4900, 5200 and 5300, 7960, 7975 and 7990), + // and are admitted farthest first, so zone order is the exact reverse of distance order and any tie (a clamp, a + // coarse bucket, a cap on either key) shows as a swapped pair. + [Fact] + public void ShipsOutToEightThousandUnitsAreOrderedByDistanceBothWaysWhenAdmittedFarthestFirst() + { + var at = float2(500, 0); + var (s, observer) = TargetScene(7, at); + var distances = new[] { 7990f, 7975f, 7960f, 7900f, 7000f, 6100f, 5300f, 5200f, 4900f, 4600f, 4000f, 3600f, 3100f, 2900f, 1500f, 700f }; + for (var i = 0; i < distances.Length; i++) Sight(s, observer, Polar(at, distances[i], i * 1.9f)); + var order = ByDistance(s, observer, 120f); + Assert.True(order.Count(t => t.Chunk.HasValue) >= 8 && order.Count(t => t.Entity != null) == distances.Length, $"degenerate: {order.Count} candidates"); + var ships = order.Where(t => t.Entity != null).Select(t => length(t.Entity.Position.xz - at)).ToList(); + Assert.Equal(ships.OrderBy(d => d).ToList(), ships); + Assert.Equal(ships.Distinct().Count(), ships.Count); + Assert.True(ships.Last() > 7900f); + AssertPressesWalk(observer, order); + } + + // The same pins in a crowded zone: far more than 60 entities stand in it, ships the observer has not detected + // among them out to 8000 units, so a leak or a bent key gated on the zone's size shows here. + [Fact] + public void ShipsTheObserverHasNotDetectedAreNeverPickedInACrowdedZone() + { + var at = float2(500, 0); + var (s, observer) = TargetScene(7, at); + var seen = new[] { 6200f, 4700f, 2500f, 900f, 120f, 5400f }; + for (var i = 0; i < seen.Length; i++) Sight(s, observer, Polar(at, seen[i], i * 1.3f + .4f)); + var hidden = new List<TargetRef>(); + for (var i = 0; i < 110; i++) + hidden.Add(Unseen(s, Polar(at, 3f * MathF.Pow(1.0885f, i), i * 2.4f))); + var order = ByDistance(s, observer, 120f); + Assert.True(s.Zone.Entities.Count > 100, $"zone holds {s.Zone.Entities.Count}"); + Assert.True(order.Count > seen.Length && order.Count(t => t.Entity != null) == seen.Length, $"degenerate: {order.Count} candidates"); + Assert.All(hidden, h => Assert.DoesNotContain(h, order)); + Assert.True(hidden.Max(h => length(h.Entity.Position.xz - at)) > 7500f, "the hidden ships do not reach the far window"); + AssertPressesWalk(observer, order); + foreach (var h in hidden.Where((_, i) => i % 3 == 0)) + { + var to = h.Entity.Position.xz - at; + observer.Aim = float3(to.x, 0, to.y); + observer.SetTarget(TargetRef.None); + Assert.True(observer.TargetUnderReticle()); + Assert.DoesNotContain(observer.Target.Value, hidden); + } + } } From 255af22ac871ba021f4e299ac167f188e15f7214 Mon Sep 17 00:00:00 2001 From: Nibu <nibu@minds.nibu.gamecult.org> Date: Fri, 13 Nov 2026 15:30:04 +0000 Subject: [PATCH 106/190] Docs: close the stale new-game leftovers Bring settings-globals, mining, prior-art, headless probe record and the release map true to the scenarios menu and current seeding. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- docs/aetheria-release-map.md | 1 - docs/headless-playground-cut.md | 19 ++++++++++--------- docs/mining-cut.md | 2 +- ...rategic-ai-arena-living-world-prior-art.md | 3 ++- docs/settings-globals-cut.md | 5 +++-- 5 files changed, 16 insertions(+), 14 deletions(-) diff --git a/docs/aetheria-release-map.md b/docs/aetheria-release-map.md index c270c297c..83892fc69 100644 --- a/docs/aetheria-release-map.md +++ b/docs/aetheria-release-map.md @@ -504,7 +504,6 @@ record. | follow-up | `ambiguous-hardpoint-origin` | demo | Save correctness for package hulls. | | follow-up | `delaunay-exact-predicates` | demo | Galaxy links; a silently unlinked zone could strand a demo run. | | follow-up | `failed-start-scene-halts` | demo | The New Game failure path the demo's missing-cast refusal uses. | -| follow-up | `stale-docs-after-scenarios-menu` | demo | Docs that describe the old New Game path. | | follow-up | `scratch-carry-drafts` | demo | The ship `.cc` draft bears on `demo-ship-cc-timing`. | | follow-up | `faction-lore-notes-r3` | full game | Vault setting notes; no demo cut reads them. | | follow-up | `mining-impacts-through-contract` | full game | Mining Cut 4 is parked. | diff --git a/docs/headless-playground-cut.md b/docs/headless-playground-cut.md index 51c3f1bb5..d6ca6104a 100644 --- a/docs/headless-playground-cut.md +++ b/docs/headless-playground-cut.md @@ -127,10 +127,11 @@ All of this is Unity code: | Save | `SaveRun` `:241-249`, called at quit `:236` and warp `:635` | action-bar slots (`:246`) | | Death | `BindToEntity` subscribes `Death` -> `Die` (`:1053`); `Die` `:1080-1115` clears the run (`:1088`) | `Time.time`, `Observable.EveryUpdate` post-fx | | Tick | `Update` `:1151-1220`: input `:1189-1216`, then `Zone.Update(Time.deltaTime)` `:1218` | `Time.deltaTime`, pause flag | -| Dead code | `IntroCutscene` `:772-799`; its only call is commented out (`:760`) | coroutine, `Time.time` | ### 2.2 Already headless +- Past probe: the measurements below were taken at an earlier commit and their line anchors + are not maintained; re-run the probe before relying on a number or an anchor. - `Aetheria.Shared/Aetheria.Shared.csproj` compiles `Assets/Scripts/ServerShared/**` plus UniRx (`UniRxLibrary`) and Ink with no Unity defines. It is the Unity-independence check. @@ -141,23 +142,23 @@ All of this is Unity code: - a player `LonginusX` spawned through `LoadoutGenerator`; - thrust by hand-set `MovementDirection` reached 142 m/s in 5 s; - a `Minion` patrol moved the player ship 642 units in 10 s; - - `TryDock` and `TryUndock` succeeded (`Entity.cs:721-755`); - - `Ship.EnterWormhole` followed by stepping fired `OnEnteredWormhole` (`Ship.cs:82-90,372`); - - `Death` fired on hull damage (`Entity.cs:277-280`); + - `TryDock` and `TryUndock` succeeded; + - `Ship.EnterWormhole` followed by stepping fired `OnEnteredWormhole`; + - `Death` fired on hull damage; - `RunSave.Capture` and `RunSave.Commit` wrote a 489 KB `run.cc`. - Settings: `GameSettings` is a ScriptableObject (`GameSettings.cs:11`) holding ServerShared classes. - `tools/AetherDb/AuthoredSettings.cs` reads them from the asset YAML. The probe placed every field (0 unplaced). - Two lifecycle inputs are Unity-only `GameSettings` fields: `StartingHullName` - (`GameSettings.cs:17`, authored `LonginusX`) and `WormholeDistanceRatio` (`:23`, + (`GameSettings.cs:13`, authored `Longinus`) and `WormholeDistanceRatio` (`:16`, authored 0.75). - Randomness: - `ItemManager.Random` is seeded by the constructor argument (`ItemManager.cs:35`); a new run's seed is `RunStart.ItemSeed(galaxy, step)`, from `Galaxy.Seed`. - - `Galaxy` is clock-seeded only when `seed == 0` (`Galaxy.cs:108,158`). - - `Zone` seeds from the zone name (`Zone.cs:54`). - - `Zone.Update` runs belt updates on `Task.Run` (`Zone.cs:144`). It is still - deterministic (probe: identical traces). + - `Galaxy` takes its seed from the run (`Galaxy.cs:119`); a zero seed throws. + - `Zone` seeds from the zone name: `CombatSeed` (`Zone.cs:162`), with `DropSeed` mixing in the run's seed (`:163`). + - Probe: `Zone.Update` was deterministic (identical traces) when belt updates ran on `Task.Run`; + no `Task.Run` remains in `Zone.cs`. ### 2.3 Agents diff --git a/docs/mining-cut.md b/docs/mining-cut.md index 7c5be8297..ce23094dc 100644 --- a/docs/mining-cut.md +++ b/docs/mining-cut.md @@ -301,7 +301,7 @@ resources **(probe: 8 belts, 0 authored)**. - A: Composition is derived: `Comp_c(o) = Abundance_o × exp(Variance × g(hash(belt key, index, o)))`, normalized, with `g ∈ [-1, 1]`. Nothing is stored. Existing saves work, and key 4 is retired. - B: `ZoneGenerator` writes `BodyData.Resources` per belt at generation, and the chunk jitter is derived. Belts in - runs started before Cut 5 have empty compositions until New Game. + runs started before Cut 5 have empty compositions until a new run. - C: Per-belt only, with no per-chunk variation. - **Recommended: A.** It has one owner (the catalog) and nothing to migrate. It follows the same "derived, never stored" spirit as branding. The operator's wording ("the chunk's composition") argues against C. If B is chosen, diff --git a/docs/research/2026-10-21-strategic-ai-arena-living-world-prior-art.md b/docs/research/2026-10-21-strategic-ai-arena-living-world-prior-art.md index 42f0ee20c..87a1bb7c9 100644 --- a/docs/research/2026-10-21-strategic-ai-arena-living-world-prior-art.md +++ b/docs/research/2026-10-21-strategic-ai-arena-living-world-prior-art.md @@ -390,7 +390,8 @@ Battlecode, Halite, CodinGame, BWAPI/SSCAIT/AIIDE/CIG, SC2 AI Arena, Lux, CodeCl - **The Colosseum follow-up.** `aetheria-release:follow_up:colosseum-npc-lab` (in force; owner "Aetheria Agents and the headless simulation") names its foundations: - an observation and action seam (agents hold live `Ship`, `Zone` and `ItemManager` references); - - seeding `ItemManager.Random` and the MIConvexHull randoms; + - seeding for tournament reproducibility: `ItemManager.Random` already takes the run's seed + (`RunStart.ItemSeed`), and no MIConvexHull source remains in the repo; - a replay recorder; - a headless tournament runner on Yggdrasil with ratings; - a primitive vocabulary; diff --git a/docs/settings-globals-cut.md b/docs/settings-globals-cut.md index b031ba4bf..f1b2e0582 100644 --- a/docs/settings-globals-cut.md +++ b/docs/settings-globals-cut.md @@ -495,8 +495,9 @@ landed type differs from it by the one attribute. (the helper) [2 now]. - `rg -n "ScriptableObject" Assets/Scripts/ServerShared` must stay 0. - operator: - - Play smoke: main menu, then New Game (tutorial). The tutorial galaxy generates, - and the starting ship is LonginusX. + - Play smoke: main menu, then New Game, then the Tutorial Galaxy scenario (listed under + development, in editor and development builds). The prelude galaxy generates, and the + starting ship is `Settings.StartingHullName` (`Longinus`). - In a station trade menu and the properties panel, item names show tier colours: Legendary orange, Uncommon green. None is black. - The inventory shows armour and durability gradients, and hit flashes use the From ce5d0125408df4eb44f9a214cd2b9aa3d5bf48de Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Tue, 17 Nov 2026 18:53:45 +0100 Subject: [PATCH 107/190] Wren becomes a test fixture; compose and validate refuse an offered hull with no schematic Move the starter-box aetheria.wren package from GameData/Mods to tests/fixtures/mods (LFS rule added) so it no longer ships; the Wren tests compose it through TestCatalog.RepoWithFixtures. ShipModCatalog.SchematicFault, built on LoadoutGenerator.IsOffered, excludes an offered hull with no schematic lines at compose and is reported by ship-authoring validate. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .gitattributes | 2 + Assets/Scripts/ServerShared/ShipModCatalog.cs | 13 +++++ docs/element-ids.md | 2 +- docs/mining-cut-refresh.md | 4 +- .../ElementIdUpgradeTests.cs | 2 +- .../RestoredHullsTests.cs | 1 + .../ShipModCatalogTests.cs | 47 +++++++++++++++++++ .../Aetheria.Shared.Tests/ShipProductTests.cs | 24 ++++++++++ tests/Aetheria.Shared.Tests/TestCatalog.cs | 21 +++++++++ .../Aetheria.Shared.Tests/WrenPackageTests.cs | 10 ++-- .../fixtures/mods}/aetheria.wren/ship.cc | 0 .../fixtures/mods}/aetheria.wren/ship.glb | 0 tools/AetherDb/ShipAuthoringCommands.cs | 4 ++ 13 files changed, 121 insertions(+), 9 deletions(-) rename {GameData/Mods => tests/fixtures/mods}/aetheria.wren/ship.cc (100%) rename {GameData/Mods => tests/fixtures/mods}/aetheria.wren/ship.glb (100%) diff --git a/.gitattributes b/.gitattributes index 9d4b872b4..87c9db929 100644 --- a/.gitattributes +++ b/.gitattributes @@ -55,6 +55,8 @@ GameData/*.cc filter=lfs diff=lfs merge=lfs -text GameData/Mods/**/*.cc filter=lfs diff=lfs merge=lfs -text GameData/Mods/**/*.glb filter=lfs diff=lfs merge=lfs -text +tests/fixtures/mods/**/*.cc filter=lfs diff=lfs merge=lfs -text +tests/fixtures/mods/**/*.glb filter=lfs diff=lfs merge=lfs -text tools/blender/tests/fixtures/*.glb filter=lfs diff=lfs merge=lfs -text *.a filter=lfs diff=lfs merge=lfs -text *AkSoundEngine filter=lfs diff=lfs merge=lfs -text diff --git a/Assets/Scripts/ServerShared/ShipModCatalog.cs b/Assets/Scripts/ServerShared/ShipModCatalog.cs index 88dc06b85..d085974b4 100644 --- a/Assets/Scripts/ServerShared/ShipModCatalog.cs +++ b/Assets/Scripts/ServerShared/ShipModCatalog.cs @@ -110,6 +110,7 @@ public static class ShipModCatalog if (shipIds.Contains(ship.Id)) Exclude(directory, $"ship ID collides with an existing catalog ship authoring record."); if (StationKinds.HullKindFault(cache, hull) is { } kindFault) Exclude(directory, kindFault); + if (SchematicFault(cache, ship, package.Products) is { } schematicFault) Exclude(directory, schematicFault); foreach (var product in package.Products) { if (!factionKeys.Contains(product.Manufacturer.Key)) @@ -157,6 +158,18 @@ public static class ShipModCatalog } } + // Why a package's hull cannot go on the market, or null: a hull offered through any of its products is drawn on the map and + // the schematic by its lines (ShipModVisual.BuildLineMesh builds nothing from none), so an offered hull without any is + // excluded. An unoffered stand-in is left alone. Offered is LoadoutGenerator.IsOffered, the one reader of NotOffered + // (ruling off-market-is-unoffered-product); `items` is the catalog the products' bins resolve in. A product whose bin + // line the catalog does not hold is not judged here: the catalog read refuses it. + public static string SchematicFault(CultCache items, ShipAuthoring ship, FactionProductData[] products) + { + if (ship.SchematicLines != null && ship.SchematicLines.Any(line => line?.Points != null && line.Points.Length > 0)) return null; + var offered = products.Any(product => (product.Bin == null || items.Get(product.Bin.Line) != null) && LoadoutGenerator.IsOffered(items, product)); + return offered ? $"{ship.Id}: the hull is offered on the market but has no schematic lines." : null; + } + public static Package ReadPackage(string shipPath) { var path = Path.GetFullPath(shipPath); diff --git a/docs/element-ids.md b/docs/element-ids.md index b4ae9584a..32ccdafc8 100644 --- a/docs/element-ids.md +++ b/docs/element-ids.md @@ -26,7 +26,7 @@ that some intermediate pins read a single-file v3 store silently and drop the id writers, keep a pre-upgrade copy of any real store (`GameData/Aetheria.cc` and the mod packages are tracked in git; player saves and run stores are not), and do not roll the pin back after a store has been written under the new one. -The shipped mod packages (`GameData/Mods/aetheria.wren/ship.cc`, `aetheria.nakovalnya/ship.cc`) held only default +The shipped mod package (`GameData/Mods/aetheria.nakovalnya/ship.cc`) and the test fixture package (`tests/fixtures/mods/aetheria.wren/ship.cc`) held only default placeholders (`0` and `[]`) in the retired `HullData` slots 21 and 22, which the new CultLib refuses to write over (`CultSchemaConflictException`). They were regenerated with `AetherDb ship-authoring regenerate <ship.cc> apply`, which loads the records, writes them into a fresh file under the current schema, requires them to read back identical and replaces the file. Both diff --git a/docs/mining-cut-refresh.md b/docs/mining-cut-refresh.md index 7adb1e951..b0bf89420 100644 --- a/docs/mining-cut-refresh.md +++ b/docs/mining-cut-refresh.md @@ -304,11 +304,11 @@ Every mining question is ruled. - LFS staging set. `SubstanceCleanBreakTests` fails loudly on any LFS pointer it scans, so the job must restore every LFS-tracked file under `Assets/`, `Packages/`, `ProjectSettings/` and `GameData/*.cc` that is not a binary-media extension (the test's `BinaryExtensions` denylist): 99 files at `83e6957de`, 96 `*.asset` and 3 - `*.cc` (`GameData/Aetheria.cc`, `GameData/Mods/aetheria.nakovalnya/ship.cc`, `GameData/Mods/aetheria.wren/ship.cc`), + `*.cc` (`GameData/Aetheria.cc`, `GameData/Mods/aetheria.nakovalnya/ship.cc`, `tests/fixtures/mods/aetheria.wren/ship.cc`), which includes `ProjectSettings/ProjectSettings.asset` and `Assets/Resources/Settings.asset`. Derive the list from the merged tree instead of hand-copying it: `git ls-files Assets Packages ProjectSettings 'GameData/*.cc' | git check-attr --stdin filter | grep 'lfs$' | sed 's/: filter: lfs//' | grep -viE '\.(png|jpg|jpeg|tga|tif|tiff|psd|bmp|gif|exr|hdr|dds|wav|mp3|ogg|mp4|fbx|glb|blend|ttf|otf|dll|so|pdb|msgpack|zip|bank)$'`, - then copy each path from the `/lfs` mount over the checkout. That set (99: the 97 the sbsar guards read plus the two mod `ship.cc` files the Nakovalnya and Wren tests open) makes `SubstanceCleanBreakTests` green and nothing more: staging only two files turns it red. For a fully green suite also stage `GameData/Mods/*/ship.glb` (the catalog excludes a package with an invalid GLB header, failing about 520 tests) and the LFS `.ttf`/`.otf` fonts `CreditsTests.FontCreditsShowWhatTheFontsThemselvesEmbed` reads. + then copy each path from the `/lfs` mount over the checkout. That set (99: the 97 the sbsar guards read plus the two mod `ship.cc` files the Nakovalnya and Wren tests open) makes `SubstanceCleanBreakTests` green and nothing more: staging only two files turns it red. For a fully green suite also stage `GameData/Mods/*/ship.glb` and `tests/fixtures/mods/*/ship.glb` (the catalog excludes a package with an invalid GLB header, failing about 520 tests) and the LFS `.ttf`/`.otf` fonts `CreditsTests.FontCreditsShowWhatTheFontsThemselvesEmbed` reads. - Unity batchmode compile of the merged tree (Self, in a worktree, never with the operator's editor open on the main tree). This is the Cut 1 renderer compile the map still owes. - Operator: fly through a belt (the Cut 1 check the map still owes). Rocks orbit smoothly, and the minimap diff --git a/tests/Aetheria.Shared.Tests/ElementIdUpgradeTests.cs b/tests/Aetheria.Shared.Tests/ElementIdUpgradeTests.cs index d94222635..682b20409 100644 --- a/tests/Aetheria.Shared.Tests/ElementIdUpgradeTests.cs +++ b/tests/Aetheria.Shared.Tests/ElementIdUpgradeTests.cs @@ -107,7 +107,7 @@ public class ElementIdUpgradeTests { using var directory = new TempDirectory(); var copy = Path.Combine(directory.Path, "ship.cc"); - File.Copy(Path.Combine(RunStartTests.FindRepoRoot(), "GameData", "Mods", "aetheria.wren", "ship.cc"), copy); + File.Copy(Path.Combine(RunStartTests.FindRepoRoot(), "tests", "fixtures", "mods", "aetheria.wren", "ship.cc"), copy); var bytes = File.ReadAllBytes(copy); var (hull, visual, products) = ShipAuthoringStore.Load(copy); diff --git a/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs b/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs index 121d468b3..f5d3e8498 100644 --- a/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs +++ b/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs @@ -61,6 +61,7 @@ public sealed class RestoredHullsTests } internal static CultCache OpenCatalog() => OpenReadOnlyRealCatalog(TestCatalog.Repo); + internal static CultCache OpenCatalogWithFixtures() => OpenReadOnlyRealCatalog(TestCatalog.RepoWithFixtures); // Shared tutorial-galaxy construction settings (Assets/Resources/Settings.asset's own values), factored out // so every test that needs a real tutorial Galaxy -- not just EntranceZoneAlwaysGetsADockedStationAcrossSeeds diff --git a/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs b/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs index 175a6bd9f..b4003954c 100644 --- a/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs @@ -49,6 +49,53 @@ public sealed class ShipModCatalogTests : IDisposable AssertOnlyTheDerivedFile(); } + // A package selling one product through the one product writer, with or without schematic lines and offered or not. + private void PricedPackage(string id, bool lines, bool offered) + { + var factionKey = AddFaction(); + WritePackage(id, id, tweak: ship => + { + ship.Hull.Price = 100; + if (!lines) ship.Visual.SchematicLines = new List<ShipPolyline>(); + }); + using var cache = ShipAuthoringStore.Open(Path.Combine(Mods, id, "ship.cc"), writable: true); + ShipAuthoringStore.WriteProduct(cache, id, new FactionProductData + { + Name = id + " product", + Design = new CultRecordRef<CraftedItemData>(ShipModCatalog.HullKey(id)), + Manufacturer = new CultRecordRef<Faction>(factionKey), + NotOffered = !offered + }); + cache.FlushAsync().Wait(); + } + + private CultRecordKey AddFaction() + { + using var cache = AetheriaStores.Open(Shipped, catalogWritable: true); + var existing = cache.GetAll<Faction>().FirstOrDefault(); + var key = existing != null ? cache.RefOf(existing).Key : cache.Upsert(new Faction { Name = "Acme", ShortName = "ACM" }).Key; + cache.FlushAsync().Wait(); + return key; + } + + // An offered hull is drawn by its schematic lines (ShipModVisual.BuildLineMesh builds nothing from none), so one without any + // is left out of the catalog with its reason; an offered hull with lines and an unoffered stand-in without them both compose. + [Fact] + public void ComposeExcludesAnOfferedHullWithoutSchematicLinesAndKeepsTheRest() + { + PricedPackage("mod.offeredbare", lines: false, offered: true); + PricedPackage("mod.offeredlined", lines: true, offered: true); + PricedPackage("mod.standin", lines: false, offered: false); + + var composition = ShipModCatalog.Compose(Shipped, Derived, Mods); + + Assert.Equal(new[] { "mod.offeredlined", "mod.standin" }, composition.Included.OrderBy(id => id, StringComparer.Ordinal)); + var excluded = Assert.Single(composition.Excluded); + Assert.Equal("mod.offeredbare", excluded.Package); + Assert.Contains("mod.offeredbare", excluded.Reason); + Assert.Contains("no schematic", excluded.Reason); + } + // A package's station kind is checked per package: a bad one is left out, named with its reason, and the derived catalog // still opens. The shipped catalog's own check is unchanged. [Fact] diff --git a/tests/Aetheria.Shared.Tests/ShipProductTests.cs b/tests/Aetheria.Shared.Tests/ShipProductTests.cs index 82f094e88..0ee2db012 100644 --- a/tests/Aetheria.Shared.Tests/ShipProductTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipProductTests.cs @@ -99,6 +99,30 @@ public sealed class ShipProductTests : IDisposable } } + // validate gives the verdict compose gives: an offered hull with no schematic lines is refused, an unoffered one is not. + [Fact] + public void ValidateRefusesAnOfferedHullWithoutSchematicLinesAsComposeDoes() + { + Environment.CurrentDirectory = _root.Path; + string Bare(string id, bool offered) + { + var directory = ShipFixture.WritePackage(Mods, id, id, tweak: ship => { ship.Hull.Price = 100; ship.Visual.SchematicLines = new List<ShipPolyline>(); }); + var path = Path.Combine(directory, "ship.cc"); + using var cache = ShipAuthoringStore.Open(path, writable: true); + var product = Product(id + " product", _acme, id); + product.NotOffered = !offered; + ShipAuthoringStore.WriteProduct(cache, id, product); + cache.FlushAsync().Wait(); + return path; + } + + var (code, _, error) = Run("validate", Bare("mod.offered", offered: true)); + Assert.Equal(1, code); + Assert.Contains("no schematic", error); + Assert.Equal(0, Run("validate", Bare("mod.standin", offered: false)).Item1); + Assert.Equal(new[] { "mod.standin" }, ShipModCatalog.Compose(Shipped, Derived, Mods).Included); + } + [Fact] public void APackageWithAnUnknownMakerIsExcluded() { diff --git a/tests/Aetheria.Shared.Tests/TestCatalog.cs b/tests/Aetheria.Shared.Tests/TestCatalog.cs index 60d41c996..2561406f2 100644 --- a/tests/Aetheria.Shared.Tests/TestCatalog.cs +++ b/tests/Aetheria.Shared.Tests/TestCatalog.cs @@ -18,6 +18,12 @@ internal static class TestCatalog // The repo's catalog with its first-party packages composed in, resolved once per test process. public static string Repo => Shared.Value; + private static readonly Lazy<string> SharedWithFixtures = new Lazy<string>(() => ForRepoWithFixtures(RunStartTests.FindRepoRoot())); + + // The repo's catalog with its first-party packages and the test fixture packages (tests/fixtures/mods) composed in. For a + // test whose subject is a fixture package; Repo is the catalog the game ships. + public static string RepoWithFixtures => SharedWithFixtures.Value; + // The shipped assembly's own [CultDocument] types and nothing the test assembly registers (CultDocumentRegistry.ForTypes // does not re-scan the AppDomain), so this assembly's fixture documents never become catalog globals the real catalog // must hold. The one registry every test that opens a real catalog, and the composition behind Repo, uses. @@ -34,6 +40,21 @@ internal static class TestCatalog return Resolve(Path.Combine(repoRoot, "GameData", "Aetheria.cc"), Path.Combine(repoRoot, "GameData", "Mods"), work); } + // ForRepo over a mods root assembled from GameData/Mods and tests/fixtures/mods, copied into the per-call temp directory. + public static string ForRepoWithFixtures(string repoRoot) + { + var work = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "aetheria-testcatalog-" + Guid.NewGuid().ToString("N"))).FullName; + AppDomain.CurrentDomain.ProcessExit += (_, _) => { try { Directory.Delete(work, true); } catch (IOException) { } }; + var mods = Path.Combine(work, "Mods"); + foreach (var root in new[] { Path.Combine(repoRoot, "GameData", "Mods"), Path.Combine(repoRoot, "tests", "fixtures", "mods") }) + foreach (var package in Directory.GetDirectories(root)) + { + var target = Directory.CreateDirectory(Path.Combine(mods, Path.GetFileName(package))).FullName; + foreach (var file in Directory.GetFiles(package)) File.Copy(file, Path.Combine(target, Path.GetFileName(file))); + } + return Resolve(Path.Combine(repoRoot, "GameData", "Aetheria.cc"), mods, work); + } + public static string Resolve(string shippedCatalog, string modsRoot, string workDir) { // Every directory under the first-party tree is a package. The game treats a directory without a ship.cc as not a diff --git a/tests/Aetheria.Shared.Tests/WrenPackageTests.cs b/tests/Aetheria.Shared.Tests/WrenPackageTests.cs index bb95cbb55..3395d7f32 100644 --- a/tests/Aetheria.Shared.Tests/WrenPackageTests.cs +++ b/tests/Aetheria.Shared.Tests/WrenPackageTests.cs @@ -5,7 +5,7 @@ using Xunit; using static CultMath.math; using Random = CultMath.Random; -// GameData/Mods/aetheria.wren: a first-party package written by `ship-authoring starter --like Djinni`, then priced and given +// tests/fixtures/mods/aetheria.wren: a test fixture package, not shipped with the game, written by `ship-authoring starter --like Djinni`, then priced and given // an unoffered Aeronautics Unlimited product by `ship-authoring price` and `product`; its model is the starter's boxed // stand-in. It is the pipeline's proof from a hull package on disk to a ship that flies in the headless simulation: the // package composes into the catalog, its mounts take catalog gear, and the fitted ship moves under thrust. `fly` cannot @@ -19,7 +19,7 @@ public sealed class WrenPackageTests [Fact] public void TheStarterPackageIsInTheComposedCatalogWithTheStatsOfItsLike() { - using var cache = RestoredHullsTests.OpenCatalog(); + using var cache = RestoredHullsTests.OpenCatalogWithFixtures(); var hull = Wren(cache); var like = cache.GetByName<HullData>("Djinni"); Assert.NotNull(hull); @@ -34,7 +34,7 @@ public sealed class WrenPackageTests [Fact] public void TheStarterIsMadeButNeverOffered() { - using var cache = RestoredHullsTests.OpenCatalog(); + using var cache = RestoredHullsTests.OpenCatalogWithFixtures(); var hull = Wren(cache); var product = Assert.Single(cache.GetAll<FactionProductData>(), p => p.Design.Key.Equals(ShipModCatalog.HullKey(Id))); Assert.Equal("Aeronautics Unlimited", cache.Get(product.Manufacturer).Name); @@ -47,7 +47,7 @@ public sealed class WrenPackageTests [Fact] public void EveryMountTakesACatalogDesign() { - using var cache = RestoredHullsTests.OpenCatalog(); + using var cache = RestoredHullsTests.OpenCatalogWithFixtures(); var designs = cache.GetAll<EquippableItemData>().ToArray(); var bare = Wren(cache).Hardpoints.Where(hardpoint => !designs.Any(hardpoint.Takes)).Select(hardpoint => $"{hardpoint.Transform} ({hardpoint.Type})").ToArray(); // No shield design fits a 1x1 yet (hardpoint-fit lists Djinni's 4-cell shield with none either); every other mount does. @@ -57,7 +57,7 @@ public sealed class WrenPackageTests [Fact] public void TheStarterFliesUnderThrust() { - using var cache = RestoredHullsTests.OpenCatalog(); + using var cache = RestoredHullsTests.OpenCatalogWithFixtures(); var ship = RestoredHullsTests.BuildThrustedShip(cache, "Wren"); var start = ship.Velocity; ship.MovementDirection = float2(0, 1); diff --git a/GameData/Mods/aetheria.wren/ship.cc b/tests/fixtures/mods/aetheria.wren/ship.cc similarity index 100% rename from GameData/Mods/aetheria.wren/ship.cc rename to tests/fixtures/mods/aetheria.wren/ship.cc diff --git a/GameData/Mods/aetheria.wren/ship.glb b/tests/fixtures/mods/aetheria.wren/ship.glb similarity index 100% rename from GameData/Mods/aetheria.wren/ship.glb rename to tests/fixtures/mods/aetheria.wren/ship.glb diff --git a/tools/AetherDb/ShipAuthoringCommands.cs b/tools/AetherDb/ShipAuthoringCommands.cs index 458ae4038..4298bc198 100644 --- a/tools/AetherDb/ShipAuthoringCommands.cs +++ b/tools/AetherDb/ShipAuthoringCommands.cs @@ -53,6 +53,10 @@ public static class ShipAuthoringCommands var judged = model != null && File.Exists(model) ? "records and model" : "records only, no model yet"; if (judged == "records and model") ShipModCatalog.ReadPackage(args[1]); else ShipAuthoringStore.ValidateLoaded(hull, ship, products); + // Compose refuses an offered hull with no schematic; the author sees that verdict here, before compose. + // A package with no products is never offered, so the shipped catalog (which only resolves a product's bin) is opened for none. + using var catalog = products.Length > 0 ? AetherDb.Open().Cache : null; + if (ShipModCatalog.SchematicFault(catalog, ship, products) is { } fault) throw new InvalidOperationException(fault); Console.WriteLine($"{ship.Id}: {hull.Name}, {hull.Hardpoints.Count} hardpoints, {ship.Anchors.Count} anchors, {ship.SchematicLines.Count} lines ({judged})"); return 0; } From 8b2d1f5442df2090943f28b36db7e1f41cc1527c Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Tue, 17 Nov 2026 19:12:07 +0100 Subject: [PATCH 108/190] Compose and validate judge a package's bins; the schematic gate reads offered-ness through them MarketFault (renamed from SchematicFault) refuses a product bin whose line is neither an unbinned shipped product nor an unbinned product of the same package, which the catalog read would crash boot on, and which let an offered hull with no lines pass through a cross-package bin. The carve-out guard is gone: IsOffered now has an overload taking a line resolver, so it judges package-own lines too. Tests pin bin-derived offeredness, any-vs-all products, null SchematicLines and the exclusion of bad bins with the derived catalog still opening. The LFS staging derivation includes tests/fixtures/mods. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../Scripts/ServerShared/LoadoutGenerator.cs | 7 +- Assets/Scripts/ServerShared/ShipModCatalog.cs | 26 ++-- docs/mining-cut-refresh.md | 4 +- .../ShipModCatalogTests.cs | 136 ++++++++++++++---- .../Aetheria.Shared.Tests/ShipProductTests.cs | 13 +- tools/AetherDb/ShipAuthoringCommands.cs | 6 +- 6 files changed, 148 insertions(+), 44 deletions(-) diff --git a/Assets/Scripts/ServerShared/LoadoutGenerator.cs b/Assets/Scripts/ServerShared/LoadoutGenerator.cs index fcd554efd..62e8632a1 100644 --- a/Assets/Scripts/ServerShared/LoadoutGenerator.cs +++ b/Assets/Scripts/ServerShared/LoadoutGenerator.cs @@ -257,8 +257,11 @@ public class LoadoutGenerator // Whether a product is on the market at all (ruling off-market-is-unoffered-product). The one reader of NotOffered. A bin is // offered only if both it and its line are (ruling bin-inherits-line-offered); the catalog read guarantees a bin's line exists. - public static bool IsOffered(CultCache items, FactionProductData product) => - !product.NotOffered && (product.Bin == null || !items.Get(product.Bin.Line).NotOffered); + public static bool IsOffered(CultCache items, FactionProductData product) => IsOffered(product, line => items.Get(line)); + + // The same reader for a caller whose bin lines are not all in one catalog yet (ShipModCatalog.MarketFault, over a package's own products). + public static bool IsOffered(FactionProductData product, Func<CultRecordRef<FactionProductData>, FactionProductData> lineOf) => + !product.NotOffered && (product.Bin == null || !lineOf(product.Bin.Line).NotOffered); // How much this outfitter favors a product: its maker's preference times the product's share of it. The one weight of // generation and of ChooseProduct. A bin takes the share of its maker's stock that would pass its floor and its line takes diff --git a/Assets/Scripts/ServerShared/ShipModCatalog.cs b/Assets/Scripts/ServerShared/ShipModCatalog.cs index d085974b4..0e5bd801c 100644 --- a/Assets/Scripts/ServerShared/ShipModCatalog.cs +++ b/Assets/Scripts/ServerShared/ShipModCatalog.cs @@ -110,7 +110,7 @@ public static class ShipModCatalog if (shipIds.Contains(ship.Id)) Exclude(directory, $"ship ID collides with an existing catalog ship authoring record."); if (StationKinds.HullKindFault(cache, hull) is { } kindFault) Exclude(directory, kindFault); - if (SchematicFault(cache, ship, package.Products) is { } schematicFault) Exclude(directory, schematicFault); + if (MarketFault(cache, ship, package.Products) is { } marketFault) Exclude(directory, marketFault); foreach (var product in package.Products) { if (!factionKeys.Contains(product.Manufacturer.Key)) @@ -158,16 +158,24 @@ public static class ShipModCatalog } } - // Why a package's hull cannot go on the market, or null: a hull offered through any of its products is drawn on the map and - // the schematic by its lines (ShipModVisual.BuildLineMesh builds nothing from none), so an offered hull without any is - // excluded. An unoffered stand-in is left alone. Offered is LoadoutGenerator.IsOffered, the one reader of NotOffered - // (ruling off-market-is-unoffered-product); `items` is the catalog the products' bins resolve in. A product whose bin - // line the catalog does not hold is not judged here: the catalog read refuses it. - public static string SchematicFault(CultCache items, ShipAuthoring ship, FactionProductData[] products) + // Why a package's products cannot join the catalog, or null; the one judgement Compose and `ship-authoring validate` share. + // `items` is the shipped catalog. A product's bin may name only a product line the shipped catalog holds or one of the + // package's own products (and that line must not be a bin itself): the catalog read refuses any other bin, and a line in + // another package is no promise, since packages compose independently. With every bin resolved, a hull offered through any of its + // products is drawn on the map and the schematic by its lines (ShipModVisual.BuildLineMesh builds nothing from none), so an + // offered hull without any is refused; an unoffered stand-in is left alone. Offered is LoadoutGenerator.IsOffered, the one + // reader of NotOffered (ruling off-market-is-unoffered-product), resolving a line among the package's own products too. + public static string MarketFault(CultCache items, ShipAuthoring ship, FactionProductData[] products) { + var own = new Dictionary<CultRecordKey, FactionProductData>(); + foreach (var product in products) own[ProductKey(ship.Id, product.Manufacturer.Key)] = product; + FactionProductData LineOf(CultRecordRef<FactionProductData> line) => items.Get(line) ?? (own.TryGetValue(line.Key, out var found) ? found : null); + foreach (var product in products.Where(product => product.Bin != null)) + if (LineOf(product.Bin.Line) is not { } line || line.Bin != null) + return $"{ship.Id}: product '{product.Name}' bins a line that is neither an unbinned shipped product nor an unbinned product of this package."; if (ship.SchematicLines != null && ship.SchematicLines.Any(line => line?.Points != null && line.Points.Length > 0)) return null; - var offered = products.Any(product => (product.Bin == null || items.Get(product.Bin.Line) != null) && LoadoutGenerator.IsOffered(items, product)); - return offered ? $"{ship.Id}: the hull is offered on the market but has no schematic lines." : null; + return products.Any(product => LoadoutGenerator.IsOffered(product, LineOf)) + ? $"{ship.Id}: the hull is offered on the market but has no schematic lines." : null; } public static Package ReadPackage(string shipPath) diff --git a/docs/mining-cut-refresh.md b/docs/mining-cut-refresh.md index b0bf89420..8a5fdcd9e 100644 --- a/docs/mining-cut-refresh.md +++ b/docs/mining-cut-refresh.md @@ -302,12 +302,12 @@ Every mining question is ruled. `ssh:` remote). Push from a `--shared --no-checkout` clone, and mount the LFS blobs. This is recorded so the next Hands does not rediscover it. - LFS staging set. `SubstanceCleanBreakTests` fails loudly on any LFS pointer it scans, so the job must restore - every LFS-tracked file under `Assets/`, `Packages/`, `ProjectSettings/` and `GameData/*.cc` that is not a + every LFS-tracked file under `Assets/`, `Packages/`, `ProjectSettings/`, `GameData/*.cc` and `tests/fixtures/mods/*.cc` that is not a binary-media extension (the test's `BinaryExtensions` denylist): 99 files at `83e6957de`, 96 `*.asset` and 3 `*.cc` (`GameData/Aetheria.cc`, `GameData/Mods/aetheria.nakovalnya/ship.cc`, `tests/fixtures/mods/aetheria.wren/ship.cc`), which includes `ProjectSettings/ProjectSettings.asset` and `Assets/Resources/Settings.asset`. Derive the list from the merged tree instead of hand-copying it: - `git ls-files Assets Packages ProjectSettings 'GameData/*.cc' | git check-attr --stdin filter | grep 'lfs$' | sed 's/: filter: lfs//' | grep -viE '\.(png|jpg|jpeg|tga|tif|tiff|psd|bmp|gif|exr|hdr|dds|wav|mp3|ogg|mp4|fbx|glb|blend|ttf|otf|dll|so|pdb|msgpack|zip|bank)$'`, + `git ls-files Assets Packages ProjectSettings 'GameData/*.cc' 'tests/fixtures/mods/*.cc' | git check-attr --stdin filter | grep 'lfs$' | sed 's/: filter: lfs//' | grep -viE '\.(png|jpg|jpeg|tga|tif|tiff|psd|bmp|gif|exr|hdr|dds|wav|mp3|ogg|mp4|fbx|glb|blend|ttf|otf|dll|so|pdb|msgpack|zip|bank)$'`, then copy each path from the `/lfs` mount over the checkout. That set (99: the 97 the sbsar guards read plus the two mod `ship.cc` files the Nakovalnya and Wren tests open) makes `SubstanceCleanBreakTests` green and nothing more: staging only two files turns it red. For a fully green suite also stage `GameData/Mods/*/ship.glb` and `tests/fixtures/mods/*/ship.glb` (the catalog excludes a package with an invalid GLB header, failing about 520 tests) and the LFS `.ttf`/`.otf` fonts `CreditsTests.FontCreditsShowWhatTheFontsThemselvesEmbed` reads. - Unity batchmode compile of the merged tree (Self, in a worktree, never with the operator's editor open on the main tree). This is the Cut 1 renderer compile the map still owes. diff --git a/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs b/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs index b4003954c..5a4f38093 100644 --- a/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipModCatalogTests.cs @@ -49,43 +49,71 @@ public sealed class ShipModCatalogTests : IDisposable AssertOnlyTheDerivedFile(); } - // A package selling one product through the one product writer, with or without schematic lines and offered or not. - private void PricedPackage(string id, bool lines, bool offered) - { - var factionKey = AddFaction(); - WritePackage(id, id, tweak: ship => - { - ship.Hull.Price = 100; - if (!lines) ship.Visual.SchematicLines = new List<ShipPolyline>(); - }); - using var cache = ShipAuthoringStore.Open(Path.Combine(Mods, id, "ship.cc"), writable: true); - ShipAuthoringStore.WriteProduct(cache, id, new FactionProductData - { - Name = id + " product", - Design = new CultRecordRef<CraftedItemData>(ShipModCatalog.HullKey(id)), - Manufacturer = new CultRecordRef<Faction>(factionKey), - NotOffered = !offered - }); - cache.FlushAsync().Wait(); - } - - private CultRecordKey AddFaction() + // A maker (by name) the shipped catalog holds, made on first use. + private CultRecordKey Maker(string name) { using var cache = AetheriaStores.Open(Shipped, catalogWritable: true); - var existing = cache.GetAll<Faction>().FirstOrDefault(); - var key = existing != null ? cache.RefOf(existing).Key : cache.Upsert(new Faction { Name = "Acme", ShortName = "ACM" }).Key; + var existing = cache.GetAll<Faction>().FirstOrDefault(faction => faction.Name == name); + var key = existing != null ? cache.RefOf(existing).Key : cache.Upsert(new Faction { Name = name, ShortName = name.Substring(0, 3).ToUpperInvariant() }).Key; cache.FlushAsync().Wait(); return key; } + // A shipped product line a package's product can bin. + private CultRecordKey ShippedLine(string name, bool notOffered) + { + var maker = Maker("Acme"); + using var cache = AetheriaStores.Open(Shipped, catalogWritable: true); + var hull = cache.Upsert(new HullData { Name = name + " hull", Shape = ShipAuthoringTests.Fixture().Hull.Shape, Price = 10 }); + var line = cache.Upsert(new FactionProductData + { + Name = name, + Design = new CultRecordRef<CraftedItemData>(hull.Key), + Manufacturer = new CultRecordRef<Faction>(maker), + NotOffered = notOffered + }); + cache.FlushAsync().Wait(); + return line.Key; + } + + // One product of a package: its maker, whether it is itself off the market, and the line it bins, if any. + private sealed record Sale(string Maker, bool NotOffered = false, CultRecordKey? Bin = null); + + // A priced package selling the given products through the one product writer, with or without schematic lines + // (`lines` null leaves the record's SchematicLines null). + private void PricedPackage(string id, bool? lines, params Sale[] sales) + { + var makers = sales.Select(sale => Maker(sale.Maker)).ToArray(); + WritePackage(id, id, tweak: ship => + { + ship.Hull.Price = 100; + if (lines == false) ship.Visual.SchematicLines = new List<ShipPolyline>(); + if (lines == null) ship.Visual.SchematicLines = null; + }); + using var cache = ShipAuthoringStore.Open(Path.Combine(Mods, id, "ship.cc"), writable: true); + for (var n = 0; n < sales.Length; n++) + ShipAuthoringStore.WriteProduct(cache, id, new FactionProductData + { + Name = $"{id} product {n}", + Design = new CultRecordRef<CraftedItemData>(ShipModCatalog.HullKey(id)), + Manufacturer = new CultRecordRef<Faction>(makers[n]), + NotOffered = sales[n].NotOffered, + Bin = sales[n].Bin is { } line ? new ProductBin { Line = new CultRecordRef<FactionProductData>(line), Floor = 1f } : null + }); + cache.FlushAsync().Wait(); + } + + private static string Excluded(ShipModCatalog.Composition composition, string package) => + composition.Excluded.SingleOrDefault(entry => entry.Package == package)?.Reason; + // An offered hull is drawn by its schematic lines (ShipModVisual.BuildLineMesh builds nothing from none), so one without any // is left out of the catalog with its reason; an offered hull with lines and an unoffered stand-in without them both compose. [Fact] public void ComposeExcludesAnOfferedHullWithoutSchematicLinesAndKeepsTheRest() { - PricedPackage("mod.offeredbare", lines: false, offered: true); - PricedPackage("mod.offeredlined", lines: true, offered: true); - PricedPackage("mod.standin", lines: false, offered: false); + PricedPackage("mod.offeredbare", lines: false, new Sale("Acme")); + PricedPackage("mod.offeredlined", lines: true, new Sale("Acme")); + PricedPackage("mod.standin", lines: false, new Sale("Acme", NotOffered: true)); var composition = ShipModCatalog.Compose(Shipped, Derived, Mods); @@ -96,6 +124,62 @@ public sealed class ShipModCatalogTests : IDisposable Assert.Contains("no schematic", excluded.Reason); } + // A hull is offered when any product of it is, and a binned product is offered only if its line is (ruling bin-inherits-line-offered): + // the verdict is IsOffered's, not a read of the product's own NotOffered. + [Fact] + public void OfferedNessComesFromAnyProductAndFromTheBinsLine() + { + var offeredLine = ShippedLine("Offered Line", notOffered: false); + var closedLine = ShippedLine("Closed Line", notOffered: true); + PricedPackage("mod.binoffered", lines: false, new Sale("Acme", Bin: offeredLine)); + PricedPackage("mod.binclosed", lines: false, new Sale("Acme", Bin: closedLine)); + PricedPackage("mod.oneoftwo", lines: false, new Sale("Acme", NotOffered: true), new Sale("Rival")); + + var composition = ShipModCatalog.Compose(Shipped, Derived, Mods); + + Assert.Contains("no schematic", Excluded(composition, "mod.binoffered")); + Assert.Null(Excluded(composition, "mod.binclosed")); + Assert.Contains("no schematic", Excluded(composition, "mod.oneoftwo")); + Assert.Equal(new[] { "mod.binclosed" }, composition.Included); + } + + [Fact] + public void ANullSchematicIsNoSchematicWhenOffered() + { + PricedPackage("mod.nulled", lines: null, new Sale("Acme")); + PricedPackage("mod.nulledstandin", lines: null, new Sale("Acme", NotOffered: true)); + + var composition = ShipModCatalog.Compose(Shipped, Derived, Mods); + + Assert.Contains("no schematic", Excluded(composition, "mod.nulled")); + Assert.Equal(new[] { "mod.nulledstandin" }, composition.Included); + } + + // A bin's line is a shipped product or one of the package's own, never another package's and never nothing: the catalog read + // refuses such a bin at boot, so compose leaves the package out and the derived catalog opens. + [Fact] + public void ComposeExcludesAPackageWhoseBinNamesNoShippedOrOwnLine() + { + var shipped = ShippedLine("Shipped Line", notOffered: false); + var maker = Maker("Acme"); + PricedPackage("mod.lined", lines: true, new Sale("Acme")); + PricedPackage("mod.cross", lines: false, new Sale("Rival", Bin: ShipModCatalog.ProductKey("mod.lined", maker))); + PricedPackage("mod.nothing", lines: true, new Sale("Acme", Bin: new CultRecordKey("product:nowhere"))); + PricedPackage("mod.shippedbin", lines: true, new Sale("Acme", Bin: shipped)); + PricedPackage("mod.ownbin", lines: true, new Sale("Acme"), new Sale("Rival", Bin: ShipModCatalog.ProductKey("mod.ownbin", maker))); + + PricedPackage("mod.binofbin", lines: true, new Sale("Acme", Bin: shipped), new Sale("Rival", Bin: ShipModCatalog.ProductKey("mod.binofbin", maker))); + + var (catalog, excluded) = ShipModCatalog.ResolveCatalog(Shipped, Derived, Mods); + + Assert.Equal(new[] { "mod.binofbin", "mod.cross", "mod.nothing" }, excluded.Select(entry => entry.Package).OrderBy(id => id, StringComparer.Ordinal)); + Assert.All(excluded, entry => Assert.Contains("bins a line", entry.Reason)); + Assert.Equal(Derived, catalog); + using var cache = AetheriaStores.Open(Derived); + Assert.Contains("mod.ownbin product 1", cache.GetAll<FactionProductData>().Select(product => product.Name)); + Assert.DoesNotContain("mod.cross product 0", cache.GetAll<FactionProductData>().Select(product => product.Name)); + } + // A package's station kind is checked per package: a bad one is left out, named with its reason, and the derived catalog // still opens. The shipped catalog's own check is unchanged. [Fact] diff --git a/tests/Aetheria.Shared.Tests/ShipProductTests.cs b/tests/Aetheria.Shared.Tests/ShipProductTests.cs index 0ee2db012..638f408b6 100644 --- a/tests/Aetheria.Shared.Tests/ShipProductTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipProductTests.cs @@ -104,13 +104,14 @@ public sealed class ShipProductTests : IDisposable public void ValidateRefusesAnOfferedHullWithoutSchematicLinesAsComposeDoes() { Environment.CurrentDirectory = _root.Path; - string Bare(string id, bool offered) + string Bare(string id, bool offered, bool nullLines = false, CultRecordKey? bin = null) { - var directory = ShipFixture.WritePackage(Mods, id, id, tweak: ship => { ship.Hull.Price = 100; ship.Visual.SchematicLines = new List<ShipPolyline>(); }); + var directory = ShipFixture.WritePackage(Mods, id, id, tweak: ship => { ship.Hull.Price = 100; ship.Visual.SchematicLines = nullLines ? null : new List<ShipPolyline>(); }); var path = Path.Combine(directory, "ship.cc"); using var cache = ShipAuthoringStore.Open(path, writable: true); var product = Product(id + " product", _acme, id); product.NotOffered = !offered; + if (bin is { } line) product.Bin = new ProductBin { Line = new CultRecordRef<FactionProductData>(line), Floor = 1f }; ShipAuthoringStore.WriteProduct(cache, id, product); cache.FlushAsync().Wait(); return path; @@ -120,6 +121,14 @@ public sealed class ShipProductTests : IDisposable Assert.Equal(1, code); Assert.Contains("no schematic", error); Assert.Equal(0, Run("validate", Bare("mod.standin", offered: false)).Item1); + // A null SchematicLines is no schematic, as for compose. + var (nullCode, _, nullError) = Run("validate", Bare("mod.nulled", offered: true, nullLines: true)); + Assert.Equal(1, nullCode); + Assert.Contains("no schematic", nullError); + // A bin naming no shipped product and no product of the package is refused, as compose excludes it. + var (binCode, _, binError) = Run("validate", Bare("mod.badbin", offered: true, bin: new CultRecordKey("product:nowhere"))); + Assert.Equal(1, binCode); + Assert.Contains("bins a line", binError); Assert.Equal(new[] { "mod.standin" }, ShipModCatalog.Compose(Shipped, Derived, Mods).Included); } diff --git a/tools/AetherDb/ShipAuthoringCommands.cs b/tools/AetherDb/ShipAuthoringCommands.cs index 4298bc198..3b3ea9051 100644 --- a/tools/AetherDb/ShipAuthoringCommands.cs +++ b/tools/AetherDb/ShipAuthoringCommands.cs @@ -53,10 +53,10 @@ public static class ShipAuthoringCommands var judged = model != null && File.Exists(model) ? "records and model" : "records only, no model yet"; if (judged == "records and model") ShipModCatalog.ReadPackage(args[1]); else ShipAuthoringStore.ValidateLoaded(hull, ship, products); - // Compose refuses an offered hull with no schematic; the author sees that verdict here, before compose. - // A package with no products is never offered, so the shipped catalog (which only resolves a product's bin) is opened for none. + // Compose's verdict on a package's bins and its offered hull's schematic; the author sees it here, before compose. + // A package with no products has no bin and is never offered, so the shipped catalog is opened for none. using var catalog = products.Length > 0 ? AetherDb.Open().Cache : null; - if (ShipModCatalog.SchematicFault(catalog, ship, products) is { } fault) throw new InvalidOperationException(fault); + if (ShipModCatalog.MarketFault(catalog, ship, products) is { } fault) throw new InvalidOperationException(fault); Console.WriteLine($"{ship.Id}: {hull.Name}, {hull.Hardpoints.Count} hardpoints, {ship.Anchors.Count} anchors, {ship.SchematicLines.Count} lines ({judged})"); return 0; } From 40a5457c9ee8c64e9bab6f8d5d682537514baa2a Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Thu, 19 Nov 2026 20:14:26 +0100 Subject: [PATCH 109/190] Retire the prelude and the tutorial: the cast, the scenario and the save own what they bundled Galaxy.IsPrelude, SavedGame.IsTutorial (key 11 retired), TutorialGalaxy, TutorialGenerationSettings, its Settings.asset block and the dead GalaxyStage/Galaxy constructor parameters (PlayerSettings, narrative directory) are gone. The rules they bundled move to their owners: GalaxyCast.InfluenceScale (demo and test cast .5, main 1) carried by Galaxy and saved as SavedGame key 17, so a pre-cut run is refused at Continue with a message; Scenario.EntranceStation (MainGalaxy false) decides the forced entrance station instead of the galaxy; GalaxyStage.Cast(cast) replaces Prelude. The six arenas that read the authored cast generate DemoTerminus.Cast; Development lists only Main Galaxy. TutorialBackgroundSettings is renamed CastBackgroundSettings in the asset YAML. Tests build their galaxy from TestCasts.Wide and Background, the retired block's values, so every test galaxy is unchanged. Suite at 8b2d1f544: 4 red (font credits, chunk info, trojan swarm, two-ai digest, Windows). After: the same 4, digest unchanged. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Resources/Settings.asset | 4 +- Assets/Scripts/Gameplay/ActionGameManager.cs | 5 +- Assets/Scripts/Gameplay/GameSettings.cs | 3 +- Assets/Scripts/ServerShared/Galaxy.cs | 56 ++++----- Assets/Scripts/ServerShared/GalaxyStage.cs | 27 ++--- Assets/Scripts/ServerShared/RunStart.cs | 6 +- Assets/Scripts/ServerShared/SavedGame.cs | 10 +- Assets/Scripts/ServerShared/Scenario.cs | 6 +- Assets/Scripts/ServerShared/ScenarioStage.cs | 4 +- .../Scenarios/AiFusedDiscipline.cs | 2 +- Assets/Scripts/ServerShared/Scenarios/Arcs.cs | 2 +- Assets/Scripts/ServerShared/Scenarios/Belt.cs | 2 +- .../ServerShared/Scenarios/Crossing.cs | 2 +- .../ServerShared/Scenarios/DemoTerminus.cs | 9 +- .../ServerShared/Scenarios/DjinniShakedown.cs | 2 +- Assets/Scripts/ServerShared/Scenarios/Duel.cs | 2 +- .../ServerShared/Scenarios/FusedRounds.cs | 2 +- .../ServerShared/Scenarios/LauncherAngles.cs | 2 +- .../Scripts/ServerShared/Scenarios/LockOn.cs | 2 +- .../ServerShared/Scenarios/LongHaul.cs | 2 +- .../ServerShared/Scenarios/MainGalaxy.cs | 2 + .../Scripts/ServerShared/Scenarios/Pursuit.cs | 2 +- .../ServerShared/Scenarios/RefusedRounds.cs | 2 +- .../ServerShared/Scenarios/Scenarios.cs | 2 +- .../ServerShared/Scenarios/StarvedReactor.cs | 2 +- .../ServerShared/Scenarios/TutorialGalaxy.cs | 17 --- .../Scenarios/TutorialGalaxy.cs.meta | 11 -- .../ServerShared/Scenarios/WeaponFeel.cs | 2 +- Assets/Scripts/ServerShared/Settings.cs | 8 +- Assets/Scripts/ServerShared/ZoneGenerator.cs | 24 ++-- Assets/Scripts/UI/MainMenu.cs | 14 ++- .../ChildrenWithinReachTests.cs | 9 +- .../ConsumableSupplyTests.cs | 5 +- .../DemoTerminusTests.cs | 58 ++++------ .../FireControlCut6cTests.cs | 1 + tests/Aetheria.Shared.Tests/LoadoutTests.cs | 1 + .../Aetheria.Shared.Tests/MiningCut3Tests.cs | 12 +- .../Aetheria.Shared.Tests/MiningCut5bTests.cs | 2 + .../OrbitsFromFieldTests.cs | 9 +- .../OreGeographyTests.cs | 16 +-- .../Aetheria.Shared.Tests/PlaceNamesTests.cs | 4 +- .../ProductChoiceTests.cs | 1 + .../RestoredHullsTests.cs | 94 +++++++-------- tests/Aetheria.Shared.Tests/RunGoalTests.cs | 2 +- tests/Aetheria.Shared.Tests/RunSaveTests.cs | 2 + tests/Aetheria.Shared.Tests/RunSeedFixture.cs | 1 + .../RunStartGearTests.cs | 4 +- tests/Aetheria.Shared.Tests/RunStartTests.cs | 16 ++- tests/Aetheria.Shared.Tests/ScenarioTests.cs | 109 +++++++++++++----- .../Aetheria.Shared.Tests/StationKindTests.cs | 28 ++--- .../StationPlacementTests.cs | 9 +- .../SunsNeverGreenTests.cs | 7 +- tests/Aetheria.Shared.Tests/TestCasts.cs | 18 +++ tools/AetherDb/Program.cs | 11 +- 54 files changed, 334 insertions(+), 321 deletions(-) delete mode 100644 Assets/Scripts/ServerShared/Scenarios/TutorialGalaxy.cs delete mode 100644 Assets/Scripts/ServerShared/Scenarios/TutorialGalaxy.cs.meta create mode 100644 tests/Aetheria.Shared.Tests/TestCasts.cs diff --git a/Assets/Resources/Settings.asset b/Assets/Resources/Settings.asset index c12d32c99..95d783c85 100644 --- a/Assets/Resources/Settings.asset +++ b/Assets/Resources/Settings.asset @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:711ded55b95c512e3803df7682e44f0a9bb83ad36a384432781dc12dc5dadf0a -size 12630 +oid sha256:9705712101eaff9f702d793735d4f4db903638aaaae1467c72e5f432464cc48c +size 12410 diff --git a/Assets/Scripts/Gameplay/ActionGameManager.cs b/Assets/Scripts/Gameplay/ActionGameManager.cs index a47577d38..efab44bd9 100644 --- a/Assets/Scripts/Gameplay/ActionGameManager.cs +++ b/Assets/Scripts/Gameplay/ActionGameManager.cs @@ -740,8 +740,7 @@ public class ActionGameManager : MonoBehaviour Settings.ZoneSettings, Settings.PlanetSettings, CurrentGalaxy, - galaxyZone, - CurrentGalaxy.IsPrelude + galaxyZone ); galaxyZone.Contents = new Zone(ItemManager, Settings.PlanetSettings, galaxyZone.PackedContents, galaxyZone, CurrentGalaxy); } @@ -861,7 +860,7 @@ public class ActionGameManager : MonoBehaviour { RunStart.GenerateArena(ItemManager, Settings.ZoneSettings, Settings.PlanetSettings, CurrentGalaxy, scenario); PopulateLevel(CurrentGalaxy.Entrance); - return RunStart.Stage(ItemManager, Zone, scenario, Settings.StartingHullName, Settings.TutorialGenerationSettings, failures); + return RunStart.Stage(ItemManager, Zone, scenario, Settings.StartingHullName, failures); }), failures, Debug.LogException); if (staged == null) diff --git a/Assets/Scripts/Gameplay/GameSettings.cs b/Assets/Scripts/Gameplay/GameSettings.cs index 9d89c5822..ec9f895a5 100644 --- a/Assets/Scripts/Gameplay/GameSettings.cs +++ b/Assets/Scripts/Gameplay/GameSettings.cs @@ -22,8 +22,7 @@ public class GameSettings : ScriptableObject public float MinimapAsteroidSize = 3; public float MinimapIconSize = 1f / 32; public float PlanetRotationSpeed = 1; - public TutorialGenerationSettings TutorialGenerationSettings; - public SectorBackgroundSettings TutorialBackgroundSettings; + public SectorBackgroundSettings CastBackgroundSettings; public SectorBackgroundSettings SectorBackgroundSettings; public SectorGenerationSettings SectorGenerationSettings; public BodySettingsCollection[] BodySettingsCollections; diff --git a/Assets/Scripts/ServerShared/Galaxy.cs b/Assets/Scripts/ServerShared/Galaxy.cs index 797e77764..929fa3493 100644 --- a/Assets/Scripts/ServerShared/Galaxy.cs +++ b/Assets/Scripts/ServerShared/Galaxy.cs @@ -26,7 +26,10 @@ public class Galaxy public GalaxyZone Exit { get; private set; } public Dictionary<Faction, FactionRelationship> FactionRelationships { get; } = new Dictionary<Faction, FactionRelationship>(); private Action<string> Log { get; } - public bool IsPrelude { get; } + + // How far each faction's authored InfluenceDistance reaches in this galaxy (InfluenceOf): the cast's InfluenceScale, + // 1 for a main galaxy. Carried by the save because every zone generated after Continue reads it. + public float InfluenceScale { get; } // The run's seed, minted once by GalaxyStage.SeedFrom and carried by the save (SavedGame.Seed). It seeds // generation, the run's item draws (RunStart) and the zone's drop dice (Zone.DropSeed). @@ -51,7 +54,9 @@ public class Galaxy public Galaxy(CultCache cultCache, SavedGame savedGame, Action<string> log) { - IsPrelude = savedGame.IsTutorial; + InfluenceScale = savedGame.InfluenceScale > 0 + ? savedGame.InfluenceScale + : throw new InvalidOperationException($"the save has no {nameof(InfluenceScale)} ({savedGame.InfluenceScale}); a run saved before InfluenceScale existed cannot be continued"); _cache = cultCache; Log = log; Background = savedGame.Background; @@ -112,7 +117,7 @@ public class Galaxy uint seed) { _cache = cache; - IsPrelude = false; + InfluenceScale = 1; Background = background; Log = log; var factions = cache.GetAll<Faction>(); @@ -186,11 +191,11 @@ public class Galaxy return _cache.GetAll<Faction>().FirstOrDefault(f => f.Name.StartsWith(name, StringComparison.InvariantCultureIgnoreCase)); } - // A cast member of a prelude galaxy, by name. A name the catalog does not hold refuses the galaxy, naming the field. + // A cast member of a cast galaxy, by name. A name the catalog does not hold refuses the galaxy, naming the field. private Faction ResolveCast(string field, string name) => ResolveFaction(name) ?? throw new InvalidOperationException($"cast faction {name} ({field}) is not in the catalog"); - // Gives a prelude galaxy its gate: the antagonist's home is the boss zone and the exit. The only writer of Exit + // Gives a cast galaxy its gate: the antagonist's home is the boss zone and the exit. The only writer of Exit // besides the constructors. public void PlaceGate(Faction antagonist) { @@ -198,23 +203,24 @@ public class Galaxy Exit = HomeZones[antagonist]; } - // How many jumps a faction's influence reaches in this galaxy: its authored distance, halved (rounding up) in a - // prelude. Derived, never written back to the catalog's Faction, so one galaxy's generation cannot change the next. + // How many jumps a faction's influence reaches in this galaxy: its authored distance scaled by the galaxy's + // InfluenceScale (the cast decides the scale), rounding up. Derived, never written back to the catalog's Faction, + // so one galaxy's generation cannot change the next. public int InfluenceOf(Faction faction) => - IsPrelude ? (faction.InfluenceDistance + 1) / 2 : faction.InfluenceDistance; + (int) MathF.Ceiling(faction.InfluenceDistance * InfluenceScale); public Galaxy( - TutorialGenerationSettings settings, + GalaxyCast cast, SectorBackgroundSettings background, CultCache cache, - PlayerSettings playerSettings, - DirectoryInfo narrativeDirectory, Action<string> log, Action<string> progressCallback, uint seed) { _cache = cache; - IsPrelude = true; + InfluenceScale = cast.InfluenceScale > 0 + ? cast.InfluenceScale + : throw new InvalidOperationException($"the cast's {nameof(cast.InfluenceScale)} must be positive, got {cast.InfluenceScale}"); Background = background; Log = log; @@ -223,32 +229,32 @@ public class Galaxy var factions = new List<Faction>(); - var protagonistFaction = ResolveCast(nameof(settings.ProtagonistFaction), settings.ProtagonistFaction); + var protagonistFaction = ResolveCast(nameof(cast.ProtagonistFaction), cast.ProtagonistFaction); factions.Add(protagonistFaction); - var antagonistFaction = ResolveCast(nameof(settings.AntagonistFaction), settings.AntagonistFaction); + var antagonistFaction = ResolveCast(nameof(cast.AntagonistFaction), cast.AntagonistFaction); factions.Add(antagonistFaction); - var bufferFaction = ResolveCast(nameof(settings.BufferFaction), settings.BufferFaction); + var bufferFaction = ResolveCast(nameof(cast.BufferFaction), cast.BufferFaction); factions.Add(bufferFaction); // A cast without a quest faction places no quest zone. - var questFaction = string.IsNullOrEmpty(settings.QuestFaction) + var questFaction = string.IsNullOrEmpty(cast.QuestFaction) ? null - : ResolveCast(nameof(settings.QuestFaction), settings.QuestFaction); + : ResolveCast(nameof(cast.QuestFaction), cast.QuestFaction); if (questFaction != null) factions.Add(questFaction); - var neutralFactions = settings.NeutralFactions - .Select(name => ResolveCast(nameof(settings.NeutralFactions), name)) + var neutralFactions = cast.NeutralFactions + .Select(name => ResolveCast(nameof(cast.NeutralFactions), name)) .ToArray(); factions.AddRange(neutralFactions); Factions = factions.ToArray(); foreach (var faction in Factions) FactionRelationships[faction] = FactionRelationship.Neutral; - Zones = GenerateZones(settings.ZoneCount, ref random, progressCallback); + Zones = GenerateZones(cast.ZoneCount, ref random, progressCallback); - GenerateLinks(settings.LinkDensity, progressCallback); + GenerateLinks(cast.LinkDensity, progressCallback); CalculateDistanceMatrix(progressCallback); @@ -302,15 +308,11 @@ public class Galaxy CalculateFactionInfluence(progressCallback); - // No boss zone and no Exit yet (PlaceGate comes after): the prelude is one region. - BuildProvinces(settings.ProvinceZones); + // No boss zone and no Exit yet (PlaceGate comes after): a cast galaxy is one region. + BuildProvinces(cast.ProvinceZones); NamePlaces(ref random, progressCallback); - // progressCallback?.Invoke("Weaving Narrative"); - // var processor = new StoryProcessor(playerSettings, narrativeDirectory, this, ref random, Log); - // processor.ProcessStories(); - progressCallback?.Invoke("Done!"); if(progressCallback!=null) Thread.Sleep(500); // Inserting Delay to make it seem like it's doing more work lmao } diff --git a/Assets/Scripts/ServerShared/GalaxyStage.cs b/Assets/Scripts/ServerShared/GalaxyStage.cs index a93e25f89..4bea4d6c7 100644 --- a/Assets/Scripts/ServerShared/GalaxyStage.cs +++ b/Assets/Scripts/ServerShared/GalaxyStage.cs @@ -1,5 +1,4 @@ using System; -using System.IO; using GameCult.Caching; using MessagePack; using static CultMath.math; @@ -13,11 +12,8 @@ public sealed class GalaxyStage { private readonly SectorGenerationSettings _sector; private readonly SectorBackgroundSettings _sectorBackground; - private readonly TutorialGenerationSettings _prelude; - private readonly SectorBackgroundSettings _preludeBackground; + private readonly SectorBackgroundSettings _castBackground; private readonly CultCache _cache; - private readonly PlayerSettings _playerSettings; - private readonly DirectoryInfo _narrativeDirectory; private readonly Action<string> _log; private readonly Action<string> _progress; private readonly Func<uint> _clock; @@ -25,22 +21,16 @@ public sealed class GalaxyStage public GalaxyStage( SectorGenerationSettings sector, SectorBackgroundSettings sectorBackground, - TutorialGenerationSettings prelude, - SectorBackgroundSettings preludeBackground, + SectorBackgroundSettings castBackground, CultCache cache, - PlayerSettings playerSettings, - DirectoryInfo narrativeDirectory, Action<string> log, Action<string> progress = null, Func<uint> clock = null) { _sector = sector; _sectorBackground = sectorBackground; - _prelude = prelude; - _preludeBackground = preludeBackground; + _castBackground = castBackground; _cache = cache; - _playerSettings = playerSettings; - _narrativeDirectory = narrativeDirectory; _log = log; _progress = progress; _clock = clock ?? (() => (uint) (DateTime.Now.Ticks % uint.MaxValue)); @@ -65,13 +55,10 @@ public sealed class GalaxyStage return new Galaxy(_sector, background, _cache, _log, _progress, Seed); } - // A prelude galaxy: the tutorial settings and their fixed factions, centred in dense cloud. - public Galaxy Prelude() => Prelude(_prelude); - - // A prelude galaxy of the given fixed cast, centred in dense cloud. - public Galaxy Prelude(TutorialGenerationSettings cast) + // A galaxy of the given fixed cast, centred in dense cloud. + public Galaxy Cast(GalaxyCast cast) { - var background = Copy(_preludeBackground); + var background = Copy(_castBackground); var random = new Random(Seed); var iteration = 1; do @@ -79,7 +66,7 @@ public sealed class GalaxyStage background.NoisePosition = random.NextFloat() * 1000; _progress?.Invoke($"Finding Galaxy Position: iteration {iteration++}"); } while (background.CloudDensity(float2(.5f)) < .5f); - return new Galaxy(cast, background, _cache, _playerSettings, _narrativeDirectory, _log, _progress, Seed); + return new Galaxy(cast, background, _cache, _log, _progress, Seed); } private static SectorBackgroundSettings Copy(SectorBackgroundSettings settings) => diff --git a/Assets/Scripts/ServerShared/RunStart.cs b/Assets/Scripts/ServerShared/RunStart.cs index 4e6808859..282693eb2 100644 --- a/Assets/Scripts/ServerShared/RunStart.cs +++ b/Assets/Scripts/ServerShared/RunStart.cs @@ -27,7 +27,7 @@ public static class RunStart { SeedItems(itemManager, galaxy, ArenaStep); return galaxy.Entrance.PackedContents = ZoneGenerator.GenerateZone( - itemManager, zoneSettings, planetSettings, galaxy, galaxy.Entrance, galaxy.IsPrelude, scenario.Ambient); + itemManager, zoneSettings, planetSettings, galaxy, galaxy.Entrance, scenario.EntranceStation, scenario.Ambient); } // Runs a start and answers whether it produced a run: null, with the reason in `failures`, when `start` throws or @@ -49,10 +49,10 @@ public static class RunStart // with the player, a pilot for each piloted one. Returns null, with every failure listed and the arena unchanged, // unless the whole scenario staged. public static Staged Stage(ItemManager itemManager, Zone arena, Scenario scenario, string startingHull, - TutorialGenerationSettings tutorialGenerationSettings, List<string> failures) + List<string> failures) { SeedItems(itemManager, arena.Galaxy, StageStep); - var stage = new ScenarioStage(itemManager, arena, startingHull, tutorialGenerationSettings); + var stage = new ScenarioStage(itemManager, arena, startingHull); scenario.Stage(stage); var reported = failures.Count; failures.AddRange(stage.Failures); diff --git a/Assets/Scripts/ServerShared/SavedGame.cs b/Assets/Scripts/ServerShared/SavedGame.cs index cf225ab8b..867714a5e 100644 --- a/Assets/Scripts/ServerShared/SavedGame.cs +++ b/Assets/Scripts/ServerShared/SavedGame.cs @@ -42,8 +42,7 @@ public class SavedGame [Key(10)] public SavedActionBarBinding[] ActionBarBindings; - [Key(11)] - public bool IsTutorial; + // Key(11): retired, do not reuse (a retired run-mode flag) // Read only by a save written before Standings: its entries follow galaxy.Factions order, not Factions order, so // Galaxy trusts it only when the two orders cannot differ (see Galaxy's save constructor). @@ -68,6 +67,11 @@ public class SavedGame // null in a save written before it, which then reads Relationships. [Key(16)] public List<SavedStanding> Standings; + + // Galaxy.InfluenceScale: every zone generated after Continue reads it (ZoneGenerator's factionPresence). Written only + // by RunSave.Capture and read only by Galaxy's save constructor, which refuses a save without one (0). + [Key(17)] + public float InfluenceScale; } [MessagePackObject] @@ -122,7 +126,7 @@ public static class RunSave CurrentZoneEntity = currentZone.Entities.IndexOf(currentEntity), Entrance = Array.IndexOf(galaxy.Zones, galaxy.Entrance), Exit = Array.IndexOf(galaxy.Zones, galaxy.Exit), - IsTutorial = galaxy.IsPrelude, + InfluenceScale = galaxy.InfluenceScale, ActionBarBindings = actionBar, Credits = credits, Seed = galaxy.Seed diff --git a/Assets/Scripts/ServerShared/Scenario.cs b/Assets/Scripts/ServerShared/Scenario.cs index 72b084866..d1d79b87b 100644 --- a/Assets/Scripts/ServerShared/Scenario.cs +++ b/Assets/Scripts/ServerShared/Scenario.cs @@ -22,7 +22,11 @@ public abstract class Scenario // the scenario's conditions. public virtual bool Ambient => true; - // Which galaxy the run is in: stage.Main() or stage.Prelude(). + // True: the arena's zone always gets a generated faction station with a docking bay, whatever its seed rolls + // (ZoneGenerator). False: its stations are rolled like any other zone's. + public virtual bool EntranceStation => true; + + // Which galaxy the run is in: stage.Main() or stage.Cast(cast). public abstract Galaxy Generate(GalaxyStage stage); // What the run starts with: exactly one stage.Player, and anything else the scenario places. diff --git a/Assets/Scripts/ServerShared/ScenarioStage.cs b/Assets/Scripts/ServerShared/ScenarioStage.cs index b7a19b87f..622a5972b 100644 --- a/Assets/Scripts/ServerShared/ScenarioStage.cs +++ b/Assets/Scripts/ServerShared/ScenarioStage.cs @@ -23,12 +23,11 @@ public sealed class ScenarioStage private readonly HashSet<Entity> _fitted = new HashSet<Entity>(); private readonly HashSet<Entity> _cargoAuthored = new HashSet<Entity>(); - internal ScenarioStage(ItemManager items, Zone arena, string startingHull, TutorialGenerationSettings tutorialGenerationSettings) + internal ScenarioStage(ItemManager items, Zone arena, string startingHull) { _items = items; Arena = arena; StartingHull = startingHull; - TutorialGenerationSettings = tutorialGenerationSettings; Credits = items.GameplaySettings.StartingCredits; // A design named without a product is chosen by the generator's ChooseProduct. The stage outfits with no faction, // so every maker is reachable and the run's seed draws. @@ -38,7 +37,6 @@ public sealed class ScenarioStage public Galaxy Galaxy => Arena.Galaxy; public Zone Arena { get; } public string StartingHull { get; } - public TutorialGenerationSettings TutorialGenerationSettings { get; } // What the run starts with: the gameplay settings' starting credits unless the scenario sets another amount. public int Credits { get; set; } diff --git a/Assets/Scripts/ServerShared/Scenarios/AiFusedDiscipline.cs b/Assets/Scripts/ServerShared/Scenarios/AiFusedDiscipline.cs index beb4235da..bdfc153fd 100644 --- a/Assets/Scripts/ServerShared/Scenarios/AiFusedDiscipline.cs +++ b/Assets/Scripts/ServerShared/Scenarios/AiFusedDiscipline.cs @@ -13,7 +13,7 @@ public sealed class AiFusedDiscipline : Scenario public static readonly CultMath.float2 Hostile = float2(0, 700), Neutral = float2(500, 300); - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/Arcs.cs b/Assets/Scripts/ServerShared/Scenarios/Arcs.cs index 8846d006b..6da63b0e2 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Arcs.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Arcs.cs @@ -26,7 +26,7 @@ public sealed class Arcs : Scenario // holding every gun down. The guided launchers fire only on a lock, which that run cannot give them, so they carry the default three crates. public const int TurretAmmoCrates = 22, PlayerAmmoCrates = 42, PlayerMissileCrates = 3; - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/Belt.cs b/Assets/Scripts/ServerShared/Scenarios/Belt.cs index 50c815f6d..7058b993b 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Belt.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Belt.cs @@ -17,7 +17,7 @@ public sealed class Belt : Scenario public override uint Seed => 86; public override bool Ambient => false; - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/Crossing.cs b/Assets/Scripts/ServerShared/Scenarios/Crossing.cs index e77f50166..be5a1fe06 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Crossing.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Crossing.cs @@ -33,7 +33,7 @@ public sealed class Crossing : Scenario public const float ProjectorRange = 997f; public static readonly CultMath.float2 Waiting = Origin + float2(0, ProjectorRange * .8f); - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/DemoTerminus.cs b/Assets/Scripts/ServerShared/Scenarios/DemoTerminus.cs index f4dce7be7..7d8fbe330 100644 --- a/Assets/Scripts/ServerShared/Scenarios/DemoTerminus.cs +++ b/Assets/Scripts/ServerShared/Scenarios/DemoTerminus.cs @@ -2,10 +2,10 @@ using float2 = CultMath.float2; // The demo: one gate, one region and one boss, with a fixed cast. The Pirates are the protagonist's ostensible // employer, Zhestokost the antagonist whose home is the boss zone and the exit, Lucent Media and Aeronautics Unlimited -// the neutrals. A prelude galaxy of that cast; the player, who is not a Pirate, flies the base Longinus. +// the neutrals. A galaxy of that cast at half influence; the player, who is not a Pirate, flies the base Longinus. public sealed class DemoTerminus : Scenario { - public static readonly TutorialGenerationSettings Cast = new TutorialGenerationSettings + public static readonly GalaxyCast Cast = new GalaxyCast { ProtagonistFaction = "Pirates", AntagonistFaction = "Zhe", @@ -13,7 +13,8 @@ public sealed class DemoTerminus : Scenario NeutralFactions = new[] { "Aero" }, QuestFaction = null, ZoneCount = 64, - LinkDensity = .5f + LinkDensity = .5f, + InfluenceScale = .5f }; public override string Name => "Terminus (Demo)"; @@ -23,7 +24,7 @@ public sealed class DemoTerminus : Scenario public override Galaxy Generate(GalaxyStage stage) { - var galaxy = stage.Prelude(Cast); + var galaxy = stage.Cast(Cast); galaxy.PlaceGate(galaxy.ResolveFaction(Cast.AntagonistFaction)); return galaxy; } diff --git a/Assets/Scripts/ServerShared/Scenarios/DjinniShakedown.cs b/Assets/Scripts/ServerShared/Scenarios/DjinniShakedown.cs index 43d23d0b3..1b853571c 100644 --- a/Assets/Scripts/ServerShared/Scenarios/DjinniShakedown.cs +++ b/Assets/Scripts/ServerShared/Scenarios/DjinniShakedown.cs @@ -14,7 +14,7 @@ public sealed class DjinniShakedown : Scenario // Where the targets sit: the ballistic mount faces +z, so Ahead is inside its arc and Abeam outside it. public static readonly float2 Ahead = new float2(0, 400), Abeam = new float2(400, 0); - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/Duel.cs b/Assets/Scripts/ServerShared/Scenarios/Duel.cs index 67bca118d..508277643 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Duel.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Duel.cs @@ -10,7 +10,7 @@ public sealed class Duel : Scenario public override uint Seed => 104; public override bool Ambient => false; - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/FusedRounds.cs b/Assets/Scripts/ServerShared/Scenarios/FusedRounds.cs index 7498465c3..8f3fd024e 100644 --- a/Assets/Scripts/ServerShared/Scenarios/FusedRounds.cs +++ b/Assets/Scripts/ServerShared/Scenarios/FusedRounds.cs @@ -26,7 +26,7 @@ public sealed class FusedRounds : Scenario // The shooter is staged at this quality, so the damage its Cluster Cannon deals does not ride the item stream. public const float StagedQuality = .6f; - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/LauncherAngles.cs b/Assets/Scripts/ServerShared/Scenarios/LauncherAngles.cs index 61a798b1c..efd13e1aa 100644 --- a/Assets/Scripts/ServerShared/Scenarios/LauncherAngles.cs +++ b/Assets/Scripts/ServerShared/Scenarios/LauncherAngles.cs @@ -10,7 +10,7 @@ public sealed class LauncherAngles : Scenario public override uint Seed => 105; public override bool Ambient => false; - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/LockOn.cs b/Assets/Scripts/ServerShared/Scenarios/LockOn.cs index 4f8c4dfa9..8e14c3ff6 100644 --- a/Assets/Scripts/ServerShared/Scenarios/LockOn.cs +++ b/Assets/Scripts/ServerShared/Scenarios/LockOn.cs @@ -35,7 +35,7 @@ public sealed class LockOn : Scenario _quality = quality; } - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/LongHaul.cs b/Assets/Scripts/ServerShared/Scenarios/LongHaul.cs index 18e158247..692a5adbc 100644 --- a/Assets/Scripts/ServerShared/Scenarios/LongHaul.cs +++ b/Assets/Scripts/ServerShared/Scenarios/LongHaul.cs @@ -8,7 +8,7 @@ public sealed class LongHaul : Scenario "warp, quit and Continue keep items, tier and brand; death disables Continue."; public override uint Seed => 106; - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) => stage.Player(stage.Generated(stage.StartingHull), float2.zero); diff --git a/Assets/Scripts/ServerShared/Scenarios/MainGalaxy.cs b/Assets/Scripts/ServerShared/Scenarios/MainGalaxy.cs index 3e4482d3c..d8a484b7b 100644 --- a/Assets/Scripts/ServerShared/Scenarios/MainGalaxy.cs +++ b/Assets/Scripts/ServerShared/Scenarios/MainGalaxy.cs @@ -7,6 +7,8 @@ public sealed class MainGalaxy : Scenario public override string Id => "main-galaxy"; public override string Brief => "The full galaxy: factions drawn at random, bosses guarding the road to the exit."; + public override bool EntranceStation => false; + public override Galaxy Generate(GalaxyStage stage) => stage.Main(); public override void Stage(ScenarioStage stage) => diff --git a/Assets/Scripts/ServerShared/Scenarios/Pursuit.cs b/Assets/Scripts/ServerShared/Scenarios/Pursuit.cs index 2e490a2a6..7bde23745 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Pursuit.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Pursuit.cs @@ -22,7 +22,7 @@ public sealed class Pursuit : Scenario public override uint Seed => 111; public override bool Ambient => false; - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/RefusedRounds.cs b/Assets/Scripts/ServerShared/Scenarios/RefusedRounds.cs index 88cdd3fdb..384a7f286 100644 --- a/Assets/Scripts/ServerShared/Scenarios/RefusedRounds.cs +++ b/Assets/Scripts/ServerShared/Scenarios/RefusedRounds.cs @@ -15,7 +15,7 @@ public sealed class RefusedRounds : Scenario // The one target, ahead of the nose: inside every forward mount's arc. public static readonly CultMath.float2 Target = float2(0, 300); - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/Scenarios.cs b/Assets/Scripts/ServerShared/Scenarios/Scenarios.cs index 752b33e28..60d291985 100644 --- a/Assets/Scripts/ServerShared/Scenarios/Scenarios.cs +++ b/Assets/Scripts/ServerShared/Scenarios/Scenarios.cs @@ -5,7 +5,7 @@ public static class Scenarios { public static readonly Scenario[] Modes = { new DemoTerminus() }; - public static readonly Scenario[] Development = { new TutorialGalaxy(), new MainGalaxy() }; + public static readonly Scenario[] Development = { new MainGalaxy() }; public static readonly Scenario[] Tests = { diff --git a/Assets/Scripts/ServerShared/Scenarios/StarvedReactor.cs b/Assets/Scripts/ServerShared/Scenarios/StarvedReactor.cs index 2f3dff97b..ccef7e151 100644 --- a/Assets/Scripts/ServerShared/Scenarios/StarvedReactor.cs +++ b/Assets/Scripts/ServerShared/Scenarios/StarvedReactor.cs @@ -10,7 +10,7 @@ public sealed class StarvedReactor : Scenario public override uint Seed => 102; public override bool Ambient => false; - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Scenarios/TutorialGalaxy.cs b/Assets/Scripts/ServerShared/Scenarios/TutorialGalaxy.cs deleted file mode 100644 index 1ff521865..000000000 --- a/Assets/Scripts/ServerShared/Scenarios/TutorialGalaxy.cs +++ /dev/null @@ -1,17 +0,0 @@ -using float2 = CultMath.float2; - -// New Game as it has always been: a prelude galaxy, entered in the starting hull of the protagonist faction. -public sealed class TutorialGalaxy : Scenario -{ - public override string Name => "Tutorial Galaxy"; - public override string Id => "tutorial-galaxy"; - public override string Brief => "A small galaxy of fixed factions, entered in a ship of the protagonist faction."; - - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(); - - public override void Stage(ScenarioStage stage) - { - var protagonist = stage.Galaxy.ResolveFaction(stage.TutorialGenerationSettings.ProtagonistFaction); - stage.Player(stage.Generated(stage.StartingHull, protagonist), float2.zero); - } -} diff --git a/Assets/Scripts/ServerShared/Scenarios/TutorialGalaxy.cs.meta b/Assets/Scripts/ServerShared/Scenarios/TutorialGalaxy.cs.meta deleted file mode 100644 index 3f7c8777a..000000000 --- a/Assets/Scripts/ServerShared/Scenarios/TutorialGalaxy.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 94d688b37c5044dd9b67865c706d8918 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/Scenarios/WeaponFeel.cs b/Assets/Scripts/ServerShared/Scenarios/WeaponFeel.cs index 0817cfa80..f6f8eb337 100644 --- a/Assets/Scripts/ServerShared/Scenarios/WeaponFeel.cs +++ b/Assets/Scripts/ServerShared/Scenarios/WeaponFeel.cs @@ -14,7 +14,7 @@ public sealed class WeaponFeel : Scenario // The one target, ahead of the nose: inside every forward mount's arc. public static readonly CultMath.float2 Target = float2(0, 400); - public override Galaxy Generate(GalaxyStage stage) => stage.Prelude(DemoTerminus.Cast); + public override Galaxy Generate(GalaxyStage stage) => stage.Cast(DemoTerminus.Cast); public override void Stage(ScenarioStage stage) { diff --git a/Assets/Scripts/ServerShared/Settings.cs b/Assets/Scripts/ServerShared/Settings.cs index 1d83bd692..523e773f1 100644 --- a/Assets/Scripts/ServerShared/Settings.cs +++ b/Assets/Scripts/ServerShared/Settings.cs @@ -94,8 +94,10 @@ public class SectorGenerationSettings public int BossCount; } -[Serializable, MessagePackObject(keyAsPropertyName:true), JsonObject] -public class TutorialGenerationSettings +// The fixed cast of a galaxy a scenario generates through GalaxyStage.Cast: who plays which part, how big the galaxy is, +// and how far the factions' authored influence reaches (Galaxy.InfluenceOf). Held by the scenario that casts it; no +// asset or store holds one. +public class GalaxyCast { public string ProtagonistFaction; public string AntagonistFaction; @@ -106,6 +108,8 @@ public class TutorialGenerationSettings public int ZoneCount = 32; // Zones per resource province (Provinces.Partition): calibration, not a gate. public int ProvinceZones = Provinces.DefaultZonesPerProvince; + // Multiplies every faction's authored InfluenceDistance in this galaxy (rounding up); 1 leaves them as authored. + public float InfluenceScale = 1; } [Serializable, MessagePackObject(keyAsPropertyName:true), JsonObject] diff --git a/Assets/Scripts/ServerShared/ZoneGenerator.cs b/Assets/Scripts/ServerShared/ZoneGenerator.cs index 5b82a9a1a..42c4c15c0 100644 --- a/Assets/Scripts/ServerShared/ZoneGenerator.cs +++ b/Assets/Scripts/ServerShared/ZoneGenerator.cs @@ -43,7 +43,7 @@ public static class ZoneGenerator PlanetSettings planetSettings, Galaxy galaxy, GalaxyZone galaxyZone, - bool isTutorial = false, + bool entranceStation = false, bool ambient = true) { var pack = new ZonePack(); @@ -294,15 +294,15 @@ public static class ZoneGenerator var storyStations = galaxyZone.Locations.Where(story => story.Type == LocationType.Station).ToArray(); var stationCount = (int)(random.NextFloat() * (factionPresence + 1)) + storyStations.Length; - // Enemy count below is based on this pre-override value, so the tutorial entrance doesn't gain an enemy + // Enemy count below is based on this pre-override value, so the entrance station zone doesn't gain an enemy // just because its station got forced. var baseStationCount = stationCount; - // Operator ruling, 2026-09-25 (docs/locomotion-cut.md, "Tutorial station"): the entrance zone always - // gets a generated faction station with a docking bay, deterministically. Galaxy.cs halves influence and - // picks the lowest-influence unowned zone for Entrance, which otherwise rolls stationCount 0 on every - // seed. galaxy.Entrance is reference-identity, not a name comparison. - var isTutorialEntrance = isTutorial && galaxyZone == galaxy.Entrance; - if (isTutorialEntrance && stationCount < 1) stationCount = 1; + // Operator ruling, 2026-09-25 (docs/locomotion-cut.md): a scenario that declares an entrance station + // (Scenario.EntranceStation) gets a generated faction station with a docking bay in its entrance zone, + // deterministically. A cast galaxy's halved influence and its lowest-influence unowned Entrance otherwise roll + // stationCount 0 on every seed. galaxy.Entrance is reference-identity, not a name comparison. + var isEntranceStation = entranceStation && galaxyZone == galaxy.Entrance; + if (isEntranceStation && stationCount < 1) stationCount = 1; // A station's source is a well-bearing body alone on its ring whose rail clears every massive sibling's extent (the // sibling's support, or its Roche margin if more) and the largest reach of any station or turret hull: whatever hull // is built there, its Lagrange orbit then sits clear of any other body. @@ -318,7 +318,7 @@ public static class ZoneGenerator // (the rail, how far a body on it keeps others out, whether it is a station's own orbit rather than a base's) var sources = candidates.Skip(candidates.Length / 2).Take(stationCount) .Select(p => (orbit: orbitMap[p], extent: Extent(p), direct: false)).ToArray(); - if (isTutorialEntrance && candidates.Length == 0) + if (isEntranceStation && candidates.Length == 0) { // The entrance gets a station whatever its bodies: it orbits a root node beyond its ring group (or, for a body, its // whole family), never at a ring member's distance, and sits there, not at a Lagrange point. @@ -326,7 +326,7 @@ public static class ZoneGenerator var rootNode = roots.FirstOrDefault(p => p.Children.Count > 0) ?? (roots.Count > 1 ? roots.OrderByDescending(p => p.Mass).First() : null); if (rootNode == null) throw new InvalidOperationException( - "The tutorial entrance zone must always get a station, but it has no candidate orbit at all -- every planet in the zone is a parentless root."); + "The entrance station zone must always get a station, but it has no candidate orbit at all -- every planet in the zone is a parentless root."); var distance = rootNode.Empty ? (1 + GravityField.RingReach) * GravityField.Beta * rootNode.Children.Where(Massive).Min(c => c.Distance) : Extent(rootNode); @@ -445,9 +445,9 @@ public static class ZoneGenerator StationKinds.Choose(cache, nearestFaction, $"{seed}:station:{i}", itemManager.Log)); if (station == null) { - if (isTutorialEntrance) + if (isEntranceStation) throw new InvalidOperationException( - $"The tutorial entrance zone must always get a station, but {nearestFaction?.Name} has no station loadout to generate."); + $"The entrance station zone must always get a station, but {nearestFaction?.Name} has no station loadout to generate."); continue; } station.Orbit = cache.RefOf(lagrangeOrbit); diff --git a/Assets/Scripts/UI/MainMenu.cs b/Assets/Scripts/UI/MainMenu.cs index e7aba3357..f867b9e8c 100644 --- a/Assets/Scripts/UI/MainMenu.cs +++ b/Assets/Scripts/UI/MainMenu.cs @@ -120,9 +120,14 @@ public class MainMenu : MonoBehaviour Debug.Log("run store has no SavedGame; Continue disabled"); _nextMenu.panel.AddButton("Continue", saved == null ? (Action) null : () => { - try { RunSave.RequireDesigns(cache, saved); } + Galaxy galaxy; + try + { + RunSave.RequireDesigns(cache, saved); + galaxy = new Galaxy(cache, saved, Debug.Log); + } catch (InvalidOperationException error) { Refuse("Cannot continue this run", error.Message); return; } - ActionGameManager.CurrentGalaxy = new Galaxy(cache, saved, Debug.Log); + ActionGameManager.CurrentGalaxy = galaxy; EnterGame(); }); } @@ -246,11 +251,8 @@ public class MainMenu : MonoBehaviour var stage = new GalaxyStage( Settings.SectorGenerationSettings, Settings.SectorBackgroundSettings, - Settings.TutorialGenerationSettings, - Settings.TutorialBackgroundSettings, + Settings.CastBackgroundSettings, ActionGameManager.CultCache, - ActionGameManager.PlayerSettings, - ActionGameManager.GameDataDirectory.CreateSubdirectory("Narrative"), Debug.Log, state => generatorState = state); Task.Run(() => RunStart.Generate(scenario, stage)).ContinueWith(generation => diff --git a/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs b/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs index ccf3fae29..0d5c39c21 100644 --- a/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs +++ b/tests/Aetheria.Shared.Tests/ChildrenWithinReachTests.cs @@ -40,10 +40,9 @@ public sealed class ChildrenWithinReachTests : IClassFixture<ChildrenWithinReach cache.AddBackingStore(new GameCult.Caching.MessagePack.SingleFileMessagePackBackingStore(catalog), AetheriaStores.CatalogTypes); cache.AddBackingStore(new GameCult.Caching.MessagePack.SingleFileMessagePackBackingStore(Path.Combine(dir, "run.cc")), AetheriaStores.RunTypes); var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); - var galaxy = new Galaxy(authored.Read<TutorialGenerationSettings>("TutorialGenerationSettings"), - authored.Read<SectorBackgroundSettings>("TutorialBackgroundSettings"), - cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(dir, "Narrative")), _ => { }, null, seed); + var galaxy = new Galaxy(TestCasts.Wide, + authored.Read<SectorBackgroundSettings>("CastBackgroundSettings"), + cache, _ => { }, null, seed); var items = new ItemManager(1u, cache, new ProvenanceLedger(), authored.Read<GameplaySettings>("GameplaySettings"), _ => { }); var planetSettings = authored.Read<PlanetSettings>("PlanetSettings"); foreach (var galaxyZone in galaxy.Zones) @@ -51,7 +50,7 @@ public sealed class ChildrenWithinReachTests : IClassFixture<ChildrenWithinReach Settings = authored.Read<ZoneGenerationSettings>("ZoneSettings"); tune?.Invoke(Settings); var pack = ZoneGenerator.GenerateZone(items, Settings, planetSettings, galaxy, galaxyZone, - galaxyZone == galaxy.Entrance && galaxy.IsPrelude, false); + true, false); foreach (var belt in pack.Planets.Select(cache.Get).OfType<AsteroidBeltData>()) { Belts++; diff --git a/tests/Aetheria.Shared.Tests/ConsumableSupplyTests.cs b/tests/Aetheria.Shared.Tests/ConsumableSupplyTests.cs index 9878d95c6..083f7ac0f 100644 --- a/tests/Aetheria.Shared.Tests/ConsumableSupplyTests.cs +++ b/tests/Aetheria.Shared.Tests/ConsumableSupplyTests.cs @@ -139,6 +139,7 @@ public sealed class ConsumableSupplyTests : IDisposable _caches.Add(cache); var game = new SavedGame { + InfluenceScale = 1, Factions = new[] { maker }, Relationships = new[] { FactionRelationship.Neutral }, HomeZones = new Dictionary<int, int> { { 0, 0 } }, @@ -282,8 +283,8 @@ public sealed class ConsumableSupplyTests : IDisposable cache.Upsert(new FactionProductData { Name = "Overdrive by Maker", Design = new CultRecordRef<CraftedItemData>(overdrive.Key), Manufacturer = maker }); var authored = AuthoredSettings.Load(repo); - var galaxy = new Galaxy(authored.Read<TutorialGenerationSettings>("TutorialGenerationSettings"), - authored.Read<SectorBackgroundSettings>("TutorialBackgroundSettings"), cache, new PlayerSettings(), Directory.CreateDirectory(Path.Combine(_root, "Narrative")), _ => { }, null, 1); + var galaxy = new Galaxy(TestCasts.Wide, + authored.Read<SectorBackgroundSettings>("CastBackgroundSettings"), cache, _ => { }, null, 1); var items = new ItemManager(1u, cache, new ProvenanceLedger(), authored.Read<GameplaySettings>("GameplaySettings"), _ => { }); int stations = 0, ships = 0; diff --git a/tests/Aetheria.Shared.Tests/DemoTerminusTests.cs b/tests/Aetheria.Shared.Tests/DemoTerminusTests.cs index 54f46a57c..6298d30e8 100644 --- a/tests/Aetheria.Shared.Tests/DemoTerminusTests.cs +++ b/tests/Aetheria.Shared.Tests/DemoTerminusTests.cs @@ -8,7 +8,7 @@ using System.Linq; using CultMath; using Xunit; -// The demo scenario (aetheria-release, cut demo-galaxy): a prelude galaxy of a fixed cast whose antagonist's home is the +// The demo scenario (aetheria-release, cut demo-galaxy): a galaxy of a fixed cast whose antagonist's home is the // boss zone and the exit. The cast, the Pirates included, is in the shipped catalog. public sealed partial class RunStartTests { @@ -82,7 +82,7 @@ public sealed partial class RunStartTests Assert.DoesNotContain(_cache.GetAll<Faction>(), faction => faction.Name.StartsWith("Pirates", StringComparison.Ordinal)); var refusal = Assert.Throws<InvalidOperationException>(() => DemoGalaxy(1)); Assert.Contains("Pirates", refusal.Message); - Assert.Contains(nameof(TutorialGenerationSettings.ProtagonistFaction), refusal.Message); + Assert.Contains(nameof(GalaxyCast.ProtagonistFaction), refusal.Message); } // The operator's ruling is that the first release is a demo: the one scenario a release build lists says so by name. @@ -144,12 +144,12 @@ public sealed partial class RunStartTests string.Join(",", zone.AdjacentZones.Select(adjacent => Array.IndexOf(g.Zones, adjacent)).OrderBy(index => index)))); Galaxy Reference(uint seed, float density) { - var cast = new TutorialGenerationSettings + var cast = new GalaxyCast { ProtagonistFaction = "Pirates", AntagonistFaction = "Zhe", BufferFaction = "Luc", - NeutralFactions = new[] { "Aero" }, QuestFaction = null, ZoneCount = 64, LinkDensity = density + NeutralFactions = new[] { "Aero" }, QuestFaction = null, ZoneCount = 64, LinkDensity = density, InfluenceScale = .5f }; - return RunStart.Generate(new Scripted(false, _ => { }, seed, galaxy => galaxy.Prelude(cast)), Inputs()); + return RunStart.Generate(new Scripted(false, _ => { }, seed, stage => stage.Cast(cast)), Inputs()); } foreach (var seed in DemoSeeds) @@ -172,50 +172,42 @@ public sealed partial class RunStartTests // A name that resolves to nothing refuses the galaxy whichever cast field names it, and the refusal names the field. [Theory] - [InlineData(nameof(TutorialGenerationSettings.ProtagonistFaction))] - [InlineData(nameof(TutorialGenerationSettings.AntagonistFaction))] - [InlineData(nameof(TutorialGenerationSettings.BufferFaction))] - [InlineData(nameof(TutorialGenerationSettings.QuestFaction))] - [InlineData(nameof(TutorialGenerationSettings.NeutralFactions))] + [InlineData(nameof(GalaxyCast.ProtagonistFaction))] + [InlineData(nameof(GalaxyCast.AntagonistFaction))] + [InlineData(nameof(GalaxyCast.BufferFaction))] + [InlineData(nameof(GalaxyCast.QuestFaction))] + [InlineData(nameof(GalaxyCast.NeutralFactions))] public void AnUnresolvedCastNameRefusesTheGalaxyNamingItsField(string field) { - var cast = new TutorialGenerationSettings - { - ProtagonistFaction = _tutorialSettings.ProtagonistFaction, - AntagonistFaction = _tutorialSettings.AntagonistFaction, - BufferFaction = _tutorialSettings.BufferFaction, - QuestFaction = _tutorialSettings.QuestFaction, - NeutralFactions = _tutorialSettings.NeutralFactions, - ZoneCount = _tutorialSettings.ZoneCount, - LinkDensity = _tutorialSettings.LinkDensity - }; - typeof(TutorialGenerationSettings).GetField(field).SetValue(cast, field == nameof(cast.NeutralFactions) ? new[] { "Nonesuch" } : "Nonesuch"); - var scenario = new Scripted(false, _ => { }, generate: galaxy => galaxy.Prelude(cast)); + var cast = TestCasts.Wide; + typeof(GalaxyCast).GetField(field).SetValue(cast, field == nameof(cast.NeutralFactions) ? new[] { "Nonesuch" } : "Nonesuch"); + var scenario = new Scripted(false, _ => { }, generate: stage => stage.Cast(cast)); var refusal = Assert.Throws<InvalidOperationException>(() => RunStart.Generate(scenario, Inputs())); Assert.Contains(field, refusal.Message); } - // What a release build lists under New Game is the demo alone; the tutorial and the main galaxy are listed only in + // What a release build lists under New Game is the demo alone; the main galaxy is listed only in // editor and development builds (MainMenu.ShowScenarios), beside the test arenas. [Fact] public void ReleaseBuildsListOnlyTheDemo() { Assert.Equal(new[] { typeof(DemoTerminus) }, Scenarios.Modes.Select(scenario => scenario.GetType())); - Assert.Equal(new[] { typeof(TutorialGalaxy), typeof(MainGalaxy) }, Scenarios.Development.Select(scenario => scenario.GetType())); + Assert.Equal(new[] { typeof(MainGalaxy) }, Scenarios.Development.Select(scenario => scenario.GetType())); } - // The tutorial is the galaxy it was before the demo: its cast, homes, entrance and ownership at a fixed seed, with - // no exit and no boss zone. + // The wide test cast at half influence is the galaxy it was before the prelude was retired: its cast, homes, entrance + // and ownership at a fixed seed, with no exit and no boss zone. Homes, entrance and owners depend on InfluenceOf, so + // an InfluenceScale of 1 or a lost halving fails it. [Fact] - public void TutorialGalaxy_unchanged() + public void CastGalaxyAtHalfInfluenceIsUnchanged() { - var galaxy = RunStart.Generate(new TutorialGalaxy(), Inputs(() => GalaxySeed)); - Assert.Equal(TutorialSeed1, TutorialShape(galaxy)); - Assert.True(galaxy.Exit == null, "the tutorial has no exit"); - Assert.True(galaxy.BossZones.Count == 0, $"the tutorial has {galaxy.BossZones.Count} boss zones"); + var galaxy = RunStart.Generate(new Scripted(false, _ => { }, generate: stage => stage.Cast(TestCasts.Wide)), Inputs(() => GalaxySeed)); + Assert.Equal(WideCastSeed1, CastShape(galaxy)); + Assert.True(galaxy.Exit == null, "a cast galaxy has no exit until its scenario places the gate"); + Assert.True(galaxy.BossZones.Count == 0, $"the cast galaxy has {galaxy.BossZones.Count} boss zones"); } - private static string TutorialShape(Galaxy g) => + private static string CastShape(Galaxy g) => string.Join(",", g.Factions.Select(f => f.Name)) + " | homes " + string.Join(",", g.Factions.Select(f => g.HomeZones.TryGetValue(f, out var z) ? Array.IndexOf(g.Zones, z) : -2)) + " | entrance " + Array.IndexOf(g.Zones, g.Entrance) + @@ -223,6 +215,6 @@ public sealed partial class RunStartTests " | owners " + string.Join(",", g.Zones.Select(z => z.Owner == null ? "-" : z.Owner.ShortName)); // Measured at seed 1 under CultMath 0.3.0 (cultmath-unity-v0.3.0); the noise kernel changed there, which re-rolled the galaxy. - private const string TutorialSeed1 = + private const string WideCastSeed1 = "Miss Terri’s Sugariffic Snack Company,Zhestokost,Lucent Media,Adrasteia,Aeronautics Unlimited,Finch Cybernetics | homes 3,44,40,19,0,30 | entrance 12 | zones 64 | owners AU,AU,Finch,Miss Terri's,Lucent,Zhestokost,-,Lucent,AU,AU,Lucent,Adrasteia,-,Finch,Zhestokost,-,Adrasteia,-,AU,Adrasteia,AU,Zhestokost,Miss Terri's,-,AU,Finch,Miss Terri's,-,Zhestokost,-,Finch,-,-,AU,-,-,-,-,Miss Terri's,AU,Lucent,-,Finch,-,Zhestokost,AU,-,Zhestokost,Adrasteia,Adrasteia,AU,Miss Terri's,Finch,AU,Finch,-,Lucent,Zhestokost,-,AU,Miss Terri's,Zhestokost,-,Lucent"; } diff --git a/tests/Aetheria.Shared.Tests/FireControlCut6cTests.cs b/tests/Aetheria.Shared.Tests/FireControlCut6cTests.cs index 991af3b44..7ec6abaf5 100644 --- a/tests/Aetheria.Shared.Tests/FireControlCut6cTests.cs +++ b/tests/Aetheria.Shared.Tests/FireControlCut6cTests.cs @@ -234,6 +234,7 @@ public sealed class FireControlCut6cTests : IDisposable // Targeting Maker, so IsAvailable rejects Targeting Maker's products by allegiance. var game = new SavedGame { + InfluenceScale = 1, Factions = new[] { maker }, Relationships = new[] { FactionRelationship.Neutral }, HomeZones = new Dictionary<int, int> { { 0, 0 } }, diff --git a/tests/Aetheria.Shared.Tests/LoadoutTests.cs b/tests/Aetheria.Shared.Tests/LoadoutTests.cs index 3697d7345..4a114637e 100644 --- a/tests/Aetheria.Shared.Tests/LoadoutTests.cs +++ b/tests/Aetheria.Shared.Tests/LoadoutTests.cs @@ -494,6 +494,7 @@ public sealed class LoadoutTests : IDisposable var game = new SavedGame { + InfluenceScale = 1, Factions = Array.Empty<CultRecordRef<Faction>>(), Relationships = Array.Empty<FactionRelationship>(), HomeZones = new Dictionary<int, int>(), diff --git a/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs b/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs index 95dbacd1f..5051a3b8d 100644 --- a/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs +++ b/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs @@ -830,14 +830,14 @@ public sealed partial class MiningCut3Tests : IDisposable Galaxy galaxy; try { - galaxy = new Galaxy(RestoredHullsTests.TutorialGalaxySettings(), RestoredHullsTests.TutorialBackgroundSettings(), - cache, new PlayerSettings(), new DirectoryInfo(dir), _ => { }, null, seed); + galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, + cache, _ => { }, null, seed); } catch (Exception) { continue; } // Galaxy's own seed-dependent flakiness (RestoredHullsTests) var items = new ItemManager(1u, cache, new ProvenanceLedger(), GameSettings(), _ => { }); foreach (var zone in galaxy.Zones.Take(4)) { - var pack = ZoneGenerator.GenerateZone(items, RestoredHullsTests.TutorialZoneSettings(), RestoredHullsTests.AuthoredPlanetSettings(), galaxy, zone, isTutorial: zone == galaxy.Entrance); + var pack = ZoneGenerator.GenerateZone(items, RestoredHullsTests.TutorialZoneSettings(), RestoredHullsTests.AuthoredPlanetSettings(), galaxy, zone, entranceStation: zone == galaxy.Entrance); foreach (var body in pack.Planets) { if (!(cache.Get(body) is AsteroidBeltData belt)) continue; @@ -874,13 +874,13 @@ public sealed partial class MiningCut3Tests : IDisposable Galaxy galaxy; try { - galaxy = new Galaxy(RestoredHullsTests.TutorialGalaxySettings(), RestoredHullsTests.TutorialBackgroundSettings(), - cache, new PlayerSettings(), new DirectoryInfo(dir), _ => { }, null, seed); + galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, + cache, _ => { }, null, seed); } catch (Exception) { return null; } var items = new ItemManager(1u, cache, new ProvenanceLedger(), GameSettings(), _ => { }); return galaxy.Zones.Take(6).SelectMany(zone => - ZoneGenerator.GenerateZone(items, RestoredHullsTests.TutorialZoneSettings(), RestoredHullsTests.AuthoredPlanetSettings(), galaxy, zone, isTutorial: zone == galaxy.Entrance) + ZoneGenerator.GenerateZone(items, RestoredHullsTests.TutorialZoneSettings(), RestoredHullsTests.AuthoredPlanetSettings(), galaxy, zone, entranceStation: zone == galaxy.Entrance) .Planets.Select(body => cache.Get(body)).OfType<AsteroidBeltData>().Select(belt => cache.Get(belt.Kind).Name)) .ToArray(); } diff --git a/tests/Aetheria.Shared.Tests/MiningCut5bTests.cs b/tests/Aetheria.Shared.Tests/MiningCut5bTests.cs index 9ad960a77..5165a0f1e 100644 --- a/tests/Aetheria.Shared.Tests/MiningCut5bTests.cs +++ b/tests/Aetheria.Shared.Tests/MiningCut5bTests.cs @@ -46,6 +46,7 @@ public sealed class MiningCut5bTests : IDisposable MiningCut5aTests.Stock(scene, kind, (ore, 1f)); var game = new SavedGame { + InfluenceScale = 1, Seed = 5, Factions = new CultRecordRef<Faction>[0], Relationships = new FactionRelationship[0], HomeZones = new Dictionary<int, int>(), BossZones = new Dictionary<int, int>(), DiscoveredZones = new[] { 0 }, ActionBarBindings = new SavedActionBarBinding[0], Entrance = 0, Exit = -1 @@ -222,6 +223,7 @@ public sealed class MiningCut5bTests : IDisposable { var game = new SavedGame { + InfluenceScale = 1, Factions = new CultRecordRef<Faction>[0], Relationships = new FactionRelationship[0], HomeZones = new Dictionary<int, int>(), BossZones = new Dictionary<int, int>(), DiscoveredZones = new[] { 0 }, ActionBarBindings = new SavedActionBarBinding[0], Exit = -1 diff --git a/tests/Aetheria.Shared.Tests/OrbitsFromFieldTests.cs b/tests/Aetheria.Shared.Tests/OrbitsFromFieldTests.cs index 7a399587f..ffe29bbc1 100644 --- a/tests/Aetheria.Shared.Tests/OrbitsFromFieldTests.cs +++ b/tests/Aetheria.Shared.Tests/OrbitsFromFieldTests.cs @@ -251,13 +251,12 @@ public sealed class OrbitsFromFieldTests : IDisposable cache.AddBackingStore(new GameCult.Caching.MessagePack.SingleFileMessagePackBackingStore(catalog), AetheriaStores.CatalogTypes); cache.AddBackingStore(new GameCult.Caching.MessagePack.SingleFileMessagePackBackingStore(Path.Combine(dir, "run.cc")), AetheriaStores.RunTypes); var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); - var tutorial = authored.Read<TutorialGenerationSettings>("TutorialGenerationSettings"); - var galaxy = new Galaxy(tutorial, authored.Read<SectorBackgroundSettings>("TutorialBackgroundSettings"), - cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(dir, "Narrative")), _ => { }, null, seed); + var tutorial = TestCasts.Wide; + var galaxy = new Galaxy(tutorial, authored.Read<SectorBackgroundSettings>("CastBackgroundSettings"), + cache, _ => { }, null, seed); var items = new ItemManager(1u, cache, new ProvenanceLedger(), authored.Read<GameplaySettings>("GameplaySettings"), _ => { }); var pack = ZoneGenerator.GenerateZone(items, authored.Read<ZoneGenerationSettings>("ZoneSettings"), authored.Read<PlanetSettings>("PlanetSettings"), galaxy, galaxy.Entrance, - galaxy.IsPrelude, false); + true, false); var zone = new Zone(items, authored.Read<PlanetSettings>("PlanetSettings"), pack, galaxy.Entrance, galaxy); var hosting = zone.Planets.Values.Select(body => body.Orbit.Key).ToHashSet(); diff --git a/tests/Aetheria.Shared.Tests/OreGeographyTests.cs b/tests/Aetheria.Shared.Tests/OreGeographyTests.cs index 20c1e9043..764ec66c0 100644 --- a/tests/Aetheria.Shared.Tests/OreGeographyTests.cs +++ b/tests/Aetheria.Shared.Tests/OreGeographyTests.cs @@ -128,14 +128,14 @@ public sealed class OreGeographyTests : IDisposable return reached; } - private static Galaxy Build(CultCache cache, bool prelude, uint seed, TutorialGenerationSettings cast = null) => prelude - ? new Galaxy(cast ?? Authored.Read<TutorialGenerationSettings>("TutorialGenerationSettings"), Authored.Read<SectorBackgroundSettings>("TutorialBackgroundSettings"), - cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed) + private static Galaxy Build(CultCache cache, bool prelude, uint seed, GalaxyCast cast = null) => prelude + ? new Galaxy(cast ?? TestCasts.Wide, Authored.Read<SectorBackgroundSettings>("CastBackgroundSettings"), + cache, _ => { }, null, seed) : new Galaxy(Authored.Read<SectorGenerationSettings>("SectorGenerationSettings"), Authored.Read<SectorBackgroundSettings>("SectorBackgroundSettings"), cache, _ => { }, null, seed); // Galaxy refuses some seeds (RestoredHullsTests calls it seed-dependent flakiness); those are skipped. - private static Galaxy TryBuild(CultCache cache, bool prelude, uint seed, TutorialGenerationSettings cast = null) + private static Galaxy TryBuild(CultCache cache, bool prelude, uint seed, GalaxyCast cast = null) { try { return Build(cache, prelude, seed, cast); } catch (Exception) { return null; } @@ -151,14 +151,14 @@ public sealed class OreGeographyTests : IDisposable Enumerable.Range(1, (int) last).Select(seed => SharedGalaxy(prelude, (uint) seed)).Where(galaxy => galaxy != null); // The demo's cast: the same fixed cast, with the province size chosen. - private static TutorialGenerationSettings Cast(int provinceZones) + private static GalaxyCast Cast(int provinceZones) { var cast = DemoTerminus.Cast; - return new TutorialGenerationSettings + return new GalaxyCast { ProtagonistFaction = cast.ProtagonistFaction, AntagonistFaction = cast.AntagonistFaction, BufferFaction = cast.BufferFaction, NeutralFactions = cast.NeutralFactions, QuestFaction = cast.QuestFaction, ZoneCount = cast.ZoneCount, LinkDensity = cast.LinkDensity, - ProvinceZones = provinceZones + ProvinceZones = provinceZones, InfluenceScale = cast.InfluenceScale }; } @@ -929,7 +929,7 @@ public sealed class OreGeographyTests : IDisposable { foreach (var zone in galaxy.Zones.Take(zones)) { - var pack = ZoneGenerator.GenerateZone(items, RestoredHullsTests.TutorialZoneSettings(), RestoredHullsTests.AuthoredPlanetSettings(), galaxy, zone, isTutorial: zone == galaxy.Entrance); + var pack = ZoneGenerator.GenerateZone(items, RestoredHullsTests.TutorialZoneSettings(), RestoredHullsTests.AuthoredPlanetSettings(), galaxy, zone, entranceStation: zone == galaxy.Entrance); foreach (var belt in pack.Planets.Select(body => cache.Get(body)).OfType<AsteroidBeltData>()) yield return (belt, zone, pack); } diff --git a/tests/Aetheria.Shared.Tests/PlaceNamesTests.cs b/tests/Aetheria.Shared.Tests/PlaceNamesTests.cs index 9490d049b..0d53a1706 100644 --- a/tests/Aetheria.Shared.Tests/PlaceNamesTests.cs +++ b/tests/Aetheria.Shared.Tests/PlaceNamesTests.cs @@ -30,8 +30,8 @@ public sealed class PlaceNamesTests : IDisposable } private static Galaxy Build(CultCache cache, bool prelude, uint seed) => prelude - ? new Galaxy(Authored.Read<TutorialGenerationSettings>("TutorialGenerationSettings"), Authored.Read<SectorBackgroundSettings>("TutorialBackgroundSettings"), - cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed) + ? new Galaxy(TestCasts.Wide, Authored.Read<SectorBackgroundSettings>("CastBackgroundSettings"), + cache, _ => { }, null, seed) : new Galaxy(Authored.Read<SectorGenerationSettings>("SectorGenerationSettings"), Authored.Read<SectorBackgroundSettings>("SectorBackgroundSettings"), cache, _ => { }, null, seed); diff --git a/tests/Aetheria.Shared.Tests/ProductChoiceTests.cs b/tests/Aetheria.Shared.Tests/ProductChoiceTests.cs index 76ad7c2f8..768bc8a14 100644 --- a/tests/Aetheria.Shared.Tests/ProductChoiceTests.cs +++ b/tests/Aetheria.Shared.Tests/ProductChoiceTests.cs @@ -128,6 +128,7 @@ public sealed class ProductChoiceTests : IDisposable var outZ = cache.GetByName<Faction>("OutZ"); var game = new SavedGame { + InfluenceScale = 1, // Alpha's headquarters are in zone 0 and Zeta's in zone 1. Factions = new[] { cache.RefOf(outA), cache.RefOf(outZ), cache.RefOf(cache.GetByName<Faction>("Alpha")), cache.RefOf(cache.GetByName<Faction>("Zeta")) }, Relationships = new[] { FactionRelationship.Neutral, FactionRelationship.Neutral, FactionRelationship.Neutral, FactionRelationship.Neutral }, diff --git a/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs b/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs index f5d3e8498..f33e11a46 100644 --- a/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs +++ b/tests/Aetheria.Shared.Tests/RestoredHullsTests.cs @@ -63,8 +63,8 @@ public sealed class RestoredHullsTests internal static CultCache OpenCatalog() => OpenReadOnlyRealCatalog(TestCatalog.Repo); internal static CultCache OpenCatalogWithFixtures() => OpenReadOnlyRealCatalog(TestCatalog.RepoWithFixtures); - // Shared tutorial-galaxy construction settings (Assets/Resources/Settings.asset's own values), factored out - // so every test that needs a real tutorial Galaxy -- not just EntranceZoneAlwaysGetsADockedStationAcrossSeeds + // Shared cast-galaxy construction settings (Assets/Resources/Settings.asset's own values), factored out + // so every test that needs a real cast Galaxy -- not just EntranceZoneAlwaysGetsADockedStationAcrossSeeds // -- builds it the same way instead of re-inlining the same ~20 fields. internal static PlanetSettings AuthoredPlanetSettings() => AuthoredSettings.Load(RunStartTests.FindRepoRoot()).Read<PlanetSettings>("PlanetSettings"); @@ -88,18 +88,6 @@ public sealed class RestoredHullsTests NameData = new string[0], }; - internal static TutorialGenerationSettings TutorialGalaxySettings() => new TutorialGenerationSettings - { - ProtagonistFaction = "Miss", AntagonistFaction = "Zhe", BufferFaction = "Luc", - NeutralFactions = new[] { "Aero", "Finch" }, QuestFaction = "Adras", LinkDensity = .5f, ZoneCount = 64, - }; - - internal static SectorBackgroundSettings TutorialBackgroundSettings() => new SectorBackgroundSettings - { - NoiseAmplitude = 1, NoiseOffset = .3f, NoiseGain = .7f, NoiseLacunarity = 2, NoiseFrequency = .1f, - NoisePosition = 536.5106f, CloudExponent = 10, CloudAmplitude = .01f, - }; - // A station's orbit is a copy of its source planet's own (Parent, Distance) (ZoneGenerator.CreateLagrangeOrbit), // so it always matches that one planet. It matches MORE than one planet only when the source planet shares its // distance with a sibling under the same parent -- exactly what ZoneGenerator's potentialLagrangePoints filter @@ -159,10 +147,10 @@ public sealed class RestoredHullsTests var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); for (var seed = 1u; seed <= 64u; seed++) { - var galaxy = new Galaxy(TutorialGalaxySettings(), TutorialBackgroundSettings(), cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed); + var galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, cache, _ => { }, null, seed); foreach (var zone in galaxy.Zones.Where(z => !ReferenceEquals(z, galaxy.Entrance))) { - var orbits = ParentedPlanetOrbits(cache, ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, zone, isTutorial: false, ambient: false)); + var orbits = ParentedPlanetOrbits(cache, ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, zone, entranceStation: false, ambient: false)); if (orbits.Length > 0 && !HasGenuineLagrangeCandidate(orbits)) return (seed, zone.Name); } } @@ -380,8 +368,8 @@ public sealed class RestoredHullsTests public void EntranceZoneAlwaysGetsADockedStationAcrossSeeds() { var zoneSettings = TutorialZoneSettings(); - var tutorialSettings = TutorialGalaxySettings(); - var background = TutorialBackgroundSettings(); + var tutorialSettings = TestCasts.Wide; + var background = TestCasts.Background; var gameData = TestCatalog.Repo; var sawGenuineLagrangeOrbit = false; for (uint seed = 1; seed <= 25; seed++) @@ -390,10 +378,10 @@ public sealed class RestoredHullsTests try { using var cache = OpenReadOnlyRealCatalogWithScratchRun(gameData, scratchRun); - var galaxy = new Galaxy(tutorialSettings, background, cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed); + var galaxy = new Galaxy(tutorialSettings, background, cache, _ => { }, null, seed); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, entranceStation: true); var dockedStation = pack.Entities.OfType<OrbitalEntityPack>() .FirstOrDefault(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station && e.DockingBays.Length > 0); @@ -413,15 +401,15 @@ public sealed class RestoredHullsTests // Cut 1 fix batch 3 (F6, N1): a per-seed strengthening of the "across seeds" test above. That test only // requires a genuine Lagrange orbit at least once in 25 seeds; it says nothing about a seed where a genuine // candidate DID exist but the station landed on the widened fallback anyway (which the widening condition's - // own isTutorialEntrance-and-empty-candidates guard should make impossible). This pins the normal case + // own entranceStationEntrance-and-empty-candidates guard should make impossible). This pins the normal case // directly, seed by seed: whenever the entrance zone actually has a genuine (non-rosette) Lagrange candidate, // its station must be seated on one. [Fact] public void EntranceStationSitsOnAGenuineLagrangeOrbitWheneverOneExists() { var zoneSettings = TutorialZoneSettings(); - var tutorialSettings = TutorialGalaxySettings(); - var background = TutorialBackgroundSettings(); + var tutorialSettings = TestCasts.Wide; + var background = TestCasts.Background; var gameData = TestCatalog.Repo; var sawGenuineCandidate = false; for (uint seed = 1; seed <= 25; seed++) @@ -430,10 +418,10 @@ public sealed class RestoredHullsTests try { using var cache = OpenReadOnlyRealCatalogWithScratchRun(gameData, scratchRun); - var galaxy = new Galaxy(tutorialSettings, background, cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed); + var galaxy = new Galaxy(tutorialSettings, background, cache, _ => { }, null, seed); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, entranceStation: true); var planetOrbits = pack.Planets.Select(p => cache.Get(cache.Get(p).Orbit)).Where(o => o.Parent.IsSet()).ToArray(); var hasGenuineCandidate = planetOrbits.Any(o => planetOrbits.Count(c => c.Parent.Key.Equals(o.Parent.Key) && abs(c.Distance - o.Distance) < .1f) == 1); @@ -468,7 +456,7 @@ public sealed class RestoredHullsTests try { using var cache = OpenReadOnlyRealCatalogWithScratchRun(gameData, scratchRun); - var galaxy = new Galaxy(TutorialGalaxySettings(), TutorialBackgroundSettings(), cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed: 1u); + var galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, cache, _ => { }, null, seed: 1u); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); var zoneSettings = TutorialZoneSettings(); @@ -478,7 +466,7 @@ public sealed class RestoredHullsTests zoneSettings.SubZoneCount = new ExponentialLerp { Exponent = 1, Minimum = 0, Maximum = 0 }; Assert.Throws<InvalidOperationException>(() => - ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true)); + ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, entranceStation: true)); } finally { @@ -503,7 +491,7 @@ public sealed class RestoredHullsTests try { using var cache = OpenReadOnlyRealCatalogWithScratchRun(gameData, scratchRun); - var galaxy = new Galaxy(TutorialGalaxySettings(), TutorialBackgroundSettings(), cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed: 1u); + var galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, cache, _ => { }, null, seed: 1u); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); var zoneSettings = TutorialZoneSettings(); @@ -512,7 +500,7 @@ public sealed class RestoredHullsTests zoneSettings.SatelliteCreationProbability = 0; zoneSettings.BinaryCreationProbability = 0; - var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, entranceStation: true); var roots = pack.Planets.Select(p => cache.Get(cache.Get(p).Orbit)).Count(o => !o.Parent.IsSet()); Assert.True(roots > 1, $"this fixture no longer produces a multi-root entrance (only {roots} root); it no longer tests the fragmented-topology case."); @@ -542,8 +530,8 @@ public sealed class RestoredHullsTests public void EntranceStationPhaseDiffersFromEveryPlanetAtItsOwnDistanceAcrossSeeds() { var zoneSettings = TutorialZoneSettings(); - var tutorialSettings = TutorialGalaxySettings(); - var background = TutorialBackgroundSettings(); + var tutorialSettings = TestCasts.Wide; + var background = TestCasts.Background; var gameData = TestCatalog.Repo; var checkedAny = false; @@ -553,10 +541,10 @@ public sealed class RestoredHullsTests try { using var cache = OpenReadOnlyRealCatalogWithScratchRun(gameData, scratchRun); - var galaxy = new Galaxy(tutorialSettings, background, cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed); + var galaxy = new Galaxy(tutorialSettings, background, cache, _ => { }, null, seed); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, zoneSettings, AuthoredPlanetSettings(), galaxy, galaxy.Entrance, entranceStation: true); var dockedStation = pack.Entities.OfType<OrbitalEntityPack>() .FirstOrDefault(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station && e.DockingBays.Length > 0); @@ -688,7 +676,7 @@ public sealed class RestoredHullsTests // real zone from a real galaxy (e.g. one already known to have no Lagrange candidate) and make it the Entrance. private static Galaxy BuildGalaxyWithForcedEntrance(CultCache cache, uint seed, string entranceZoneName) { - var galaxy = new Galaxy(TutorialGalaxySettings(), TutorialBackgroundSettings(), cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed); + var galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, cache, _ => { }, null, seed); var target = galaxy.Zones.Single(z => z.Name == entranceZoneName); var factions = galaxy.Factions; @@ -715,7 +703,7 @@ public sealed class RestoredHullsTests Relationships = factions.Select(f => galaxy.FactionRelationships[f]).ToArray(), DiscoveredZones = Array.Empty<int>(), Background = galaxy.Background, - IsTutorial = true, + InfluenceScale = .5f, }; return new Galaxy(cache, game, _ => { }); } @@ -750,7 +738,7 @@ public sealed class RestoredHullsTests var galaxy = BuildGalaxyWithForcedEntrance(cache, seed, zoneName); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, galaxy.Entrance, entranceStation: true); var station = pack.Entities.OfType<OrbitalEntityPack>() .FirstOrDefault(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station && e.DockingBays.Length > 0); @@ -799,24 +787,24 @@ public sealed class RestoredHullsTests try { using var cache = OpenReadOnlyRealCatalogWithScratchRun(gameData, scratchRun); - var galaxy = new Galaxy(TutorialGalaxySettings(), TutorialBackgroundSettings(), cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed: 1u); + var galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, cache, _ => { }, null, seed: 1u); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); - int StationCount(GalaxyZone zone, bool isTutorial) => - ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, zone, isTutorial) + int StationCount(GalaxyZone zone, bool entranceStation) => + ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, zone, entranceStation) .Entities.OfType<OrbitalEntityPack>() .Count(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station); // (a) A non-entrance tutorial zone that naturally rolls zero stations keeps that roll under - // isTutorial: true -- the floor must not leak past the galaxy.Entrance reference check. - // The zone is chosen by its natural roll: zero stations without the tutorial floor (isTutorial: false). - var otherZone = galaxy.Zones.First(z => !ReferenceEquals(z, galaxy.Entrance) && StationCount(z, isTutorial: false) == 0); + // entranceStation: true -- the floor must not leak past the galaxy.Entrance reference check. + // The zone is chosen by its natural roll: zero stations without the tutorial floor (entranceStation: false). + var otherZone = galaxy.Zones.First(z => !ReferenceEquals(z, galaxy.Entrance) && StationCount(z, entranceStation: false) == 0); Assert.NotSame(galaxy.Entrance, otherZone); - Assert.Equal(0, StationCount(otherZone, isTutorial: true)); + Assert.Equal(0, StationCount(otherZone, entranceStation: true)); - // (b) The entrance zone itself, generated for a non-tutorial game (isTutorial: false), keeps its - // natural roll too -- the floor must not leak past the isTutorial flag either. - Assert.Equal(0, StationCount(galaxy.Entrance, isTutorial: false)); + // (b) The entrance zone itself, generated for a non-tutorial game (entranceStation: false), keeps its + // natural roll too -- the floor must not leak past the entranceStation flag either. + Assert.Equal(0, StationCount(galaxy.Entrance, entranceStation: false)); } finally { @@ -827,7 +815,7 @@ public sealed class RestoredHullsTests // Cut 1 fix batch 2 (Soul's finding #2, baseStationCount): the entrance override raises stationCount (the // orbit-selection floor) but must not also raise the enemyCount roll, which is keyed to baseStationCount // (the pre-override value) precisely so the forced station doesn't buy the zone an extra enemy. Seed 1's - // entrance zone rolls baseStationCount 0 (confirmed via the isTutorial: false StationCount == 0 above) and + // entrance zone rolls baseStationCount 0 (confirmed via the entranceStation: false StationCount == 0 above) and // the override raises stationCount to 1; this pins the resulting ship count at the value baseStationCount // produces. It must fail if the enemy-count formula is changed to add stationCount instead (it would add a // ship instead of zero). @@ -839,10 +827,10 @@ public sealed class RestoredHullsTests try { using var cache = OpenReadOnlyRealCatalogWithScratchRun(gameData, scratchRun); - var galaxy = new Galaxy(TutorialGalaxySettings(), TutorialBackgroundSettings(), cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed: 1u); + var galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, cache, _ => { }, null, seed: 1u); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, galaxy.Entrance, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, galaxy.Entrance, entranceStation: true); var stationCount = pack.Entities.OfType<OrbitalEntityPack>().Count(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station); // Soul's finding (this cut's fix batch 3): pack.Entities.OfType<ShipPack>().Count() also counts the // zone's neutral wanderers (ZoneGenerator.cs's own EligibleWandererFactions spawn, keyed to @@ -869,12 +857,12 @@ public sealed class RestoredHullsTests // here by boosting one faction's presence there (HomeZone distance 0, InfluenceDistance 50, so the roll's // floor(rand * (factionPresence+1)) is overwhelmingly likely nonzero) via the same public SavedGame round // trip BuildGalaxyWithForcedEntrance uses, not by touching ZoneGenerator's private roll. Verified directly: - // temporarily widening every zone (dropping ZoneGenerator's isTutorialEntrance guard) turns this fixture's + // temporarily widening every zone (dropping ZoneGenerator's entranceStationEntrance guard) turns this fixture's // station count from 0 into 2, so a natural nonzero roll really is hiding behind the empty candidate set. // Must fail if that guard is dropped for real. private static Galaxy BuildGalaxyWithBoostedPresence(CultCache cache, uint seed, string zoneName) { - var galaxy = new Galaxy(TutorialGalaxySettings(), TutorialBackgroundSettings(), cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed); + var galaxy = new Galaxy(TestCasts.Wide, TestCasts.Background, cache, _ => { }, null, seed); var target = galaxy.Zones.Single(z => z.Name == zoneName); var factions = galaxy.Factions; @@ -906,7 +894,7 @@ public sealed class RestoredHullsTests Relationships = factions.Select(f => galaxy.FactionRelationships[f]).ToArray(), DiscoveredZones = Array.Empty<int>(), Background = galaxy.Background, - IsTutorial = true, + InfluenceScale = .5f, }; return new Galaxy(cache, game, _ => { }); } @@ -925,7 +913,7 @@ public sealed class RestoredHullsTests Assert.NotSame(galaxy.Entrance, zone); var items = new ItemManager(1u, cache, new ProvenanceLedger(), Settings(), _ => { }); - var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, zone, isTutorial: true); + var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), AuthoredPlanetSettings(), galaxy, zone, entranceStation: true); // Confirms this fixture still has no genuine (non-rosette) Lagrange candidate -- a regression here // would mean the fixture no longer probes what this test claims to probe. diff --git a/tests/Aetheria.Shared.Tests/RunGoalTests.cs b/tests/Aetheria.Shared.Tests/RunGoalTests.cs index c01927ecb..6d4646284 100644 --- a/tests/Aetheria.Shared.Tests/RunGoalTests.cs +++ b/tests/Aetheria.Shared.Tests/RunGoalTests.cs @@ -21,7 +21,7 @@ public sealed partial class RunStartTests private ZonePack BossZonePack(Galaxy galaxy, ItemManager items, GalaxyZone zone, bool ambient = true, uint seed = 7) { items.Random = new CultMath.Random(seed); - return ZoneGenerator.GenerateZone(items, _zoneSettings, _planetSettings, galaxy, zone, galaxy.IsPrelude, ambient); + return ZoneGenerator.GenerateZone(items, _zoneSettings, _planetSettings, galaxy, zone, entranceStation: zone == galaxy.Entrance, ambient); } private Zone ZoneOf(Galaxy galaxy, GalaxyZone zone) => diff --git a/tests/Aetheria.Shared.Tests/RunSaveTests.cs b/tests/Aetheria.Shared.Tests/RunSaveTests.cs index 545c1681a..33b139fb9 100644 --- a/tests/Aetheria.Shared.Tests/RunSaveTests.cs +++ b/tests/Aetheria.Shared.Tests/RunSaveTests.cs @@ -458,6 +458,7 @@ public sealed class RunSaveTests : IDisposable var game = new SavedGame { + InfluenceScale = 1, Factions = Array.Empty<CultRecordRef<Faction>>(), Relationships = Array.Empty<FactionRelationship>(), HomeZones = new Dictionary<int, int>(), @@ -841,6 +842,7 @@ public sealed class RunSaveTests : IDisposable // HomeZones lists the factions in reverse of their saved order. private static SavedGame Game(CultCache cache, params Faction[] factions) => new SavedGame { + InfluenceScale = 1, Factions = factions.Select(f => cache.RefOf(f)).ToArray(), Relationships = factions.Select(_ => FactionRelationship.Neutral).ToArray(), HomeZones = factions.Select((_, i) => factions.Length - 1 - i).ToDictionary(i => i, _ => 0), diff --git a/tests/Aetheria.Shared.Tests/RunSeedFixture.cs b/tests/Aetheria.Shared.Tests/RunSeedFixture.cs index 0152584b7..2f4acf413 100644 --- a/tests/Aetheria.Shared.Tests/RunSeedFixture.cs +++ b/tests/Aetheria.Shared.Tests/RunSeedFixture.cs @@ -9,6 +9,7 @@ internal static class RunSeedFixture { var game = new SavedGame { + InfluenceScale = 1, Seed = seed, Factions = new CultRecordRef<Faction>[0], Relationships = new FactionRelationship[0], diff --git a/tests/Aetheria.Shared.Tests/RunStartGearTests.cs b/tests/Aetheria.Shared.Tests/RunStartGearTests.cs index 2d0e1fb67..9abaae4a6 100644 --- a/tests/Aetheria.Shared.Tests/RunStartGearTests.cs +++ b/tests/Aetheria.Shared.Tests/RunStartGearTests.cs @@ -79,9 +79,9 @@ public sealed partial class RunStartTests } [Fact] - public void APreludeNoLongerOffersEverything() + public void ACastGalaxyNoLongerOffersEverything() { - Assert.True(_galaxy.IsPrelude); + Assert.Equal(.5f, _galaxy.InfluenceScale); var (absentProduct, _) = AbsentMaker("AbsentToPrelude"); var generator = GeneratorFor(_galaxy, "PreludeLoner"); Assert.False(generator.IsAvailable(absentProduct)); diff --git a/tests/Aetheria.Shared.Tests/RunStartTests.cs b/tests/Aetheria.Shared.Tests/RunStartTests.cs index efd17eb71..3ea2f2fdc 100644 --- a/tests/Aetheria.Shared.Tests/RunStartTests.cs +++ b/tests/Aetheria.Shared.Tests/RunStartTests.cs @@ -17,7 +17,7 @@ using float2 = CultMath.float2; using float3 = CultMath.float3; // RunStart owns what a new run starts with, and Zone.Admit is the one admission into a zone (docs/scenarios-cut.md, -// 2.2 and R). Every test stages into a real arena: the entrance zone of a prelude galaxy at a fixed seed, built from a +// 2.2 and R). Every test stages into a real arena: the entrance zone of a cast galaxy at a fixed seed, built from a // scratch copy of the catalog the game boots (TestCatalog) and the authored settings (Assets/Resources/Settings.asset). public sealed partial class RunStartTests : IDisposable { @@ -31,7 +31,6 @@ public sealed partial class RunStartTests : IDisposable private readonly PlanetSettings _planetSettings; private readonly string _startingHull; private readonly Faction _protagonist; - private readonly TutorialGenerationSettings _tutorialSettings; public RunStartTests() { @@ -49,10 +48,9 @@ public sealed partial class RunStartTests : IDisposable var authored = AuthoredSettings.Load(repo); _zoneSettings = authored.Read<ZoneGenerationSettings>("ZoneSettings"); _planetSettings = authored.Read<PlanetSettings>("PlanetSettings"); - var tutorial = _tutorialSettings = authored.Read<TutorialGenerationSettings>("TutorialGenerationSettings"); - _galaxy = new Galaxy(tutorial, authored.Read<SectorBackgroundSettings>("TutorialBackgroundSettings"), - _cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(_root, "Narrative")), _ => { }, null, GalaxySeed); + var tutorial = TestCasts.Wide; + _galaxy = new Galaxy(tutorial, authored.Read<SectorBackgroundSettings>("CastBackgroundSettings"), + _cache, _ => { }, null, GalaxySeed); _items = new ItemManager(1u, _cache, new ProvenanceLedger(), RestoredHullsTests.PinnedFlight(authored.Read<GameplaySettings>("GameplaySettings")), _ => { }); _protagonist = _galaxy.ResolveFaction(tutorial.ProtagonistFaction); @@ -125,11 +123,11 @@ public sealed partial class RunStartTests : IDisposable var background = authored.Read<SectorBackgroundSettings>("SectorBackgroundSettings"); var sector = authored.Read<SectorGenerationSettings>("SectorGenerationSettings"); sector.ZoneCount = 8; - var tutorial = authored.Read<TutorialGenerationSettings>("TutorialGenerationSettings"); + var tutorial = TestCasts.Wide; var main = Assert.Throws<ArgumentOutOfRangeException>(() => new Galaxy(sector, background, _cache, _ => { }, null, 0)); var prelude = Assert.Throws<ArgumentOutOfRangeException>(() => - new Galaxy(tutorial, background, _cache, new PlayerSettings(), new DirectoryInfo(_root), _ => { }, null, 0)); + new Galaxy(tutorial, background, _cache, _ => { }, null, 0)); foreach (var refusal in new[] { main, prelude }) { Assert.Equal("seed", refusal.ParamName); @@ -161,7 +159,7 @@ public sealed partial class RunStartTests : IDisposable public void EveryFactionsStationsCarryOnlyGearItCanReachIncludingAHeaterAndAReactor() { var galaxy = MainSectorGalaxy(); - Assert.False(galaxy.IsPrelude); + Assert.Equal(1f, galaxy.InfluenceScale); var zone = Arena(true); foreach (var faction in galaxy.Factions) { diff --git a/tests/Aetheria.Shared.Tests/ScenarioTests.cs b/tests/Aetheria.Shared.Tests/ScenarioTests.cs index 7303931f0..03dcb9f9a 100644 --- a/tests/Aetheria.Shared.Tests/ScenarioTests.cs +++ b/tests/Aetheria.Shared.Tests/ScenarioTests.cs @@ -17,7 +17,7 @@ using float2 = CultMath.float2; using float3 = CultMath.float3; // Scenarios S2 (docs/scenarios-cut.md, R): every new run is a scenario. The fixture is RunStartTests': a scratch copy -// of the shipped catalog, the authored settings and a prelude galaxy at a fixed seed. +// of the shipped catalog, the authored settings and a cast galaxy at a fixed seed. public sealed partial class RunStartTests { // A test's own scenario: a script given inline, staged into the fixture's arena or launched whole. @@ -33,7 +33,7 @@ public sealed partial class RunStartTests _ambient = ambient; _stage = stage; _seed = seed; - _generate = generate ?? (galaxy => galaxy.Prelude()); + _generate = generate ?? (stage => stage.Cast(TestCasts.Wide)); } public override string Name => "Scripted"; @@ -54,9 +54,8 @@ public sealed partial class RunStartTests return new GalaxyStage( authored.Read<SectorGenerationSettings>("SectorGenerationSettings"), authored.Read<SectorBackgroundSettings>("SectorBackgroundSettings"), - authored.Read<TutorialGenerationSettings>("TutorialGenerationSettings"), - authored.Read<SectorBackgroundSettings>("TutorialBackgroundSettings"), - _cache, new PlayerSettings(), Directory.CreateDirectory(Path.Combine(_root, "Narrative")), _ => { }, null, clock); + authored.Read<SectorBackgroundSettings>("CastBackgroundSettings"), + _cache, _ => { }, null, clock); } // What MainMenu.Launch and StartGame do with a scenario: its galaxy, its arena, then staging. beforeStaging stands in @@ -67,14 +66,14 @@ public sealed partial class RunStartTests var arena = new Zone(_items, _planetSettings, RunStart.GenerateArena(_items, _zoneSettings, _planetSettings, galaxy, scenario), galaxy.Entrance, galaxy); beforeStaging?.Invoke(); var failures = new List<string>(); - var staged = RunStart.Stage(_items, arena, scenario, _startingHull, _tutorialSettings, failures); + var staged = RunStart.Stage(_items, arena, scenario, _startingHull, failures); return (galaxy, arena, staged, failures); } private RunStart.Staged Stage(Zone zone, Scenario scenario) { var failures = new List<string>(); - var staged = RunStart.Stage(_items, zone, scenario, _startingHull, _tutorialSettings, failures); + var staged = RunStart.Stage(_items, zone, scenario, _startingHull, failures); Assert.True(failures.Count == 0, string.Join("; ", failures)); Assert.NotNull(staged); return staged; @@ -86,7 +85,7 @@ public sealed partial class RunStartTests var entities = zone.Entities.ToList(); var agents = zone.Agents.ToList(); var failures = new List<string>(); - Assert.Null(RunStart.Stage(_items, zone, scenario, _startingHull, _tutorialSettings, failures)); + Assert.Null(RunStart.Stage(_items, zone, scenario, _startingHull, failures)); SafeAssert.Unchanged(zone, entities, agents); return failures; } @@ -123,26 +122,25 @@ public sealed partial class RunStartTests Assert.Equal(1234, poor.Credits); } - // The two game modes are what New Game did: the tutorial a prelude galaxy and a starting-hull ship of the - // protagonist faction at the entrance's origin; the main galaxy a main galaxy and a starting-hull ship there. Both - // arenas keep their generated ships. + // The two game modes are what New Game did: the demo a cast galaxy at half influence and a starting-hull ship at the + // entrance's origin; the main galaxy a main galaxy at full influence and a starting-hull ship there. Both arenas + // keep their generated ships. [Fact] public void ModesMatchOldNewGame() { Assert.Equal("Longinus", _startingHull); - var tutorial = Launch(new TutorialGalaxy(), Inputs(() => GalaxySeed)); - Assert.Empty(tutorial.failures); - Assert.True(tutorial.galaxy.IsPrelude, "the tutorial is a prelude galaxy"); - Assert.Equal(_startingHull, tutorial.staged.Player.HullData.Name); - Assert.Same(tutorial.galaxy.ResolveFaction(_tutorialSettings.ProtagonistFaction), tutorial.staged.Player.Faction); - Assert.Equal(float3.zero, tutorial.staged.Player.Position); - Assert.Empty(tutorial.staged.Entities); - Assert.Contains(tutorial.arena.Pack.Entities, entity => entity is ShipPack { IsPlayerShip: false }); + var demo = Launch(new DemoTerminus(), Inputs(() => GalaxySeed)); + Assert.Empty(demo.failures); + Assert.Equal(.5f, demo.galaxy.InfluenceScale); + Assert.Equal(_startingHull, demo.staged.Player.HullData.Name); + Assert.Equal(float3.zero, demo.staged.Player.Position); + Assert.Empty(demo.staged.Entities); + Assert.Contains(demo.arena.Pack.Entities, entity => entity is ShipPack { IsPlayerShip: false }); var main = Launch(new MainGalaxy(), Inputs(() => GalaxySeed)); Assert.Empty(main.failures); - Assert.False(main.galaxy.IsPrelude, "the main galaxy is not a prelude"); + Assert.Equal(1f, main.galaxy.InfluenceScale); Assert.Equal(_startingHull, main.staged.Player.HullData.Name); Assert.Equal(float3.zero, main.staged.Player.Position); Assert.Empty(main.staged.Entities); @@ -209,12 +207,12 @@ public sealed partial class RunStartTests Assert.NotEqual(Layout(a), Layout(b)); } - // Generating a galaxy writes nothing a later one reads: a prelude leaves the catalog's faction influence as authored. + // Generating a galaxy writes nothing a later one reads: a cast galaxy leaves the catalog's faction influence as authored. [Fact] public void AGalaxyLeavesTheCatalogsFactionsAsAuthored() { var authored = _cache.GetAll<Faction>().ToDictionary(faction => faction, faction => faction.InfluenceDistance); - RunStart.Generate(new TutorialGalaxy(), Inputs()); + RunStart.Generate(new DemoTerminus(), Inputs()); RunStart.Generate(new MainGalaxy(), Inputs()); Assert.All(authored, pair => Assert.Equal(pair.Value, pair.Key.InfluenceDistance)); } @@ -233,7 +231,7 @@ public sealed partial class RunStartTests [InlineData(34u, false)] public void EveryZoneIsLinked(uint seed, bool prelude) { - var galaxy = RunStart.Generate(new Scripted(true, _ => { }, seed, stage => prelude ? stage.Prelude() : stage.Main()), Inputs()); + var galaxy = RunStart.Generate(new Scripted(true, _ => { }, seed, stage => prelude ? stage.Cast(TestCasts.Wide) : stage.Main()), Inputs()); Assert.All(galaxy.Zones, zone => Assert.Equal(galaxy.Zones.Length, zone.Distance.Count)); var positions = galaxy.Zones.Select(zone => zone.Position).ToArray(); @@ -438,7 +436,7 @@ public sealed partial class RunStartTests public void UndockingAdmitsWithNoAgent() { var zone = Arena(true); - var player = Stage(zone, new TutorialGalaxy()).Player; + var player = Stage(zone, new Scripted(false, stage => stage.Player(stage.Generated(stage.StartingHull), float2(0, 0)))).Player; var station = zone.Entities.First(entity => entity is OrbitalEntity && entity.DockingBays.Count > 0); var agents = zone.Agents.Count; @@ -617,18 +615,69 @@ public sealed partial class RunStartTests Assert.Empty(UnsoldAndUnplaced(runs)); } - // Whether a run is the prelude is the galaxy's fact (Galaxy.IsPrelude); a save records it with no second owner. + // How far influence reaches is the galaxy's fact (Galaxy.InfluenceScale); a save records it with no second owner, and + // a save without one (written before it existed) is refused by name rather than read as full influence. [Fact] - public void SaveReadsPrelude() + public void InfluenceScaleRoundTripsAndOldSavesAreRefused() { var arena = Arena(true); - var (prelude, _) = RunSave.Capture(_cache, _galaxy, arena, null, new SavedActionBarBinding[0], 0); - Assert.True(prelude.IsTutorial); - + var (demo, _) = RunSave.Capture(_cache, _galaxy, arena, null, new SavedActionBarBinding[0], 0); + Assert.Equal(.5f, demo.InfluenceScale); var (main, _) = RunSave.Capture(_cache, MainSectorGalaxy(), arena, null, new SavedActionBarBinding[0], 0); - Assert.False(main.IsTutorial); + Assert.Equal(1f, main.InfluenceScale); + + var old = Assert.Throws<InvalidOperationException>(() => new Galaxy(_cache, new SavedGame + { + Zones = demo.Zones, Factions = demo.Factions, HomeZones = demo.HomeZones, BossZones = demo.BossZones, + Entrance = demo.Entrance, Exit = demo.Exit, DiscoveredZones = demo.DiscoveredZones, Background = demo.Background, + Relationships = demo.Relationships, Standings = demo.Standings, Seed = demo.Seed, + InfluenceScale = 0, + }, _ => { })); + Assert.Contains(nameof(SavedGame.InfluenceScale), old.Message); } + // The halving is the cast's: InfluenceOf scales a faction's authored distance by the galaxy's InfluenceScale, rounding up. + [Fact] + public void InfluenceOfMatchesTheHalving() + { + var half = _galaxy; + var full = MainSectorGalaxy(); + var faction = _cache.GetAll<Faction>().First(); + var authored = faction.InfluenceDistance; + try + { + for (var distance = 0; distance <= 10; distance++) + { + faction.InfluenceDistance = distance; + Assert.Equal((distance + 1) / 2, half.InfluenceOf(faction)); + Assert.Equal(distance, full.InfluenceOf(faction)); + } + } + finally { faction.InfluenceDistance = authored; } + } + + // Whether the arena gets a forced entrance station is the scenario's declaration, not the galaxy's. At a seed whose + // natural roll is zero stations, a scenario declaring one gets a docking station and the same arena generated without + // the declaration gets none. + [Fact] + public void EntranceStationIsTheScenariosDeclaration() + { + Assert.True(new DemoTerminus().EntranceStation); + Assert.False(new MainGalaxy().EntranceStation); + + var natural = ZoneGenerator.GenerateZone(_items, _zoneSettings, _planetSettings, _galaxy, _galaxy.Entrance, entranceStation: false, ambient: false); + var forced = ZoneGenerator.GenerateZone(_items, _zoneSettings, _planetSettings, _galaxy, _galaxy.Entrance, entranceStation: true, ambient: false); + Assert.Equal(0, StationsOf(natural)); + Assert.True(StationsOf(forced) >= 1); + + // Through RunStart, the scenario's declaration is what reaches the generator. + Assert.True(StationsOf(RunStart.GenerateArena(_items, _zoneSettings, _planetSettings, _galaxy, new DemoTerminus())) >= 1); + Assert.Equal(0, StationsOf(RunStart.GenerateArena(_items, _zoneSettings, _planetSettings, _galaxy, new MainGalaxy()))); + } + + private int StationsOf(ZonePack pack) => + pack.Entities.OfType<OrbitalEntityPack>().Count(entity => (_cache.Get(entity.Hull.Data) as HullData)?.HullType == HullType.Station); + // PlayerSettings Key 2, the never-written tutorial flag, is retired: a player.cc written with it still loads, every other field intact. [Fact] public void OldPlayerSettingsLoad() diff --git a/tests/Aetheria.Shared.Tests/StationKindTests.cs b/tests/Aetheria.Shared.Tests/StationKindTests.cs index 02db0c081..dc28fd955 100644 --- a/tests/Aetheria.Shared.Tests/StationKindTests.cs +++ b/tests/Aetheria.Shared.Tests/StationKindTests.cs @@ -352,11 +352,10 @@ public sealed class StationKindTests : IDisposable stock?.Invoke(w); var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); var dir = Path.Combine(_root, "galaxy" + _worlds++); - var galaxy = new Galaxy(authored.Read<TutorialGenerationSettings>("TutorialGenerationSettings"), - authored.Read<SectorBackgroundSettings>("TutorialBackgroundSettings"), w.Cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(dir, "Narrative")), _ => { }, null, 3); + var galaxy = new Galaxy(TestCasts.Wide, + authored.Read<SectorBackgroundSettings>("CastBackgroundSettings"), w.Cache, _ => { }, null, 3); var pack = ZoneGenerator.GenerateZone(w.Items, authored.Read<ZoneGenerationSettings>("ZoneSettings"), - authored.Read<PlanetSettings>("PlanetSettings"), galaxy, galaxy.Entrance, galaxy.IsPrelude, true); + authored.Read<PlanetSettings>("PlanetSettings"), galaxy, galaxy.Entrance, true, true); Assert.NotEmpty(pack.Entities.OfType<OrbitalEntityPack>()); return pack.Orbits.Select(orbit => w.Cache.Get(orbit)).Select(orbit => (orbit.Distance, orbit.Phase)).ToArray(); } @@ -376,11 +375,10 @@ public sealed class StationKindTests : IDisposable foreach (var faction in new[] { w.Au, w.Zh, w.Lucent }) foreach (var kind in new[] { "mining", "shipyard", "depot", "power" }) w.Sell(faction, kind); var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); - var galaxy = new Galaxy(authored.Read<TutorialGenerationSettings>("TutorialGenerationSettings"), - authored.Read<SectorBackgroundSettings>("TutorialBackgroundSettings"), w.Cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(_root, "galaxy" + _worlds++, "Narrative")), _ => { }, null, 3); + var galaxy = new Galaxy(TestCasts.Wide, + authored.Read<SectorBackgroundSettings>("CastBackgroundSettings"), w.Cache, _ => { }, null, 3); return galaxy.Zones.Take(8).SelectMany(zone => ZoneGenerator.GenerateZone(w.Items, authored.Read<ZoneGenerationSettings>("ZoneSettings"), - authored.Read<PlanetSettings>("PlanetSettings"), galaxy, zone, zone == galaxy.Entrance && galaxy.IsPrelude, true) + authored.Read<PlanetSettings>("PlanetSettings"), galaxy, zone, true, true) .Entities.OfType<OrbitalEntityPack>().Where(e => e.Kind.IsSet()).Select(e => e.Kind.Key.Value)).ToArray(); } var first = Kinds(); @@ -397,15 +395,14 @@ public sealed class StationKindTests : IDisposable w.StandIn("depot", w.Lucent, "power"); w.StandIn("depot", w.Zh, "power"); var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); - var galaxy = new Galaxy(authored.Read<TutorialGenerationSettings>("TutorialGenerationSettings"), - authored.Read<SectorBackgroundSettings>("TutorialBackgroundSettings"), w.Cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(_root, "zones", "Narrative")), _ => { }, null, 5); + var galaxy = new Galaxy(TestCasts.Wide, + authored.Read<SectorBackgroundSettings>("CastBackgroundSettings"), w.Cache, _ => { }, null, 5); var stations = 0; var fallbacks = 0; foreach (var galaxyZone in galaxy.Zones.Take(8)) { var pack = ZoneGenerator.GenerateZone(w.Items, authored.Read<ZoneGenerationSettings>("ZoneSettings"), - authored.Read<PlanetSettings>("PlanetSettings"), galaxy, galaxyZone, galaxyZone == galaxy.Entrance && galaxy.IsPrelude, true); + authored.Read<PlanetSettings>("PlanetSettings"), galaxy, galaxyZone, true, true); foreach (var station in pack.Entities.OfType<OrbitalEntityPack>().Where(e => w.HullOf(e).HullType == HullType.Station)) { stations++; @@ -473,11 +470,10 @@ public sealed class StationKindTests : IDisposable } var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); - var galaxy = new Galaxy(authored.Read<TutorialGenerationSettings>("TutorialGenerationSettings"), - authored.Read<SectorBackgroundSettings>("TutorialBackgroundSettings"), world.Cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(_root, "galaxy" + _worlds++, "Narrative")), _ => { }, null, 5); + var galaxy = new Galaxy(TestCasts.Wide, + authored.Read<SectorBackgroundSettings>("CastBackgroundSettings"), world.Cache, _ => { }, null, 5); var entrance = ZoneGenerator.GenerateZone(world.Items, authored.Read<ZoneGenerationSettings>("ZoneSettings"), - authored.Read<PlanetSettings>("PlanetSettings"), galaxy, galaxy.Entrance, galaxy.IsPrelude, true); + authored.Read<PlanetSettings>("PlanetSettings"), galaxy, galaxy.Entrance, true, true); Assert.Contains(entrance.Entities.OfType<OrbitalEntityPack>(), e => world.HullOf(e).HullType == HullType.Station); } diff --git a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs index b265ead4d..33441e369 100644 --- a/tests/Aetheria.Shared.Tests/StationPlacementTests.cs +++ b/tests/Aetheria.Shared.Tests/StationPlacementTests.cs @@ -52,10 +52,9 @@ public sealed class StationPlacementTests : IDisposable cache.AddBackingStore(new GameCult.Caching.MessagePack.SingleFileMessagePackBackingStore(Path.Combine(dir, "run.cc")), AetheriaStores.RunTypes); var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); var settings = authored.Read<GameplaySettings>("GameplaySettings"); - var galaxy = new Galaxy(authored.Read<TutorialGenerationSettings>("TutorialGenerationSettings"), - authored.Read<SectorBackgroundSettings>("TutorialBackgroundSettings"), - cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(dir, "Narrative")), _ => { }, null, seed); + var galaxy = new Galaxy(TestCasts.Wide, + authored.Read<SectorBackgroundSettings>("CastBackgroundSettings"), + cache, _ => { }, null, seed); var items = new ItemManager(1u, cache, new ProvenanceLedger(), settings, _ => { }); stock?.Invoke(items); foreach (var galaxyZone in entranceOnly ? new[] { galaxy.Entrance } : galaxy.Zones.Take(zonesPerSeed)) @@ -65,7 +64,7 @@ public sealed class StationPlacementTests : IDisposable var zoneSettings = authored.Read<ZoneGenerationSettings>("ZoneSettings"); tune?.Invoke(zoneSettings); var pack = ZoneGenerator.GenerateZone(items, zoneSettings, authored.Read<PlanetSettings>("PlanetSettings"), galaxy, galaxyZone, - galaxyZone == galaxy.Entrance && galaxy.IsPrelude, true); + true, true); var zone = new Zone(items, authored.Read<PlanetSettings>("PlanetSettings"), pack, galaxyZone, galaxy); zone.Update(.02f); yield return new Built(seed, zone, items); diff --git a/tests/Aetheria.Shared.Tests/SunsNeverGreenTests.cs b/tests/Aetheria.Shared.Tests/SunsNeverGreenTests.cs index 37eafc01a..d1f9f73de 100644 --- a/tests/Aetheria.Shared.Tests/SunsNeverGreenTests.cs +++ b/tests/Aetheria.Shared.Tests/SunsNeverGreenTests.cs @@ -181,10 +181,9 @@ public sealed class SunsNeverGreenTests : IDisposable cache.AddBackingStore(new GameCult.Caching.MessagePack.SingleFileMessagePackBackingStore(catalog), AetheriaStores.CatalogTypes); cache.AddBackingStore(new GameCult.Caching.MessagePack.SingleFileMessagePackBackingStore(Path.Combine(dir, "run.cc")), AetheriaStores.RunTypes); var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot()); - var tutorial = authored.Read<TutorialGenerationSettings>("TutorialGenerationSettings"); - var galaxy = new Galaxy(tutorial, authored.Read<SectorBackgroundSettings>("TutorialBackgroundSettings"), - cache, new PlayerSettings(), - Directory.CreateDirectory(Path.Combine(dir, "Narrative")), _ => { }, null, seed); + var tutorial = TestCasts.Wide; + var galaxy = new Galaxy(tutorial, authored.Read<SectorBackgroundSettings>("CastBackgroundSettings"), + cache, _ => { }, null, seed); var items = new ItemManager(1u, cache, new ProvenanceLedger(), authored.Read<GameplaySettings>("GameplaySettings"), _ => { }); var zoneSettings = authored.Read<ZoneGenerationSettings>("ZoneSettings"); adjust(zoneSettings); diff --git a/tests/Aetheria.Shared.Tests/TestCasts.cs b/tests/Aetheria.Shared.Tests/TestCasts.cs new file mode 100644 index 000000000..05759557c --- /dev/null +++ b/tests/Aetheria.Shared.Tests/TestCasts.cs @@ -0,0 +1,18 @@ +// The two fixtures every cast-galaxy test builds from: the values the retired Settings.asset block held (Miss, Zhe, Luc, +// Aero and Finch, Adras, 64 zones, half influence), so every test galaxy is what it was. A test fixture is not new +// faction material (ruling miss-terris-belongs-to-emily-r3). +internal static class TestCasts +{ + internal static GalaxyCast Wide => new GalaxyCast + { + ProtagonistFaction = "Miss", AntagonistFaction = "Zhe", BufferFaction = "Luc", + NeutralFactions = new[] { "Aero", "Finch" }, QuestFaction = "Adras", LinkDensity = .5f, ZoneCount = 64, + InfluenceScale = .5f, + }; + + internal static SectorBackgroundSettings Background => new SectorBackgroundSettings + { + NoiseAmplitude = 1, NoiseOffset = .3f, NoiseGain = .7f, NoiseLacunarity = 2, NoiseFrequency = .1f, + NoisePosition = 536.5106f, CloudExponent = 10, CloudAmplitude = .01f, + }; +} diff --git a/tools/AetherDb/Program.cs b/tools/AetherDb/Program.cs index 2caaaed4b..39e4284ff 100644 --- a/tools/AetherDb/Program.cs +++ b/tools/AetherDb/Program.cs @@ -560,7 +560,7 @@ public static class Program private static int SettingsDump() { var authored = AuthoredSettings.Load(AetherDb.FindRoot()); - authored.Dump("TutorialGenerationSettings", 2); + authored.Dump("CastBackgroundSettings", 2); Console.WriteLine(); authored.Dump("GameplaySettings", 2); return 0; @@ -572,15 +572,10 @@ public static class Program { var authored = AuthoredSettings.Load(AetherDb.FindRoot()); - var tutorial = authored.Read<TutorialGenerationSettings>("TutorialGenerationSettings"); - var background = authored.Read<SectorBackgroundSettings>("TutorialBackgroundSettings"); + var background = authored.Read<SectorBackgroundSettings>("CastBackgroundSettings"); var zones = authored.Read<ZoneGenerationSettings>("ZoneSettings"); var gameplay = authored.Read<GameplaySettings>("GameplaySettings"); - Console.WriteLine($"tutorial: protagonist {tutorial.ProtagonistFaction}, antagonist {tutorial.AntagonistFaction}, " + - $"buffer {tutorial.BufferFaction}, quest {tutorial.QuestFaction}, " + - $"neutrals [{string.Join(", ", tutorial.NeutralFactions ?? new string[0])}], " + - $"{tutorial.ZoneCount} zones, link density {tutorial.LinkDensity}"); Console.WriteLine($"background: frequency {background.NoiseFrequency}, amplitude {background.NoiseAmplitude}, " + $"cloud exponent {background.CloudExponent}, density at centre {background.CloudDensity(new float2(.5f)):0.000}"); Console.WriteLine($"zones: sun mass {zones.SunMass}, planet mass {zones.PlanetMass}, satellite passes {zones.SatellitePasses}, " + @@ -600,8 +595,6 @@ public static class Program else if (gameplay.Tiers.Any(t => string.IsNullOrEmpty(t.Name) || t.Quality <= 0)) missing.Add("GameplaySettings.Tiers (a tier parsed without a name or quality)"); if (gameplay.DefaultEntitySettings == null) missing.Add("GameplaySettings.DefaultEntitySettings"); if (gameplay.QualityPriceModifier == null || gameplay.QualityPriceModifier.Maximum <= 0) missing.Add("GameplaySettings.QualityPriceModifier"); - if (tutorial.NeutralFactions == null || tutorial.NeutralFactions.Length != 2) missing.Add($"TutorialGenerationSettings.NeutralFactions (expected 2, got {tutorial.NeutralFactions?.Length ?? 0})"); - if (string.IsNullOrEmpty(tutorial.ProtagonistFaction)) missing.Add("TutorialGenerationSettings.ProtagonistFaction"); Console.WriteLine($"\n{authored.Unplaced.Count} fields in the asset had nowhere to go"); foreach (var field in authored.Unplaced.Take(20)) Console.WriteLine($" {field}"); From f2ddf70c128ed29dc6d43b0bc451ff592ff58d87 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Thu, 19 Nov 2026 20:14:30 +0100 Subject: [PATCH 110/190] Merge checklist step 4 describes the game after the prelude: Terminus (Demo), Main Galaxy, the scenario's EntranceStation Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- docs/merge-to-master-checklist.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/merge-to-master-checklist.md b/docs/merge-to-master-checklist.md index 270b5625b..664f464b2 100644 --- a/docs/merge-to-master-checklist.md +++ b/docs/merge-to-master-checklist.md @@ -33,7 +33,7 @@ Compiled 2026-09-29 by Eyes from the maps on the branch. Pointers are `doc:line` ### 2b. Fresh launch (no `run.cc`, no `player.cc`) 3. **Launch to main menu.** Expect no Addressables errors, and the Groups window shows `Assets/Content` under `Default Local Group` (`addressables-cut.md:301`). `player.cc` appears and Continue is disabled (`cultcache-migration-cut.md:2746`). Proves: Addressables Cut 1, CultCache cutover. The 09-17 smoke covered the last two on the old tree; this is a cheap recheck on the new schema. -4. **New Game, then a scenario.** New Game opens the scenario picker (`MainMenu.ShowScenarios`); a development build lists modes (Terminus (Demo)), development (Tutorial Galaxy, Main Galaxy) and test arenas, a release build lists only the modes. Pick Tutorial Galaxy or Terminus (Demo). Expect the galaxy generates and the start ship is the Longinus (`settings-globals-cut.md:498`, an expectation, not a recorded check for this stack). Expect a Zenith station with a docking bay in the entrance zone every time (`locomotion-cut.md:375`). Proves: locomotion Cut 1 station rule. +4. **New Game, then a scenario.** New Game opens the scenario picker (`MainMenu.ShowScenarios`); a development build lists modes (Terminus (Demo)), development (Main Galaxy) and test arenas, a release build lists only the modes. Pick Terminus (Demo). Expect the galaxy generates and the start ship is the Longinus (`settings-globals-cut.md:498`, an expectation, not a recorded check for this stack). Expect a Zenith station with a docking bay in the entrance zone every time, because the scenario declares `EntranceStation` (`locomotion-cut.md:375`). Proves: locomotion Cut 1 station rule. 5. **Addressables, "Use Asset Database".** Ships, turret and Zenith spawn; thruster and aether-drive particles show; fire an instant weapon (Autocannon) and a charged one (ChargeBlast SG); action bar icons show (`addressables-cut.md:362-366`). Proves: Addressables Cut 2. ### 2c. Flight, power and economy From 8aff1b878916ef64d42bb191a6c80e0affb4927e Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Thu, 19 Nov 2026 20:34:03 +0100 Subject: [PATCH 111/190] Settings: drop TorqueFloor and AgentFiringMinDot, authored values no code reads Both were already unplaced at 8b2d1f544 (Soul finding orphan-asset-fields on cut-retire-prelude.s1); AetherDb settings now reports 0 unplaced fields. Operator, 2026-11-19: delete the orphaned settings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- Assets/Resources/Settings.asset | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Assets/Resources/Settings.asset b/Assets/Resources/Settings.asset index 95d783c85..1c37213be 100644 --- a/Assets/Resources/Settings.asset +++ b/Assets/Resources/Settings.asset @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:9705712101eaff9f702d793735d4f4db903638aaaae1467c72e5f432464cc48c -size 12410 +oid sha256:9ad71cb30db7301f1e81be7fec21edb6e6da54b1553a13e44cac7a1effc99c36 +size 12361 From 28666e3550f70dc9bdf117fb0e468769214a2d90 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Thu, 19 Nov 2026 19:39:03 +0100 Subject: [PATCH 112/190] A directional thruster's emitter is one-sided, and the catalog refuses one that fires along its push The exhaust is born along each triangle's normal of the emitter mesh, and every Nakovalnya, Wren and starter emitter was a thin closed box, so it fired both ways along the thruster axis. The generator now writes one side: hull_source keeps of a hull source's emit mesh only the triangles facing its anchor's yaw (the exhaust), and the starter's thruster boxes carry a single exhaust face. ShipModCatalog.Bind, which Compose and ship-authoring validate both run, reads the emitter geometry from the GLB (world transform included) and refuses a directional thruster whose emitter has any face or vertex normal with a non-negative dot with the push, naming the anchor. The rule is the directional class's alone; a ring thruster would bring its own. The Nakovalnya and Wren ship.glb are regenerated through Build + Package and the starter; ship.cc, anchors, node indices and every non-emitter node are unchanged. Blender smokes and the test GLBs now give thrusters an exhaust-facing emitter and a matching Rotation. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/ShipModCatalog.cs | 152 ++++++++++++++++++ GameData/Mods/aetheria.nakovalnya/ship.glb | 4 +- docs/moddable-ship-authoring.md | 7 +- .../ShipEmitterExhaustTests.cs | 70 ++++++++ tests/Aetheria.Shared.Tests/ShipFixture.cs | 27 +++- tests/Aetheria.Shared.Tests/ShipRigTests.cs | 8 +- tests/fixtures/mods/aetheria.wren/ship.glb | 4 +- tools/AetherDb/ShipStarterCommand.cs | 11 +- tools/blender/aetheria_ships/hull_source.py | 28 +++- tools/blender/tests/smoke_hull_source.py | 9 +- tools/blender/tests/smoke_mounts.py | 10 +- tools/blender/tests/smoke_package.py | 10 +- tools/blender/tests/test_hull_source.py | 38 ++++- 13 files changed, 349 insertions(+), 29 deletions(-) create mode 100644 tests/Aetheria.Shared.Tests/ShipEmitterExhaustTests.cs diff --git a/Assets/Scripts/ServerShared/ShipModCatalog.cs b/Assets/Scripts/ServerShared/ShipModCatalog.cs index 0e5bd801c..6d509f011 100644 --- a/Assets/Scripts/ServerShared/ShipModCatalog.cs +++ b/Assets/Scripts/ServerShared/ShipModCatalog.cs @@ -4,6 +4,7 @@ using System.IO; using System.Linq; using GameCult.Caching; using Newtonsoft.Json.Linq; +using System.Numerics; using System.Text; // Builds the one catalog snapshot CultCache needs. Sources remain the shipped catalog and each @@ -284,6 +285,7 @@ public static class ShipModCatalog foreach (var anchor in ship.Anchors) if (anchor.Role == "shield" && !modelNodes[anchor.ModelNodeId].PositiveScale) throw new InvalidOperationException($"{ship.Id}: shield anchor {anchor.Id} needs three positive scale radii on model node {anchor.ModelNodeId}, with no matrix."); + BindExhaust(hull, ship, modelNodes, modelPath); BindRig(ship, modelNodes); CultRecordRefs.Validate(hull); return new Package @@ -293,6 +295,156 @@ public static class ShipModCatalog }; } + // A thruster emitter's mesh is the surface its exhaust is born from, along each triangle's normal, so the mesh has to face + // the way the exhaust goes. Every thruster is a directional thruster today: its Rotation faces its exhaust, the push + // is the opposite way, and an emitter triangle whose normal has a non-negative dot with the push would fire exhaust + // along it (a closed box fires both ways). A thruster of another class, a ring thruster whose exhaust leaves radially, + // is not this rule's to judge: it would come with its own class on the hardpoint and its own rule beside this one. + private static void BindExhaust(HullData hull, ShipAuthoring ship, Dictionary<string, (uint Index, bool HasMesh, int Parent, bool PositiveScale)> nodes, string modelPath) + { + var emitters = ship.Anchors.Where(anchor => anchor.Role == "thruster-emitter").ToArray(); + if (emitters.Length == 0) return; + var model = GlbGeometry.Read(modelPath); + foreach (var anchor in emitters) + { + var hardpoint = hull.Hardpoints.FirstOrDefault(candidate => candidate.Type == HardpointType.Thruster && candidate.Transform == anchor.Id); + if (hardpoint == null) continue; + var facing = hardpoint.Rotation.Direction(); + // The model's frame is glTF's, nose toward +Z and port toward +X (the Blender kit's nose at -Y and port at +X, + // through the exporter's Y-up conversion): a hardpoint facing (x, y) in the grid faces (-x, 0, y) in the model. + var push = -new Vector3(-facing.x, 0f, facing.y); + var wrong = model.Normals((int)nodes[anchor.ModelNodeId].Index).Count(normal => Vector3.Dot(normal, push) >= 0f); + if (wrong > 0) + throw new InvalidOperationException($"{ship.Id}: thruster emitter {anchor.Id} has {wrong} face or vertex normal(s) that do not face its exhaust " + + $"({hardpoint.Rotation}); a directional thruster's emitter fires only along its exhaust, so it must be one-sided, not a closed box."); + } + } + + // The triangles of a GLB as the node tree places them, read for the one question the emitter rule asks: which way each + // face points. Float positions and normals, indices of 1, 2 or 4 bytes or none, no sparse, no compression: a model the + // exporter writes. Anything else is refused as unreadable rather than guessed at. + private sealed class GlbGeometry + { + private readonly JObject _json; + private readonly byte[] _bin; + private readonly string _path; + + private GlbGeometry(JObject json, byte[] bin, string path) { _json = json; _bin = bin; _path = path; } + + public static GlbGeometry Read(string path) + { + var bytes = File.ReadAllBytes(path); + var jsonLength = (int)BitConverter.ToUInt32(bytes, 12); + var json = JObject.Parse(Encoding.UTF8.GetString(bytes, 20, jsonLength)); + var at = 20 + jsonLength; + var bin = at + 8 <= bytes.Length && BitConverter.ToUInt32(bytes, at + 4) == 0x004E4942u + ? bytes.Skip(at + 8).Take((int)BitConverter.ToUInt32(bytes, at)).ToArray() : Array.Empty<byte>(); + return new GlbGeometry(json, bin, path); + } + + // Unit normals in the model frame: each triangle's face normal (its winding, flipped when the node's world transform + // mirrors, as glTF says) and each vertex normal the primitive carries. + public IEnumerable<Vector3> Normals(int node) + { + var world = World(node); + var mirrored = world.GetDeterminant() < 0f; + var meshIndex = (int?)_json["nodes"][node]["mesh"]; + if (meshIndex == null) yield break; + foreach (var primitive in (JArray)_json["meshes"][meshIndex.Value]["primitives"]) + { + var attributes = (JObject)primitive["attributes"]; + if (primitive["extensions"] != null) throw Unreadable($"mesh {meshIndex} uses a primitive extension"); + var positions = Vectors((int)attributes["POSITION"]).Select(point => Vector3.Transform(point, world)).ToArray(); + var indices = primitive["indices"] == null ? Enumerable.Range(0, positions.Length).ToArray() : Indices((int)primitive["indices"]); + for (var i = 0; i + 2 < indices.Length; i += 3) + { + var face = Vector3.Cross(positions[indices[i + 1]] - positions[indices[i]], positions[indices[i + 2]] - positions[indices[i]]); + if (face.LengthSquared() < 1e-12f) continue; + yield return Vector3.Normalize(mirrored ? -face : face); + } + if (attributes["NORMAL"] != null) + foreach (var normal in Vectors((int)attributes["NORMAL"])) + if (normal.LengthSquared() > 1e-12f) yield return Vector3.Normalize(Vector3.TransformNormal(normal, world)); + } + } + + // Row-vector matrices, so a child's world is its local times its parent's world. + private Matrix4x4 World(int node) + { + var parents = new Dictionary<int, int>(); + var nodes = (JArray)_json["nodes"]; + for (var parent = 0; parent < nodes.Count; parent++) + foreach (var child in nodes[parent]["children"]?.Select(token => (int)token) ?? Enumerable.Empty<int>()) parents[child] = parent; + var world = Matrix4x4.Identity; + for (int at = node, steps = 0; steps <= nodes.Count; steps++) + { + world *= Local((JObject)nodes[at]); + if (!parents.TryGetValue(at, out at)) break; + } + return world; + } + + private static Matrix4x4 Local(JObject node) + { + if (node["matrix"] is JArray m) + { + var v = m.Select(token => (float)token).ToArray(); + return new Matrix4x4(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12], v[13], v[14], v[15]); + } + float[] Of(string key, float[] fallback) => node[key] is JArray a ? a.Select(token => (float)token).ToArray() : fallback; + var scale = Of("scale", new[] { 1f, 1f, 1f }); + var rotation = Of("rotation", new[] { 0f, 0f, 0f, 1f }); + var translation = Of("translation", new[] { 0f, 0f, 0f }); + return Matrix4x4.CreateScale(scale[0], scale[1], scale[2]) * + Matrix4x4.CreateFromQuaternion(new Quaternion(rotation[0], rotation[1], rotation[2], rotation[3])) * + Matrix4x4.CreateTranslation(translation[0], translation[1], translation[2]); + } + + // The bytes an accessor reads from: its view's slice of the BIN chunk, at the view's stride. + private (int Offset, int Stride, int Count, int Component, string Type) Locate(int accessor) + { + var a = (JObject)_json["accessors"][accessor]; + if (a["sparse"] != null || a["bufferView"] == null) throw Unreadable($"accessor {accessor} is sparse or has no buffer view"); + var view = (JObject)_json["bufferViews"][(int)a["bufferView"]]; + var component = (int)a["componentType"]; + var type = (string)a["type"]; + var width = (component == 5126 || component == 5125 ? 4 : component == 5123 ? 2 : 1) * (type == "VEC3" ? 3 : 1); + var offset = ((int?)view["byteOffset"] ?? 0) + ((int?)a["byteOffset"] ?? 0); + var stride = (int?)view["byteStride"] ?? width; + var count = (int)a["count"]; + if (offset < 0 || count < 0 || (count > 0 && offset + (long)(count - 1) * stride + width > _bin.Length)) throw Unreadable($"accessor {accessor} reaches past the BIN chunk"); + return (offset, stride, count, component, type); + } + + private Vector3[] Vectors(int accessor) + { + var (offset, stride, count, component, type) = Locate(accessor); + if (component != 5126 || type != "VEC3") throw Unreadable($"accessor {accessor} is not float VEC3"); + var result = new Vector3[count]; + for (var i = 0; i < count; i++) + { + var at = offset + i * stride; + result[i] = new Vector3(BitConverter.ToSingle(_bin, at), BitConverter.ToSingle(_bin, at + 4), BitConverter.ToSingle(_bin, at + 8)); + } + return result; + } + + private int[] Indices(int accessor) + { + var (offset, stride, count, component, type) = Locate(accessor); + if (type != "SCALAR" || component != 5121 && component != 5123 && component != 5125) throw Unreadable($"accessor {accessor} is not an index accessor"); + var result = new int[count]; + for (var i = 0; i < count; i++) + { + var at = offset + i * stride; + result[i] = component == 5121 ? _bin[at] : component == 5123 ? BitConverter.ToUInt16(_bin, at) : (int)BitConverter.ToUInt32(_bin, at); + } + return result; + } + + private InvalidOperationException Unreadable(string reason) => new InvalidOperationException($"{_path}: emitter geometry is unreadable: {reason}."); + } + // The rig the record states must be the rig the model has: every joint is a node, each joint's Parent and each mount's // Joint is the nearest joint above its node, ancestors without an id being walked through by ReadNodeIds, and a radiator // mesh sits under no joint. diff --git a/GameData/Mods/aetheria.nakovalnya/ship.glb b/GameData/Mods/aetheria.nakovalnya/ship.glb index 3dac76cc9..af1e370e6 100644 --- a/GameData/Mods/aetheria.nakovalnya/ship.glb +++ b/GameData/Mods/aetheria.nakovalnya/ship.glb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:90a503473e3b12251c225b7fe283b2fc5b45a25e6e47839d1c3d78e3ac61b00c -size 843452 +oid sha256:ab3fdd340bf27fc8c2a6149ce6be9159215cf26b3eabd290064ffe40b2e96512 +size 839556 diff --git a/docs/moddable-ship-authoring.md b/docs/moddable-ship-authoring.md index 81871b2dc..057b7d511 100644 --- a/docs/moddable-ship-authoring.md +++ b/docs/moddable-ship-authoring.md @@ -216,7 +216,12 @@ a radiator, `weapon-mount` for an energy, ballistic or launcher hardpoint. An internal hardpoint (reactor, sensors, shield and the rest) has no anchor, and an anchor taking its id is refused. A thruster's or radiator's anchor node is a mesh: the thruster's is not rendered and is the surface its exhaust emits from, -the radiator's is rendered. A weapon mount is a point, and each one needs at +the radiator's is rendered. A directional thruster's emitter is one-sided: the +exhaust is born along each triangle's normal, so every normal must face the way +the hardpoint's Rotation faces (opposite the push), and a closed box, which also +fires along the push, is refused by Compose and `validate` naming the anchor. In +the Blender kit's frame a hull source's emit mesh is cut to the side facing its +anchor's yaw. A ring thruster would be its own class with its own rule. A weapon mount is a point, and each one needs at least one `weapon-muzzle` anchor whose `ParentId` is the weapon's mount id. `articulation` is reserved for pivots and is never a mount; no pivot is planned until pivots move onto `HullData`. `ShipModPlan` then maps the diff --git a/tests/Aetheria.Shared.Tests/ShipEmitterExhaustTests.cs b/tests/Aetheria.Shared.Tests/ShipEmitterExhaustTests.cs new file mode 100644 index 000000000..466ee8837 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ShipEmitterExhaustTests.cs @@ -0,0 +1,70 @@ +using System; +using System.IO; +using System.Linq; +using Xunit; + +// A directional thruster's emitter mesh is the surface its exhaust is born from, along each triangle's normal, so every +// normal must face the exhaust, opposite the push (ShipModCatalog.BindExhaust). A closed box fires both ways: the operator +// saw the same thrusters firing whichever way the ship strafed. A ring thruster is a class of its own with its own rule and +// is not exercised here. +public sealed class ShipEmitterExhaustTests : IDisposable +{ + private readonly TempDirectory _directory = new TempDirectory(); + + public void Dispose() => _directory.Dispose(); + + private string Thruster => Path.Combine(_directory.Path, "mod.skiff", "ship.cc"); + + // The fixture thruster's hardpoint Rotation is None, so its exhaust leaves toward glTF's +Z; its emitter, one quad + // wound to face +Z, is the one-sided emitter the generator writes. + private void Write(Action<ShipParts> tweak = null, string from = null, string to = null) + { + ShipFixture.WritePackage(_directory.Path, "mod.skiff", tweak: tweak); + if (from == null) return; + var json = ShipFixture.GlbJson(ShipFixture.Nodes); + Assert.Contains(from, json); + File.WriteAllBytes(Path.Combine(_directory.Path, "mod.skiff", "skiff.glb"), ShipFixture.Glb(json.Replace(from, to), ShipFixture.MeshBytes())); + } + + private static void Reversed(ShipParts ship) => ship.Hull.Hardpoints.Single(hardpoint => hardpoint.Transform == "thruster.port").Rotation = ItemRotation.Reversed; + + [Fact] + public void AOneSidedEmitterFacingItsExhaustIsAccepted() + { + Write(); + Assert.Equal("mod.skiff", ShipModCatalog.ReadPackage(Thruster).Visual.Id); + } + + [Fact] + public void AClosedBoxEmitterIsRefusedNamingItsAnchor() + { + Write(from: @"""name"":""thruster-port"",""mesh"":1", to: @"""name"":""thruster-port"",""mesh"":0"); + var message = Assert.Throws<InvalidOperationException>(() => ShipModCatalog.ReadPackage(Thruster)).Message; + Assert.Contains("thruster emitter thruster.port", message); + Assert.Contains("one-sided", message); + } + + [Fact] + public void AnEmitterFacingTheWrongWayIsRefused() + { + // The same quad toward +Z under a thruster that now faces aft: its exhaust would leave along the push. + Write(Reversed); + Assert.Contains("thruster emitter thruster.port", Assert.Throws<InvalidOperationException>(() => ShipModCatalog.ReadPackage(Thruster)).Message); + } + + [Fact] + public void TheNodesTurnDecidesWhichWayTheEmitterFaces() + { + // Turned half a circle about Y, the quad's +Z becomes -Z: the exhaust of an aft-facing thruster. + Write(Reversed, from: @"""name"":""thruster-port"",""mesh"":1", to: @"""name"":""thruster-port"",""mesh"":1,""rotation"":[0,1,0,0]"); + Assert.Equal("mod.skiff", ShipModCatalog.ReadPackage(Thruster).Visual.Id); + } + + [Fact] + public void TheShippedAndFixturePackagesPass() + { + var root = RunStartTests.FindRepoRoot(); + foreach (var ship in new[] { Path.Combine("GameData", "Mods", "aetheria.nakovalnya"), Path.Combine("tests", "fixtures", "mods", "aetheria.wren") }) + Assert.NotNull(ShipModCatalog.ReadPackage(Path.Combine(root, ship, "ship.cc"))); + } +} diff --git a/tests/Aetheria.Shared.Tests/ShipFixture.cs b/tests/Aetheria.Shared.Tests/ShipFixture.cs index 9f2e1c75f..ac41ece2f 100644 --- a/tests/Aetheria.Shared.Tests/ShipFixture.cs +++ b/tests/Aetheria.Shared.Tests/ShipFixture.cs @@ -22,22 +22,33 @@ internal static class ShipFixture 1, 0, 0, 0, 1, 0, 0, 0, 1 }; - public static byte[] MeshBytes() => Tetrahedron.SelectMany(BitConverter.GetBytes).ToArray(); + // One-sided quad in the z = 0 plane, wound counter-clockwise seen from +Z, so its normal is +Z (glTF's nose): the emitter + // of a thruster whose Rotation is None, which faces its exhaust ahead. Four vertices and six 16-bit indices follow the + // tetrahedron in the BIN chunk. + private static readonly float[] Quad = { 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0 }; + private static readonly ushort[] QuadIndices = { 0, 1, 2, 0, 2, 3 }; + + public static byte[] MeshBytes() => + Tetrahedron.SelectMany(BitConverter.GetBytes).Concat(Quad.SelectMany(BitConverter.GetBytes)).Concat(QuadIndices.SelectMany(BitConverter.GetBytes)).ToArray(); + + // The model's geometry as glTF JSON members (meshes, accessors, bufferViews, buffers) over MeshBytes: mesh 0 is the + // tetrahedron, mesh 1 the quad. + public static string Geometry => + @"""meshes"":[{""primitives"":[{""attributes"":{""POSITION"":0}}]},{""primitives"":[{""attributes"":{""POSITION"":1},""indices"":2}]}]," + + @"""accessors"":[{""bufferView"":0,""componentType"":5126,""count"":12,""type"":""VEC3"",""min"":[0,0,0],""max"":[1,1,1]}," + + @"{""bufferView"":1,""componentType"":5126,""count"":4,""type"":""VEC3"",""min"":[0,0,0],""max"":[1,1,0]}," + + @"{""bufferView"":2,""componentType"":5123,""count"":6,""type"":""SCALAR""}]," + + $@"""bufferViews"":[{{""buffer"":0,""byteLength"":144}},{{""buffer"":0,""byteOffset"":144,""byteLength"":48}},{{""buffer"":0,""byteOffset"":192,""byteLength"":12}}],""buffers"":[{{""byteLength"":{MeshBytes().Length}}}]"; // The GLB carries a glTF scene naming every node: glTFast instantiates a scene, and a scene-less file has none. // Nodes in meshNodes (default MeshNodes) get the shared tetrahedron mesh, whose vertices live in the BIN chunk (MeshBytes). public static string GlbJson(string[] nodes, string[] meshNodes = null) { meshNodes ??= MeshNodes; - var length = MeshBytes().Length; - var mesh = nodes.Any(meshNodes.Contains) - ? @",""meshes"":[{""primitives"":[{""attributes"":{""POSITION"":0}}]}]," + - @"""accessors"":[{""bufferView"":0,""componentType"":5126,""count"":12,""type"":""VEC3"",""min"":[0,0,0],""max"":[1,1,1]}]," + - $@"""bufferViews"":[{{""buffer"":0,""byteLength"":{length}}}],""buffers"":[{{""byteLength"":{length}}}]" - : ""; + var mesh = nodes.Any(meshNodes.Contains) ? "," + Geometry : ""; return @"{""asset"":{""version"":""2.0""},""scene"":0,""scenes"":[{""nodes"":[" + string.Join(",", nodes.Select((_, index) => index)) + @"]}]" + mesh + @",""nodes"":[" + string.Join(",", nodes.Select(node => - $@"{{""name"":""{node}""{(meshNodes.Contains(node) ? @",""mesh"":0" : "")},""extras"":{{""aetheria.id"":""{node}""}}}}")) + "]}"; + $@"{{""name"":""{node}""{(meshNodes.Contains(node) ? node.StartsWith("thruster") ? @",""mesh"":1" : @",""mesh"":0" : "")},""extras"":{{""aetheria.id"":""{node}""}}}}")) + "]}"; } public static byte[] Glb(string json, byte[] bin = null) diff --git a/tests/Aetheria.Shared.Tests/ShipRigTests.cs b/tests/Aetheria.Shared.Tests/ShipRigTests.cs index fbad3ec05..657a2f03b 100644 --- a/tests/Aetheria.Shared.Tests/ShipRigTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipRigTests.cs @@ -209,13 +209,13 @@ public sealed class ShipRigTests : IDisposable private static string GlbJson(Node[] nodes) { - var text = new StringBuilder(@"{""asset"":{""version"":""2.0""},""meshes"":[{""primitives"":[{""attributes"":{""POSITION"":0}}]}],""nodes"":["); + var text = new StringBuilder(@"{""asset"":{""version"":""2.0""}," + ShipFixture.Geometry + @",""nodes"":["); for (var index = 0; index < nodes.Length; index++) { var node = nodes[index]; var kids = Enumerable.Range(0, nodes.Length).Where(child => nodes[child].Parent == node.Name).ToArray(); text.Append(index > 0 ? "," : "").Append($@"{{""name"":""{node.Name}"""); - if (node.Mesh) text.Append(@",""mesh"":0"); + if (node.Mesh) text.Append(node.Name.StartsWith("thruster") ? @",""mesh"":1" : @",""mesh"":0"); if (node.Id != null) text.Append($@",""extras"":{{""aetheria.id"":""{node.Id}""}}"); if (kids.Length > 0) text.Append(@",""children"":[" + string.Join(",", kids) + "]"); text.Append('}'); @@ -238,7 +238,7 @@ public sealed class ShipRigTests : IDisposable ship.Visual.Anchors.Single(anchor => anchor.Id == "gun").Joint = "wrist"; tweak?.Invoke(ship); }); - File.WriteAllBytes(Path.Combine(directory, "skiff.glb"), ShipFixture.Glb(GlbJson(nodes ?? RigNodes))); + File.WriteAllBytes(Path.Combine(directory, "skiff.glb"), ShipFixture.Glb(GlbJson(nodes ?? RigNodes), ShipFixture.MeshBytes())); return Path.Combine(directory, "ship.cc"); } @@ -348,7 +348,7 @@ public sealed class ShipRigTests : IDisposable public void NodeParentsAreTheNearestTaggedAncestorAndRootsHaveNone() { var path = Path.Combine(_directory.Path, "rig.glb"); - File.WriteAllBytes(path, ShipFixture.Glb(GlbJson(RigNodes))); + File.WriteAllBytes(path, ShipFixture.Glb(GlbJson(RigNodes), ShipFixture.MeshBytes())); var nodes = ShipModCatalog.ReadNodeIds(path); Assert.Equal(-1, nodes["arm"].Parent); Assert.Equal((int)nodes["arm"].Index, nodes["elbow"].Parent); diff --git a/tests/fixtures/mods/aetheria.wren/ship.glb b/tests/fixtures/mods/aetheria.wren/ship.glb index 03b70b729..08f3e5c7e 100644 --- a/tests/fixtures/mods/aetheria.wren/ship.glb +++ b/tests/fixtures/mods/aetheria.wren/ship.glb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:98bf1b4a0e19e67568930ca79b9d61529c21c63dd74ee8df3d3f1d419d3a81cc -size 6964 +oid sha256:3980ea88075b07bece2f64f315fde34bb7214ae0c9fb40d766556e12bb4b8a5a +size 5872 diff --git a/tools/AetherDb/ShipStarterCommand.cs b/tools/AetherDb/ShipStarterCommand.cs index 2a502a1f5..ebb3f4682 100644 --- a/tools/AetherDb/ShipStarterCommand.cs +++ b/tools/AetherDb/ShipStarterCommand.cs @@ -25,6 +25,9 @@ public static class ShipStarterCommand public float3 Position; // Box half-extents; null for an empty node. Scale is the node scale, used by the shield envelope. public float3? Half; + // A directional thruster emitter has one face, the (axis, sign) its exhaust leaves by in the Blender frame; a box with all six + // would fire exhaust both ways along the push. These drives push toward the bow (Reversed), so the exhaust leaves aft, +Y. + public (int Axis, int Sign)? Face; public float3? Scale; } @@ -43,8 +46,8 @@ public static class ShipStarterCommand new Part { Id = "collider", Role = "hull-collider", Half = new float3(3f, 5f, 1f) }, new Part { Id = "shield", Role = "shield", Scale = new float3(4f, 6f, 2.5f) }, new Part { Id = "tractor", Role = "tractor", Position = new float3(0f, -5f, 0f) }, - new Part { Id = "thruster.port", Role = "thruster-emitter", Mount = HardpointType.Thruster, Cell = new int2(0, 0), Size = new int2(2, 1), Position = new float3(2.2f, 5.4f, 0f), Half = new float3(.4f, .6f, .4f) }, - new Part { Id = "thruster.starboard", Role = "thruster-emitter", Mount = HardpointType.Thruster, Cell = new int2(2, 0), Size = new int2(2, 1), Position = new float3(-2.2f, 5.4f, 0f), Half = new float3(.4f, .6f, .4f) }, + new Part { Id = "thruster.port", Role = "thruster-emitter", Mount = HardpointType.Thruster, Cell = new int2(0, 0), Size = new int2(2, 1), Position = new float3(2.2f, 5.4f, 0f), Half = new float3(.4f, .6f, .4f), Face = (1, 1) }, + new Part { Id = "thruster.starboard", Role = "thruster-emitter", Mount = HardpointType.Thruster, Cell = new int2(2, 0), Size = new int2(2, 1), Position = new float3(-2.2f, 5.4f, 0f), Half = new float3(.4f, .6f, .4f), Face = (1, 1) }, new Part { Id = "radiator", Role = "radiator-mesh", Mount = HardpointType.Radiator, Cell = new int2(1, 1), Size = new int2(2, 1), Position = new float3(0f, 2f, 1.1f), Half = new float3(1.5f, .8f, .08f) }, new Part { Id = "gun.port", Role = "weapon-mount", Mount = HardpointType.Energy, Cell = new int2(0, 5), Position = new float3(1.8f, -3f, 1.1f) }, new Part { Id = "gun.port.muzzle", Role = "weapon-muzzle", Parent = "gun.port", Position = new float3(1.8f, -4f, 1.1f) }, @@ -125,8 +128,8 @@ public static class ShipStarterCommand var positions = new List<float>(); var normals = new List<float>(); var indices = new List<ushort>(); - // Six faces, outward normals, in the Blender frame; Gltf() turns each into glTF's. - foreach (var (axis, sign) in new[] { (0, 1), (0, -1), (1, 1), (1, -1), (2, 1), (2, -1) }) + // Six faces (one for a thruster emitter), outward normals, in the Blender frame; Gltf() turns each into glTF's. + foreach (var (axis, sign) in part.Face != null ? new[] { part.Face.Value } : new[] { (0, 1), (0, -1), (1, 1), (1, -1), (2, 1), (2, -1) }) { var u = (axis + 1) % 3; var v = (axis + 2) % 3; diff --git a/tools/blender/aetheria_ships/hull_source.py b/tools/blender/aetheria_ships/hull_source.py index 2d6d0ca16..99d15c615 100644 --- a/tools/blender/aetheria_ships/hull_source.py +++ b/tools/blender/aetheria_ships/hull_source.py @@ -14,7 +14,8 @@ with it (a hull that redefines or shadows an included language fails a check): lines ECHO line = [layer, cyclic, [[x, y, z], ...]] one line per kit part that draws one, points in the Ship Root frame (lowpoly.scad lp_line under lp_at frames); layer is one of KIT_LAYERS <zone> the zone's geometry, OFF; a donor's zone is named "<donor>:<zone>" - emit:<id>, rad:<id> the mesh of a thruster-emitter or radiator-mesh anchor + emit:<id>, rad:<id> the mesh of a thruster-emitter or radiator-mesh anchor; build() keeps of an emitter only the triangles + that face its exhaust (exhaust_face), so a closed box an author draws becomes its one exhaust-facing side marks OFF, a tiny cube at the first point of each kit line, drawn through the frame the geometry is drawn in (lp_line) Frame: Ship Root, metres, nose -Y, starboard -X, up +Z. build() also takes the hull's HullData.HullType ("Ship", @@ -183,6 +184,28 @@ def parse_off(text): return Mesh(vertices, tuple(triangles)) +def exhaust_face(mesh, yaw): + """The part of a thruster emitter's mesh that faces its exhaust, which leaves the way the anchor faces (its yaw: 0 the nose, + -Y; 90 port, +X): the triangles whose outward normal lies within 60 degrees of it, with the vertices they use. The + exhaust of a thruster is born along each triangle's normal of this mesh, so an emitter with a triangle facing the + other way fires along the push too: a directional thruster's emitter is one-sided. The hull source draws the surface + in whatever solid is convenient (a thin box); the closed sides drop here, and a mesh with no side facing the exhaust + is left empty, which the emitter-has-a-mesh check refuses. A future ring thruster, whose exhaust leaves radially, is a + different emitter with its own rule and does not come through here.""" + facing = (math.sin(math.radians(yaw)), -math.cos(math.radians(yaw))) + kept = [] + for a, b, c in mesh.triangles: + pa, pb, pc = mesh.vertices[a], mesh.vertices[b], mesh.vertices[c] + u, v = [pb[i] - pa[i] for i in range(3)], [pc[i] - pa[i] for i in range(3)] + normal = (u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]) + length = math.sqrt(sum(n * n for n in normal)) + if length > 0 and (normal[0] * facing[0] + normal[1] * facing[1]) / length > 0.5: + kept.append((a, b, c)) + used = sorted({i for tri in kept for i in tri}) + renumber = {old: new for new, old in enumerate(used)} + return Mesh(tuple(mesh.vertices[i] for i in used), tuple(tuple(renumber[i] for i in tri) for tri in kept)) + + def parse_echoes(text, name): """The values of every 'ECHO: <name> = <value>' line. OpenSCAD prints JSON-compatible values.""" values = [] @@ -439,6 +462,9 @@ def build(runner, library, hull_type, projector): if len(set(ids)) != len(ids) or any(a.role not in ANCHOR_ROLES for a in anchors): raise HullSourceError("The hull source's anchors repeat an id or name a role a hull source does not make") anchor_meshes = {a.id: parse_off(runner(MESH_ROLES[a.role] + a.id)[0]) for a in anchors if a.role in MESH_ROLES} + for a in anchors: + if a.role == "thruster-emitter": + anchor_meshes[a.id] = exhaust_face(anchor_meshes[a.id], a.yaw) kit_lines = read_lines(runner("lines")[1]) judge = donor or own body_zone = f"{donor.faction}:{donor.body}" if donor else own.body diff --git a/tools/blender/tests/smoke_hull_source.py b/tools/blender/tests/smoke_hull_source.py index a3676b0c7..3916eeefa 100644 --- a/tools/blender/tests/smoke_hull_source.py +++ b/tools/blender/tests/smoke_hull_source.py @@ -167,6 +167,8 @@ def make_ship(scene, fixture, ship_id, extent, length, rows): bpy.ops.aetheria.add_ship_hardpoint() hp = state.hardpoints[len(state.hardpoints) - 1] hp.mount_id, hp.kind, hp.x, hp.y, hp.footprint = mount_id, kind, x, y, "#" + if kind == THRUSTER: + hp.rotation = "2" # Reversed: the hull sources' drives sit at the stern, their emitters yawed 180 so the exhaust leaves aft result, message = run(bpy.ops.aetheria.save_ship_layout) require(result == {"FINISHED"}, f"Save was refused: {message}") package = MODS / ship_id @@ -586,7 +588,7 @@ def shared_ids_refused(scene, box, collection, ship_id, package, objects, number def check_poses(collection, root, runner): """Every built anchor stands where the hull source says in Ship Root's frame, turned as it says, and the emitter and - radiator meshes are the source's meshes in that frame.""" + radiator meshes are the source's meshes in that frame (an emitter's cut to the side that faces its exhaust).""" inverse = root.matrix_world.inverted() for anchor in hull_source.read_anchors(runner("anchors")[1]): obj = bpy.data.objects[anchor.id] @@ -599,7 +601,10 @@ def check_poses(collection, root, runner): f"{anchor.id} is turned {math.degrees(turn):.1f} degrees, not {anchor.yaw}") if anchor.role in hull_source.MESH_ROLES: made = sorted(tuple(round(c, 3) for c in (inverse @ obj.matrix_world @ v.co)) for v in obj.data.vertices) - wanted = sorted(tuple(round(c, 3) for c in v) for v in hull_source.parse_off(runner(hull_source.MESH_ROLES[anchor.role] + anchor.id)[0]).vertices) + source = hull_source.parse_off(runner(hull_source.MESH_ROLES[anchor.role] + anchor.id)[0]) + if anchor.role == "thruster-emitter": # Build keeps of an emitter only the side facing its exhaust + source = hull_source.exhaust_face(source, anchor.yaw) + wanted = sorted(tuple(round(c, 3) for c in v) for v in source.vertices) require(len(made) == len(wanted) and all(approx(a, b, 2e-3) for a, b in zip(made, wanted)), f"The mesh of {anchor.id} is not the source's mesh in Ship Root's frame") diff --git a/tools/blender/tests/smoke_mounts.py b/tools/blender/tests/smoke_mounts.py index 53418abb1..ee623537d 100644 --- a/tools/blender/tests/smoke_mounts.py +++ b/tools/blender/tests/smoke_mounts.py @@ -69,6 +69,14 @@ def quad(name, size): return mesh +def exhaust_quad(name, size): + """A thruster emitter for a hardpoint of Rotation None: an upright quad whose one side faces the nose (-Y), the way its exhaust leaves.""" + mesh = bpy.data.meshes.new(name) + half = size / 2 + mesh.from_pydata([(-half, 0, -half), (half, 0, -half), (half, 0, half), (-half, 0, half)], [], [(0, 1, 2, 3)]) + return mesh + + def tetrahedron(name): mesh = bpy.data.meshes.new(name) mesh.from_pydata([(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1)], [], [(0, 2, 1), (0, 1, 3), (0, 3, 2), (1, 2, 3)]) @@ -294,7 +302,7 @@ def main(): tag(new_object(collection, "Hull Collider", tetrahedron("Hull Collider"), parent=root), "hull-collider", "collider") tag(new_object(collection, "Shield", None, parent=root), "shield", "shield") tag(new_object(collection, "Tractor", None, (0, 2, 0), root), "tractor", "tractor") - disc = new_object(collection, "Thruster", quad("Thruster", 0.4), (0, 8, 0), root) + disc = new_object(collection, "Thruster", exhaust_quad("Thruster", 0.4), (0, 8, 0), root) tag(disc, "thruster-emitter", "thruster") for mount, kind, x, y in (("thruster", "3", 2, 0), ("reactor.a", "5", 2, 2)): bpy.ops.aetheria.add_ship_hardpoint() diff --git a/tools/blender/tests/smoke_package.py b/tools/blender/tests/smoke_package.py index 886c349e2..6d0322dea 100644 --- a/tools/blender/tests/smoke_package.py +++ b/tools/blender/tests/smoke_package.py @@ -53,6 +53,14 @@ def quad(name, size=1.0): return mesh +def exhaust_quad(name, size): + """A thruster emitter for a hardpoint of Rotation None: an upright quad whose one side faces the nose (-Y), the way its exhaust leaves.""" + mesh = bpy.data.meshes.new(name) + half = size / 2 + mesh.from_pydata([(-half, 0, -half), (half, 0, -half), (half, 0, half), (-half, 0, half)], [], [(0, 1, 2, 3)]) + return mesh + + def tagged(collection, name, data, role=None, anchor_id=None, location=(0, 0, 0), parent=None): obj = bpy.data.objects.new(name, data) obj.location = location @@ -345,7 +353,7 @@ def main(): tagged(ship, "Hull Collider", tetrahedron("Hull Collider"), "hull-collider", "collider") tagged(ship, "Shield", None, "shield", "shield") tagged(ship, "Tractor", None, "tractor", "tractor", (0, 2, 0)) - disc = tagged(ship, "Thruster", quad("Thruster", 0.4), "thruster-emitter", "thruster", (0, -1, 0)) + disc = tagged(ship, "Thruster", exhaust_quad("Thruster", 0.4), "thruster-emitter", "thruster", (0, -1, 0)) gun = tagged(ship, "Gun", None, "weapon-mount", "gun", (1, 0, 0)) tagged(ship, "Gun Muzzle", None, "weapon-muzzle", "gun.muzzle", (0, 0.5, 0), parent=gun) tagged(ship, "Radiator", quad("Radiator", 0.5), "radiator-mesh", "radiator", (-1, 0, 0)) diff --git a/tools/blender/tests/test_hull_source.py b/tools/blender/tests/test_hull_source.py index e77ec11b2..9cd7f21c9 100644 --- a/tools/blender/tests/test_hull_source.py +++ b/tools/blender/tests/test_hull_source.py @@ -28,7 +28,7 @@ SECRET = "SECRET-NAME-7" # a value a hull source supplies and no refusal may ec def box(x0, x1, y0, y1, z0, z1): """An OFF text for an axis-aligned box: 8 vertices, 6 quads (12 triangles once fanned).""" v = [(x, y, z) for z in (z0, z1) for y in (y0, y1) for x in (x0, x1)] - quads = [(0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3)] + quads = [(0, 2, 3, 1), (4, 5, 7, 6), (0, 1, 5, 4), (2, 6, 7, 3), (0, 4, 6, 2), (1, 3, 7, 5)] # outward, counter-clockwise from outside rows = ["OFF", "8 6 0"] + [f"{x} {y} {z}" for x, y, z in v] + [f"4 {a} {b} {c} {d}" for a, b, c, d in quads] return "\n".join(rows) @@ -339,9 +339,9 @@ class JudgementTests(unittest.TestCase): self.assertEqual(fixture.failed(), ["the triangle count lies inside the brief's budget"], budget) def test_the_budget_counts_the_triangles_of_the_emitter_meshes_too(self): - # 12 + 12 triangles of zones, 12 of the emitter: a budget of 30 holds without the emitter and not with it + # 12 + 12 triangles of zones, 2 of the emitter (its exhaust-facing side): a budget of 25 holds without it and not with it fixture = Fixture() - fixture.parts["brief"] = ("", brief(triangles=(10, 30))) + fixture.parts["brief"] = ("", brief(triangles=(10, 25))) self.assertEqual(fixture.failed(), ["the triangle count lies inside the brief's budget"]) def test_the_length_is_a_range_with_two_ends(self): @@ -385,6 +385,38 @@ class JudgementTests(unittest.TestCase): fixture.parts["emit:Th.A"] = ("", "") self.assertEqual(fixture.failed(), ["every emitter and radiator anchor has a mesh"]) + @staticmethod + def _normals(mesh): + """The unit outward normal of each triangle.""" + out = [] + for a, b, c in mesh.triangles: + pa, pb, pc = (mesh.vertices[i] for i in (a, b, c)) + u, v = [pb[i] - pa[i] for i in range(3)], [pc[i] - pa[i] for i in range(3)] + n = (u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]) + length = sum(x * x for x in n) ** 0.5 + out.append(tuple(round(x / length) for x in n)) + return out + + def test_an_emitter_keeps_only_the_side_that_faces_its_exhaust(self): + # The thin box the hull source draws is closed; its exhaust leaves the way the anchor faces (yaw 180 aft, +Y; yaw 90 + # port, +X; yaw 0 the nose, -Y), and only the triangles facing that way are the emitter. + for yaw, thin, facing in ((180, (5, 5.1, "y"), (0, 1, 0)), (0, (5, 5.1, "y"), (0, -1, 0)), (90, (5, 5.1, "x"), (1, 0, 0))): + fixture = Fixture() + fixture.parts["anchors"] = ("", echo("anchor", ["Gun.A", "weapon-mount", [0, 0, 3], 0, ""]) + + echo("anchor", ["Gun.A.muzzle", "weapon-muzzle", [0, -3, 3], 0, "Gun.A"]) + + echo("anchor", ["Th.A", "thruster-emitter", [1, 5, 1], yaw, ""])) + fixture.parts["emit:Th.A"] = (box(5, 5.1, 1, 2, 0.5, 1.5) if thin[2] == "x" else box(0.5, 1.5, 5, 5.1, 0.5, 1.5), "") + mesh = fixture.build().anchor_meshes["Th.A"] + self.assertEqual(len(mesh.triangles), 2, yaw) + self.assertEqual(set(self._normals(mesh)), {facing}, yaw) + + def test_an_emitter_with_no_side_facing_its_exhaust_is_refused(self): + # A single quad that faces the push, not the exhaust, has nothing left once the wrong side is dropped. + fixture = Fixture() + quad_toward_push = "OFF\n4 1 0\n0.5 5 0.5\n1.5 5 0.5\n1.5 5 1.5\n0.5 5 1.5\n4 0 1 2 3" # normal -Y, anchor exhaust +Y + fixture.parts["emit:Th.A"] = (quad_toward_push, "") + self.assertEqual(fixture.failed(), ["every emitter and radiator anchor has a mesh"]) + def test_the_collider_zone_is_the_languages_body(self): self.assertEqual(Fixture().build().body_zone, "primary") From a8ccfac6f17ac16d527867cab59a7670f4864967 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Thu, 19 Nov 2026 19:57:38 +0100 Subject: [PATCH 113/190] Soul fixes for the emitter gate: refuse-side tests, normal matrix, geometry-hiding extensions only, one quarter-turn authority The tests now cover the dot == 0 and tilted cases, vertex normals against the winding, a mirrored node and a non-uniform scale, and allowed and refused extensions. Vertex normals take the inverse transpose of the node's world matrix. Only KHR_draco_mesh_compression and EXT_meshopt_compression, which store geometry the gate cannot read, are refused; other extensions pass. The generator refuses a thruster emitter yaw that is not a quarter turn, so the gate's four-direction Rotation is the one authority for which way an emitter faces. An emitter anchor with no thruster hardpoint stays skipped in the gate: ShipAuthoringStore.Validate already refuses it before Bind. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/ShipModCatalog.cs | 14 ++- .../ShipEmitterExhaustTests.cs | 100 ++++++++++++++++++ tools/blender/aetheria_ships/hull_source.py | 4 + tools/blender/tests/test_hull_source.py | 9 ++ 4 files changed, 125 insertions(+), 2 deletions(-) diff --git a/Assets/Scripts/ServerShared/ShipModCatalog.cs b/Assets/Scripts/ServerShared/ShipModCatalog.cs index 6d509f011..91bbc296d 100644 --- a/Assets/Scripts/ServerShared/ShipModCatalog.cs +++ b/Assets/Scripts/ServerShared/ShipModCatalog.cs @@ -308,6 +308,8 @@ public static class ShipModCatalog foreach (var anchor in emitters) { var hardpoint = hull.Hardpoints.FirstOrDefault(candidate => candidate.Type == HardpointType.Thruster && candidate.Transform == anchor.Id); + // An emitter anchor with no thruster hardpoint is already a package fault: ShipAuthoringStore.Validate (run by Read and + // PackageOf before Bind) refuses a mount-role anchor that is not the mount of a hardpoint of its type. if (hardpoint == null) continue; var facing = hardpoint.Rotation.Direction(); // The model's frame is glTF's, nose toward +Z and port toward +X (the Blender kit's nose at -Y and port at +X, @@ -353,7 +355,9 @@ public static class ShipModCatalog foreach (var primitive in (JArray)_json["meshes"][meshIndex.Value]["primitives"]) { var attributes = (JObject)primitive["attributes"]; - if (primitive["extensions"] != null) throw Unreadable($"mesh {meshIndex} uses a primitive extension"); + if (primitive["extensions"] is JObject extensions && extensions.Properties().Any(p => HidesGeometry(p.Name))) + throw Unreadable($"mesh {meshIndex} is compressed by {extensions.Properties().First(p => HidesGeometry(p.Name)).Name}"); + var normalMatrix = Matrix4x4.Invert(world, out var inverse) ? Matrix4x4.Transpose(inverse) : throw Unreadable($"node {node} has a transform that cannot be inverted"); var positions = Vectors((int)attributes["POSITION"]).Select(point => Vector3.Transform(point, world)).ToArray(); var indices = primitive["indices"] == null ? Enumerable.Range(0, positions.Length).ToArray() : Indices((int)primitive["indices"]); for (var i = 0; i + 2 < indices.Length; i += 3) @@ -364,7 +368,7 @@ public static class ShipModCatalog } if (attributes["NORMAL"] != null) foreach (var normal in Vectors((int)attributes["NORMAL"])) - if (normal.LengthSquared() > 1e-12f) yield return Vector3.Normalize(Vector3.TransformNormal(normal, world)); + if (normal.LengthSquared() > 1e-12f) yield return Vector3.Normalize(Vector3.TransformNormal(normal, normalMatrix)); } } @@ -406,6 +410,8 @@ public static class ShipModCatalog var a = (JObject)_json["accessors"][accessor]; if (a["sparse"] != null || a["bufferView"] == null) throw Unreadable($"accessor {accessor} is sparse or has no buffer view"); var view = (JObject)_json["bufferViews"][(int)a["bufferView"]]; + if (view["extensions"] is JObject viewExtensions && viewExtensions.Properties().Any(p => HidesGeometry(p.Name))) + throw Unreadable($"accessor {accessor} is compressed by {viewExtensions.Properties().First(p => HidesGeometry(p.Name)).Name}"); var component = (int)a["componentType"]; var type = (string)a["type"]; var width = (component == 5126 || component == 5125 ? 4 : component == 5123 ? 2 : 1) * (type == "VEC3" ? 3 : 1); @@ -442,6 +448,10 @@ public static class ShipModCatalog return result; } + // The extensions that store geometry in a form this reader does not decode; any other (materials, variants) leaves the + // positions and normals where the accessors say. + private static bool HidesGeometry(string extension) => extension == "KHR_draco_mesh_compression" || extension == "EXT_meshopt_compression"; + private InvalidOperationException Unreadable(string reason) => new InvalidOperationException($"{_path}: emitter geometry is unreadable: {reason}."); } diff --git a/tests/Aetheria.Shared.Tests/ShipEmitterExhaustTests.cs b/tests/Aetheria.Shared.Tests/ShipEmitterExhaustTests.cs index 466ee8837..edb0ac8b2 100644 --- a/tests/Aetheria.Shared.Tests/ShipEmitterExhaustTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipEmitterExhaustTests.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Linq; +using Newtonsoft.Json.Linq; using Xunit; // A directional thruster's emitter mesh is the surface its exhaust is born from, along each triangle's normal, so every @@ -67,4 +68,103 @@ public sealed class ShipEmitterExhaustTests : IDisposable foreach (var ship in new[] { Path.Combine("GameData", "Mods", "aetheria.nakovalnya"), Path.Combine("tests", "fixtures", "mods", "aetheria.wren") }) Assert.NotNull(ShipModCatalog.ReadPackage(Path.Combine(root, ship, "ship.cc"))); } + + // The fixture package whose thruster node carries a mesh of the test's own (a third mesh appended to the BIN chunk), with + // optional vertex normals, an edit to the node, and an edit to the primitive. The thruster's Rotation is None: the exhaust + // leaves toward +Z and the push is -Z. + private string WriteCustom(float[] positions, ushort[] indices, float[] normals = null, Action<JObject> node = null, Action<JObject> primitive = null) + { + ShipFixture.WritePackage(_directory.Path, "mod.skiff"); + var json = JObject.Parse(ShipFixture.GlbJson(ShipFixture.Nodes)); + var bin = ShipFixture.MeshBytes().ToList(); + int View(byte[] bytes) + { + while (bin.Count % 4 != 0) bin.Add(0); + ((JArray)json["bufferViews"]).Add(new JObject { ["buffer"] = 0, ["byteOffset"] = bin.Count, ["byteLength"] = bytes.Length }); + bin.AddRange(bytes); + return ((JArray)json["bufferViews"]).Count - 1; + } + int Accessor(int view, int component, int count, string type) + { + ((JArray)json["accessors"]).Add(new JObject { ["bufferView"] = view, ["componentType"] = component, ["count"] = count, ["type"] = type }); + return ((JArray)json["accessors"]).Count - 1; + } + var attributes = new JObject { ["POSITION"] = Accessor(View(positions.SelectMany(BitConverter.GetBytes).ToArray()), 5126, positions.Length / 3, "VEC3") }; + if (normals != null) attributes["NORMAL"] = Accessor(View(normals.SelectMany(BitConverter.GetBytes).ToArray()), 5126, normals.Length / 3, "VEC3"); + var made = new JObject { ["attributes"] = attributes, ["indices"] = Accessor(View(indices.SelectMany(BitConverter.GetBytes).ToArray()), 5123, indices.Length, "SCALAR") }; + primitive?.Invoke(made); + ((JArray)json["meshes"]).Add(new JObject { ["primitives"] = new JArray(made) }); + var thruster = json["nodes"].Single(n => (string)n["name"] == "thruster-port"); + thruster["mesh"] = ((JArray)json["meshes"]).Count - 1; + node?.Invoke((JObject)thruster); + json["buffers"][0]["byteLength"] = bin.Count + (4 - bin.Count % 4) % 4; + File.WriteAllBytes(Path.Combine(_directory.Path, "mod.skiff", "skiff.glb"), ShipFixture.Glb(json.ToString(Newtonsoft.Json.Formatting.None), bin.ToArray())); + return Thruster; + } + + private static readonly ushort[] Quad = { 0, 1, 2, 0, 2, 3 }; + + // A unit quad with counter-clockwise normal n (in the XZ plane's span: n = (sin a, 0, cos a)), a measured from +Z. + private static float[] Plane(double degrees) + { + var (s, c) = (Math.Sin(degrees * Math.PI / 180), Math.Cos(degrees * Math.PI / 180)); + var t = new[] { (float)c, 0f, (float)-s }; + return new[] { 0f, 0f, 0f, t[0], 0f, t[2], t[0], 1f, t[2], 0f, 1f, 0f }; + } + + private static float[] Repeat(float x, float y, float z) => Enumerable.Repeat(new[] { x, y, z }, 4).SelectMany(v => v).ToArray(); + + private bool Accepts(string ship) + { + try { ShipModCatalog.ReadPackage(ship); return true; } + catch (InvalidOperationException error) when (error.Message.Contains("thruster emitter thruster.port")) { return false; } + } + + [Theory] + [InlineData(0, true), InlineData(60, true), InlineData(-60, true), InlineData(89, true), InlineData(-89, true), + InlineData(91, false), InlineData(-91, false), InlineData(120, false), InlineData(180, false)] + public void ATiltedEmitterIsJudgedByItsDotWithThePush(double degrees, bool accepted) => + Assert.Equal(accepted, Accepts(WriteCustom(Plane(degrees), Quad))); + + [Fact] + public void VertexNormalsThatContradictTheWindingAreRefused() + { + // Unity's Mesh Renderer shape emits along the vertex normals, so a face wound toward the exhaust is not enough. + Assert.True(Accepts(WriteCustom(Plane(0), Quad, Repeat(0, 0, 1)))); + Assert.False(Accepts(WriteCustom(Plane(0), Quad, Repeat(0, 0, -1)))); + Assert.False(Accepts(WriteCustom(Plane(0), Quad, Repeat(1, 0, 0)))); + } + + [Fact] + public void AMirroredNodeFlipsTheWindingAndIsJudgedByWhatItDrawsNotWhatItIsWound() + { + // Scaled -1 in X the quad's winding reverses in the world, so glTF's front face is the other one. + Action<JObject> mirror = node => node["scale"] = new JArray(-1, 1, 1); + Assert.True(Accepts(WriteCustom(Plane(0), Quad, node: mirror))); + Assert.False(Accepts(WriteCustom(Plane(180), Quad, node: mirror))); + } + + [Fact] + public void VertexNormalsFollowTheInverseTransposeUnderNonUniformScale() + { + // A quarter turn's eighth about Y over a stretch of 4 in X: the plane with local normal (1,0,1) keeps a normal toward + // +Z (0.75 of it), where transforming the normal like a position would send it toward -Z. + Action<JObject> stretched = node => { node["scale"] = new JArray(4, 1, 1); node["rotation"] = new JArray(0, 0.3826834f, 0, 0.9238795f); }; + var tangent = (float)(1 / Math.Sqrt(2)); + var positions = new[] { 0f, 0f, 0f, tangent, 0f, -tangent, tangent, 1f, -tangent, 0f, 1f, 0f }; + Assert.True(Accepts(WriteCustom(positions, Quad, Repeat(tangent, 0, tangent), stretched))); + } + + [Fact] + public void OnlyExtensionsThatHideGeometryAreRefused() + { + Assert.True(Accepts(WriteCustom(Plane(0), Quad, primitive: p => p["extensions"] = JObject.Parse(@"{""KHR_materials_variants"":{""mappings"":[]}}")))); + var compressed = WriteCustom(Plane(0), Quad, primitive: p => p["extensions"] = JObject.Parse(@"{""KHR_draco_mesh_compression"":{""bufferView"":0,""attributes"":{""POSITION"":0}}}")); + Assert.Contains("compressed by KHR_draco_mesh_compression", Assert.Throws<InvalidOperationException>(() => ShipModCatalog.ReadPackage(compressed)).Message); + } + + [Fact] + public void ASidewaysEmitterWhoseNormalIsPerpendicularToThePushIsRefused() => + // Normal exactly +X, dot with the push exactly 0: the rule is non-negative, so it fires along the axis it is not meant to. + Assert.False(Accepts(WriteCustom(new[] { 0f, 0f, 0f, 0f, 1f, 0f, 0f, 1f, 1f, 0f, 0f, 1f }, Quad))); } diff --git a/tools/blender/aetheria_ships/hull_source.py b/tools/blender/aetheria_ships/hull_source.py index 99d15c615..4c7771e94 100644 --- a/tools/blender/aetheria_ships/hull_source.py +++ b/tools/blender/aetheria_ships/hull_source.py @@ -464,6 +464,10 @@ def build(runner, library, hull_type, projector): anchor_meshes = {a.id: parse_off(runner(MESH_ROLES[a.role] + a.id)[0]) for a in anchors if a.role in MESH_ROLES} for a in anchors: if a.role == "thruster-emitter": + # The hardpoint Rotation the catalog gate judges the emitter against is one of four directions, so the one authority + # for which way an emitter faces is a quarter turn; a source that turns one otherwise is refused here, not rounded. + if abs(a.yaw / 90 - round(a.yaw / 90)) > 1e-6: + raise HullSourceError("The hull source turns a thruster emitter by something other than a quarter turn") anchor_meshes[a.id] = exhaust_face(anchor_meshes[a.id], a.yaw) kit_lines = read_lines(runner("lines")[1]) judge = donor or own diff --git a/tools/blender/tests/test_hull_source.py b/tools/blender/tests/test_hull_source.py index 9cd7f21c9..ce78c313f 100644 --- a/tools/blender/tests/test_hull_source.py +++ b/tools/blender/tests/test_hull_source.py @@ -410,6 +410,15 @@ class JudgementTests(unittest.TestCase): self.assertEqual(len(mesh.triangles), 2, yaw) self.assertEqual(set(self._normals(mesh)), {facing}, yaw) + def test_an_emitter_turned_off_a_quarter_turn_is_refused(self): + # The gate knows four directions (a hardpoint Rotation); an emitter yawed 45 degrees has none, so it is not rounded. + fixture = Fixture() + fixture.parts["anchors"] = ("", echo("anchor", ["Gun.A", "weapon-mount", [0, 0, 3], 0, ""]) + + echo("anchor", ["Gun.A.muzzle", "weapon-muzzle", [0, -3, 3], 0, "Gun.A"]) + + echo("anchor", ["Th.A", "thruster-emitter", [1, 5, 1], 45, ""])) + with self.assertRaises(hs.HullSourceError): + fixture.build() + def test_an_emitter_with_no_side_facing_its_exhaust_is_refused(self): # A single quad that faces the push, not the exhaust, has nothing left once the wrong side is dropped. fixture = Fixture() From a3c492d54fb1d28744ebb0c06ab8dd5692407a24 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Thu, 19 Nov 2026 20:39:45 +0100 Subject: [PATCH 114/190] Pin that a compressed bufferView under an emitter's accessor is refused Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../ShipEmitterExhaustTests.cs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/Aetheria.Shared.Tests/ShipEmitterExhaustTests.cs b/tests/Aetheria.Shared.Tests/ShipEmitterExhaustTests.cs index edb0ac8b2..e3af827dc 100644 --- a/tests/Aetheria.Shared.Tests/ShipEmitterExhaustTests.cs +++ b/tests/Aetheria.Shared.Tests/ShipEmitterExhaustTests.cs @@ -167,4 +167,22 @@ public sealed class ShipEmitterExhaustTests : IDisposable public void ASidewaysEmitterWhoseNormalIsPerpendicularToThePushIsRefused() => // Normal exactly +X, dot with the push exactly 0: the rule is non-negative, so it fires along the axis it is not meant to. Assert.False(Accepts(WriteCustom(new[] { 0f, 0f, 0f, 0f, 1f, 0f, 0f, 1f, 1f, 0f, 0f, 1f }, Quad))); + + [Theory] + [InlineData("KHR_draco_mesh_compression"), InlineData("EXT_meshopt_compression")] + public void AnAccessorWhoseBufferViewIsCompressedIsRefused(string extension) + { + // The compression sits on the bufferView, not the primitive: the accessor's bytes are not positions. + var path = WriteCustom(Plane(0), Quad); + var glb = Path.Combine(_directory.Path, "mod.skiff", "skiff.glb"); + var bytes = File.ReadAllBytes(glb); + var length = (int)BitConverter.ToUInt32(bytes, 12); + var json = JObject.Parse(System.Text.Encoding.UTF8.GetString(bytes, 20, length)); + var views = (JArray)json["bufferViews"]; + var positions = (int)json["accessors"][(int)json["meshes"].Last["primitives"][0]["attributes"]["POSITION"]]["bufferView"]; + views[positions]["extensions"] = JObject.Parse("{\"" + extension + "\":{}}"); + var bin = bytes.Skip(28 + length).ToArray(); + File.WriteAllBytes(glb, ShipFixture.Glb(json.ToString(Newtonsoft.Json.Formatting.None), bin)); + Assert.Contains("compressed by " + extension, Assert.Throws<InvalidOperationException>(() => ShipModCatalog.ReadPackage(path)).Message); + } } From 5ea472fce29b9d278ac3a42df5e3b4458177aa3f Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Thu, 19 Nov 2026 19:48:46 +0100 Subject: [PATCH 115/190] Import Ghostlight c43eb54 synchronous kernel set as native/aetherlight Verbatim copy of lib, action, clock, journal, grammar (+tests), lens, cover, import_key_tests, patch (lines 1-6059 and 7906-9606) and the base_world fixtures, with the pruned Cargo.toml/Cargo.lock and a gitignore line for the target dir. native/aetherlight/.gitattributes pins `-text` so the verbatim bytes survive autocrlf checkouts. lib.rs still names the leave-set modules, so this commit does not build; the next commit makes it compile. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .gitignore | 1 + native/aetherlight/.gitattributes | 2 + native/aetherlight/Cargo.lock | 794 + native/aetherlight/Cargo.toml | 24 + native/aetherlight/src/action.rs | 2858 +++ native/aetherlight/src/clock.rs | 213 + native/aetherlight/src/cover.rs | 1105 + native/aetherlight/src/grammar.rs | 209 + native/aetherlight/src/grammar/tests.rs | 745 + native/aetherlight/src/import_key_tests.rs | 752 + native/aetherlight/src/journal.rs | 2990 +++ native/aetherlight/src/lens.rs | 379 + native/aetherlight/src/lib.rs | 19173 ++++++++++++++++ native/aetherlight/src/patch.rs | 7760 +++++++ .../aetherlight/tests/fixtures/base_world.cc | Bin 0 -> 557056 bytes .../tests/fixtures/base_world.digests | 3 + .../aetherlight/tests/fixtures/base_world.id | 1 + 17 files changed, 37009 insertions(+) create mode 100644 native/aetherlight/.gitattributes create mode 100644 native/aetherlight/Cargo.lock create mode 100644 native/aetherlight/Cargo.toml create mode 100644 native/aetherlight/src/action.rs create mode 100644 native/aetherlight/src/clock.rs create mode 100644 native/aetherlight/src/cover.rs create mode 100644 native/aetherlight/src/grammar.rs create mode 100644 native/aetherlight/src/grammar/tests.rs create mode 100644 native/aetherlight/src/import_key_tests.rs create mode 100644 native/aetherlight/src/journal.rs create mode 100644 native/aetherlight/src/lens.rs create mode 100644 native/aetherlight/src/lib.rs create mode 100644 native/aetherlight/src/patch.rs create mode 100644 native/aetherlight/tests/fixtures/base_world.cc create mode 100644 native/aetherlight/tests/fixtures/base_world.digests create mode 100644 native/aetherlight/tests/fixtures/base_world.id diff --git a/.gitignore b/.gitignore index ac9c49142..8f15133d1 100644 --- a/.gitignore +++ b/.gitignore @@ -113,3 +113,4 @@ tests/_scratch_* # Stryker.NET mutation reports (regenerated per run) StrykerOutput/ +native/aetherlight/target/ diff --git a/native/aetherlight/.gitattributes b/native/aetherlight/.gitattributes new file mode 100644 index 000000000..14b915993 --- /dev/null +++ b/native/aetherlight/.gitattributes @@ -0,0 +1,2 @@ +# Verbatim fork of Ghostlight: bytes are the contract (digests, fixtures). No newline conversion. +* -text diff --git a/native/aetherlight/Cargo.lock b/native/aetherlight/Cargo.lock new file mode 100644 index 000000000..d79ad2fc6 --- /dev/null +++ b/native/aetherlight/Cargo.lock @@ -0,0 +1,794 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aetherlight" +version = "0.1.0" +dependencies = [ + "chrono", + "cultcache-rs", + "rmp-serde", + "serde", + "serde_json", + "sha2", + "tempfile", + "thiserror", + "unicode-normalization", + "unicode-properties", + "uuid", +] + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bitflags" +version = "2.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "cc" +version = "1.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "509591b7bcd67f4ef775afad7662703b4935daaa6ec0e5605cfb1090b32a2b6d" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "cultcache-rs" +version = "0.1.0" +source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a0199a064526427150191#85f7024a35ea42cf9f0a0199a064526427150191" +dependencies = [ + "anyhow", + "chrono", + "cultcache-rs-derive", + "fs2", + "redb", + "rmp-serde", + "serde", + "serde_bytes", + "serde_json", + "uuid", + "windows-sys 0.59.0", +] + +[[package]] +name = "cultcache-rs-derive" +version = "0.1.0" +source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a0199a064526427150191#85f7024a35ea42cf9f0a0199a064526427150191" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890" + +[[package]] +name = "fs2" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "redb" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e925444704b5f17d32bf42f5b6e2df050bceebc3dcd6e71cc73dafe8092e839" +dependencies = [ + "libc", +] + +[[package]] +name = "rmp" +version = "0.8.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ba8be72d372b2c9b35542551678538b562e7cf86c3315773cae48dfbfe7790c" +dependencies = [ + "num-traits", +] + +[[package]] +name = "rmp-serde" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f81bee8c8ef9b577d1681a70ebbc962c232461e397b22c208c43c04b67a155" +dependencies = [ + "rmp", + "serde", +] + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_bytes" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "tinyvec" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-normalization" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" + +[[package]] +name = "uuid" +version = "1.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cefc03fd367c0c6d4305de1b312cf00248c4114f4a0418ce6a6af769e3b0bd9" +dependencies = [ + "getrandom", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-bindgen" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.119", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/native/aetherlight/Cargo.toml b/native/aetherlight/Cargo.toml new file mode 100644 index 000000000..ec8f9d37e --- /dev/null +++ b/native/aetherlight/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "aetherlight" +version = "0.1.0" +edition = "2024" +license = "MIT" +publish = false + +# Its own workspace: the crate builds on its own, outside any parent manifest. +[workspace] + +[dependencies] +chrono = { version = "0.4", features = ["serde"] } +cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "85f7024a35ea42cf9f0a0199a064526427150191", package = "cultcache-rs" } +rmp-serde = "1.3" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +sha2 = "0.10" +thiserror = "2" +unicode-normalization = "0.1.25" +unicode-properties = "0.1.4" +uuid = { version = "1", features = ["v4", "serde"] } + +[dev-dependencies] +tempfile = "3" diff --git a/native/aetherlight/src/action.rs b/native/aetherlight/src/action.rs new file mode 100644 index 000000000..bbfddae96 --- /dev/null +++ b/native/aetherlight/src/action.rs @@ -0,0 +1,2858 @@ +//! The invocation pipeline: catalog lookup, role binding, precondition +//! evaluation, effect-ceiling checking, band selection, and lowering. +//! +//! One entry point, [`exercise`], reached from `reduce`'s `ExerciseDecision` arm +//! and from `apply_effect`'s `DecisionExercised` arm, so a forged effect is +//! re-derived by the same function that produced the honest one. Nothing else +//! draws a band, and the draw goes through the one `digest()` owner. + +use super::patch::{ + self, Affordance, Audience, AudienceSpec, BoundPrecondition, Bounds, ComponentOpKind, Cost, + Precondition, Quantity, RefKind, Role, WorldPatch, +}; +use super::{ + AffordanceId, AuthorityGrant, AuthorityTarget, CommandId, DecisionEvent, DecisionInvocation, + DecisionOpportunity, EdgeId, EntityId, EventId, FictionalMinutes, GrantedAffordance, + KernelError, Magnitude, SubjectId, Target, WorldId, WorldState, digest, +}; +use serde::Serialize; +use std::collections::{BTreeMap, BTreeSet}; + +/// The complete failure set of one affordance invocation. Sorted and complete +/// like `Mismatch`, and like it never serialized: it states the affordance +/// contract, which no commit records. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum ActionMismatch { + UnboundRole { + role: Role, + }, + UnknownRole { + role: Role, + }, + DuplicateRoleBinding { + role: Role, + }, + UnknownTarget { + role: Role, + }, + TargetKindMismatch { + role: Role, + expected: RefKind, + actual: RefKind, + }, + ActorNotPresent { + precondition: usize, + }, + TargetUnreachable { + precondition: usize, + }, + InsufficientHolding { + precondition: usize, + }, + SlotNotProposed { + slot: usize, + }, + UnknownSlot { + slot: usize, + }, + DuplicateSlotProposal { + slot: usize, + }, + MagnitudeShapeMismatch { + slot: usize, + }, + MagnitudeOverCeiling { + slot: usize, + }, + ZeroMagnitude { + slot: usize, + }, + SpeechRequired, + SpeechNotCarried, + EmptySpeech, + EmptyDisplay, + /// The acting subject's effective authority covers no such target under + /// this kind. A target that walked out of the jurisdiction while the + /// proposal was in flight arrives here, not as a rebind: what the actor is + /// authorized over is in the digest, the world it reaches is not. + NotAuthorized { + precondition: usize, + }, + /// No forum takes this grievance, or its standing does not reach the actor. + NoStanding { + precondition: usize, + }, + /// An invocation bound the reserved `actor` role. + ActorRoleBound, + /// A slot would grant authority the acting subject does not itself hold + /// over that ground. Without this, any holder mints unlimited authority in + /// one step and the whole component is decorative. + DelegationNotMonotone { + slot: usize, + }, + /// The actor does not hold the bound fact at the required confidence. A + /// re-appraisal that lowered its own confidence while the proposal was in + /// flight arrives here rather than as a rebind: confidence is admission-only. + FactUnknown { + precondition: usize, + }, + /// The actor has no audience at all: unplaced for co-location, or outside a + /// channel it does not control. + NoAudience { + precondition: usize, + }, + /// The addressed subject is not inside that audience. A target that walked + /// out of the room while the proposal was in flight arrives here: the + /// preimage holds what the actor *is*, not the world it reaches. + CannotReach { + precondition: usize, + }, + /// The actor holds no commitment of that kind to the bound referent. + NotCommitted { + precondition: usize, + }, +} + +/// The band draw's whole preimage. Five fields, none of them from the +/// invocation's payload: the proposer varies the attempt and cannot vary the +/// draw. `affordance` is the id carried by the kernel-verified grant, so the +/// draw cannot be steered by an affordance the scope does not hold. +#[derive(Serialize)] +struct BandPreimage { + world_id: WorldId, + revision: u64, + command_id: CommandId, + affordance: AffordanceId, + band_count: usize, +} + +/// Catalog lookup, binding, admission, draw, lowering, event. Stages 1 through 4 +/// accumulate one complete rejection set and return it sorted before anything is +/// drawn or lowered, so nothing past the gate can fail on caller input. +/// +/// The entry arrives as a [`GrantedAffordance`], which only `require_granted` +/// can build: the grant check is the type, not a call a third caller might +/// forget. Nothing here reads `invocation.affordance`. +pub(super) fn exercise( + state: &WorldState, + command_id: CommandId, + current: &DecisionOpportunity, + granted: &GrantedAffordance<'_>, + invocation: &DecisionInvocation, +) -> Result<DecisionEvent, KernelError> { + let entry = granted.entry; + let actor = current.scope.subject_id; + let mut rejections = Vec::new(); + + let components = super::scope_components(state, actor); + let authority = super::effective_authority(&components.authority, &components.delegated); + let bindings = bind_roles(state, actor, entry, invocation, &mut rejections); + check_preconditions(state, actor, &authority, entry, &bindings, &mut rejections); + check_proposals(entry, invocation, &mut rejections); + check_delegation(state, &authority, entry, &bindings, &mut rejections); + + if !rejections.is_empty() { + rejections.sort(); + return Err(KernelError::ActionRejected(rejections)); + } + + let band = select_band(state, command_id, granted.id, entry)?; + let operations = lower(entry, band, actor, state.now, invocation, &bindings)?; + let mut effects = if operations.is_empty() { + Vec::new() + } else { + // The same resolver, the same per-operation preconditions, the same + // conservation equation the declaration lane passes. + patch::resolve_patch( + state, + command_id, + &WorldPatch { + declarations: Vec::new(), + operations, + evidence: Vec::new(), + }, + None, + None, + ) + .map_err(KernelError::PatchRejected)? + .operations + }; + + // The speech lowering: kernel-owned, not a slot, and unreachable by any + // proposer, band, or effect ceiling. The audience comes from the entry's one + // speech precondition, so a world's `whisper` and `proclaim` lower through + // the same two operations with a different audience and the kernel learns no + // genre. Addressing does not narrow the fan-out: a voice fills its audience. + let speech = match (&invocation.speech, entry.carries_speech) { + (Some(statement), true) => { + let fact = EntityId(patch::derive_id( + patch::ENTITY_NAMESPACE, + state.world_id, + command_id, + &patch::DraftHandle::new(SPEECH_HANDLE), + Some(SPEECH_INDEX), + )); + let to = speech_audience(entry, &bindings)?; + effects.splice( + 0..0, + [ + patch::ResolvedOp::AssertClaim { + fact, + statement: statement.clone(), + by: actor, + }, + patch::ResolvedOp::Communicate { + speaker: actor, + fact, + to, + }, + ], + ); + Some(fact) + } + _ => None, + }; + // The display lowering: the same standing as speech, from the same + // allocation site under the second discriminator. It needs no entry + // field and reads no audience precondition: a body is visible to the room + // whatever the entry addresses, so `proclaim` down a horn still shrugs at + // whoever stands beside the speaker. + let display = invocation.display.as_ref().map(|statement| { + let fact = EntityId(patch::derive_id( + patch::ENTITY_NAMESPACE, + state.world_id, + command_id, + &patch::DraftHandle::new(SPEECH_HANDLE), + Some(DISPLAY_INDEX), + )); + let at = usize::from(speech.is_some()) * 2; + effects.splice( + at..at, + [ + patch::ResolvedOp::AssertClaim { + fact, + statement: statement.clone(), + by: actor, + }, + patch::ResolvedOp::Display { actor, fact }, + ], + ); + fact + }); + + let revision = super::resolution_revision(state)?; + Ok(DecisionEvent { + id: EventId::for_command(command_id), + revision, + scope: current.scope, + controller_id: current.controller_id, + affordance: granted.id, + speech, + display, + band, + effects, + }) +} + +/// The synthetic handle every minted claim allocates under. It is synthesized +/// only in Active and declarations are Draft-only, so no world-declared handle +/// can collide with it. +const SPEECH_HANDLE: &str = "ghostlight.speech"; + +/// The speech index, passed as `derive_id`'s discriminator. It is `0` for every +/// invocation because one invocation carries one utterance; it exists so a +/// second minted claim needs no second allocation idiom. +const SPEECH_INDEX: &str = "0"; + +/// The display index: the second claim one invocation may mint, under the +/// same handle and allocation site as speech. +const DISPLAY_INDEX: &str = "1"; + +/// The audience a speech-carrying entry names. The declaration validator already +/// refused an entry with none (`SpeechWithoutAudience`) or two +/// (`AmbiguousSpeechAudience`), so anything else here is a corrupt catalog. +fn speech_audience( + entry: &Affordance, + bindings: &BTreeMap<Role, Target>, +) -> Result<Audience, KernelError> { + entry + .preconditions + .iter() + .find_map(|precondition| match precondition { + Precondition::CanBroadcast { via } | Precondition::CanReach { via, .. } => { + bound_audience(via, bindings) + } + _ => None, + }) + .ok_or_else(|| KernelError::Invariant("a speech-carrying entry names no audience".into())) +} + +/// Stage 2. The acting subject is never a declared role: the kernel binds the +/// reserved name `actor` to it and refuses an invocation that tries to. A +/// binding that happens to name the actor through a declared role is legal and +/// unremarkable. +fn bind_roles( + state: &WorldState, + actor: SubjectId, + entry: &Affordance, + invocation: &DecisionInvocation, + rejections: &mut Vec<ActionMismatch>, +) -> BTreeMap<Role, Target> { + let declared: BTreeMap<&Role, RefKind> = entry + .roles + .iter() + .map(|spec| (&spec.role, spec.kind)) + .collect(); + let mut bound: BTreeMap<Role, Target> = BTreeMap::new(); + let mut seen: BTreeSet<&Role> = BTreeSet::new(); + for binding in &invocation.bindings { + if binding.role.0 == patch::ACTOR_ROLE { + rejections.push(ActionMismatch::ActorRoleBound); + continue; + } + if !seen.insert(&binding.role) { + rejections.push(ActionMismatch::DuplicateRoleBinding { + role: binding.role.clone(), + }); + continue; + } + let Some(expected) = declared.get(&binding.role).copied() else { + rejections.push(ActionMismatch::UnknownRole { + role: binding.role.clone(), + }); + continue; + }; + let Some(actual) = live_kind(state, binding.target) else { + rejections.push(ActionMismatch::UnknownTarget { + role: binding.role.clone(), + }); + continue; + }; + let fits = match (expected, actual) { + (RefKind::Subject(None), RefKind::Subject(_)) => true, + (expected, actual) => expected == actual, + }; + if fits { + bound.insert(binding.role.clone(), binding.target); + } else { + rejections.push(ActionMismatch::TargetKindMismatch { + role: binding.role.clone(), + expected, + actual, + }); + } + } + for spec in &entry.roles { + if !seen.contains(&spec.role) { + rejections.push(ActionMismatch::UnboundRole { + role: spec.role.clone(), + }); + } + } + // The kernel's own binding, added after the caller's so nothing can shadow + // it: a slot that must land on the actor says `actor` and the proposer has + // no say. Without it, a levy's `Transfer` would need the proposer to name + // the payee, and an authorized collector could lawfully take a tax and send + // it to a friend. + bound.insert(Role(patch::ACTOR_ROLE.into()), Target::Subject(actor)); + bound +} + +/// What a target actually is in committed state. `None` means the target keys no +/// live partition in its namespace. +fn live_kind(state: &WorldState, target: Target) -> Option<RefKind> { + match target { + Target::Subject(subject_id) => state + .subjects + .get(&subject_id) + .map(|subject| RefKind::Subject(Some(subject.kind))), + Target::Entity(entity_id) => state + .entities + .get(&entity_id) + .map(|record| RefKind::Entity(record.kind)), + Target::Edge(edge_id) => state + .edges + .get(&edge_id) + .map(|_| RefKind::Edge(patch::EdgeKind::Route)), + } +} + +/// Stage 3, in declaration order, each failure carrying its index so a test can +/// name the exact precondition that refused. Role binding is this caller's job: +/// each declared `Precondition` is lowered through stage 2's bindings into a +/// `BoundPrecondition` and handed to the one evaluator. A precondition whose +/// role stage 2 left unbound is skipped here, because stage 2 already named it. +fn check_preconditions( + state: &WorldState, + actor: SubjectId, + authority: &BTreeSet<AuthorityGrant>, + entry: &Affordance, + bindings: &BTreeMap<Role, Target>, + rejections: &mut Vec<ActionMismatch>, +) { + for (index, precondition) in entry.preconditions.iter().enumerate() { + let Some(bound) = bind_precondition(precondition, bindings) else { + continue; + }; + if let Some(mismatch) = evaluate(state, actor, authority, index, &bound) { + rejections.push(mismatch); + } + } +} + +/// The catalog's role indirection lowered to canonical referents. `None` means +/// a role is unbound or bound to the wrong namespace, which stage 2 named. +fn bind_precondition( + precondition: &Precondition, + bindings: &BTreeMap<Role, Target>, +) -> Option<BoundPrecondition> { + let place = |role: &Role| match bindings.get(role)? { + Target::Entity(entity_id) => Some(*entity_id), + _ => None, + }; + Some(match precondition { + Precondition::Present { at } => BoundPrecondition::Present { at: place(at)? }, + Precondition::Reachable { to, within } => BoundPrecondition::Reachable { + to: place(to)?, + within: *within, + }, + Precondition::Holds { resource, at_least } => BoundPrecondition::Holds { + resource: place(resource)?, + at_least: *at_least, + }, + Precondition::Authorized { over, kind } => BoundPrecondition::Authorized { + over: bindings.get(over).copied()?, + kind: kind.clone(), + }, + Precondition::HasStanding { grievance } => BoundPrecondition::HasStanding { + grievance: grievance.clone(), + }, + Precondition::Knows { fact, at_least } => BoundPrecondition::Knows { + fact: place(fact)?, + at_least: *at_least, + }, + Precondition::CanBroadcast { via } => BoundPrecondition::CanBroadcast { + via: bound_audience(via, bindings)?, + }, + Precondition::CanReach { subject, via } => BoundPrecondition::CanReach { + subject: match bindings.get(subject)? { + Target::Subject(subject_id) => *subject_id, + _ => return None, + }, + via: bound_audience(via, bindings)?, + }, + Precondition::Committed { to, kind } => BoundPrecondition::Committed { + to: match bindings.get(to)? { + Target::Subject(subject_id) => *subject_id, + _ => return None, + }, + kind: *kind, + }, + }) +} + +/// The one precondition reader, over referents that are already canonical. +/// Returns the complete set in declaration order; an empty set is "all hold". +/// The tick reads only its emptiness — an `ActionMismatch` never surfaces to +/// anyone from there. +pub(super) fn preconditions_hold( + state: &WorldState, + actor: SubjectId, + checks: &[BoundPrecondition], +) -> Vec<ActionMismatch> { + let components = super::scope_components(state, actor); + let authority = super::effective_authority(&components.authority, &components.delegated); + checks + .iter() + .enumerate() + .filter_map(|(index, check)| evaluate(state, actor, &authority, index, check)) + .collect() +} + +/// One check against committed state. `index` is the position within the slice +/// the caller passed in, which is what every `precondition: usize` means. +fn evaluate( + state: &WorldState, + actor: SubjectId, + authority: &BTreeSet<AuthorityGrant>, + index: usize, + check: &BoundPrecondition, +) -> Option<ActionMismatch> { + let holds = match check { + BoundPrecondition::Present { at } => { + return (state.positions.get(&actor).map(|position| position.place) != Some(*at)) + .then_some(ActionMismatch::ActorNotPresent { + precondition: index, + }); + } + BoundPrecondition::Reachable { to, within } => { + return (!reachable(state, actor, authority, *to, *within)).then_some( + ActionMismatch::TargetUnreachable { + precondition: index, + }, + ); + } + BoundPrecondition::Holds { resource, at_least } => { + state + .holdings + .get(&actor) + .and_then(|held| held.get(resource)) + .map_or(0, |quantity| quantity.0) + >= at_least.0 + } + BoundPrecondition::Authorized { over, kind } => { + return (!authority + .iter() + .any(|grant| &grant.kind == kind && super::covers(state, grant.over, *over))) + .then_some(ActionMismatch::NotAuthorized { + precondition: index, + }); + } + BoundPrecondition::HasStanding { grievance } => { + return (!state.redress.get(grievance).is_some_and(|forum| { + super::covers(state, forum.standing, Target::Subject(actor)) + })) + .then_some(ActionMismatch::NoStanding { + precondition: index, + }); + } + BoundPrecondition::Knows { fact, at_least } => { + return (!state + .knowledge + .get(&actor) + .and_then(|held| held.get(fact)) + .is_some_and(|held| held.confidence >= *at_least)) + .then_some(ActionMismatch::FactUnknown { + precondition: index, + }); + } + BoundPrecondition::CanBroadcast { via } => { + return (!super::can_broadcast(state, actor, via)).then_some( + ActionMismatch::NoAudience { + precondition: index, + }, + ); + } + BoundPrecondition::CanReach { subject, via } => { + return (!super::audience(state, actor, via).contains(subject)).then_some( + ActionMismatch::CannotReach { + precondition: index, + }, + ); + } + // A linear scan of one subject's own small map. No key lookup is needed + // and none is offered, which is why a `CommitmentKey` never has to be + // guessable. + BoundPrecondition::Committed { to, kind } => { + return (!state.commitments.get(&actor).is_some_and(|held| { + held.values().any(|commitment| { + commitment.counterparty == Some(*to) && commitment.kind == *kind + }) + })) + .then_some(ActionMismatch::NotCommitted { + precondition: index, + }); + } + }; + (!holds).then_some(ActionMismatch::InsufficientHolding { + precondition: index, + }) +} + +/// The catalog's role indirection lowered to the canonical audience: the entry +/// names a role, the invoker binds a channel to it, and every reader of reach +/// sees one shape. `None` means the role is unbound, which stage 2 already named. +fn bound_audience(via: &AudienceSpec, bindings: &BTreeMap<Role, Target>) -> Option<Audience> { + match via { + AudienceSpec::Colocated => Some(Audience::Colocated), + AudienceSpec::Channel(role) => match bindings.get(role).copied() { + Some(Target::Entity(entity_id)) => Some(Audience::Channel(entity_id)), + _ => None, + }, + } +} + +/// Stage 4, beside the ceilings: an authority a slot would grant or revoke +/// must not exceed the actor's own. For a grant this is the monotonicity +/// envelope — no holder mints authority it does not itself hold. For a +/// revocation it is the same envelope read the other way: an actor may not +/// strip ground it holds no jurisdiction over, so revocation is not a lever +/// for reaching past one's own authority. Every slot is checked, not just the +/// drawn band's, for the same reason every ceiling is — the proposer commits +/// to a complete attempt and cannot see the band. +/// +/// The rule is action-lane only, and that is not two truths. The patch lane's +/// `GrantAuthority`/`RevokeAuthority` is admitted by the world owner; +/// monotonicity *is* the action lane's authority envelope, and both lanes +/// reach one `apply_operation` with the identical mutation. +fn check_delegation( + state: &WorldState, + authority: &BTreeSet<AuthorityGrant>, + entry: &Affordance, + bindings: &BTreeMap<Role, Target>, + rejections: &mut Vec<ActionMismatch>, +) { + for (index, slot) in entry.effect_slots.iter().enumerate() { + let kind = match &slot.op_kind { + ComponentOpKind::GrantAuthority { kind } + | ComponentOpKind::RevokeAuthority { kind } => kind, + _ => continue, + }; + let Some(over) = slot + .roles + .get(1) + .and_then(|role| bindings.get(role)) + .copied() + .and_then(authority_target_of) + else { + continue; + }; + if !authority.iter().any(|grant| { + &grant.kind == kind && super::covers(state, grant.over, over.as_referent()) + }) { + rejections.push(ActionMismatch::DelegationNotMonotone { slot: index }); + } + } +} + +/// The authority target a bound referent names. A route is jurisdictional +/// ground but never a grant's target, so a slot bound to one lowers to nothing. +fn authority_target_of(target: Target) -> Option<AuthorityTarget> { + match target { + Target::Subject(subject_id) => Some(AuthorityTarget::Subject(subject_id)), + Target::Entity(entity_id) => Some(AuthorityTarget::PlaceSubtree(entity_id)), + Target::Edge(_) => None, + } +} + +/// Dijkstra over the live route graph, admitting the open routes this subject +/// may traverse — the same `route_admits` rule the resolver applies to a +/// `Relocate`, so a subject with the right authority can plan a path through +/// its own restricted ground — and +/// relaxing in `EdgeId` order, pruning any path whose accumulated cost exceeds +/// `within`. Cost 0 — already standing there — succeeds; `Present` is the strict +/// form. An unplaced actor reaches nothing. +/// +/// This reads routes the scope digest does not cover, which is deliberate: the +/// alternative binds a proposal to a transitively large slice of world topology +/// and rejects it whenever anything near the actor commits. Admission runs at +/// commit against live state instead, so a route that closed while the proposal +/// was in flight makes this fail rather than letting a stale path commit. +fn reachable( + state: &WorldState, + actor: SubjectId, + authority: &BTreeSet<AuthorityGrant>, + destination: EntityId, + within: Cost, +) -> bool { + let Some(origin) = state.positions.get(&actor).map(|position| position.place) else { + return false; + }; + let mut best: BTreeMap<EntityId, u64> = BTreeMap::from([(origin, 0)]); + let mut settled: BTreeSet<EntityId> = BTreeSet::new(); + let ceiling = u64::from(within.0); + loop { + let Some((place, cost)) = best + .iter() + .filter(|(place, _)| !settled.contains(place)) + .min_by_key(|(place, cost)| (**cost, **place)) + .map(|(place, cost)| (*place, *cost)) + else { + return false; + }; + if place == destination { + return true; + } + settled.insert(place); + let outbound: Vec<(EdgeId, EntityId, u64)> = state + .edges + .iter() + .filter(|(_, record)| record.is_open()) + .filter_map(|(edge_id, record)| { + let (from, to) = record.endpoints(); + let next = if from == place { + to + } else if to == place { + from + } else { + return None; + }; + patch::route_admits(state, authority, record.access(), next) + .then(|| (*edge_id, next, u64::from(record.cost().0))) + }) + .collect(); + for (_, next, step) in outbound { + let total = cost + step; + if total <= ceiling && best.get(&next).is_none_or(|known| total < *known) { + best.insert(next, total); + } + } + } +} + +/// Stage 4. Every slot is checked, not just the ones the selected band names: +/// the proposer cannot see the band, so it commits to a complete attempt, and +/// checking every slot makes the ceiling total. +fn check_proposals( + entry: &Affordance, + invocation: &DecisionInvocation, + rejections: &mut Vec<ActionMismatch>, +) { + let mut seen: BTreeSet<usize> = BTreeSet::new(); + for proposed in &invocation.proposed { + if !seen.insert(proposed.slot) { + rejections.push(ActionMismatch::DuplicateSlotProposal { + slot: proposed.slot, + }); + continue; + } + let Some(slot) = entry.effect_slots.get(proposed.slot) else { + rejections.push(ActionMismatch::UnknownSlot { + slot: proposed.slot, + }); + continue; + }; + match (slot.bounds, proposed.magnitude) { + (Bounds::None, Magnitude::None) => {} + (Bounds::Quantity(ceiling), Magnitude::Quantity(value)) => { + if value.0 == 0 { + rejections.push(ActionMismatch::ZeroMagnitude { + slot: proposed.slot, + }); + } else if value.0 > ceiling.0 { + rejections.push(ActionMismatch::MagnitudeOverCeiling { + slot: proposed.slot, + }); + } + } + (Bounds::Cost(ceiling), Magnitude::Cost(value)) => { + if value.0 == 0 { + rejections.push(ActionMismatch::ZeroMagnitude { + slot: proposed.slot, + }); + } else if value.0 > ceiling.0 { + rejections.push(ActionMismatch::MagnitudeOverCeiling { + slot: proposed.slot, + }); + } + } + _ => rejections.push(ActionMismatch::MagnitudeShapeMismatch { + slot: proposed.slot, + }), + } + } + for slot in 0..entry.effect_slots.len() { + if !seen.contains(&slot) { + rejections.push(ActionMismatch::SlotNotProposed { slot }); + } + } + // `Statement` is serde-transparent, so a value that arrived through + // deserialization rather than through the constructor is re-checked here + // rather than trusted. + match (&invocation.speech, entry.carries_speech) { + // A speech-carrying entry addresses someone; a silent turn that only + // displays still addresses the room, so it is not `SpeechRequired`. + (None, true) if invocation.display.is_none() => { + rejections.push(ActionMismatch::SpeechRequired); + } + (Some(_), false) => rejections.push(ActionMismatch::SpeechNotCarried), + (Some(speech), true) if !patch::is_canonical_text(speech.as_str()) => { + rejections.push(ActionMismatch::EmptySpeech); + } + _ => {} + } + if invocation + .display + .as_ref() + .is_some_and(|display| !patch::is_canonical_text(display.as_str())) + { + rejections.push(ActionMismatch::EmptyDisplay); + } +} + +/// The only entropy in the kernel: one digest, one modulo, one cumulative walk. +/// Modulo rather than rejection sampling — the bias is bounded by +/// `total_weight / 2^64`, and a rejection loop would need its counter in the +/// preimage, which is a second entropy shape for a rounding error nobody can +/// measure. +fn select_band( + state: &WorldState, + command_id: CommandId, + affordance: AffordanceId, + entry: &Affordance, +) -> Result<usize, KernelError> { + let draw = digest(&BandPreimage { + world_id: state.world_id, + revision: state.revision, + command_id, + affordance, + band_count: entry.outcome_bands.len(), + })?; + let head = draw + .strip_prefix("sha256:") + .and_then(|hex| hex.get(..16)) + .and_then(|head| u64::from_str_radix(head, 16).ok()) + .ok_or_else(|| KernelError::Invariant("band draw digest is not hex".into()))?; + let total: u128 = entry + .outcome_bands + .iter() + .map(|band| u128::from(band.weight)) + .sum(); + if total == 0 { + return Err(KernelError::Invariant( + "affordance has no outcome band".into(), + )); + } + let mut position = u128::from(head) % total; + for (index, band) in entry.outcome_bands.iter().enumerate() { + let weight = u128::from(band.weight); + if position < weight { + return Ok(index); + } + position -= weight; + } + Err(KernelError::Invariant( + "band weights did not cover the draw".into(), + )) +} + +/// Stage 7. One arm per `ComponentOpKind`, every referent read from the slot's +/// roles resolved through the bindings, every magnitude from the proposal for +/// that slot. An empty band lowers to nothing. +fn lower( + entry: &Affordance, + band: usize, + actor: SubjectId, + now: FictionalMinutes, + invocation: &DecisionInvocation, + bindings: &BTreeMap<Role, Target>, +) -> Result<Vec<patch::ComponentOp>, KernelError> { + let malformed = || KernelError::Invariant("admitted affordance slot is malformed".into()); + let band = entry + .outcome_bands + .get(band) + .ok_or_else(|| KernelError::Invariant("selected band does not exist".into()))?; + let mut operations = Vec::new(); + for slot_index in &band.effects { + let slot = entry.effect_slots.get(*slot_index).ok_or_else(malformed)?; + let magnitude = invocation + .proposed + .iter() + .find(|proposed| proposed.slot == *slot_index) + .map(|proposed| proposed.magnitude) + .ok_or_else(malformed)?; + let target = |position: usize| -> Result<Target, KernelError> { + slot.roles + .get(position) + .and_then(|role| bindings.get(role)) + .copied() + .ok_or_else(malformed) + }; + let subject = |position: usize| -> Result<patch::Ref<SubjectId>, KernelError> { + match target(position)? { + Target::Subject(subject_id) => Ok(patch::Ref::Existing(subject_id)), + _ => Err(malformed()), + } + }; + let entity = |position: usize| -> Result<patch::Ref<EntityId>, KernelError> { + match target(position)? { + Target::Entity(entity_id) => Ok(patch::Ref::Existing(entity_id)), + _ => Err(malformed()), + } + }; + let edge = |position: usize| -> Result<patch::Ref<EdgeId>, KernelError> { + match target(position)? { + Target::Edge(edge_id) => Ok(patch::Ref::Existing(edge_id)), + _ => Err(malformed()), + } + }; + let quantity = || -> Result<Quantity, KernelError> { + match magnitude { + Magnitude::Quantity(value) => Ok(value), + _ => Err(malformed()), + } + }; + let dependency = |position: usize| -> Result<patch::DependencyRef, KernelError> { + Ok(match target(position)? { + Target::Subject(subject_id) => { + patch::DependencyRef::Subject(patch::Ref::Existing(subject_id)) + } + Target::Entity(entity_id) => { + patch::DependencyRef::Resource(patch::Ref::Existing(entity_id)) + } + Target::Edge(edge_id) => patch::DependencyRef::Route(patch::Ref::Existing(edge_id)), + }) + }; + let grant_over = |position: usize| -> Result<patch::AuthorityTargetRef, KernelError> { + Ok(match target(position)? { + Target::Subject(subject_id) => { + patch::AuthorityTargetRef::Subject(patch::Ref::Existing(subject_id)) + } + Target::Entity(entity_id) => { + patch::AuthorityTargetRef::PlaceSubtree(patch::Ref::Existing(entity_id)) + } + Target::Edge(_) => return Err(malformed()), + }) + }; + operations.push(match &slot.op_kind { + // `due` is computed here, so a proposer cannot set one, and the + // pressure source is the acting subject, so it cannot be forged. + ComponentOpKind::CreateCommitment { + kind, + horizon, + period, + } => patch::ComponentOp::CreateCommitment { + subject: subject(0)?, + counterparty: Some(subject(1)?), + kind: *kind, + due: now.checked_add(*horizon).ok_or_else(malformed)?, + period: *period, + checks: Vec::new(), + // The world named the action; that name is what was promised. + // A proposer cannot supply the text, so it cannot promise more + // than the affordance carries. + statement: patch::Statement::new(format!("a promise made through {}", entry.kind.0)) + .ok_or_else(malformed)?, + }, + ComponentOpKind::AdvancePressure { by } => patch::ComponentOp::AdvancePressure { + source: patch::PressureSourceRef::Subject(patch::Ref::Existing(actor)), + target: subject(0)?, + by: *by, + }, + ComponentOpKind::ReducePressure { by } => patch::ComponentOp::ReducePressure { + source: patch::PressureSourceRef::Subject(patch::Ref::Existing(actor)), + target: subject(0)?, + by: *by, + }, + ComponentOpKind::ResolvePressure => patch::ComponentOp::ResolvePressure { + source: patch::PressureSourceRef::Subject(patch::Ref::Existing(actor)), + target: subject(0)?, + }, + ComponentOpKind::Relocate => patch::ComponentOp::Relocate { + subject: subject(0)?, + via: edge(1)?, + }, + ComponentOpKind::OpenRoute => patch::ComponentOp::OpenRoute { route: edge(0)? }, + ComponentOpKind::CloseRoute => patch::ComponentOp::CloseRoute { route: edge(0)? }, + ComponentOpKind::AlterCost => patch::ComponentOp::AlterCost { + route: edge(0)?, + cost: match magnitude { + Magnitude::Cost(value) => value, + _ => return Err(malformed()), + }, + }, + ComponentOpKind::Transfer => patch::ComponentOp::Transfer { + from: subject(0)?, + to: subject(1)?, + resource: entity(2)?, + qty: quantity()?, + }, + ComponentOpKind::Transform => patch::ComponentOp::Transform { + holder: subject(0)?, + from_resource: entity(1)?, + into_resource: entity(2)?, + qty: quantity()?, + }, + ComponentOpKind::Consume => patch::ComponentOp::Consume { + holder: subject(0)?, + resource: entity(1)?, + qty: quantity()?, + }, + ComponentOpKind::Bind => patch::ComponentOp::Bind { + subject: subject(0)?, + target: dependency(1)?, + }, + ComponentOpKind::Release => patch::ComponentOp::Release { + subject: subject(0)?, + target: dependency(1)?, + }, + ComponentOpKind::GrantAuthority { kind } => patch::ComponentOp::GrantAuthority { + holder: subject(0)?, + grant: patch::AuthorityGrantRef { + kind: kind.clone(), + over: grant_over(1)?, + }, + }, + ComponentOpKind::RevokeAuthority { kind } => patch::ComponentOp::RevokeAuthority { + holder: subject(0)?, + grant: patch::AuthorityGrantRef { + kind: kind.clone(), + over: grant_over(1)?, + }, + }, + ComponentOpKind::InstallIncumbent { office } => patch::ComponentOp::InstallIncumbent { + institution: subject(0)?, + office: office.clone(), + incumbent: subject(1)?, + }, + ComponentOpKind::VacateOffice { office } => patch::ComponentOp::VacateOffice { + institution: subject(0)?, + office: office.clone(), + }, + ComponentOpKind::AcquireKnowledge { confidence } => { + patch::ComponentOp::AcquireKnowledge { + subject: subject(0)?, + fact: entity(1)?, + source: patch::AuthoredSource::Witnessed, + confidence: *confidence, + } + } + ComponentOpKind::Witness { confidence } => patch::ComponentOp::Witness { + fact: entity(0)?, + place: entity(1)?, + confidence: *confidence, + }, + ComponentOpKind::Forget => patch::ComponentOp::Forget { + subject: subject(0)?, + fact: entity(1)?, + }, + }); + } + Ok(operations) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::custody_tests::custody_kernel; + use crate::patch::{ + AffordanceDeclaration, ComponentOp, DraftHandle, OutcomeBand, Ref as PatchRef, ResolvedOp, + RoleSpec, + }; + use crate::tests::{ + ADMIT_KIND, COMMAND_KIND, Civic, LEVY_KIND, OPENING_BALANCE, SEIZURE_GRIEVANCE, Topology, + WARDEN_OFFICE, activate, affordance_named, auth_principal, authority_kind, civic_world, + command, custody_world, grant_to, grievance, office, operations, opportunity_for, + over_place, over_subject, human_principal, reject_owner, submit_owner, + }; + use crate::{ + AffordanceKindName, AuthenticatedCaller, AuthoredSource, CallerId, CommandBody, Confidence, + Declaration, EffectSlot, EntityKind, ProposedEffect, RoleBinding, Statement, SubmitReceipt, + WorldEffect, WorldKernel, WorldPatch, WorldSnapshot, apply_effect, + }; + use std::collections::BTreeSet; + + struct Bench { + kernel: WorldKernel, + active: WorldSnapshot, + carry: AffordanceId, + clerk: SubjectId, + keeper: SubjectId, + tithe: EntityId, + ingot: EntityId, + yard: EntityId, + gate: EntityId, + shutter: EdgeId, + } + + fn bench(directory: &std::path::Path, title: &str) -> Bench { + let mut kernel = custody_kernel(directory, title); + let (topology, custody, active) = custody_world(&mut kernel); + let carry = affordance_named(&active, "carry"); + Bench { + kernel, + active, + carry, + clerk: custody.holder, + keeper: custody.counterparty, + tithe: custody.tithe, + ingot: custody.ingot, + yard: topology.yard, + gate: topology.gate, + shutter: topology.shutter, + } + } + + /// `exercise` only accepts a grant the kernel resolved, so a test walks the + /// same gate `reduce` does rather than reaching into the catalog. + fn draw_once( + state: &WorldState, + command_id: CommandId, + opportunity: &DecisionOpportunity, + invocation: &DecisionInvocation, + ) -> Result<DecisionEvent, KernelError> { + let granted = crate::require_granted(state, opportunity, invocation.affordance)?; + exercise(state, command_id, opportunity, &granted, invocation) + } + + fn binding(role: &str, target: Target) -> RoleBinding { + RoleBinding { + role: Role(role.into()), + target, + } + } + + impl Bench { + /// A Carry the clerk proposes. The actor is never a role, so a Carry + /// that moves the actor's own goods binds `from` to its own id. + fn carry_of(&self, qty: u64, place: EntityId, resource: EntityId) -> DecisionInvocation { + DecisionInvocation { + affordance: self.carry, + bindings: vec![ + binding("from", Target::Subject(self.clerk)), + binding("recipient", Target::Subject(self.keeper)), + binding("place", Target::Entity(place)), + binding("resource", Target::Entity(resource)), + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(qty)), + }], + speech: None, + display: None, + } + } + + fn carry(&self, qty: u64, place: EntityId) -> DecisionInvocation { + self.carry_of(qty, place, self.tithe) + } + + fn clerk_opportunity(&self) -> DecisionOpportunity { + opportunity_for(&self.active, self.clerk) + } + + fn try_exercise( + &self, + invocation: &DecisionInvocation, + ) -> Result<DecisionEvent, KernelError> { + let opportunity = self.clerk_opportunity(); + draw_once( + &self.kernel.state, + CommandId::issue(), + &opportunity, + invocation, + ) + } + + fn rejections(&self, invocation: &DecisionInvocation) -> Vec<ActionMismatch> { + match self.try_exercise(invocation) { + Err(KernelError::ActionRejected(rejected)) => rejected, + other => panic!("expected an action rejection, got {other:?}"), + } + } + + fn commit(&mut self, invocation: DecisionInvocation) -> SubmitReceipt { + let opportunity = self.clerk_opportunity(); + let caller = CallerId::Controller(opportunity.controller_id); + self.kernel + .submit( + command( + &self.active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .expect("the invocation commits") + } + + fn held(&self, holder: SubjectId) -> u64 { + self.kernel + .state + .holdings + .get(&holder) + .and_then(|held| held.get(&self.tithe)) + .map_or(0, |quantity| quantity.0) + } + + /// The same Carry attempt against a sibling entry: one dial moved, one + /// name. The catalog is Draft-only, so a variant is declared rather + /// than patched into committed state. + fn variant(&self, invocation: &DecisionInvocation, kind: &str) -> DecisionInvocation { + DecisionInvocation { + affordance: affordance_named(&self.active, kind), + ..invocation.clone() + } + } + + fn refresh(&mut self) { + self.active = self.kernel.snapshot().unwrap(); + } + } + + #[test] + fn a_missing_present_precondition_names_itself() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "Present"); + let before = bench.kernel.state.clone(); + + // The clerk stands in the yard, so a Carry bound to the gate fails the + // first precondition and nothing else. + assert_eq!( + bench.rejections(&bench.carry(1, bench.gate)), + vec![ActionMismatch::ActorNotPresent { precondition: 0 }] + ); + assert_eq!(bench.kernel.state.revision, before.revision); + assert_eq!(bench.kernel.state.holdings, before.holdings); + assert_eq!(bench.kernel.state.events, before.events); + } + + #[test] + fn spending_more_than_held_fails_the_holds_precondition() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "Holds"); + let greedy = bench.variant(&bench.carry(1, bench.yard), "carry_greedy"); + assert_eq!( + bench.rejections(&greedy), + vec![ActionMismatch::InsufficientHolding { precondition: 1 }] + ); + + // Absence is zero, so a resource the clerk holds none of gives the same + // name at the boundary rather than a second one. + let ingot = bench.variant(&bench.carry_of(1, bench.yard, bench.ingot), "carry_holds"); + assert_eq!( + bench.rejections(&ingot), + vec![ActionMismatch::InsufficientHolding { precondition: 0 }] + ); + } + + #[test] + fn a_reachable_precondition_reads_only_open_public_routes() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = bench(directory.path(), "Reachable"); + // Yard to gate over open public routes is the ramp (12) plus the span + // (7): the shutter is closed and the toll stair is restricted. A budget + // of NEAR_REACH covers only the shutter, FAR_REACH covers the two-hop + // path. + let attempt = bench.carry(1, bench.gate); + let near = bench.variant(&attempt, "carry_near"); + let far = bench.variant(&attempt, "carry_far"); + assert_eq!( + bench.rejections(&near), + vec![ActionMismatch::TargetUnreachable { precondition: 0 }] + ); + assert!(bench.try_exercise(&far).is_ok()); + + // Opening the one-hop shutter shortens the path, and closing it again + // restores the two-hop cost: the check reads the live graph rather than + // anything the proposal was bound against. + let before = bench.kernel.snapshot().unwrap(); + submit_owner( + &mut bench.kernel, + &before, + operations(vec![ComponentOp::OpenRoute { + route: PatchRef::Existing(bench.shutter), + }]), + ); + bench.refresh(); + assert!(bench.try_exercise(&near).is_ok()); + + let before = bench.kernel.snapshot().unwrap(); + submit_owner( + &mut bench.kernel, + &before, + operations(vec![ComponentOp::CloseRoute { + route: PatchRef::Existing(bench.shutter), + }]), + ); + bench.refresh(); + assert_eq!( + bench.rejections(&near), + vec![ActionMismatch::TargetUnreachable { precondition: 0 }] + ); + } + + #[test] + fn an_unbound_or_miskinded_role_is_rejected_with_the_complete_set() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "Roles"); + let mut invocation = bench.carry(1, bench.yard); + // Drop `recipient`, add an undeclared role, and bind `resource` to a + // place: one rejection carrying all three, sorted. + invocation.bindings = vec![ + binding("from", Target::Subject(bench.clerk)), + binding("place", Target::Entity(bench.yard)), + binding("resource", Target::Entity(bench.yard)), + binding("porter", Target::Subject(bench.keeper)), + ]; + let mut expected = vec![ + ActionMismatch::UnboundRole { + role: Role("recipient".into()), + }, + ActionMismatch::UnknownRole { + role: Role("porter".into()), + }, + ActionMismatch::TargetKindMismatch { + role: Role("resource".into()), + expected: RefKind::Entity(EntityKind::Resource), + actual: RefKind::Entity(EntityKind::Place), + }, + ]; + expected.sort(); + assert_eq!(bench.rejections(&invocation), expected); + } + + #[test] + fn a_duplicated_or_unknown_binding_target_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "Bindings"); + let mut twice = bench.carry(1, bench.yard); + twice + .bindings + .push(binding("resource", Target::Entity(bench.tithe))); + assert!( + bench + .rejections(&twice) + .contains(&ActionMismatch::DuplicateRoleBinding { + role: Role("resource".into()) + }) + ); + + let mut unknown = bench.carry(1, bench.yard); + unknown.bindings[3] = binding("resource", Target::Entity(EntityId::issue())); + assert!( + bench + .rejections(&unknown) + .contains(&ActionMismatch::UnknownTarget { + role: Role("resource".into()) + }) + ); + } + + #[test] + fn a_magnitude_over_its_slot_ceiling_is_rejected_and_within_it_commits() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = bench(directory.path(), "Ceiling"); + assert_eq!( + bench.rejections(&bench.carry(4, bench.yard)), + vec![ActionMismatch::MagnitudeOverCeiling { slot: 0 }] + ); + + let clerk_before = bench.held(bench.clerk); + let keeper_before = bench.held(bench.keeper); + let receipt = bench.commit(bench.carry(3, bench.yard)); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert_eq!(bench.held(bench.clerk), clerk_before - 3); + assert_eq!(bench.held(bench.keeper), keeper_before + 3); + assert_eq!( + bench.held(bench.clerk) + bench.held(bench.keeper), + clerk_before + keeper_before, + "the conserved total is unchanged" + ); + } + + #[test] + fn a_magnitude_of_the_wrong_shape_or_zero_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "Shape"); + for magnitude in [Magnitude::Cost(Cost(2)), Magnitude::None] { + let mut invocation = bench.carry(1, bench.yard); + invocation.proposed[0].magnitude = magnitude; + assert_eq!( + bench.rejections(&invocation), + vec![ActionMismatch::MagnitudeShapeMismatch { slot: 0 }] + ); + } + assert_eq!( + bench.rejections(&bench.carry(0, bench.yard)), + vec![ActionMismatch::ZeroMagnitude { slot: 0 }] + ); + } + + #[test] + fn every_slot_must_be_proposed_exactly_once() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "Slots"); + let mut missing = bench.carry(1, bench.yard); + missing.proposed.clear(); + assert_eq!( + bench.rejections(&missing), + vec![ActionMismatch::SlotNotProposed { slot: 0 }] + ); + + let mut twice = bench.carry(1, bench.yard); + twice.proposed.push(twice.proposed[0]); + assert_eq!( + bench.rejections(&twice), + vec![ActionMismatch::DuplicateSlotProposal { slot: 0 }] + ); + + let mut unknown = bench.carry(1, bench.yard); + unknown.proposed.push(ProposedEffect { + slot: 7, + magnitude: Magnitude::None, + }); + assert_eq!( + bench.rejections(&unknown), + vec![ActionMismatch::UnknownSlot { slot: 7 }] + ); + } + + #[test] + fn speech_is_required_exactly_when_the_entry_carries_it() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "Speech"); + let mut spoken_carry = bench.carry(1, bench.yard); + spoken_carry.speech = Some(Statement::new("Take it.").unwrap()); + assert_eq!( + bench.rejections(&spoken_carry), + vec![ActionMismatch::SpeechNotCarried] + ); + + let speak = affordance_named(&bench.active, "speak"); + let mut silent_speak = DecisionInvocation { + affordance: speak, + bindings: Vec::new(), + proposed: Vec::new(), + speech: None, + display: None, + }; + assert_eq!( + bench.rejections(&silent_speak), + vec![ActionMismatch::SpeechRequired] + ); + + // `Statement` is serde-transparent, so a value that arrived without the + // constructor is re-checked here rather than trusted. + silent_speak.speech = Some(serde_json::from_str::<Statement>("\" \"").unwrap()); + assert_eq!( + bench.rejections(&silent_speak), + vec![ActionMismatch::EmptySpeech] + ); + } + + #[test] + fn the_same_command_id_always_selects_the_same_band() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "Bands"); + // Three equally weighted bands, so the draw alone decides. + let opportunity = bench.clerk_opportunity(); + let invocation = bench.variant(&bench.carry(1, bench.yard), "carry_chance"); + let draw = |command_id: CommandId, invocation: &DecisionInvocation| { + draw_once(&bench.kernel.state, command_id, &opportunity, invocation) + .expect("the invocation is admissible") + .band + }; + + let command_id = CommandId::issue(); + let fixed = draw(command_id, &invocation); + for _ in 0..100 { + assert_eq!(draw(command_id, &invocation), fixed); + } + + // No caller-supplied value influences the draw: not a binding order, + // not a magnitude. + let mut reordered = invocation.clone(); + reordered.bindings.reverse(); + assert_eq!(draw(command_id, &reordered), fixed); + let mut heavier = invocation.clone(); + heavier.proposed[0].magnitude = Magnitude::Quantity(Quantity(3)); + assert_eq!(draw(command_id, &heavier), fixed); + + // The command id is the only varying term at one revision. + let mut seen = BTreeSet::new(); + for _ in 0..64 { + seen.insert(draw(CommandId::issue(), &invocation)); + } + assert!( + seen.len() > 1, + "varying only the command id must reach more than one band" + ); + } + + #[test] + fn a_zero_effect_band_commits_nothing_but_the_event() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = bench(directory.path(), "EmptyBand"); + let idle = bench.variant(&bench.carry(3, bench.yard), "carry_idle"); + + let holdings = bench.kernel.state.holdings.clone(); + let positions = bench.kernel.state.positions.clone(); + let edges = bench.kernel.state.edges.clone(); + let revision = bench.kernel.state.revision; + + let event = bench + .try_exercise(&idle) + .expect("an empty band is admissible"); + assert_eq!(event.band, 0); + assert!(event.effects.is_empty()); + + let receipt = bench.commit(idle); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert_eq!(bench.kernel.state.holdings, holdings); + assert_eq!(bench.kernel.state.positions, positions); + assert_eq!(bench.kernel.state.edges, edges); + assert_eq!(bench.kernel.state.events.len(), 1); + assert_eq!(bench.kernel.state.revision, revision + 1); + } + + #[test] + fn a_committed_event_carries_the_exact_lowered_operations() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = bench(directory.path(), "Lowering"); + let receipt = bench.commit(bench.carry(2, bench.yard)); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + let event = bench + .kernel + .state + .events + .last() + .expect("the committed event"); + assert_eq!( + event.effects, + vec![ResolvedOp::Transfer { + from: bench.clerk, + to: bench.keeper, + resource: bench.tithe, + qty: Quantity(2), + }] + ); + } + + /// Soul: contract 10's discriminating case. `a_zero_effect_band_commits_ + /// nothing_but_the_event` proves an empty band commits nothing, and + /// `a_committed_event_carries_the_exact_lowered_operations` proves a + /// one-slot entry lowers what it declares — neither separates a slot the + /// proposer offered from a slot the draw admitted. This entry declares two + /// slots on disjoint bands and proposes both within their ceilings: only + /// the drawn band's slot may appear in `event.effects`, and the other slot + /// must move no partition. Both bands are exercised, so neither branch + /// passes by never being taken. + #[test] + fn soul_only_the_selected_bands_effects_are_committed() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = bench(directory.path(), "SelectedBand"); + let split_id = affordance_named(&bench.active, "carry_split"); + let split = DecisionInvocation { + affordance: split_id, + bindings: vec![ + binding("from", Target::Subject(bench.clerk)), + binding("recipient", Target::Subject(bench.keeper)), + binding("place", Target::Entity(bench.yard)), + binding("resource", Target::Entity(bench.tithe)), + ], + proposed: vec![ + ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(2)), + }, + ProposedEffect { + slot: 1, + magnitude: Magnitude::Quantity(Quantity(1)), + }, + ], + speech: None, + display: None, + }; + let mut seen: BTreeSet<usize> = BTreeSet::new(); + + for wanted in [0usize, 1] { + // The draw is a pure function of the pre-commit revision and the + // command id, so the command id that reaches a band is findable + // before the envelope is built rather than hunted by retrying. + let opportunity = bench.clerk_opportunity(); + let command_id = (0..256) + .map(|_| CommandId::issue()) + .find(|candidate| { + draw_once(&bench.kernel.state, *candidate, &opportunity, &split) + .expect("the invocation is admissible") + .band + == wanted + }) + .expect("a two-band entry reaches both bands over 256 command ids"); + + let before_clerk = bench.held(bench.clerk); + let before_keeper = bench.held(bench.keeper); + let caller = CallerId::Controller(opportunity.controller_id); + let receipt = bench + .kernel + .submit( + command( + &bench.active, + command_id, + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation: split.clone(), + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .expect("the invocation commits"); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + bench.refresh(); + let event = bench + .kernel + .state + .events + .last() + .expect("the committed event") + .clone(); + assert_eq!(event.band, wanted); + seen.insert(event.band); + match event.band { + 0 => { + assert_eq!( + event.effects, + vec![ResolvedOp::Transfer { + from: bench.clerk, + to: bench.keeper, + resource: bench.tithe, + qty: Quantity(2), + }] + ); + assert_eq!(bench.held(bench.clerk), before_clerk - 2); + assert_eq!(bench.held(bench.keeper), before_keeper + 2); + } + 1 => { + assert_eq!( + event.effects, + vec![ResolvedOp::Consume { + holder: bench.clerk, + resource: bench.tithe, + qty: Quantity(1), + }] + ); + assert_eq!(bench.held(bench.clerk), before_clerk - 1); + assert_eq!(bench.held(bench.keeper), before_keeper); + } + other => panic!("the entry declares two bands, drew {other}"), + } + } + + assert_eq!( + seen.len(), + 2, + "both declared bands must be reachable across command ids" + ); + } + + /// Soul: `RoleSpec` persists inside the catalog, so `RefKind` had to become + /// serializable this pass. An internally tagged newtype over an `Option` + /// does not serialize; this one is adjacently tagged, and a stored + /// `Subject(None)` role is what would fault on first write if that were + /// wrong. The fixture catalog carries four such roles. + #[test] + fn soul_a_stored_role_spec_over_an_optional_subject_kind_round_trips() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "OptionalSubjectKind"); + let entry = bench + .kernel + .state + .affordance_catalog + .get(&bench.carry) + .expect("the fixture entry"); + assert!( + entry + .roles + .iter() + .any(|spec| spec.kind == RefKind::Subject(None)) + ); + + // The state row encoder and the digest owner are the same `to_vec_named` + // path the store writes through. + let encoded = rmp_serde::to_vec_named(&bench.kernel.state).expect("the state encodes"); + let decoded: WorldState = rmp_serde::from_slice(&encoded).expect("the state decodes"); + assert_eq!( + decoded.affordance_catalog, + bench.kernel.state.affordance_catalog + ); + assert!(digest(&bench.kernel.state).is_ok()); + } + + #[test] + fn a_forged_band_or_forged_effect_does_not_apply() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "ForgedAction"); + let opportunity = bench.clerk_opportunity(); + let command_id = CommandId::issue(); + let invocation = bench.carry(2, bench.yard); + let honest = draw_once(&bench.kernel.state, command_id, &opportunity, &invocation).unwrap(); + let caller = CallerId::Controller(opportunity.controller_id); + + for forged in [ + DecisionEvent { + band: 3, + ..honest.clone() + }, + DecisionEvent { + effects: vec![ResolvedOp::Transfer { + from: bench.clerk, + to: bench.keeper, + resource: bench.tithe, + qty: Quantity(OPENING_BALANCE), + }], + ..honest.clone() + }, + ] { + let mut candidate = bench.kernel.state.clone(); + let error = apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::DecisionExercised { + opportunity: opportunity.clone(), + invocation: invocation.clone(), + event: forged, + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + assert_eq!(candidate, bench.kernel.state); + } + + // The honest event still applies through the same arm. + let mut candidate = bench.kernel.state.clone(); + apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::DecisionExercised { + opportunity, + invocation: invocation.clone(), + event: honest, + }, + ) + .unwrap(); + assert_ne!(candidate.holdings, bench.kernel.state.holdings); + } + + #[test] + fn the_kernel_speak_entry_commits_its_utterance_and_no_operation() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "SpeakEntry"); + let _topology = activate(&mut kernel); + let active = kernel.snapshot().unwrap(); + let speak = affordance_named(&active, "speak"); + let human = active + .subjects + .iter() + .find(|subject| subject.human_controller.is_some()) + .expect("the human subject") + .id; + let holdings = kernel.state.holdings.clone(); + let receipt = kernel + .submit( + command( + &active, + CommandId::new(), + CallerId::Principal(human_principal()), + CommandBody::ExerciseDecision { + opportunity: opportunity_for(&active, human), + invocation: DecisionInvocation { + affordance: speak, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("I open the door.").unwrap()), + display: None, + }, + }, + ), + &auth_principal(human_principal()), + ) + .expect("the Speak entry commits"); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + let event = kernel.state.events.last().unwrap(); + assert_eq!(event.band, 0); + // The two the speech lowering prepends, and nothing from a slot. + assert_eq!(event.effects.len(), 2); + assert_eq!( + crate::tests::spoken(&kernel.state, event), + Some("I open the door.") + ); + assert_eq!(kernel.state.holdings, holdings); + } + + /// The civic bench: one world where an institution holds jurisdiction over + /// a hall, a person holds the same jurisdiction only through an office, and + /// two more people stand inside and outside that ground. + struct Civics { + kernel: WorldKernel, + active: WorldSnapshot, + topology: Topology, + civic: Civic, + } + + fn civics(directory: &std::path::Path, title: &str) -> Civics { + let mut kernel = custody_kernel(directory, title); + let (topology, civic, active) = civic_world(&mut kernel); + Civics { + kernel, + active, + topology, + civic, + } + } + + impl Civics { + fn refresh(&mut self) { + self.active = self.kernel.snapshot().unwrap(); + } + + fn call( + &self, + kind: &str, + bindings: Vec<RoleBinding>, + proposed: Vec<ProposedEffect>, + speech: Option<Statement>, + ) -> DecisionInvocation { + DecisionInvocation { + affordance: affordance_named(&self.active, kind), + bindings, + proposed, + speech, + display: None, + } + } + + /// A levy of `qty` from `payer`, always paid to the actor: the payee is + /// the reserved role, so it is not a binding the caller supplies. + fn levy(&self, payer: SubjectId, qty: u64) -> DecisionInvocation { + self.call( + "levy", + vec![ + binding("payer", Target::Subject(payer)), + binding("resource", Target::Entity(self.civic.grain)), + ], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(qty)), + }], + None, + ) + } + + fn delegate(&self, deputy: SubjectId, ground: EntityId) -> DecisionInvocation { + self.call( + "delegate", + vec![ + binding("deputy", Target::Subject(deputy)), + binding("ground", Target::Entity(ground)), + ], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ) + } + + /// Commands a subordinate to traverse a route: the fixture's one + /// `Relocate`-lowering affordance, gated by `command` authority over + /// the subordinate rather than by the subordinate's own consent. + fn deploy(&self, subordinate: SubjectId, via: EdgeId) -> DecisionInvocation { + self.call( + "deploy", + vec![ + binding("subordinate", Target::Subject(subordinate)), + binding("via", Target::Edge(via)), + ], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ) + } + + /// Strips `holder`'s `levy` grant over `ground`: the fixture's one + /// `RevokeAuthority`-lowering affordance, carrying no precondition of + /// its own so a rejection can only be the action lane's revocation + /// envelope. + fn revoke(&self, holder: SubjectId, ground: EntityId) -> DecisionInvocation { + self.call( + "revoke", + vec![ + binding("holder", Target::Subject(holder)), + binding("ground", Target::Entity(ground)), + ], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ) + } + + fn try_as( + &self, + actor: SubjectId, + invocation: &DecisionInvocation, + ) -> Result<DecisionEvent, KernelError> { + draw_once( + &self.kernel.state, + CommandId::issue(), + &opportunity_for(&self.active, actor), + invocation, + ) + } + + fn rejected_as( + &self, + actor: SubjectId, + invocation: &DecisionInvocation, + ) -> Vec<ActionMismatch> { + match self.try_as(actor, invocation) { + Err(KernelError::ActionRejected(rejected)) => rejected, + other => panic!("expected an action rejection, got {other:?}"), + } + } + + fn commit_as(&mut self, actor: SubjectId, invocation: DecisionInvocation) -> SubmitReceipt { + let opportunity = opportunity_for(&self.active, actor); + let caller = CallerId::Controller(opportunity.controller_id); + let receipt = self + .kernel + .submit( + command( + &self.active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .expect("the invocation commits"); + self.refresh(); + receipt + } + + fn admit(&mut self, ops: Vec<ComponentOp>) { + let before = self.kernel.snapshot().unwrap(); + let receipt = submit_owner(&mut self.kernel, &before, operations(ops)); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + self.refresh(); + } + + fn refuse(&mut self, ops: Vec<ComponentOp>) -> Vec<crate::Mismatch> { + let before = self.kernel.snapshot().unwrap(); + reject_owner(&mut self.kernel, &before, operations(ops)) + } + } + + /// Contract 7's third rejection: commanding outside authority, with the + /// exact failed precondition and no allocation. + #[test] + fn an_unauthorized_actor_names_the_failed_precondition() { + let directory = tempfile::tempdir().unwrap(); + let bench = civics(directory.path(), "Unauthorized"); + let before = bench.kernel.state.clone(); + assert_eq!( + bench.rejected_as(bench.civic.farmer, &bench.levy(bench.civic.reeve, 1)), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + assert_eq!(bench.kernel.state.revision, before.revision); + assert_eq!(bench.kernel.state.holdings, before.holdings); + assert_eq!(bench.kernel.state.events, before.events); + } + + /// A place jurisdiction reaches everything under it and nothing else, and + /// the answer is read live: a target that walks out of the subtree stops + /// being authorized without any digest moving. + #[test] + fn place_jurisdiction_reaches_a_containment_subtree_and_stops_at_its_edge() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = civics(directory.path(), "Subtree"); + let treasury = bench.civic.treasury; + let farmer = bench.civic.farmer; + + // The farmer stands in the chamber, whose container is the hall. + assert!(bench.try_as(treasury, &bench.levy(farmer, 1)).is_ok()); + + // The pedlar stands on the road, outside the hall entirely, and an + // unplaced subject is covered by no place target. + assert_eq!( + bench.rejected_as(treasury, &bench.levy(bench.civic.outsider, 1)), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + let unplaced = *bench + .kernel + .state + .subjects + .keys() + .find(|subject_id| !bench.kernel.state.positions.contains_key(subject_id)) + .expect("the genesis world declares an unplaced subject"); + assert_eq!( + bench.rejected_as(treasury, &bench.levy(unplaced, 1)), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + + // Walking the farmer out of the hall flips the same invocation, and a + // grant naming the subject directly authorizes it again. + bench.admit(vec![ + ComponentOp::Relocate { + subject: PatchRef::Existing(farmer), + via: PatchRef::Existing(bench.civic.passage), + }, + ComponentOp::Relocate { + subject: PatchRef::Existing(farmer), + via: PatchRef::Existing(bench.civic.causeway), + }, + ]); + assert_eq!( + bench.rejected_as(treasury, &bench.levy(farmer, 1)), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + bench.admit(vec![grant_to(treasury, LEVY_KIND, over_subject(farmer))]); + assert!(bench.try_as(treasury, &bench.levy(farmer, 1)).is_ok()); + } + + /// An office lends jurisdiction its holder does not own, vacating takes it + /// back, and a proposal bound before the vacate rebinds rather than + /// rejecting: revocation mid-flight is a `ScopeChanged`. + #[test] + fn office_delegation_grants_and_vacating_revokes() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = civics(directory.path(), "Office"); + let reeve = bench.civic.reeve; + let farmer = bench.civic.farmer; + assert!(bench.kernel.state.authority.get(&reeve).is_none()); + assert!(bench.try_as(reeve, &bench.levy(farmer, 1)).is_ok()); + + // A proposal bound before the vacate rebinds rather than rejecting. + let bound = opportunity_for(&bench.active, reeve); + let caller = CallerId::Controller(bound.controller_id); + let invocation = bench.levy(farmer, 1); + bench.admit(vec![ComponentOp::VacateOffice { + institution: PatchRef::Existing(bench.civic.treasury), + office: office(WARDEN_OFFICE), + }]); + + let holdings = bench.kernel.state.holdings.clone(); + let error = bench + .kernel + .submit( + command( + &bench.active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity: bound.clone(), + invocation, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap_err(); + let KernelError::ScopeChanged { + scope, expected, .. + } = error + else { + panic!("a vacated office is a rebind, not a rejection"); + }; + assert_eq!(scope, bound.scope); + assert_eq!(expected, bound.scope_digest); + assert_eq!(bench.kernel.state.holdings, holdings); + assert_eq!( + bench.rejected_as(reeve, &bench.levy(farmer, 1)), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + } + + /// The reserved role in both directions: an invocation may not bind it, and + /// a catalog entry may not declare it. + #[test] + fn a_levy_cannot_be_directed_away_from_the_actor() { + let directory = tempfile::tempdir().unwrap(); + let bench = civics(directory.path(), "ActorRole"); + let mut redirected = bench.levy(bench.civic.farmer, 1); + redirected + .bindings + .push(binding("actor", Target::Subject(bench.civic.outsider))); + assert_eq!( + bench.rejected_as(bench.civic.treasury, &redirected), + vec![ActionMismatch::ActorRoleBound] + ); + + // The declaration half is Draft-only, so it runs against a fresh world. + let draft_directory = tempfile::tempdir().unwrap(); + let mut draft = custody_kernel(draft_directory.path(), "ReservedRole"); + let before = draft.snapshot().unwrap(); + let handle = DraftHandle::new("thief"); + let rejected = reject_owner( + &mut draft, + &before, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![Declaration::Affordance(AffordanceDeclaration { + handle: handle.clone(), + kind: AffordanceKindName("thief".into()), + roles: vec![RoleSpec { + role: Role("actor".into()), + kind: RefKind::Subject(None), + }], + preconditions: vec![Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + assert!(rejected.contains(&crate::Mismatch::ReservedRole { handle })); + } + + /// The two rejection lanes stay distinguishable: an over-levy inside its + /// declared ceiling passes every affordance check and dies in the ledger. + #[test] + fn an_over_levy_fails_in_the_ledger_not_in_the_contract() { + let directory = tempfile::tempdir().unwrap(); + let bench = civics(directory.path(), "OverLevy"); + let error = bench + .try_as(bench.civic.treasury, &bench.levy(bench.civic.farmer, 9)) + .unwrap_err(); + let KernelError::PatchRejected(rejected) = error else { + panic!("an over-levy is a ledger rejection"); + }; + assert_eq!( + rejected, + vec![crate::Mismatch::InsufficientCustody { operation: 0 }] + ); + } + + /// A delegated grant may not exceed the granter's own, and the grant it + /// does mint is still subject to disjointness. + #[test] + fn a_delegated_grant_may_not_exceed_the_granter() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = civics(directory.path(), "Monotone"); + let treasury = bench.civic.treasury; + let outsider = bench.civic.outsider; + + // The treasury commands the road but does not levy it, so the + // precondition passes and the delegation alone is refused. + let road = bench.topology.road; + bench.admit(vec![grant_to(treasury, COMMAND_KIND, over_place(road))]); + let outside = bench.delegate(outsider, road); + assert_eq!( + bench.rejected_as(treasury, &outside), + vec![ActionMismatch::DelegationNotMonotone { slot: 0 }] + ); + + // The chamber is inside it, so the same act commits and the deputy can + // then levy there. + let inside = bench.delegate(outsider, bench.civic.chamber); + assert!(matches!( + bench.commit_as(treasury, inside), + SubmitReceipt::Applied(_) + )); + assert!( + bench + .try_as(outsider, &bench.levy(bench.civic.farmer, 1)) + .is_ok() + ); + + // An office lends exactly the kinds it delegates: the warden's `levy` + // does not make its holder a commander. + let again = bench.delegate(outsider, bench.civic.chamber); + assert_eq!( + bench.rejected_as(bench.civic.reeve, &again), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + + // The minted grant is ordinary state: repeating it changes nothing, and + // widening it to the hall would overlap what the deputy already holds. + let error = bench.try_as(treasury, &again).unwrap_err(); + let KernelError::PatchRejected(rejected) = error else { + panic!("a duplicate delegation is a patch rejection"); + }; + assert_eq!( + rejected, + vec![crate::Mismatch::NoOperationEffect { operation: 0 }] + ); + let hall = bench.civic.hall; + assert_eq!( + bench.refuse(vec![grant_to(outsider, LEVY_KIND, over_place(hall))]), + vec![crate::Mismatch::OverlappingJurisdiction { operation: 0 }] + ); + } + + /// The revocation envelope is the same predicate as the grant one, read + /// the other way: an actor may strip a `levy` grant only over ground its + /// own authority covers, so a bystander cannot use `revoke` to reach past + /// what it may otherwise touch. + #[test] + fn revoking_a_grant_requires_covering_authority_over_its_ground() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = civics(directory.path(), "RevokeEnvelope"); + let treasury = bench.civic.treasury; + let farmer = bench.civic.farmer; + let hall = bench.civic.hall; + + // The farmer holds no authority at all, so stripping the treasury's + // own `levy` grant over the hall fails the envelope before the patch + // lane ever sees the operation. + assert_eq!( + bench.rejected_as(farmer, &bench.revoke(treasury, hall)), + vec![ActionMismatch::DelegationNotMonotone { slot: 0 }] + ); + + // The treasury's own `levy` grant over the hall covers the hall, so + // the treasury may strip its own grant, and the ledger loses it. + assert!(matches!( + bench.commit_as(treasury, bench.revoke(treasury, hall)), + SubmitReceipt::Applied(_) + )); + assert!( + !bench + .kernel + .state + .authority + .get(&treasury) + .is_some_and(|grants| grants.contains(&crate::AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: crate::AuthorityTarget::PlaceSubtree(hall), + })), + "the revoked grant is gone from the ledger" + ); + } + + /// The fixture's one `Relocate`-lowering affordance: a commander may move + /// a subordinate standing under its ground, and one standing outside it + /// fails the same `Authorized` precondition every other civic act reads. + #[test] + fn deploy_relocates_a_subordinate_under_command_and_refuses_one_outside_it() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = civics(directory.path(), "Deploy"); + let treasury = bench.civic.treasury; + let farmer = bench.civic.farmer; + let outsider = bench.civic.outsider; + let chamber = bench.civic.chamber; + let hall = bench.civic.hall; + let passage = bench.civic.passage; + + // The pedlar stands on the road, outside the hall the treasury + // commands, so the precondition alone refuses the attempt. + assert_eq!( + bench.rejected_as(treasury, &bench.deploy(outsider, passage)), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + + // The farmer stands in the chamber, under the treasury's command, and + // the passage carries it into the hall the same way a direct + // `Relocate` would. + assert_eq!( + bench + .kernel + .state + .positions + .get(&farmer) + .map(|position| position.place), + Some(chamber) + ); + assert!(matches!( + bench.commit_as(treasury, bench.deploy(farmer, passage)), + SubmitReceipt::Applied(_) + )); + assert_eq!( + bench + .kernel + .state + .positions + .get(&farmer) + .map(|position| position.place), + Some(hall) + ); + } + + /// `Redress` with a reducer reader: standing is the covering predicate over + /// the forum's target, and closing the forum removes the verb's ground. + #[test] + fn a_petition_requires_standing() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = civics(directory.path(), "Petition"); + let petition = bench.call( + "petition", + Vec::new(), + Vec::new(), + Some(Statement::new("The tithe was taken twice.").unwrap()), + ); + assert_eq!( + bench.rejected_as(bench.civic.outsider, &petition), + vec![ActionMismatch::NoStanding { precondition: 0 }] + ); + + let farmer = bench.civic.farmer; + assert!(matches!( + bench.commit_as(farmer, petition.clone()), + SubmitReceipt::Applied(_) + )); + let event = bench + .kernel + .state + .events + .last() + .expect("the committed event"); + assert_eq!(event.effects.len(), 2); + assert_eq!( + crate::tests::spoken(&bench.kernel.state, event), + Some("The tithe was taken twice.") + ); + + bench.admit(vec![ComponentOp::CloseForum { + grievance: grievance(SEIZURE_GRIEVANCE), + }]); + assert_eq!( + bench.rejected_as(farmer, &petition), + vec![ActionMismatch::NoStanding { precondition: 0 }] + ); + } + + /// One predicate, two callers: the resolver's `Relocate` arm and + /// `Reachable`'s edge admission read the same `Restricted` rule, and a + /// same-patch grant then move resolves through the candidate shadow. + #[test] + fn a_restricted_route_admits_exactly_its_named_authority() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = civics(directory.path(), "Restricted"); + let walker = bench.topology.walker; + let step = ComponentOp::Relocate { + subject: PatchRef::Existing(walker), + via: PatchRef::Existing(bench.civic.postern), + }; + + // Holding nothing, and holding `admit` over the origin only, are both + // refused: the rule asks about the destination. + assert!( + bench + .refuse(vec![step.clone()]) + .contains(&crate::Mismatch::RouteAccessRestricted { operation: 0 }) + ); + let yard = bench.topology.yard; + bench.admit(vec![grant_to(walker, ADMIT_KIND, over_place(yard))]); + assert!( + bench + .refuse(vec![step.clone()]) + .contains(&crate::Mismatch::RouteAccessRestricted { operation: 0 }) + ); + + // Reachable reads the same rule from the other side. + let authority = crate::subject_authority(&bench.kernel.state, walker); + assert!(!reachable( + &bench.kernel.state, + walker, + &authority, + bench.civic.chamber, + Cost(4) + )); + + // A grant covering the destination, minted in the same patch as the + // move, resolves through the candidate authority shadow. + let hall = bench.civic.hall; + let authority = crate::subject_authority(&bench.kernel.state, walker); + assert!(!patch::route_admits( + &bench.kernel.state, + &authority, + bench.kernel.state.edges[&bench.civic.postern].access(), + bench.civic.chamber + )); + bench.admit(vec![grant_to(walker, ADMIT_KIND, over_place(hall)), step]); + assert_eq!( + bench.kernel.state.positions[&walker].place, + bench.civic.chamber + ); + let authority = crate::subject_authority(&bench.kernel.state, walker); + assert!(patch::route_admits( + &bench.kernel.state, + &authority, + bench.kernel.state.edges[&bench.civic.postern].access(), + bench.civic.chamber + )); + } + + /// The remaining institutional affordances, each proving one lowering arm: + /// `sanction` closes shared topology under a legitimacy check with an + /// interdiction band that fails, and `appoint` makes succession an act + /// someone performs under authority rather than a declared method string. + #[test] + fn sanction_and_appoint_reach_the_reducer_under_authority() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = civics(directory.path(), "Institutional"); + let treasury = bench.civic.treasury; + let passage = bench.civic.passage; + let sanction = bench.call( + "sanction", + vec![binding("road", Target::Edge(passage))], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ); + + // The reeve holds the verb but its office lends only `levy`, so the same + // act names the precondition it failed. + assert_eq!( + bench.rejected_as(bench.civic.reeve, &sanction), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + + // The treasury commands the hall, and the passage has both endpoints + // under it. The draw decides whether the interdiction lands. + let opportunity = opportunity_for(&bench.active, treasury); + let closing = (0..256) + .map(|_| CommandId::issue()) + .find(|candidate| { + draw_once(&bench.kernel.state, *candidate, &opportunity, &sanction) + .expect("the invocation is admissible") + .band + == 0 + }) + .expect("a two-band entry reaches its first band over 256 command ids"); + let caller = CallerId::Controller(opportunity.controller_id); + let receipt = bench + .kernel + .submit( + command( + &bench.active, + closing, + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation: sanction, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .expect("the sanction commits"); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + bench.refresh(); + assert!(!bench.kernel.state.edges[&passage].is_open()); + + // Appointment installs an incumbent through the action lane. + let farmer = bench.civic.farmer; + let appoint = bench.call( + "appoint", + vec![ + binding("institution", Target::Subject(treasury)), + binding("candidate", Target::Subject(farmer)), + ], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ); + assert!(matches!( + bench.commit_as(treasury, appoint), + SubmitReceipt::Applied(_) + )); + assert_eq!( + bench.kernel.state.selection[&treasury][&office("bailiff")].incumbent, + Some(farmer) + ); + } + + // --- Soul: pass-5 falsification ------------------------------------- + + /// Submits an invocation through the real command path and hands back + /// whatever the kernel decided, refusal included. + fn soul_submit( + bench: &mut Civics, + actor: SubjectId, + invocation: DecisionInvocation, + ) -> Result<SubmitReceipt, KernelError> { + let opportunity = opportunity_for(&bench.active, actor); + let caller = CallerId::Controller(opportunity.controller_id); + bench.kernel.submit( + command( + &bench.active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + } + + /// `DelegationNotMonotone` is not a fixture-only verdict: the real `submit` + /// path reaches it, and the refused act commits nothing. + #[test] + fn soul_delegation_not_monotone_reaches_the_real_command_path() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = civics(directory.path(), "SoulMonotone"); + let treasury = bench.civic.treasury; + let road = bench.topology.road; + let outsider = bench.civic.outsider; + bench.admit(vec![grant_to(treasury, COMMAND_KIND, over_place(road))]); + let invocation = bench.delegate(outsider, road); + let before = bench.kernel.state.clone(); + let error = soul_submit(&mut bench, treasury, invocation).unwrap_err(); + let KernelError::ActionRejected(rejected) = error else { + panic!("an over-wide delegation is an action rejection"); + }; + assert_eq!( + rejected, + vec![ActionMismatch::DelegationNotMonotone { slot: 0 }] + ); + assert_eq!(bench.kernel.state.revision, before.revision); + assert_eq!(bench.kernel.state.authority, before.authority); + assert_eq!(bench.kernel.state.events.len(), before.events.len()); + } + + /// The `Restricted` rule is enforced by the component writer, not only by + /// the resolver: a forged `ResolvedOp` that skipped `resolve_patch` still + /// cannot walk a subject through a door it holds no key to, and the same + /// operation succeeds the moment the key exists. + #[test] + fn soul_a_restricted_relocate_is_refused_by_the_component_writer() { + let directory = tempfile::tempdir().unwrap(); + let bench = civics(directory.path(), "SoulReducerGate"); + let walker = bench.topology.walker; + let step = ResolvedOp::Relocate { + subject_id: walker, + edge_id: bench.civic.postern, + }; + + let mut forged = bench.kernel.state.clone(); + forged.positions.insert( + walker, + crate::patch::Position { + place: bench.topology.yard, + }, + ); + let mut refused = forged.clone(); + let resolves_to = refused.revision + 1; + let error = + crate::apply_operations(&mut refused, std::slice::from_ref(&step), &[], resolves_to) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + + let mut admitted = forged; + admitted.authority.insert( + walker, + BTreeSet::from([crate::AuthorityGrant { + kind: crate::tests::authority_kind(ADMIT_KIND), + over: crate::AuthorityTarget::PlaceSubtree(bench.civic.hall), + }]), + ); + let resolves_to = admitted.revision + 1; + crate::apply_operations(&mut admitted, std::slice::from_ref(&step), &[], resolves_to) + .expect("the named key opens the door at the component writer too"); + assert_eq!(admitted.positions[&walker].place, bench.civic.chamber); + } + + /// The rebind requirement at the layer the operator sees it: a grant change + /// on the *granter* invalidates the delegate's bound opportunity, and the + /// refusal is `ScopeChanged`, not `ActionRejected`. + #[test] + fn soul_a_granter_revocation_rebinds_the_delegate() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = civics(directory.path(), "SoulRebind"); + let reeve = bench.civic.reeve; + let farmer = bench.civic.farmer; + let treasury = bench.civic.treasury; + let hall = bench.civic.hall; + + // Bound before the revocation, submitted after it. + let bound = bench.active.clone(); + let opportunity = opportunity_for(&bound, reeve); + let caller = CallerId::Controller(opportunity.controller_id); + let invocation = bench.levy(farmer, 1); + bench.admit(vec![ComponentOp::RevokeAuthority { + holder: PatchRef::Existing(treasury), + grant: crate::tests::grant_of(LEVY_KIND, over_place(hall)), + }]); + // The envelope carries the current revision, so only the stale scope + // digest can refuse it. + assert_ne!(bound.revision, bench.active.revision); + let error = bench + .kernel + .submit( + command( + &bench.active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap_err(); + assert!( + matches!(error, KernelError::ScopeChanged { .. }), + "a revoked lend is a rebind, not a rejection: {error:?}" + ); + } + + /// Structural overlap alone does not see a `Subject` grant sitting inside + /// a `PlaceSubtree` grant of the same kind: `targets_overlap` compares + /// shapes, not position, and stays that way so the answer cannot decay + /// when a subject walks somewhere. Admission catches the cross-shape case + /// live instead, in the resolver where the second grant lands, using the + /// same covering predicate `Authorized` reads. Both directions fire the + /// identical check, so whichever grant is minted second is the one that + /// is refused. + #[test] + fn soul_a_subject_grant_inside_a_place_grant_is_a_second_source() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = civics(directory.path(), "SoulOverlap"); + let treasury = bench.civic.treasury; + let farmer = bench.civic.farmer; + let hall = bench.civic.hall; + + // The farmer stands under the hall the treasury already levies, so the + // covering predicate says both grants would answer for the same + // target, and admission refuses the narrower grant landing second. + assert!(crate::covers( + &bench.kernel.state, + crate::AuthorityTarget::PlaceSubtree(hall), + Target::Subject(farmer) + )); + assert_eq!( + bench.refuse(vec![grant_to(treasury, LEVY_KIND, over_subject(farmer))]), + vec![crate::Mismatch::OverlappingJurisdiction { operation: 0 }] + ); + + // The symmetric order: a direct grant over the farmer, minted first + // under a fresh kind, blocks a later place grant that would cover + // him too. + const AUDIT_KIND: &str = "audit"; + bench.admit(vec![grant_to(treasury, AUDIT_KIND, over_subject(farmer))]); + assert_eq!( + bench.refuse(vec![grant_to(treasury, AUDIT_KIND, over_place(hall))]), + vec![crate::Mismatch::OverlappingJurisdiction { operation: 0 }] + ); + } + + /// Replay for the new arms is not a separate machine: `reduce` is a pure + /// function of committed state and the envelope, so running it twice on the + /// same pre-state yields the same effect, and that effect is exactly what + /// the commit stored. No clock and no draw entropy enter. + #[test] + fn soul_reduce_is_pure_for_every_new_civic_arm() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = civics(directory.path(), "SoulReplay"); + let treasury = bench.civic.treasury; + let farmer = bench.civic.farmer; + let outsider = bench.civic.outsider; + let chamber = bench.civic.chamber; + let passage = bench.civic.passage; + + let sanction = bench.call( + "sanction", + vec![binding("road", Target::Edge(passage))], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ); + let appoint = bench.call( + "appoint", + vec![ + binding("institution", Target::Subject(treasury)), + binding("candidate", Target::Subject(farmer)), + ], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ); + for invocation in [ + bench.levy(farmer, 2), + bench.delegate(outsider, chamber), + sanction, + appoint, + ] { + let before = bench.kernel.state.clone(); + let opportunity = opportunity_for(&bench.active, treasury); + let caller = CallerId::Controller(opportunity.controller_id); + let envelope = command( + &bench.active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation, + }, + ); + let first = crate::reduce(&before, &envelope).expect("the act reduces"); + let second = crate::reduce(&before, &envelope).expect("the act reduces again"); + assert_eq!(first, second, "reduce is not a pure function of the state"); + let receipt = bench + .kernel + .submit(envelope, &AuthenticatedCaller::fixture(caller)) + .expect("the act commits"); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + bench.refresh(); + let WorldEffect::DecisionExercised { event, .. } = first else { + panic!("an exercised decision"); + }; + assert_eq!( + bench.kernel.state.events.last().expect("a committed event"), + &event, + "the committed event is not what reduce produced" + ); + } + } + + /// `resolve_patch`'s candidate knowledge map never models `Communicate`'s + /// fan-out (see the comment beside its construction in `patch.rs`), and + /// that omission is safe only because no `ComponentOpKind` an affordance + /// may declare can lower to a knowledge write carrying + /// `KnowledgeSource::Told`. Two kinds touch knowledge: `AcquireKnowledge`, + /// whose source `lower` fixes to `AuthoredSource::Witnessed` — a type with + /// no `Told` variant to begin with — and `Witness`, which carries no source + /// field and no speaker field at all. This test pins both lowerings, at the + /// call sites that turn a declared slot into a `ComponentOp`, so a future + /// author cannot widen either without this assertion naming the change. + #[test] + fn no_component_op_kind_lowers_to_a_told_knowledge_write() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "AcquireKnowledgeLowering"); + let entry = Affordance { + kind: AffordanceKindName("witness".into()), + roles: Vec::new(), + preconditions: Vec::new(), + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::AcquireKnowledge { + confidence: Confidence::Believed, + }, + roles: vec![Role("subject".into()), Role("fact".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }; + let bindings = BTreeMap::from([ + (Role("subject".into()), Target::Subject(bench.clerk)), + (Role("fact".into()), Target::Entity(bench.tithe)), + ]); + let invocation = DecisionInvocation { + affordance: bench.carry, + bindings: Vec::new(), + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + speech: None, + display: None, + }; + let lowered = lower( + &entry, + 0, + bench.clerk, + FictionalMinutes::default(), + &invocation, + &bindings, + ) + .expect("the acquire slot lowers"); + assert_eq!( + lowered, + vec![ComponentOp::AcquireKnowledge { + subject: PatchRef::Existing(bench.clerk), + fact: PatchRef::Existing(bench.tithe), + source: AuthoredSource::Witnessed, + confidence: Confidence::Believed, + }], + "AcquireKnowledge must lower with a Witnessed source, never a forged teller" + ); + + let witnessing = Affordance { + kind: AffordanceKindName("beacon".into()), + roles: Vec::new(), + preconditions: Vec::new(), + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::Witness { + confidence: Confidence::Believed, + }, + roles: vec![Role("fact".into()), Role("place".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }; + let places = BTreeMap::from([ + (Role("fact".into()), Target::Entity(bench.tithe)), + (Role("place".into()), Target::Entity(bench.yard)), + ]); + let lowered = lower( + &witnessing, + 0, + bench.clerk, + FictionalMinutes::default(), + &invocation, + &places, + ) + .expect("the witness slot lowers"); + assert_eq!( + lowered, + vec![ComponentOp::Witness { + fact: PatchRef::Existing(bench.tithe), + place: PatchRef::Existing(bench.yard), + confidence: Confidence::Believed, + }], + "Witness must lower with no speaker field to forge" + ); + } + + /// The pin above names two knowledge-touching kinds by example, and a list + /// by example goes stale in silence. This match is exhaustive, so a new + /// `ComponentOpKind` breaks the build here and its author must say whether + /// it touches knowledge. The set that does is `AcquireKnowledge`, `Witness`, + /// and `Forget`; the first two are pinned above as unable to carry a teller, + /// and `Forget` writes no row at all — it only removes one, so it has no + /// source to forge. + #[test] + fn soul_every_knowledge_touching_op_kind_is_named_by_the_told_pin() { + fn touches_knowledge(kind: &ComponentOpKind) -> bool { + match kind { + ComponentOpKind::AcquireKnowledge { .. } + | ComponentOpKind::Witness { .. } + | ComponentOpKind::Forget => true, + ComponentOpKind::Relocate + | ComponentOpKind::OpenRoute + | ComponentOpKind::CloseRoute + | ComponentOpKind::AlterCost + | ComponentOpKind::Transfer + | ComponentOpKind::Transform + | ComponentOpKind::Consume + | ComponentOpKind::Bind + | ComponentOpKind::Release + | ComponentOpKind::GrantAuthority { .. } + | ComponentOpKind::RevokeAuthority { .. } + | ComponentOpKind::InstallIncumbent { .. } + | ComponentOpKind::VacateOffice { .. } + | ComponentOpKind::CreateCommitment { .. } + | ComponentOpKind::AdvancePressure { .. } + | ComponentOpKind::ReducePressure { .. } + | ComponentOpKind::ResolvePressure => false, + } + } + + let confidence = Confidence::Believed; + let touching = [ + ComponentOpKind::AcquireKnowledge { confidence }, + ComponentOpKind::Witness { confidence }, + ComponentOpKind::Forget, + ComponentOpKind::Relocate, + ComponentOpKind::Transfer, + ComponentOpKind::ResolvePressure, + ] + .iter() + .filter(|kind| touches_knowledge(kind)) + .count(); + assert_eq!( + touching, 3, + "the knowledge-touching set is not the one this pin names" + ); + } +} diff --git a/native/aetherlight/src/clock.rs b/native/aetherlight/src/clock.rs new file mode 100644 index 000000000..a02c21560 --- /dev/null +++ b/native/aetherlight/src/clock.rs @@ -0,0 +1,213 @@ +//! The world clock and the motion one tick produces. +//! +//! One entry point into the reducer, [`derive_motion`], reached from `reduce`'s +//! `AdvanceTime` arm and from `apply_effect`'s `TimeAdvanced` arm, so a forged +//! tick is re-derived by the same function that produced the honest one. It is +//! pure over `(state, to)`: no wall clock, no entropy, no caller value beyond +//! the span. + +use super::patch::{Commitment, CommitmentKey, CommitmentKind, DependencyTarget, MAX_ROUTE_COST}; +use super::{PressureMagnitude, PressureSource, SubjectId, WorldState, action, is_retired}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +/// Minutes since genesis. Monotonic, kernel-owned, world-level. `u64` because a +/// world clock has no bound; `Cost` is `1..=MAX_ROUTE_COST` because it weighs +/// one edge, and reusing it here would put an edge's bound on the world's age. +#[derive( + Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, +)] +#[serde(transparent)] +pub struct FictionalMinutes(pub u64); + +impl FictionalMinutes { + pub(crate) fn checked_add(self, span: TickMinutes) -> Option<Self> { + self.0.checked_add(u64::from(span.0)).map(Self) + } + + /// Minutes elapsed since an earlier reading. Saturating because the caller + /// is the attention order, which reads a stamp `verify_state_shape` already + /// holds to `<= now`. + pub(crate) fn since(self, earlier: Self) -> u64 { + self.0.saturating_sub(earlier.0) + } +} + +/// The span one `AdvanceTime` names. Constructor-checked `1..=MAX_ROUTE_COST` +/// (one year of minutes), reusing pass 2's constant as a span bound rather than +/// an edge bound: an unbounded span lets one command jump the clock past every +/// due date in the world and makes the size of a commit a caller-chosen number. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[serde(transparent)] +pub struct TickMinutes(u32); + +impl TickMinutes { + pub fn new(minutes: u32) -> Option<Self> { + (1..=MAX_ROUTE_COST) + .contains(&minutes) + .then_some(Self(minutes)) + } + + pub fn minutes(self) -> u32 { + self.0 + } +} + +/// Everything one tick moves, stated as outcomes rather than deltas so the +/// effect says what the world became. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct Motion { + /// Routines that fulfilled, in `(subject, key)` order. + pub(crate) fulfilled: Vec<RoutineFulfilled>, + /// Pressure rows written, in `(target, source)` order, with the resulting + /// magnitude — not the delta. + pub(crate) pressed: Vec<PressureWritten>, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct RoutineFulfilled { + pub(crate) subject: SubjectId, + pub(crate) key: CommitmentKey, + pub(crate) next_due: FictionalMinutes, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct PressureWritten { + pub(crate) target: SubjectId, + pub(crate) source: PressureSource, + pub(crate) magnitude: PressureMagnitude, +} + +/// The whole magnitude policy, in one place, with no per-world tuning. A +/// blocked routine raises none at all: it retries on the next tick, which is +/// what keeps an unattended subject free of spurious pressure. +mod step { + pub(super) const OBLIGATION_PAST_DUE: u32 = 1; + pub(super) const GOAL_PAST_DUE: u32 = 1; + pub(super) const DEPENDENCY_UNAVAILABLE: u32 = 1; +} + +/// Three stages, each reading only committed `state` and `to`. No stage sees +/// another stage's writes, which is what makes this a one-pass total function +/// with no ordering hazard and no partial state to reason about. +/// +/// Pressure accrues per command, not per minute: one thousand one-minute ticks +/// and one thousand-minute tick over the same span produce different +/// magnitudes. The kernel stays an exact function of the command sequence, and +/// the tick cadence is one operational constant in `runtime.rs`. +pub(super) fn derive_motion(state: &WorldState, to: FictionalMinutes) -> Motion { + let mut fulfilled = Vec::new(); + let mut pressed: BTreeMap<(SubjectId, PressureSource), u32> = BTreeMap::new(); + + for (subject, held) in &state.commitments { + // A retired subject cannot act, and neither fulfilling a routine nor + // pressing an obligation or goal is anything but that subject acting: + // its commitments stay in history, un-discharged and un-deleted, but + // the clock stops moving them the moment they are its. + if is_retired(state, *subject) { + continue; + } + for (key, commitment) in held { + if commitment.due > to { + continue; + } + match commitment.kind { + CommitmentKind::Routine => { + if let Some(next_due) = routine_rolls(state, *subject, commitment) { + fulfilled.push(RoutineFulfilled { + subject: *subject, + key: *key, + next_due, + }); + } + } + CommitmentKind::Obligation | CommitmentKind::Goal => { + let step = if commitment.kind == CommitmentKind::Obligation { + step::OBLIGATION_PAST_DUE + } else { + step::GOAL_PAST_DUE + }; + let source = PressureSource::Commitment { + subject: *subject, + key: *key, + }; + *pressed.entry((*subject, source)).or_default() += step; + } + } + } + } + + for (subject, targets) in &state.dependencies { + if is_retired(state, *subject) { + continue; + } + for target in targets { + if dependency_unavailable(state, *subject, *target) { + let source = PressureSource::Dependency(*target); + *pressed.entry((*subject, source)).or_default() += step::DEPENDENCY_UNAVAILABLE; + } + } + } + + Motion { + fulfilled, + pressed: pressed + .into_iter() + .map(|((target, source), step)| PressureWritten { + target, + source, + magnitude: PressureMagnitude( + state + .pressures + .get(&target) + .and_then(|held| held.get(&source)) + .map_or(0, |magnitude| magnitude.0) + .saturating_add(step), + ), + }) + .collect(), + } +} + +/// A routine fulfils when every one of its checks holds, and its `due` then +/// rolls forward by exactly one period per command. Catch-up arithmetic would +/// make the number of fulfilments a function of the operator's tick cadence in +/// a second place; one roll converges over subsequent ticks. +fn routine_rolls( + state: &WorldState, + subject: SubjectId, + commitment: &Commitment, +) -> Option<FictionalMinutes> { + if !action::preconditions_hold(state, subject, &commitment.checks).is_empty() { + return None; + } + commitment.due.checked_add(commitment.period?) +} + +/// Whether a subject's dependency is currently failing it. A closed route is a +/// supply failure; an unusable one is a permission question, and reading +/// authority here would drag `effective_authority` into every tick for every +/// dependency in the world. +pub(super) fn dependency_unavailable( + state: &WorldState, + subject: SubjectId, + target: DependencyTarget, +) -> bool { + match target { + DependencyTarget::Route(edge_id) => !state + .edges + .get(&edge_id) + .is_some_and(super::EdgeRecord::is_open), + // Absence is zero, per pass 3: the depender holds none of what it + // depends on. + DependencyTarget::Resource(entity_id) => !state + .holdings + .get(&subject) + .is_some_and(|held| held.contains_key(&entity_id)), + // The subject it depends on is nowhere in the world's topology. + DependencyTarget::Subject(other) => !state.positions.contains_key(&other), + } +} diff --git a/native/aetherlight/src/cover.rs b/native/aetherlight/src/cover.rs new file mode 100644 index 000000000..5d1ce4233 --- /dev/null +++ b/native/aetherlight/src/cover.rs @@ -0,0 +1,1105 @@ +//! The budgeted connected cover: one tick's partition of the active +//! opportunities into cells. +//! +//! This organ owns the partition and nothing else. [`derive_cover`] is pure +//! over its arguments — no clock, no entropy, no mailbox, no filesystem — and +//! the [`Cover`] it returns is derived and disposable. A cell never enters +//! `WorldState`, a `CommandEnvelope`, a `ScopePreimage`, a `DecisionOpportunity`, +//! or any `Declaration`; the kernel never learns a tick happened except through +//! `AdvanceTime` and ordinary one-opportunity submissions. +//! +//! The cover is a partition, never a filter: every active subject is in exactly +//! one cell every tick. The budget decides at what resolution, not whether. + +use super::{ControllerMode, DecisionOpportunity, SubjectId, WorldId}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, BTreeSet}; +use uuid::Uuid; + +/// A place, resource, or channel with more associated subjects than this +/// contributes a star centred on its lowest member instead of a clique. +/// Connectivity is identical for component purposes and the edge count stops +/// being quadratic in a crowded room. +pub(crate) const AGENCY_STAR_THRESHOLD: usize = 16; + +/// The namespace every derived cover id is salted with. A fixed constant, never +/// regenerated: two worlds in one process are separated by the world id inside +/// the name, not by a second namespace. +const COVER_NAMESPACE: &str = "ghostlight.cover.v1"; + +/// A tick's ordinal: the number of clock advances the world had committed when +/// the tick opened. The driver reads it from the world and freezes it in the +/// tick document; it is never derived from `now`, so it does not depend on the +/// span. It is threaded into every derived command id, so a resumed tick +/// re-submits the same ids and the kernel's idempotency ledger answers with the +/// original receipts instead of double-committing. +#[derive( + Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Default, +)] +#[serde(transparent)] +pub struct TickIndex(pub u64); + +/// How a subject was represented this tick. Derived from the cell, carried +/// nowhere in world state: representation is a compute budget, not world truth. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "resolution", rename_all = "snake_case")] +pub enum Resolution { + Detail, + Coarse { constituents: usize }, +} + +/// Derived from the partition, so a replayed tick over the same inputs produces +/// byte-identical ids. sha256 over `(namespace, world, tick, size, lowest +/// member)`; no `uuid/v5`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(transparent)] +pub struct CellId(Uuid); + +impl std::fmt::Display for CellId { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(formatter, "{}", self.0) + } +} + +fn derive_uuid(name: &str) -> Uuid { + let mut hasher = Sha256::new(); + hasher.update(COVER_NAMESPACE.as_bytes()); + hasher.update([0u8]); + hasher.update(name.as_bytes()); + let bytes: [u8; 16] = hasher.finalize()[..16] + .try_into() + .expect("sha256 yields at least sixteen bytes"); + Uuid::from_bytes(bytes) +} + +/// `members.len()` is in the name so a component that splits differently under +/// a different cap yields a different cell, and a resumed tick over the same +/// inputs yields the same one. +fn cell_id(world: WorldId, tick: TickIndex, members: &[SubjectId]) -> CellId { + let lowest = members + .first() + .copied() + .expect("a cell always has at least one member"); + CellId(derive_uuid(&format!( + "cell|{world:?}|{}|{}|{lowest:?}", + tick.0, + members.len() + ))) +} + +/// The stable, derived identity a cell's controller-work row is keyed by. +pub(crate) fn cell_work_uuid(world: WorldId, cell: CellId, tick: TickIndex) -> Uuid { + derive_uuid(&format!("cell-work|{world:?}|{cell}|{}", tick.0)) +} + +/// One constituent's submission id. Deterministic, so a resumed cell re-submits +/// the same id and the kernel answers from its idempotency ledger. +pub(crate) fn cell_constituent_uuid( + world: WorldId, + cell: CellId, + subject: SubjectId, + tick: TickIndex, +) -> Uuid { + derive_uuid(&format!("cell-act|{world:?}|{cell}|{subject:?}|{}", tick.0)) +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Constituent { + pub subject: SubjectId, + pub(crate) opportunity: DecisionOpportunity, +} + +/// One inference's worth of the world. A singleton keeps the detail path and its +/// membrane; a group is one inference over N labeled, never-unioned views. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Cell { + Singleton { + id: CellId, + tick: TickIndex, + member: Constituent, + }, + /// `members` is ascending by `SubjectId`; the index into it is the + /// constituent handle the model-facing tool names carry. + Group { + id: CellId, + tick: TickIndex, + members: Vec<Constituent>, + }, +} + +impl Cell { + pub(crate) fn members(&self) -> &[Constituent] { + match self { + Self::Singleton { member, .. } => std::slice::from_ref(member), + Self::Group { members, .. } => members, + } + } +} + +/// Derived, disposable, dropped at the end of a tick. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Cover { + pub tick: TickIndex, + pub cells: Vec<Cell>, + /// True when the constituent cap could not hold every active subject inside + /// the cell budget, so the cap yielded and every cell grew. "Every active + /// subject is in the cover every tick" is an ontology invariant; the cap is + /// a prompt-size preference. Rendered read-only: it is the honest signal + /// that the world outgrew its prompt budget rather than a truncation nobody + /// sees. + pub oversubscribed: bool, +} + +impl Cover { + pub fn singletons(&self) -> usize { + self.cells + .iter() + .filter(|cell| matches!(cell, Cell::Singleton { .. })) + .count() + } + + pub fn groups(&self) -> usize { + self.cells.len() - self.singletons() + } +} + +/// How many inferences one tick may spend, and how large one prompt may get. +/// Two budgets, deliberately not one: only the second bounds tokens. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CoverBudget { + /// B: cells per tick. + pub cells: u16, + /// C: the per-cell constituent cap. At least two, or a group is a singleton + /// with extra steps. + pub constituent_cap: u16, + /// U: singleton slots reserved for the head of the attention order. The + /// rest of the singleton slots carry the rotation window. + pub urgency_slots: u16, +} + +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum CoverBudgetError { + #[error("cover cell budget must be at least one")] + NoCells, + #[error("cover constituent cap must be at least two")] + CapTooSmall, +} + +impl CoverBudget { + pub fn validated(self) -> Result<Self, CoverBudgetError> { + if self.cells < 1 { + return Err(CoverBudgetError::NoCells); + } + if self.constituent_cap < 2 { + return Err(CoverBudgetError::CapTooSmall); + } + Ok(self) + } +} + +/// The scheduler's own projection, wider than any subject view and reachable +/// from no prompt builder: it is constructed by the tick driver, handed to +/// [`derive_cover`], and dropped. `run_cell` takes a `&Cell`, which contains no +/// graph, so a controller organ that could read adjacency fails to compile +/// rather than failing a test. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct AgencyGraph { + /// Ascending. Exactly the subjects with a non-Human controller assignment. + pub(crate) subjects: Vec<SubjectId>, + /// Undirected, canonicalised `(lo, hi)` with `lo < hi`. + pub(crate) edges: BTreeSet<(SubjectId, SubjectId)>, +} + +impl AgencyGraph { + /// A clique below the star threshold, a star above it. Connectivity for + /// component purposes is identical either way. + pub(crate) fn relate(&mut self, group: &BTreeSet<SubjectId>) { + let members: Vec<SubjectId> = group.iter().copied().collect(); + if members.len() < 2 { + return; + } + if members.len() > AGENCY_STAR_THRESHOLD { + let centre = members[0]; + for member in &members[1..] { + self.link(centre, *member); + } + return; + } + for (index, one) in members.iter().enumerate() { + for other in &members[index + 1..] { + self.link(*one, *other); + } + } + } + + pub(crate) fn link(&mut self, one: SubjectId, other: SubjectId) { + if one == other { + return; + } + let pair = if one < other { + (one, other) + } else { + (other, one) + }; + self.edges.insert(pair); + } +} + +/// The partition. Pure over `(world, tick, opportunities, graph, budget)`. +/// +/// `opportunities` arrives in the kernel's one attention order (pressure, then +/// attention debt, then id) and is never re-sorted and never filtered here: a +/// Human opportunity is skipped because a human turn is not an inference, which +/// is a fact about cognition rather than a scheduling preference. +pub fn derive_cover( + world: WorldId, + tick: TickIndex, + opportunities: &[DecisionOpportunity], + graph: &AgencyGraph, + budget: CoverBudget, +) -> Cover { + let active: Vec<&DecisionOpportunity> = opportunities + .iter() + .filter(|opportunity| opportunity.controller_mode != ControllerMode::Human) + .collect(); + let count = active.len(); + if count == 0 { + return Cover { + tick, + cells: Vec::new(), + oversubscribed: false, + }; + } + let constituent = |opportunity: &DecisionOpportunity| Constituent { + subject: opportunity.scope.subject_id, + opportunity: opportunity.clone(), + }; + let cell_budget = usize::from(budget.cells).max(1); + let cap = usize::from(budget.constituent_cap).max(2); + + if count <= cell_budget { + let cells = active + .iter() + .map(|opportunity| { + let member = constituent(opportunity); + Cell::Singleton { + id: cell_id(world, tick, &[member.subject]), + tick, + member, + } + }) + .collect(); + return Cover { + tick, + cells, + oversubscribed: false, + }; + } + + // Step 2. Group cells must hold the non-singletons under the cap: + // `K + ceil((N - K) / C) <= B`. The cap yields when no such partition + // exists, because coverage is the invariant and the cap is a preference. + let capacity = cap.saturating_mul(cell_budget); + let mut oversubscribed = capacity < count; + let (singleton_slots, effective_cap) = if oversubscribed { + (0usize, count.div_ceil(cell_budget)) + } else { + ((capacity - count) / (cap - 1), cap) + }; + let singleton_slots = singleton_slots.min(count); + let group_budget = cell_budget - singleton_slots; + + // Step 3. The rotation window. A stable order that does not move with + // pressure is what lets it carry a guarantee: a subject at index `i` is in + // the window exactly when `phase == i / R`, and `phase` cycles once every + // `ceil(N / R)` consecutive ticks because `now` only advances. + let urgency = usize::from(budget.urgency_slots).min(singleton_slots); + let reserve = singleton_slots - urgency; + let ascending: Vec<SubjectId> = { + let mut ids: Vec<SubjectId> = active + .iter() + .map(|opportunity| opportunity.scope.subject_id) + .collect(); + ids.sort_unstable(); + ids + }; + let mut chosen: BTreeSet<SubjectId> = BTreeSet::new(); + if reserve > 0 { + let cycle = count.div_ceil(reserve); + let phase = usize::try_from(tick.0 % cycle as u64).unwrap_or(0); + let lo = phase * reserve; + let hi = (lo + reserve).min(count); + for subject in &ascending[lo.min(count)..hi] { + chosen.insert(*subject); + } + } + // Step 4. Urgency, then backfill in the attention order. A subject in both + // reserves consumes one slot, not two, and every slot is spent. + for opportunity in active.iter().take(urgency) { + chosen.insert(opportunity.scope.subject_id); + } + for opportunity in &active { + if chosen.len() >= singleton_slots { + break; + } + chosen.insert(opportunity.scope.subject_id); + } + + let mut cells: Vec<Cell> = Vec::new(); + for opportunity in &active { + let subject = opportunity.scope.subject_id; + if !chosen.contains(&subject) { + continue; + } + let member = constituent(opportunity); + cells.push(Cell::Singleton { + id: cell_id(world, tick, &[subject]), + tick, + member, + }); + } + + // Step 5. Connected components over the remainder. + let rest: Vec<&DecisionOpportunity> = active + .iter() + .copied() + .filter(|opportunity| !chosen.contains(&opportunity.scope.subject_id)) + .collect(); + let rank: BTreeMap<SubjectId, usize> = active + .iter() + .enumerate() + .map(|(index, opportunity)| (opportunity.scope.subject_id, index)) + .collect(); + let mut groups = components(&rest, graph); + + // Step 6. A component larger than the cap is cut in id order. A chunk of a + // connected component is still a legitimate coarse group, and a graph-aware + // cut would be a second partitioning heuristic whose only payoff is + // adjacency inside a prompt that never mentions adjacency. + let mut split: Vec<Vec<SubjectId>> = Vec::new(); + for component in groups.drain(..) { + for chunk in component.chunks(effective_cap) { + split.push(chunk.to_vec()); + } + } + + // Step 7. Merge the lowest-ranked cells until the group budget is met. The + // choke falls on the quietest cells; the highest-pressure groups keep the + // smallest, sharpest prompts. Priority is read from the attention order, + // which is its one owner — the scheduler computes no second ranking. + let priority = |members: &Vec<SubjectId>| { + members + .iter() + .filter_map(|subject| rank.get(subject).copied()) + .min() + .unwrap_or(usize::MAX) + }; + split.sort_by_key(|members| (priority(members), members[0])); + let mut head = split.len(); + let mut packed: Vec<Vec<SubjectId>> = Vec::new(); + let mut bucket: Vec<SubjectId> = Vec::new(); + while head > 0 { + let open = usize::from(!bucket.is_empty()); + if head + packed.len() + open <= group_budget { + break; + } + head -= 1; + let component = split[head].clone(); + if !bucket.is_empty() && bucket.len() + component.len() > effective_cap { + packed.push(std::mem::take(&mut bucket)); + } + bucket.extend(component); + } + if !bucket.is_empty() { + packed.push(bucket); + } + split.truncate(head); + split.append(&mut packed); + // Component sizes need not pack perfectly into the cap, so the packing pass + // can end above budget. The cap yields here for the same reason it yields in + // step 2: coverage is the invariant, prompt size is the preference, and the + // operator is told rather than shown a silent truncation. + while split.len() > group_budget && split.len() >= 2 { + split.sort_by_key(|members| (priority(members), members[0])); + let last = split.pop().expect("two or more cells were established"); + let previous = split.pop().expect("two or more cells were established"); + let mut merged = previous; + merged.extend(last); + split.push(merged); + oversubscribed = true; + } + + for members in &mut split { + members.sort_unstable(); + } + split.sort_by_key(|members| (priority(members), members[0])); + let by_subject: BTreeMap<SubjectId, &DecisionOpportunity> = rest + .iter() + .map(|opportunity| (opportunity.scope.subject_id, *opportunity)) + .collect(); + for members in split { + let constituents: Vec<Constituent> = members + .iter() + .filter_map(|subject| by_subject.get(subject).map(|entry| constituent(entry))) + .collect(); + if constituents.is_empty() { + continue; + } + cells.push(Cell::Group { + id: cell_id(world, tick, &members), + tick, + members: constituents, + }); + } + + debug_assert_eq!( + cells + .iter() + .flat_map(Cell::members) + .map(|member| member.subject) + .collect::<BTreeSet<_>>() + .len(), + count, + "the cover is a partition: every active subject appears exactly once" + ); + debug_assert!(cells.len() <= cell_budget, "the cover respects its budget"); + + Cover { + tick, + cells, + oversubscribed, + } +} + +/// Union-find over the remainder's induced subgraph. Deterministic by +/// construction: a `BTreeSet` of edges in `SubjectId` order, components keyed by +/// their lowest member, members ascending. +fn components(rest: &[&DecisionOpportunity], graph: &AgencyGraph) -> Vec<Vec<SubjectId>> { + let present: BTreeSet<SubjectId> = rest + .iter() + .map(|opportunity| opportunity.scope.subject_id) + .collect(); + let mut parent: BTreeMap<SubjectId, SubjectId> = + present.iter().map(|subject| (*subject, *subject)).collect(); + + fn find(parent: &mut BTreeMap<SubjectId, SubjectId>, node: SubjectId) -> SubjectId { + let mut root = node; + while let Some(next) = parent.get(&root).copied() { + if next == root { + break; + } + root = next; + } + let mut cursor = node; + while let Some(next) = parent.get(&cursor).copied() { + if next == cursor { + break; + } + parent.insert(cursor, root); + cursor = next; + } + root + } + + for (one, other) in &graph.edges { + if !present.contains(one) || !present.contains(other) { + continue; + } + let left = find(&mut parent, *one); + let right = find(&mut parent, *other); + if left != right { + let (low, high) = if left < right { + (left, right) + } else { + (right, left) + }; + parent.insert(high, low); + } + } + + let mut buckets: BTreeMap<SubjectId, Vec<SubjectId>> = BTreeMap::new(); + for subject in &present { + let root = find(&mut parent, *subject); + buckets.entry(root).or_default().push(*subject); + } + buckets + .into_values() + .map(|mut members| { + members.sort_unstable(); + members + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{DecisionScope, ScopeDigest}; + + fn subject(index: u128) -> SubjectId { + serde_json::from_value(serde_json::json!(Uuid::from_u128(index).to_string())) + .expect("a subject id parses from its canonical uuid") + } + + fn opportunity(index: u128, mode: ControllerMode) -> DecisionOpportunity { + let subject_id = subject(index); + DecisionOpportunity { + world_id: WorldId::nil_for_test(), + revision: 1, + scope_digest: ScopeDigest::fixture(&format!("scope-{index}")), + scope: DecisionScope { subject_id }, + controller_id: serde_json::from_value(serde_json::json!( + Uuid::from_u128(index + 1_000_000).to_string() + )) + .expect("a controller id parses from its canonical uuid"), + controller_mode: mode, + affordance_ids: Vec::new(), + } + } + + fn active(count: u128) -> Vec<DecisionOpportunity> { + (1..=count) + .map(|index| opportunity(index, ControllerMode::OperationalAgent)) + .collect() + } + + fn budget(cells: u16, cap: u16, urgency: u16) -> CoverBudget { + CoverBudget { + cells, + constituent_cap: cap, + urgency_slots: urgency, + } + } + + fn covered(cover: &Cover) -> Vec<SubjectId> { + let mut subjects: Vec<SubjectId> = cover + .cells + .iter() + .flat_map(Cell::members) + .map(|member| member.subject) + .collect(); + subjects.sort_unstable(); + subjects + } + + fn derive( + opportunities: &[DecisionOpportunity], + graph: &AgencyGraph, + budget: CoverBudget, + tick: u64, + ) -> Cover { + derive_cover( + WorldId::nil_for_test(), + TickIndex(tick), + opportunities, + graph, + budget, + ) + } + + /// Verification 21, at the design profile: 2,400 subjects, 240 cells, a cap + /// of 24, 36 urgency slots. Every subject exactly once, the budget held, and + /// the head of the attention order attended in detail. + #[test] + fn soul_the_design_profile_covers_every_subject_exactly_once_inside_its_budget() { + let opportunities = active(2_400); + let cover = derive( + &opportunities, + &AgencyGraph::default(), + budget(240, 24, 36), + 0, + ); + + assert_eq!(covered(&cover).len(), 2_400); + assert_eq!( + covered(&cover).iter().collect::<BTreeSet<_>>().len(), + 2_400, + "no subject is covered twice" + ); + assert!(cover.cells.len() <= 240); + assert!(!cover.oversubscribed); + // K = floor((24*240 - 2400) / 23) = 146 singleton slots. + assert_eq!(cover.singletons(), 146); + assert_eq!(cover.groups(), 94); + assert!( + cover.cells.iter().all(|cell| cell.members().len() <= 24), + "no cell exceeds the constituent cap" + ); + + let head = opportunities[0].scope.subject_id; + let urgent: BTreeSet<SubjectId> = opportunities[..36] + .iter() + .map(|entry| entry.scope.subject_id) + .collect(); + let singletons: BTreeSet<SubjectId> = cover + .cells + .iter() + .filter_map(|cell| match cell { + Cell::Singleton { member, .. } => Some(member.subject), + Cell::Group { .. } => None, + }) + .collect(); + assert!( + singletons.contains(&head), + "the head of the order is a singleton" + ); + assert!( + urgent.is_subset(&singletons), + "every urgency slot is spent on the head of the order" + ); + } + + /// A human opportunity is not an inference. It is skipped, and skipping it + /// is not a filter on the cover: it never was a candidate. + #[test] + fn a_human_opportunity_is_never_in_a_cell() { + let opportunities = vec![ + opportunity(1, ControllerMode::Human), + opportunity(2, ControllerMode::OperationalAgent), + opportunity(3, ControllerMode::NarrativePersona), + ]; + let cover = derive(&opportunities, &AgencyGraph::default(), budget(8, 4, 1), 0); + assert_eq!(covered(&cover), vec![subject(2), subject(3)]); + } + + /// Below the budget every opportunity is its own cell and the detail path is + /// untouched. + #[test] + fn a_small_world_is_all_singletons() { + let opportunities = active(5); + let cover = derive( + &opportunities, + &AgencyGraph::default(), + budget(240, 24, 36), + 0, + ); + assert_eq!(cover.singletons(), 5); + assert_eq!(cover.groups(), 0); + assert!(!cover.oversubscribed); + } + + /// The cap yields, the budget does not. Every subject is still covered + /// exactly once and the operator learns the world outgrew the prompt bound. + #[test] + fn soul_an_oversubscribed_world_relaxes_the_cap_rather_than_dropping_a_subject() { + let opportunities = active(100); + let cover = derive(&opportunities, &AgencyGraph::default(), budget(10, 4, 2), 0); + assert!(cover.oversubscribed); + assert_eq!(covered(&cover).len(), 100); + assert_eq!(covered(&cover).iter().collect::<BTreeSet<_>>().len(), 100); + assert!(cover.cells.len() <= 10); + assert_eq!(cover.singletons(), 0, "no slot is spent on detail here"); + } + + /// The fairness arithmetic, with no persisted field behind it: a subject + /// continuously active for `ceil(N / R)` ticks is a singleton at least once. + #[test] + fn soul_every_subject_reaches_a_singleton_within_the_rotation_window() { + // N = 25, B = 12, C = 8, U = 1 → K = floor((96 - 25) / 7) = 10, R = 9. + let opportunities = active(25); + let budget = budget(12, 8, 1); + let cycle = 25usize.div_ceil(9); + let mut seen: BTreeSet<SubjectId> = BTreeSet::new(); + for tick in 0..cycle as u64 { + let cover = derive(&opportunities, &AgencyGraph::default(), budget, tick); + for cell in &cover.cells { + if let Cell::Singleton { member, .. } = cell { + seen.insert(member.subject); + } + } + } + let all: BTreeSet<SubjectId> = opportunities + .iter() + .map(|entry| entry.scope.subject_id) + .collect(); + assert_eq!(seen, all, "the window closes over every subject"); + } + + /// A narrow reserve still closes, it just takes longer. The guarantee is + /// `ceil(N / R)`, never `ceil(N / B)`: giving every cell to a singleton + /// would leave subjects out of the cover, which the ontology forbids. + #[test] + fn the_rotation_guarantee_is_over_the_reserve_not_the_cell_budget() { + let opportunities = active(25); + // K = floor((8*10 - 25) / 7) = 7, U = 6 → R = 1, cycle = 25. + let budget = budget(10, 8, 6); + let mut seen: BTreeSet<SubjectId> = BTreeSet::new(); + for tick in 0..25u64 { + let cover = derive(&opportunities, &AgencyGraph::default(), budget, tick); + for cell in &cover.cells { + if let Cell::Singleton { member, .. } = cell { + seen.insert(member.subject); + } + } + } + assert_eq!(seen.len(), 25); + } + + /// The cover is derived, not remembered: the same inputs yield the same + /// partition, the same ids, and the same order. + #[test] + fn soul_the_same_inputs_derive_an_identical_partition() { + let opportunities = active(60); + let mut graph = AgencyGraph::default(); + graph.link(subject(3), subject(4)); + graph.link(subject(4), subject(5)); + let one = derive(&opportunities, &graph, budget(10, 8, 2), 7); + let other = derive(&opportunities, &graph, budget(10, 8, 2), 7); + assert_eq!(one, other); + } + + /// Connected subjects land in one cell when the budget allows it. + #[test] + fn a_connected_component_becomes_one_coarse_cell() { + let opportunities = active(20); + let mut graph = AgencyGraph::default(); + for index in 10..20 { + graph.link(subject(10), subject(index)); + } + let cover = derive(&opportunities, &graph, budget(4, 12, 0), 0); + let component: BTreeSet<SubjectId> = (10..20).map(subject).collect(); + let together = cover.cells.iter().any(|cell| { + let members: BTreeSet<SubjectId> = + cell.members().iter().map(|entry| entry.subject).collect(); + component.is_subset(&members) + }); + assert!(together, "one component was not split across cells"); + } + + /// Property sweep: the budget and the cap hold, and coverage is exact. + #[test] + fn soul_cell_count_and_cap_hold_across_profiles() { + for count in [1u128, 3, 7, 25, 100, 401] { + for cells in [1u16, 2, 5, 12, 240] { + for cap in [2u16, 3, 8, 24] { + let opportunities = active(count); + let cover = derive( + &opportunities, + &AgencyGraph::default(), + budget(cells, cap, 3), + 11, + ); + assert!( + cover.cells.len() <= usize::from(cells), + "count {count} cells {cells} cap {cap} exceeded its budget" + ); + assert_eq!( + covered(&cover).len(), + usize::try_from(count).expect("a test fixture fits usize"), + "count {count} cells {cells} cap {cap} lost a subject" + ); + if usize::from(cap) * usize::from(cells) + >= usize::try_from(count).expect("a test fixture fits usize") + { + assert!(!cover.oversubscribed); + assert!( + cover + .cells + .iter() + .all(|cell| cell.members().len() <= usize::from(cap)), + "count {count} cells {cells} cap {cap} exceeded the cap" + ); + } else { + assert!(cover.oversubscribed); + } + } + } + } + } + + /// A crowded referent contributes a star, not a clique: connectivity is the + /// same and the edge count stops being quadratic. + #[test] + fn a_crowded_referent_relates_as_a_star() { + let crowd: BTreeSet<SubjectId> = (1..=40).map(subject).collect(); + let mut graph = AgencyGraph::default(); + graph.relate(&crowd); + assert_eq!(graph.edges.len(), 39); + + let small: BTreeSet<SubjectId> = (1..=4).map(subject).collect(); + let mut clique = AgencyGraph::default(); + clique.relate(&small); + assert_eq!(clique.edges.len(), 6); + } + + /// Derived ids are a pure function of their tuple, and distinct tuples do + /// not collide. + #[test] + fn derived_ids_are_pure_and_distinct() { + let world = WorldId::nil_for_test(); + let cell = cell_id(world, TickIndex(4), &[subject(1), subject(2)]); + assert_eq!( + cell, + cell_id(world, TickIndex(4), &[subject(1), subject(2)]) + ); + assert_ne!( + cell, + cell_id(world, TickIndex(5), &[subject(1), subject(2)]) + ); + assert_ne!(cell, cell_id(world, TickIndex(4), &[subject(1)])); + + assert_eq!( + cell_constituent_uuid(world, cell, subject(1), TickIndex(4)), + cell_constituent_uuid(world, cell, subject(1), TickIndex(4)) + ); + assert_ne!( + cell_constituent_uuid(world, cell, subject(1), TickIndex(4)), + cell_constituent_uuid(world, cell, subject(2), TickIndex(4)) + ); + assert_ne!( + cell_constituent_uuid(world, cell, subject(1), TickIndex(4)), + cell_work_uuid(world, cell, TickIndex(4)) + ); + } + + #[test] + fn a_budget_without_cells_or_with_a_singleton_cap_is_refused() { + assert_eq!(budget(0, 4, 0).validated(), Err(CoverBudgetError::NoCells)); + assert_eq!( + budget(4, 1, 0).validated(), + Err(CoverBudgetError::CapTooSmall) + ); + assert!(budget(4, 2, 0).validated().is_ok()); + } + + /// The rotation guarantee at the design profile rather than at a toy size. + /// `K = 146`, `U = 36`, so the reserve is `R = 110` and the window closes in + /// `ceil(2400 / 110) = 22` ticks. Membership is stable across the sweep, + /// which is the precondition the tight bound is stated under. + #[test] + fn soul_b_the_profile_rotation_closes_over_every_subject_in_ceil_n_over_reserve_ticks() { + let opportunities = active(2_400); + let budget = budget(240, 24, 36); + let reserve = 146 - 36; + let cycle = 2_400usize.div_ceil(reserve); + assert_eq!(cycle, 22, "the profile's window is not 22 ticks wide"); + + let mut seen: BTreeSet<SubjectId> = BTreeSet::new(); + for tick in 0..cycle as u64 { + let cover = derive(&opportunities, &AgencyGraph::default(), budget, tick); + assert_eq!(cover.singletons(), 146); + for cell in &cover.cells { + if let Cell::Singleton { member, .. } = cell { + seen.insert(member.subject); + } + } + } + assert_eq!( + seen.len(), + 2_400, + "{} subjects never reached detail inside the window", + 2_400 - seen.len() + ); + + // One tick short of the cycle must not already close it, or the bound + // is being read off a coincidence rather than the arithmetic. + let mut short: BTreeSet<SubjectId> = BTreeSet::new(); + for tick in 0..(cycle - 1) as u64 { + for cell in &derive(&opportunities, &AgencyGraph::default(), budget, tick).cells { + if let Cell::Singleton { member, .. } = cell { + short.insert(member.subject); + } + } + } + assert!(short.len() < 2_400, "the window closed a tick early"); + } + + /// The urgency slots go to the head of the attention order the kernel + /// already owns, and the rotation window goes to ascending id order. The + /// fixture arrives in descending id order so the two rankings cannot be + /// confused with each other, and no third ranking exists to explain the + /// result. + #[test] + fn soul_b_urgency_slots_follow_the_attention_order_not_the_id_order() { + let mut opportunities = active(40); + opportunities.reverse(); + // N = 40, B = 10, C = 8 → K = floor((80 - 40) / 7) = 5, U = 3, R = 2. + let cover = derive(&opportunities, &AgencyGraph::default(), budget(10, 8, 3), 0); + let singletons: BTreeSet<SubjectId> = cover + .cells + .iter() + .filter_map(|cell| match cell { + Cell::Singleton { member, .. } => Some(member.subject), + Cell::Group { .. } => None, + }) + .collect(); + assert_eq!(singletons.len(), 5); + + let head: BTreeSet<SubjectId> = opportunities[..3] + .iter() + .map(|entry| entry.scope.subject_id) + .collect(); + assert!( + head.is_subset(&singletons), + "the urgency slots did not follow the attention order" + ); + // The window is the ascending-id reserve, which here is the tail of the + // attention order: two rankings, both honoured, neither invented. + assert!( + singletons.contains(&subject(1)) && singletons.contains(&subject(2)), + "the rotation window did not follow ascending id order" + ); + } + + /// The partition is a pure function of its arguments, and the attention + /// order is one of those arguments rather than an incidental input. Equal + /// inputs derive an equal cover; a permuted order derives a different one, + /// because urgency and backfill read that order and `order_opportunities` + /// is its one owner. + #[test] + fn soul_b_the_cover_is_pure_and_the_attention_order_is_a_real_input() { + let opportunities = active(40); + let mut graph = AgencyGraph::default(); + graph.link(subject(11), subject(12)); + let budget = budget(10, 8, 3); + let ids = |cover: &Cover| -> Vec<CellId> { + cover + .cells + .iter() + .map(|cell| match cell { + Cell::Singleton { id, .. } | Cell::Group { id, .. } => *id, + }) + .collect() + }; + + let one = derive(&opportunities, &graph, budget, 5); + let other = derive(&opportunities, &graph, budget, 5); + assert_eq!(one, other, "identical inputs derived different covers"); + assert_eq!( + serde_json::to_string(&ids(&one)).unwrap(), + serde_json::to_string(&ids(&other)).unwrap(), + "identical inputs derived different cell ids" + ); + + let mut reversed = opportunities.clone(); + reversed.reverse(); + let permuted = derive(&reversed, &graph, budget, 5); + assert_eq!( + covered(&one), + covered(&permuted), + "a permutation lost or duplicated a subject" + ); + let singletons = |cover: &Cover| -> BTreeSet<SubjectId> { + cover + .cells + .iter() + .filter_map(|cell| match cell { + Cell::Singleton { member, .. } => Some(member.subject), + Cell::Group { .. } => None, + }) + .collect() + }; + assert_ne!( + singletons(&one), + singletons(&permuted), + "the attention order is not an input to the partition" + ); + // Coverage survives a permutation, but so does the sizing decision + // that partition made: shuffling the same subjects must not change + // how many cells they filled, only which subjects the singleton slots + // picked out. + assert_eq!( + one.cells.len(), + permuted.cells.len(), + "a permutation changed how many cells the same subjects filled" + ); + } + + /// Every cell in one cover carries that cover's tick index. This is what the + /// driver's "advance the clock after the cells" ordering buys: one `now`, + /// one phase, one set of derived command ids per tick. + #[test] + fn soul_b_every_cell_shares_the_covers_tick_index() { + let opportunities = active(60); + for tick in [0u64, 1, 7, 4_000] { + let cover = derive( + &opportunities, + &AgencyGraph::default(), + budget(10, 8, 2), + tick, + ); + assert_eq!(cover.tick, TickIndex(tick)); + for cell in &cover.cells { + let carried = match cell { + Cell::Singleton { tick, .. } | Cell::Group { tick, .. } => *tick, + }; + assert_eq!(carried, cover.tick, "a cell carried another tick's index"); + } + } + } + + /// Derived ids are collision-free across every cell of every tick in a full + /// sweep, and a cell key never collides with a constituent key. + #[test] + fn soul_b_derived_ids_do_not_collide_across_a_sweep_of_ticks() { + let world = WorldId::nil_for_test(); + let opportunities = active(600); + let budget = budget(60, 24, 6); + let mut cells: BTreeSet<CellId> = BTreeSet::new(); + let mut keys: BTreeSet<Uuid> = BTreeSet::new(); + let mut cell_count = 0usize; + let mut key_count = 0usize; + for tick in 0..12u64 { + let cover = derive(&opportunities, &AgencyGraph::default(), budget, tick); + for cell in &cover.cells { + let id = match cell { + Cell::Singleton { id, .. } | Cell::Group { id, .. } => *id, + }; + cells.insert(id); + cell_count += 1; + keys.insert(cell_work_uuid(world, id, cover.tick)); + key_count += 1; + for member in cell.members() { + keys.insert(cell_constituent_uuid(world, id, member.subject, cover.tick)); + key_count += 1; + } + } + } + assert!( + cell_count >= 700, + "the sweep was too small to mean anything" + ); + assert_eq!(cells.len(), cell_count, "two cells share one id"); + assert_eq!(keys.len(), key_count, "two derived command keys collide"); + } + + /// The cap yields for exactly one reason: no partition inside the budget + /// respects it. Token capacity alone does not decide that — component shapes + /// do. Here `C * B = 12 >= N = 9`, and the cap still yields, because two + /// three-member components and two isolates cannot pack into two cells of + /// four. Coverage holds and the operator is told. + #[test] + fn soul_b_the_cap_yields_when_component_shapes_cannot_pack_inside_the_budget() { + let opportunities = active(9); + let mut graph = AgencyGraph::default(); + graph.link(subject(2), subject(3)); + graph.link(subject(3), subject(4)); + graph.link(subject(5), subject(6)); + graph.link(subject(6), subject(7)); + let cover = derive(&opportunities, &graph, budget(3, 4, 0), 0); + + assert_eq!(covered(&cover).len(), 9); + assert_eq!(covered(&cover).iter().collect::<BTreeSet<_>>().len(), 9); + assert!(cover.cells.len() <= 3); + assert!( + cover.cells.iter().any(|cell| cell.members().len() > 4), + "the cap did not yield: {:?}", + cover + .cells + .iter() + .map(|cell| cell.members().len()) + .collect::<Vec<_>>() + ); + assert!( + cover.oversubscribed, + "the cap yielded without telling the operator" + ); + + // The same subjects with no edges pack cleanly and the flag stays down, + // so the flag tracks the partition rather than the subject count. + let loose = derive(&opportunities, &AgencyGraph::default(), budget(3, 4, 0), 0); + assert!(!loose.oversubscribed); + assert!(loose.cells.iter().all(|cell| cell.members().len() <= 4)); + } +} diff --git a/native/aetherlight/src/grammar.rs b/native/aetherlight/src/grammar.rs new file mode 100644 index 000000000..a11cd691a --- /dev/null +++ b/native/aetherlight/src/grammar.rs @@ -0,0 +1,209 @@ +//! The action grammar a world is bound to at creation. +//! +//! A grammar is the closed set of affordance kinds a world may declare, each +//! with its role signature and the one render path its acts take. The grammar's +//! home is the Aetheria repo; the kernel holds only this binding: the verbs it +//! enforces, and a content digest that names exactly which grammar that was. +//! The digest is derived here and nowhere else, so a binding cannot claim a +//! digest its verbs do not have. + +use crate::SubjectKind; +use crate::patch::{AffordanceKindName, EntityKind, RefKind, Role, RoleSpec, kernel_speak_entry}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; + +/// How an act of one verb reaches the player: filmed in the engine as a ship +/// action, or shown as Aetheria's portrait-and-choices conversation. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum RenderPath { + ShipAction, + Conversation, +} + +/// What a grammar role may be bound to, in the grammar's own vocabulary. Each +/// lowers to exactly one kernel `RefKind`. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum GrammarReferentKind { + Person, + Faction, + Population, + Place, + Cargo, +} + +impl GrammarReferentKind { + fn ref_kind(self) -> RefKind { + match self { + Self::Person => RefKind::Subject(Some(SubjectKind::Person)), + Self::Faction => RefKind::Subject(Some(SubjectKind::Institution)), + Self::Population => RefKind::Subject(Some(SubjectKind::Population)), + Self::Place => RefKind::Entity(EntityKind::Place), + Self::Cargo => RefKind::Entity(EntityKind::Resource), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +pub struct GrammarRole { + pub role: String, + pub referent: GrammarReferentKind, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +pub struct GrammarVerb { + pub render_path: RenderPath, + /// In signature order: the order is part of the verb. + pub roles: Vec<GrammarRole>, +} + +impl GrammarVerb { + /// Whether a declared role list is this verb's signature: same names, same + /// referent kinds, same order. + pub(crate) fn admits_roles(&self, roles: &[RoleSpec]) -> bool { + self.role_specs() == roles + } + + /// This verb's signature as the kernel declares it: the one lowering of a + /// grammar role, so declaring a verb and admitting a declaration cannot + /// disagree. + pub(crate) fn role_specs(&self) -> Vec<RoleSpec> { + self.roles + .iter() + .map(|role| RoleSpec { + role: Role(role.role.clone()), + kind: role.referent.ref_kind(), + }) + .collect() + } +} + +/// Why a bound grammar refuses an affordance entry. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum GrammarRefusal { + KindNotInGrammar, + RolesDisagree, + SpeakNotConversation, +} + +#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq, Eq)] +pub enum GrammarError { + #[error("grammar schema id is empty")] + EmptySchemaId, + #[error("grammar declares one verb kind twice")] + DuplicateVerb, + #[error("grammar digest does not match its verbs")] + DigestMismatch, +} + +/// Which grammar a world is bound to: its schema id, revision and content +/// digest. What a consumer reads; the verb table stays in the binding. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct GrammarIdentity { + pub schema_id: String, + pub revision: u32, + pub digest: String, +} + +/// The grammar a world was created under. Immutable: the only constructor +/// derives the digest, and deserialisation re-derives it and refuses a mismatch. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(try_from = "RawBinding")] +pub struct GrammarBinding { + schema_id: String, + revision: u32, + digest: String, + verbs: BTreeMap<String, GrammarVerb>, +} + +#[derive(Deserialize)] +struct RawBinding { + schema_id: String, + revision: u32, + digest: String, + verbs: BTreeMap<String, GrammarVerb>, +} + +impl TryFrom<RawBinding> for GrammarBinding { + type Error = GrammarError; + + fn try_from(raw: RawBinding) -> Result<Self, GrammarError> { + let bound = Self::new(raw.schema_id, raw.revision, raw.verbs)?; + if bound.digest != raw.digest { + return Err(GrammarError::DigestMismatch); + } + Ok(bound) + } +} + +impl GrammarBinding { + /// The one constructor. Verbs arrive in any order and are keyed by kind; + /// the digest is the sha256 of the canonical encoding of the kind-sorted + /// verbs, so the same verbs bind to the same digest however they were listed. + pub fn new( + schema_id: impl Into<String>, + revision: u32, + verbs: impl IntoIterator<Item = (String, GrammarVerb)>, + ) -> Result<Self, GrammarError> { + let schema_id = schema_id.into(); + if schema_id.is_empty() { + return Err(GrammarError::EmptySchemaId); + } + let mut table = BTreeMap::new(); + for (kind, verb) in verbs { + if table.insert(kind, verb).is_some() { + return Err(GrammarError::DuplicateVerb); + } + } + let encoded = rmp_serde::to_vec_named(&table).expect("a verb table encodes"); + let digest = format!("sha256:{:x}", Sha256::digest(encoded)); + Ok(Self { + schema_id, + revision, + digest, + verbs: table, + }) + } + + pub fn identity(&self) -> GrammarIdentity { + GrammarIdentity { + schema_id: self.schema_id.clone(), + revision: self.revision, + digest: self.digest.clone(), + } + } + + /// Every verb, in kind order. + pub(crate) fn verbs(&self) -> impl Iterator<Item = (&str, &GrammarVerb)> { + self.verbs.iter().map(|(kind, verb)| (kind.as_str(), verb)) + } + + pub(crate) fn verb(&self, kind: &str) -> Option<&GrammarVerb> { + self.verbs.get(kind) + } + + /// The one grammar check. The resolver turns a refusal into a mismatch and + /// `admit_resolved`, the only writer of the affordance catalog, into an + /// invariant error, so no path adds an entry without passing it. + pub(crate) fn refusal( + &self, + kind: &AffordanceKindName, + roles: &[RoleSpec], + ) -> Option<GrammarRefusal> { + let Some(verb) = self.verb(&kind.0) else { + return Some(GrammarRefusal::KindNotInGrammar); + }; + if !verb.admits_roles(roles) { + return Some(GrammarRefusal::RolesDisagree); + } + if *kind == kernel_speak_entry().kind && verb.render_path != RenderPath::Conversation { + return Some(GrammarRefusal::SpeakNotConversation); + } + None + } +} + +#[cfg(test)] +mod tests; diff --git a/native/aetherlight/src/grammar/tests.rs b/native/aetherlight/src/grammar/tests.rs new file mode 100644 index 000000000..85b3b1e19 --- /dev/null +++ b/native/aetherlight/src/grammar/tests.rs @@ -0,0 +1,745 @@ +use super::*; +use crate::patch::{ + AffordanceDeclaration, AffordanceKindName, AudienceSpec, Declaration, DraftHandle, EntityKind, + Mismatch, OutcomeBand, Precondition, Role, RoleSpec, +}; +use crate::tests::{auth_principal, command, creation, owner}; +use crate::{ + CallerId, CommandBody, CommandId, CreateWorld, KernelError, SubjectKind, SubmitReceipt, + WorldId, WorldKernel, WorldPatch, +}; + +fn verb(path: RenderPath, roles: &[(&str, GrammarReferentKind)]) -> GrammarVerb { + GrammarVerb { + render_path: path, + roles: roles + .iter() + .map(|(role, referent)| GrammarRole { + role: (*role).into(), + referent: *referent, + }) + .collect(), + } +} + +/// What the fixture world's genesis needs: the kernel speak entry and the +/// fixture's own `convene`. Anything else a test wants is added to it. +fn grammar_with(extra: &[(&str, GrammarVerb)]) -> GrammarBinding { + let mut verbs = vec![ + ("speak".to_owned(), verb(RenderPath::Conversation, &[])), + ("convene".to_owned(), verb(RenderPath::Conversation, &[])), + ]; + verbs.extend( + extra + .iter() + .map(|(kind, v)| ((*kind).to_owned(), v.clone())), + ); + GrammarBinding::new("aetheria.grammar", 3, verbs).unwrap() +} + +fn bound(grammar: Option<GrammarBinding>, title: &str) -> CreateWorld { + let mut world = creation(CommandId::new(), title); + world.grammar = grammar; + world +} + +fn declare(handle: &str, kind: &str, roles: &[(&str, RefKind)]) -> Declaration { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new(handle), + kind: AffordanceKindName(kind.into()), + roles: roles + .iter() + .map(|(role, kind)| RoleSpec { + role: Role((*role).into()), + kind: *kind, + }) + .collect(), + // Speech with one audience is the smallest entry the resolver does + // not refuse as inert; the grammar check does not read it. + preconditions: vec![Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + }) +} + +fn patch_of(declarations: Vec<Declaration>) -> WorldPatch { + WorldPatch { + declarations, + operations: Vec::new(), + evidence: Vec::new(), + } +} + +fn rejected(result: Result<impl Sized, KernelError>) -> Vec<Mismatch> { + match result { + Err(KernelError::PatchRejected(set)) => set, + Err(other) => panic!("expected a patch refusal, got {other:?}"), + Ok(_) => panic!("expected a patch refusal, the command was admitted"), + } +} + +/// Each call gets its own store path: kernels are created, not reopened. +fn create(world: CreateWorld) -> (tempfile::TempDir, Result<WorldKernel, KernelError>) { + let directory = tempfile::tempdir().unwrap(); + let result = WorldKernel::create( + directory.path().join("world.cc"), + world, + &auth_principal(owner()), + ) + .map(|(kernel, _)| kernel); + (directory, result) +} + +fn admit(kernel: &mut WorldKernel, patch: WorldPatch) -> Result<SubmitReceipt, KernelError> { + let snapshot = kernel.snapshot().unwrap(); + kernel.submit( + command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: None, + patch, + }, + ), + &auth_principal(owner()), + ) +} + +fn person() -> RefKind { + RefKind::Subject(Some(SubjectKind::Person)) +} + +fn place() -> RefKind { + RefKind::Entity(EntityKind::Place) +} + +fn not_in_grammar(handle: &str) -> Vec<Mismatch> { + vec![Mismatch::AffordanceKindNotInGrammar { + handle: DraftHandle::new(handle), + }] +} + +fn disagrees(handle: &str) -> Vec<Mismatch> { + vec![Mismatch::AffordanceRolesDisagreeWithGrammar { + handle: DraftHandle::new(handle), + }] +} + +#[test] +fn grammar_world_refuses_an_affordance_kind_outside_the_grammar() { + // Genesis: a declared kind the binding lacks is refused. + let mut world = bound(Some(grammar_with(&[])), "Outside"); + world.patch.declarations.push(declare("wave", "wave", &[])); + assert_eq!(rejected(create(world).1), not_in_grammar("wave")); + + // A later AdmitPatch: the same kind is refused, and a verb the grammar + // does carry is admitted by the same path. + let extra = [("hail", verb(RenderPath::Conversation, &[]))]; + let (_dir, kernel) = create(bound(Some(grammar_with(&extra)), "Outside")); + let mut kernel = kernel.unwrap(); + assert_eq!( + rejected(admit( + &mut kernel, + patch_of(vec![declare("wave", "wave", &[])]) + )), + not_in_grammar("wave") + ); + let receipt = admit(&mut kernel, patch_of(vec![declare("hail", "hail", &[])])).unwrap(); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); +} + +#[test] +fn grammar_world_refuses_a_role_signature_the_grammar_does_not_carry() { + let extra = [ + ( + "meet", + verb( + RenderPath::ShipAction, + &[ + ("who", GrammarReferentKind::Person), + ("where_", GrammarReferentKind::Place), + ], + ), + ), + ("hail", verb(RenderPath::Conversation, &[])), + ]; + let (_dir, kernel) = create(bound(Some(grammar_with(&extra)), "Signatures")); + let mut kernel = kernel.unwrap(); + for (label, roles) in [ + ("renamed", vec![("whom", person()), ("where_", place())]), + ("rekinded", vec![("who", person()), ("where_", person())]), + ("swapped", vec![("where_", place()), ("who", person())]), + ("short", vec![("who", person())]), + ( + "long", + vec![("who", person()), ("where_", place()), ("why", person())], + ), + ] { + let set = rejected(admit( + &mut kernel, + patch_of(vec![declare(label, "meet", &roles)]), + )); + assert_eq!(set, disagrees(label), "{label}"); + } + // A role on a verb the grammar declares with none. + let set = rejected(admit( + &mut kernel, + patch_of(vec![declare("hail", "hail", &[("who", person())])]), + )); + assert_eq!(set, disagrees("hail")); + // The exact signature is admitted. + let receipt = admit( + &mut kernel, + patch_of(vec![declare( + "meet", + "meet", + &[("who", person()), ("where_", place())], + )]), + ) + .unwrap(); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); +} + +#[test] +fn each_grammar_referent_kind_admits_exactly_its_own_kernel_kind() { + let kinds = [ + (GrammarReferentKind::Person, person()), + ( + GrammarReferentKind::Faction, + RefKind::Subject(Some(SubjectKind::Institution)), + ), + ( + GrammarReferentKind::Population, + RefKind::Subject(Some(SubjectKind::Population)), + ), + (GrammarReferentKind::Place, place()), + ( + GrammarReferentKind::Cargo, + RefKind::Entity(EntityKind::Resource), + ), + ]; + for (referent, own) in &kinds { + let extra = [("act", verb(RenderPath::ShipAction, &[("with", *referent)]))]; + for (_, offered) in &kinds { + let (_dir, kernel) = create(bound(Some(grammar_with(&extra)), "Referents")); + let mut kernel = kernel.unwrap(); + let result = admit( + &mut kernel, + patch_of(vec![declare("act", "act", &[("with", *offered)])]), + ); + if offered == own { + assert!( + matches!(result, Ok(SubmitReceipt::Applied(_))), + "{referent:?} refused its own kind" + ); + } else { + assert_eq!( + rejected(result), + disagrees("act"), + "{referent:?} admitted {offered:?}" + ); + } + } + } +} + +#[test] +fn grammar_world_without_speak_refuses_the_kernel_speak_grant() { + let no_speak = GrammarBinding::new( + "aetheria.grammar", + 1, + [("convene".to_owned(), verb(RenderPath::Conversation, &[]))], + ) + .unwrap(); + assert_eq!( + rejected(create(bound(Some(no_speak), "Mute")).1), + not_in_grammar(crate::patch::KERNEL_SPEAK_HANDLE) + ); + + // The kernel entry is held to the signature as well as the kind. + let loud = GrammarBinding::new( + "aetheria.grammar", + 1, + [ + ( + "speak".to_owned(), + verb( + RenderPath::Conversation, + &[("to", GrammarReferentKind::Person)], + ), + ), + ("convene".to_owned(), verb(RenderPath::Conversation, &[])), + ], + ) + .unwrap(); + assert_eq!( + rejected(create(bound(Some(loud), "Loud")).1), + disagrees(crate::patch::KERNEL_SPEAK_HANDLE) + ); +} + +#[test] +fn unbound_world_keeps_the_open_catalog() { + let mut world = bound(None, "Open"); + world + .patch + .declarations + .push(declare("wave", "wave", &[("at", person())])); + let (_dir, kernel) = create(world); + let mut kernel = kernel.unwrap(); + let receipt = admit( + &mut kernel, + patch_of(vec![declare("beacon", "beacon", &[])]), + ) + .unwrap(); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + let snapshot = kernel.snapshot().unwrap(); + assert!(snapshot.grammar.is_none()); + assert!(snapshot.affordances.len() >= 4); + assert!(snapshot.affordances.iter().all(|a| a.render_path.is_none())); + + // The state row of a world with no grammar carries no grammar key, so its + // bytes and digests are those of a world written before grammars existed. + let encoded = rmp_serde::to_vec_named(&kernel.state).unwrap(); + let keys: std::collections::BTreeMap<String, serde::de::IgnoredAny> = + rmp_serde::from_slice(&encoded).unwrap(); + assert!(!keys.contains_key("grammar")); + assert!(keys.contains_key("brief")); +} + +#[test] +fn a_bound_world_reports_its_grammar_and_derives_render_paths_from_it() { + let extra = [("dock", verb(RenderPath::ShipAction, &[]))]; + let grammar = grammar_with(&extra); + let identity = grammar.identity(); + let (_dir, kernel) = create(bound(Some(grammar), "Reports")); + let mut kernel = kernel.unwrap(); + admit(&mut kernel, patch_of(vec![declare("dock", "dock", &[])])).unwrap(); + let snapshot = kernel.snapshot().unwrap(); + assert_eq!(snapshot.grammar, Some(identity)); + let path_of = |kind: &str| { + snapshot + .affordances + .iter() + .find(|a| a.entry.kind.0 == kind) + .unwrap_or_else(|| panic!("{kind} is in the catalog")) + .render_path + }; + assert_eq!(path_of("dock"), Some(RenderPath::ShipAction)); + assert_eq!(path_of("convene"), Some(RenderPath::Conversation)); + assert_eq!(path_of("speak"), Some(RenderPath::Conversation)); +} + +#[test] +fn a_reopened_grammar_world_still_holds_its_grammar() { + let grammar = grammar_with(&[]); + let identity = grammar.identity(); + let (directory, kernel) = create(bound(Some(grammar), "Reopened")); + let kernel = kernel.unwrap(); + let world_id = kernel.snapshot().unwrap().world_id; + drop(kernel); + let mut reopened = WorldKernel::open(directory.path().join("world.cc"), world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap().grammar, Some(identity)); + assert_eq!( + rejected(admit( + &mut reopened, + patch_of(vec![declare("wave", "wave", &[])]) + )), + not_in_grammar("wave") + ); +} + +#[test] +fn the_bound_grammar_is_part_of_the_world_state_digest() { + let (_dir, kernel) = create(bound(Some(grammar_with(&[])), "Digested")); + let kernel = kernel.unwrap(); + let bound_digest = crate::state_digest(&kernel.state).unwrap(); + let mut state = kernel.state.clone(); + state.grammar = None; + let open_digest = crate::state_digest(&state).unwrap(); + state.grammar = Some(grammar_with(&[("dock", verb(RenderPath::ShipAction, &[]))])); + let other_digest = crate::state_digest(&state).unwrap(); + assert_ne!(bound_digest, open_digest); + assert_ne!(bound_digest, other_digest); +} + +#[test] +fn grammar_digest_is_derived_and_order_free() { + let forward = [ + ("alpha".to_owned(), verb(RenderPath::ShipAction, &[])), + ( + "beta".to_owned(), + verb( + RenderPath::Conversation, + &[("to", GrammarReferentKind::Person)], + ), + ), + ("gamma".to_owned(), verb(RenderPath::Conversation, &[])), + ]; + let mut reversed = forward.clone(); + reversed.reverse(); + let a = GrammarBinding::new("aetheria.grammar", 1, forward.clone()).unwrap(); + let b = GrammarBinding::new("aetheria.grammar", 1, reversed).unwrap(); + assert_eq!(a.digest, b.digest); + assert_eq!(a, b); + + // Content-derived: each part of a verb moves the digest. + let changed = |edit: &dyn Fn(&mut Vec<(String, GrammarVerb)>)| { + let mut verbs = forward.to_vec(); + edit(&mut verbs); + GrammarBinding::new("aetheria.grammar", 1, verbs) + .unwrap() + .digest + }; + assert_ne!( + a.digest, + changed(&|v| v[0].1.render_path = RenderPath::Conversation) + ); + assert_ne!(a.digest, changed(&|v| v[1].1.roles[0].role = "from".into())); + assert_ne!( + a.digest, + changed(&|v| v[1].1.roles[0].referent = GrammarReferentKind::Faction) + ); + assert_ne!(a.digest, changed(&|v| v[2].0 = "delta".into())); + assert_ne!( + a.digest, + changed(&|v| { + v.pop(); + }) + ); + // Role order is part of a verb. + let ordered = |roles: &[(&str, GrammarReferentKind)]| { + GrammarBinding::new( + "g", + 1, + [("meet".to_owned(), verb(RenderPath::ShipAction, roles))], + ) + .unwrap() + .digest + }; + assert_ne!( + ordered(&[ + ("a", GrammarReferentKind::Person), + ("b", GrammarReferentKind::Place) + ]), + ordered(&[ + ("b", GrammarReferentKind::Place), + ("a", GrammarReferentKind::Person) + ]) + ); + // The identity reads the same fields back. + let identity = a.identity(); + assert_eq!(identity.schema_id, "aetheria.grammar"); + assert_eq!(identity.revision, 1); + assert_eq!(identity.digest, a.digest); +} + +#[test] +fn a_tampered_grammar_digest_fails_to_deserialise() { + let binding = grammar_with(&[]); + let value = serde_json::to_value(&binding).unwrap(); + // Untouched: the round trip holds. + let back: GrammarBinding = serde_json::from_value(value.clone()).unwrap(); + assert_eq!(back, binding); + + // A digest the verbs do not have. + let mut forged = value.clone(); + forged["digest"] = "sha256:00".into(); + assert!(serde_json::from_value::<GrammarBinding>(forged.clone()).is_err()); + + // A verb edited under the digest it already had. + let mut edited = value; + edited["verbs"]["convene"]["render_path"] = "ship_action".into(); + assert!(serde_json::from_value::<GrammarBinding>(edited).is_err()); + + // The named encoding a state row uses refuses it the same way. + let bytes = rmp_serde::to_vec_named(&forged).unwrap(); + assert!(rmp_serde::from_slice::<GrammarBinding>(&bytes).is_err()); +} + +#[test] +fn a_grammar_names_each_verb_once_and_has_a_schema() { + assert_eq!( + GrammarBinding::new("", 1, Vec::new()).unwrap_err(), + GrammarError::EmptySchemaId + ); + assert_eq!( + GrammarBinding::new( + "g", + 1, + [ + ("hail".to_owned(), verb(RenderPath::Conversation, &[])), + ("hail".to_owned(), verb(RenderPath::ShipAction, &[])), + ] + ) + .unwrap_err(), + GrammarError::DuplicateVerb + ); +} + +/// The fixture world was written by the code at base 367e2eb, which has no +/// grammar field anywhere. Reopening it must reproduce the digests that code +/// recorded. +#[test] +fn existing_world_reopens_with_unchanged_digests() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + std::fs::write(&path, include_bytes!("../../tests/fixtures/base_world.cc")).unwrap(); + let world_id: WorldId = + serde_json::from_str(include_str!("../../tests/fixtures/base_world.id").trim()).unwrap(); + let kernel = WorldKernel::open(&path, world_id).expect("a base-written world reopens"); + let snapshot = kernel.snapshot().unwrap(); + let recorded = include_str!("../../tests/fixtures/base_world.digests"); + let mut lines = recorded.lines(); + assert_eq!(snapshot.revision.to_string(), lines.next().unwrap()); + assert_eq!(snapshot.state_digest, lines.next().unwrap()); + assert_eq!( + snapshot.last_commit_digest.as_deref(), + Some(lines.next().unwrap()) + ); + assert!(snapshot.grammar.is_none()); + // Its state still derives the recorded digest from its bytes. + assert_eq!( + crate::state_digest(&kernel.state).unwrap(), + snapshot.state_digest + ); +} + +fn submit_as( + kernel: &mut WorldKernel, + caller: CallerId, + answers: Option<crate::PatchAnswer>, + patch: WorldPatch, +) -> Result<SubmitReceipt, KernelError> { + let snapshot = kernel.snapshot().unwrap(); + kernel.submit( + command( + &snapshot, + CommandId::new(), + caller.clone(), + CommandBody::AdmitPatch { answers, patch }, + ), + &crate::AuthenticatedCaller::fixture(caller), + ) +} + +/// A bound Draft world whose revision has moved past genesis: one owner patch +/// that adds a dead-end place the elaborator can answer. +fn advanced_grammar_world() -> (tempfile::TempDir, WorldKernel, crate::EntityId) { + let extra = [("hail", verb(RenderPath::Conversation, &[]))]; + let (dir, kernel) = create(bound(Some(grammar_with(&extra)), "Advanced")); + let mut kernel = kernel.unwrap(); + let commons = *kernel.state.entities.keys().next().unwrap(); + admit( + &mut kernel, + patch_of(vec![ + Declaration::Entity(crate::patch::EntityDeclaration { + handle: DraftHandle::new("dead-end"), + label: "The Unwalked Road".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Route(crate::patch::RouteDeclaration { + handle: DraftHandle::new("gate"), + label: "The Field Gate".into(), + from: crate::patch::Ref::Existing(commons), + to: crate::patch::Ref::Draft(DraftHandle::new("dead-end")), + access: crate::patch::AccessKind::Public, + cost: crate::patch::Cost(1), + }), + ]), + ) + .unwrap(); + let dead_end = *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "The Unwalked Road") + .map(|(id, _)| id) + .unwrap(); + (dir, kernel, dead_end) +} + +type Door = (&'static str, CallerId, Option<crate::PatchAnswer>); + +/// Each door refuses an outside kind and a wrong role signature, typed, and the +/// refusal leaves the revision where it was. The owner and the consumer declare +/// unanswered only in Draft; Play and the elaborator act in Active. +fn refuse_at_each_door(kernel: &mut WorldKernel, doors: Vec<Door>) { + for (door, caller, answers) in doors { + let revision = kernel.state.revision; + let kind = submit_as( + kernel, + caller.clone(), + answers.clone(), + patch_of(vec![declare("wave", "wave", &[])]), + ); + assert_eq!(rejected(kind), not_in_grammar("wave"), "{door}"); + let roles = submit_as( + kernel, + caller, + answers, + patch_of(vec![declare("hail", "hail", &[("who", person())])]), + ); + assert_eq!(rejected(roles), disagrees("hail"), "{door}"); + assert_eq!( + kernel.state.revision, revision, + "{door} refusal moved the world" + ); + } +} + +#[test] +fn every_admission_door_refuses_outside_the_grammar_after_the_revision_has_moved() { + let (_dir, mut kernel, dead_end) = advanced_grammar_world(); + assert_eq!(kernel.state.revision, 1); + let draft_doors = vec![ + ("owner", CallerId::Principal(owner()), None), + ( + "consumer", + CallerId::System(crate::SystemCapability::Consumer { + consumer: crate::ConsumerId::of_name("grammar-door"), + }), + None, + ), + ]; + refuse_at_each_door(&mut kernel, draft_doors); + crate::tests::activate(&mut kernel); + assert!( + kernel.state.revision > 1, + "the world has moved past genesis" + ); + let answer = crate::derive_boundaries(&kernel.state) + .unwrap() + .into_iter() + .find(|boundary| { + matches!(boundary, crate::CausalBoundary::UnelaboratedDestination { place, .. } + if *place == dead_end) + }) + .expect("the dead end is an unelaborated destination"); + let active_doors = vec![ + ( + "play", + CallerId::System(crate::SystemCapability::Play), + None, + ), + ( + "elaborator", + CallerId::System(crate::SystemCapability::Elaborator { + jurisdiction: crate::JurisdictionKey::PlaceSubtree(dead_end), + }), + Some(crate::PatchAnswer::Boundary(answer)), + ), + ]; + refuse_at_each_door(&mut kernel, active_doors); + // The same path admits what the grammar carries, so the refusals above are + // the grammar's and not a closed door. + let receipt = submit_as( + &mut kernel, + CallerId::System(crate::SystemCapability::Play), + None, + patch_of(vec![declare("hail", "hail", &[])]), + ) + .unwrap(); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); +} + +#[test] +fn a_grammar_that_binds_speak_as_anything_but_conversation_is_refused_at_bind() { + let ship = |roles: &[(&str, GrammarReferentKind)]| { + GrammarBinding::new( + "aetheria.grammar", + 1, + [ + ("speak".to_owned(), verb(RenderPath::ShipAction, roles)), + ("convene".to_owned(), verb(RenderPath::Conversation, &[])), + ], + ) + .unwrap() + }; + assert_eq!( + rejected(create(bound(Some(ship(&[])), "Filmed speech")).1), + vec![Mismatch::SpeakRenderPathDisagreesWithGrammar { + handle: DraftHandle::new(crate::patch::KERNEL_SPEAK_HANDLE), + }] + ); + // A ShipAction speak with a role fails on the signature first and is still + // refused: no variant of speak but zero roles, Conversation, is admitted. + assert_eq!( + rejected( + create(bound( + Some(ship(&[("to", GrammarReferentKind::Person)])), + "Loud" + )) + .1 + ), + disagrees(crate::patch::KERNEL_SPEAK_HANDLE) + ); + // The control: Conversation speak binds. + assert!(create(bound(Some(grammar_with(&[])), "Spoken")).1.is_ok()); +} + +/// `apply_effect` re-decides an effect it is handed. An effect resolved against +/// a world with no grammar must not install an entry the bound grammar lacks: +/// the catalog's only writer holds the grammar check itself. +#[test] +fn an_effect_resolved_elsewhere_cannot_install_an_entry_outside_the_grammar() { + let extra = [ + ( + "meet", + verb( + RenderPath::ShipAction, + &[("who", GrammarReferentKind::Person)], + ), + ), + ("hail", verb(RenderPath::Conversation, &[])), + ]; + let (_dir, kernel) = create(bound(Some(grammar_with(&extra)), "Forged")); + let kernel = kernel.unwrap(); + let mut twin = kernel.state.clone(); + twin.grammar = None; + let resolve = |kind: &str, roles: &[(&str, RefKind)]| { + crate::patch::resolve_patch( + &twin, + CommandId::new(), + &patch_of(vec![declare("probe", kind, roles)]), + None, + None, + ) + .expect("the unbound twin admits any canonical kind") + }; + for (label, resolved, admitted) in [ + ("outside kind", resolve("wave", &[]), false), + ("wrong roles", resolve("meet", &[("whom", person())]), false), + ("carried verb", resolve("hail", &[]), true), + ] { + let mut state = kernel.state.clone(); + let catalog = state.affordance_catalog.len(); + let result = crate::apply_effect( + &mut state, + CommandId::new(), + &CallerId::Principal(owner()), + &crate::WorldEffect::PatchAdmitted { + answers: None, + resolved, + }, + ); + if admitted { + result.unwrap_or_else(|error| panic!("{label}: {error:?}")); + assert_eq!(state.affordance_catalog.len(), catalog + 1, "{label}"); + } else { + assert!( + matches!(result, Err(KernelError::Invariant(_))), + "{label}: {result:?}" + ); + assert_eq!(state.affordance_catalog.len(), catalog, "{label}"); + } + } +} diff --git a/native/aetherlight/src/import_key_tests.rs b/native/aetherlight/src/import_key_tests.rs new file mode 100644 index 000000000..43ca2bb9a --- /dev/null +++ b/native/aetherlight/src/import_key_tests.rs @@ -0,0 +1,752 @@ +//! One record, one subject: admission keeps the import-key mapping injective at +//! every door and at every revision, and a world nobody imported into is +//! byte-for-byte what it was before keys existed. + +use crate::patch::{ + AccessKind, ComponentOp, Cost, Declaration, DraftHandle, EntityDeclaration, EntityKind, + ImportKey, Mismatch, Ref, RouteDeclaration, +}; +use crate::tests::{activate, auth_principal, command, creation, owner}; +use crate::{ + CallerId, CommandBody, CommandId, ConsumerId, CreateWorld, EntityId, JurisdictionKey, + KernelError, NewController, PatchAnswer, SubjectDeclaration, SubjectKind, SubmitReceipt, + SystemCapability, WorldKernel, WorldPatch, +}; +use std::collections::BTreeSet; + +fn key(schema: &str, record: &str) -> ImportKey { + ImportKey::new(schema, record) +} + +fn alpha() -> ImportKey { + key("aetheria.ship", "Alpha") +} + +/// The fixture genesis with its witness imported from `alpha()`. +fn keyed_creation(title: &str) -> CreateWorld { + let mut world = creation(CommandId::new(), title); + for declaration in &mut world.patch.declarations { + if let Declaration::Subject(subject) = declaration + && subject.handle == DraftHandle::new("persona") + { + subject.import_key = Some(alpha()); + } + } + world +} + +fn create(world: CreateWorld) -> (tempfile::TempDir, Result<WorldKernel, KernelError>) { + let directory = tempfile::tempdir().unwrap(); + let result = WorldKernel::create( + directory.path().join("world.cc"), + world, + &auth_principal(owner()), + ) + .map(|(kernel, _)| kernel); + (directory, result) +} + +fn keyed_world() -> (tempfile::TempDir, WorldKernel) { + let (dir, kernel) = create(keyed_creation("Keyed")); + (dir, kernel.unwrap()) +} + +fn rejected(result: Result<impl Sized, KernelError>) -> Vec<Mismatch> { + match result { + Err(KernelError::PatchRejected(set)) => set, + Err(other) => panic!("expected a patch refusal, got {other:?}"), + Ok(_) => panic!("expected a patch refusal, the command was admitted"), + } +} + +fn patch_of(declarations: Vec<Declaration>) -> WorldPatch { + WorldPatch { + declarations, + operations: Vec::new(), + evidence: Vec::new(), + } +} + +fn submit_as( + kernel: &mut WorldKernel, + caller: CallerId, + answers: Option<PatchAnswer>, + patch: WorldPatch, +) -> Result<SubmitReceipt, KernelError> { + let snapshot = kernel.snapshot().unwrap(); + kernel.submit( + command( + &snapshot, + CommandId::new(), + caller.clone(), + CommandBody::AdmitPatch { answers, patch }, + ), + &crate::AuthenticatedCaller::fixture(caller), + ) +} + +fn commons(kernel: &WorldKernel) -> EntityId { + *kernel.state.entities.keys().next().unwrap() +} + +/// A mirror subject: the one shape every door may declare, since it needs no +/// catalog grant. +fn mirror(handle: &str, import_key: Option<ImportKey>, place: EntityId) -> Declaration { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: format!("The {handle}"), + kind: SubjectKind::Person, + controller: NewController::External { + consumer: ConsumerId::of_name("import-key"), + }, + affordances: BTreeSet::new(), + position: Some(Ref::Existing(place)), + import_key, + }) +} + +fn held(handle: &str) -> Mismatch { + Mismatch::ImportKeyHeld { + handle: DraftHandle::new(handle), + } +} + +fn duplicate(handle: &str) -> Mismatch { + Mismatch::DuplicateImportKey { + handle: DraftHandle::new(handle), + } +} + +fn malformed(handle: &str) -> Mismatch { + Mismatch::MalformedImportKey { + handle: DraftHandle::new(handle), + } +} + +fn keys_in(kernel: &WorldKernel) -> Vec<ImportKey> { + kernel + .snapshot() + .unwrap() + .subjects + .into_iter() + .filter_map(|subject| subject.import_key) + .collect() +} + +#[test] +fn one_patch_cannot_declare_two_subjects_with_one_import_key() { + // At genesis. + let mut world = creation(CommandId::new(), "Twins"); + for declaration in &mut world.patch.declarations { + if let Declaration::Subject(subject) = declaration + && (subject.handle == DraftHandle::new("persona") + || subject.handle == DraftHandle::new("operator")) + { + subject.import_key = Some(alpha()); + } + } + let (_dir, result) = create(world); + assert_eq!(rejected(result), vec![duplicate("operator")]); + + // In a later patch, with the key unheld. + let (_dir, mut kernel) = keyed_world(); + let place = commons(&kernel); + let revision = kernel.state.revision; + let beta = Some(key("aetheria.ship", "Beta")); + let error = submit_as( + &mut kernel, + CallerId::Principal(owner()), + None, + patch_of(vec![ + mirror("first", beta.clone(), place), + mirror("second", beta, place), + ]), + ); + assert_eq!(rejected(error), vec![duplicate("second")]); + assert_eq!(kernel.state.revision, revision, "a refusal moved the world"); +} + +/// The fixture world past genesis but still in Draft: the owner has added an +/// unwalked place the elaborator can later answer. +fn advanced_keyed_world() -> (tempfile::TempDir, WorldKernel, EntityId) { + let (dir, mut kernel) = keyed_world(); + let place = commons(&kernel); + submit_as( + &mut kernel, + CallerId::Principal(owner()), + None, + patch_of(vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("dead-end"), + label: "The Unwalked Road".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("gate"), + label: "The Field Gate".into(), + from: Ref::Existing(place), + to: Ref::Draft(DraftHandle::new("dead-end")), + access: AccessKind::Public, + cost: Cost(1), + }), + ]), + ) + .unwrap(); + let dead_end = *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "The Unwalked Road") + .map(|(id, _)| id) + .unwrap(); + (dir, kernel, dead_end) +} + +/// Each door names the held key, typed, and the refusal leaves the revision +/// where it was. The owner and the consumer declare in Draft only; Play and the +/// elaborator act in Active. +fn refuse_held_key_at_each_door( + kernel: &mut WorldKernel, + place: EntityId, + doors: Vec<(&str, CallerId, Option<PatchAnswer>)>, +) { + for (door, caller, answers) in doors { + let revision = kernel.state.revision; + let result = submit_as( + kernel, + caller, + answers, + patch_of(vec![mirror("copy", Some(alpha()), place)]), + ); + assert_eq!(rejected(result), vec![held("copy")], "{door}"); + assert_eq!( + kernel.state.revision, revision, + "{door} refusal moved the world" + ); + } +} + +fn consumer() -> CallerId { + CallerId::System(SystemCapability::Consumer { + consumer: ConsumerId::of_name("import-key"), + }) +} + +#[test] +fn a_held_import_key_is_refused_at_every_door_after_the_revision_has_moved() { + let (_dir, mut kernel, dead_end) = advanced_keyed_world(); + assert!(kernel.state.revision > 0, "the world has moved past genesis"); + refuse_held_key_at_each_door( + &mut kernel, + dead_end, + vec![ + ("owner", CallerId::Principal(owner()), None), + ("consumer", consumer(), None), + ], + ); + activate(&mut kernel); + let answer = crate::derive_boundaries(&kernel.state) + .unwrap() + .into_iter() + .find(|boundary| { + matches!(boundary, crate::CausalBoundary::UnelaboratedDestination { place, .. } + if *place == dead_end) + }) + .expect("the dead end is an unelaborated destination"); + refuse_held_key_at_each_door( + &mut kernel, + dead_end, + vec![ + ("play", CallerId::System(SystemCapability::Play), None), + ( + "elaborator", + CallerId::System(SystemCapability::Elaborator { + jurisdiction: JurisdictionKey::PlaceSubtree(dead_end), + }), + Some(PatchAnswer::Boundary(answer.clone())), + ), + ], + ); + // The same doors admit an unheld key, so the refusals are the key's; and + // what a door admitted is held against every later door. + let fresh = key("aetheria.ship", "Gamma"); + let receipt = submit_as( + &mut kernel, + CallerId::System(SystemCapability::Elaborator { + jurisdiction: JurisdictionKey::PlaceSubtree(dead_end), + }), + Some(PatchAnswer::Boundary(answer)), + patch_of(vec![mirror("fresh", Some(fresh.clone()), dead_end)]), + ) + .unwrap(); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + let again = submit_as( + &mut kernel, + CallerId::System(SystemCapability::Play), + None, + patch_of(vec![mirror("fresh-again", Some(fresh), dead_end)]), + ); + assert_eq!(rejected(again), vec![held("fresh-again")]); +} + +#[test] +fn a_held_import_key_is_refused_in_a_later_patch() { + let (_dir, mut kernel) = keyed_world(); + let place = commons(&kernel); + let revision = kernel.state.revision; + let error = submit_as( + &mut kernel, + CallerId::Principal(owner()), + None, + patch_of(vec![mirror("again", Some(alpha()), place)]), + ); + assert_eq!(rejected(error), vec![held("again")]); + assert_eq!(kernel.state.revision, revision); + assert_eq!(keys_in(&kernel), vec![alpha()]); +} + +#[test] +fn a_retired_subjects_import_key_is_never_reissued() { + let (_dir, mut kernel) = keyed_world(); + let place = commons(&kernel); + let witness = kernel + .snapshot() + .unwrap() + .subjects + .into_iter() + .find(|subject| subject.import_key.is_some()) + .unwrap() + .id; + submit_as( + &mut kernel, + CallerId::Principal(owner()), + None, + WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Retire { + subject: Ref::Existing(witness), + }], + evidence: Vec::new(), + }, + ) + .unwrap(); + let retired = kernel + .snapshot() + .unwrap() + .subjects + .into_iter() + .find(|subject| subject.id == witness) + .unwrap(); + assert!(retired.retired, "the witness is retired"); + assert_eq!( + retired.import_key, + Some(alpha()), + "a retired subject keeps its key" + ); + let error = submit_as( + &mut kernel, + CallerId::Principal(owner()), + None, + patch_of(vec![mirror("reborn", Some(alpha()), place)]), + ); + assert_eq!(rejected(error), vec![held("reborn")]); +} + +#[test] +fn keys_that_differ_in_any_way_are_distinct_records() { + let (_dir, mut kernel) = keyed_world(); + let place = commons(&kernel); + // Same length, case, prefix, the same concatenation split elsewhere, and + // the parts swapped: none is the held key. + let forgeries = [ + key("aetheria.ship", "Alphb"), + key("aetheria.ship", "alpha"), + key("aetheria.ship", "Alph"), + key("aetheria.ship", "Alpha2"), + key("aetheria.shipA", "lpha"), + key("aetheria.sh", "ipAlpha"), + key("Aetheria.ship", "Alpha"), + key("Alpha", "aetheria.ship"), + key("aetheria.ship2", "Alpha"), + ]; + let declarations = forgeries + .iter() + .enumerate() + .map(|(index, forged)| mirror(&format!("forged-{index}"), Some(forged.clone()), place)) + .collect(); + submit_as( + &mut kernel, + CallerId::Principal(owner()), + None, + patch_of(declarations), + ) + .expect("nine distinct keys beside the held one are admitted together"); + let held_now: BTreeSet<ImportKey> = keys_in(&kernel).into_iter().collect(); + assert_eq!(held_now.len(), forgeries.len() + 1); + // And each is then held exactly: repeating any one is refused. + for (index, forged) in forgeries.iter().enumerate() { + let again = submit_as( + &mut kernel, + CallerId::Principal(owner()), + None, + patch_of(vec![mirror("repeat", Some(forged.clone()), place)]), + ); + assert_eq!(rejected(again), vec![held("repeat")], "forgery {index}"); + } +} + +#[test] +fn a_malformed_import_key_is_refused_without_echoing_it() { + let (_dir, mut kernel) = keyed_world(); + let place = commons(&kernel); + let long = "x".repeat(201); + let wide = "é".repeat(101); + let cases = [ + key("", "Delta"), + key("aetheria.ship", ""), + key("aetheria ship", "Delta"), + key("aetheria.ship", "Del\tta"), + key("aetheria.ship", "Del\u{a0}ta"), + key("aetheria.ship", " Delta"), + key("aetheria.ship", "Delta\n"), + key(&long, "Delta"), + key("aetheria.ship", &long), + key("aetheria.ship", &wide), + key(&wide, "Delta"), + ]; + for (index, bad) in cases.iter().enumerate() { + let set = rejected(submit_as( + &mut kernel, + CallerId::Principal(owner()), + None, + patch_of(vec![mirror("bad", Some(bad.clone()), place)]), + )); + assert_eq!(set, vec![malformed("bad")], "case {index}"); + let spelled = format!("{set:?}"); + assert!( + !spelled.contains("Delta") && !spelled.contains("aetheria"), + "case {index} echoed the key" + ); + } + // The limit is 200 bytes per part, counted in bytes. + let edge = "é".repeat(100); + let at_limit = [ + key(&"x".repeat(200), &edge), + key("aetheria.ship", &"y".repeat(200)), + ]; + let declarations = at_limit + .iter() + .enumerate() + .map(|(index, limit)| mirror(&format!("edge-{index}"), Some(limit.clone()), place)) + .collect(); + submit_as( + &mut kernel, + CallerId::Principal(owner()), + None, + patch_of(declarations), + ) + .expect("keys of exactly 200 bytes per part are admitted"); +} + +#[test] +fn the_subjects_map_refuses_a_second_subject_for_one_key_even_when_resolved_elsewhere() { + let (_dir, kernel) = keyed_world(); + let place = commons(&kernel); + let resolve = |handle: &str| { + crate::patch::resolve_patch( + &kernel.state, + CommandId::new(), + &patch_of(vec![mirror( + handle, + Some(key("aetheria.ship", "Omega")), + place, + )]), + None, + None, + ) + .expect("the key is unheld at the revision both were resolved against") + }; + let (first, second) = (resolve("first"), resolve("second")); + let mut state = kernel.state.clone(); + let before = state.subjects.len(); + let effect = |resolved| crate::WorldEffect::PatchAdmitted { + answers: None, + resolved, + }; + crate::apply_effect( + &mut state, + CommandId::new(), + &CallerId::Principal(owner()), + &effect(first), + ) + .unwrap(); + assert_eq!(state.subjects.len(), before + 1); + let result = crate::apply_effect( + &mut state, + CommandId::new(), + &CallerId::Principal(owner()), + &effect(second), + ); + assert!( + matches!(result, Err(KernelError::Invariant(_))), + "{result:?}" + ); + assert_eq!( + state.subjects.len(), + before + 1, + "the second subject was installed" + ); +} + +fn contains(haystack: &[u8], needle: &[u8]) -> bool { + haystack.windows(needle.len()).any(|window| window == needle) +} + +#[test] +fn keyless_world_digests_unchanged() { + // A subject nobody imported serialises without the field at all, so every + // digest written before keys existed is the digest of the same bytes. + let (_dir, kernel) = create(creation(CommandId::new(), "Keyless")); + let kernel = kernel.unwrap(); + let state = rmp_serde::to_vec_named(&kernel.state).unwrap(); + assert!( + !contains(&state, b"import_key"), + "a keyless world grew a field" + ); + // A keyed world carries it, round-trips, and digests differently. + let (_dir, keyed) = keyed_world(); + let keyed_state = rmp_serde::to_vec_named(&keyed.state).unwrap(); + assert!(contains(&keyed_state, b"import_key")); + let back: crate::WorldState = rmp_serde::from_slice(&keyed_state).unwrap(); + assert_eq!( + crate::state_digest(&back).unwrap(), + crate::state_digest(&keyed.state).unwrap() + ); + assert_ne!( + crate::state_digest(&keyed.state).unwrap(), + crate::state_digest(&kernel.state).unwrap() + ); + // And a pre-key state deserialises with every key absent. + let stripped: crate::WorldState = rmp_serde::from_slice(&state).unwrap(); + assert!(stripped.subjects.values().all(|s| s.import_key.is_none())); +} + +#[test] +fn a_keyed_world_reopens_with_its_keys_and_digests() { + let (dir, kernel) = keyed_world(); + let snapshot = kernel.snapshot().unwrap(); + let world_id = snapshot.world_id; + drop(kernel); + let reopened = WorldKernel::open(dir.path().join("world.cc"), world_id).unwrap(); + let again = reopened.snapshot().unwrap(); + assert_eq!(again.state_digest, snapshot.state_digest); + let keys = keys_in(&reopened); + assert_eq!(keys, vec![alpha()]); + // A reader of the snapshot gets both parts back, separately. + assert_eq!(keys[0].schema(), "aetheria.ship"); + assert_eq!(keys[0].record(), "Alpha"); +} + + +#[test] +fn a_record_key_is_one_canonical_spelling() { + let (_dir, mut kernel) = keyed_world(); + let place = commons(&kernel); + let nfc = "Caf\u{e9}"; + let nfd = "Cafe\u{301}"; + let submit = |kernel: &mut WorldKernel, handle: &str, record: &str| { + submit_as( + kernel, + CallerId::Principal(owner()), + None, + patch_of(vec![mirror( + handle, + Some(key("aetheria.ship", record)), + place, + )]), + ) + }; + submit(&mut kernel, "nfc", nfc).expect("the NFC spelling is admitted"); + let refused = [ + nfd, + "Alpha\u{200b}", + "Alpha\u{0}", + "\u{feff}Alpha", + "Alpha\u{202e}", + "Alpha\u{7}", + "Del ta", + "Del\tta", + "Del\u{a0}ta", + "Del\u{2003}ta", + "Del\nta", + // The violation sits deep in a long, real-shaped path, past any prefix. + "Worldbuilding/Pre-Elysium/Factions/Powers/Minor/Cafe\u{301}", + "Worldbuilding/Pre-Elysium/Factions/Powers/Minor/Ewan\u{200b}Hart", + ]; + for (index, record) in refused.iter().enumerate() { + let set = rejected(submit(&mut kernel, "bad", record)); + assert_eq!(set, vec![malformed("bad")], "spelling {index}"); + assert!( + !format!("{set:?}").contains("Alpha"), + "spelling {index} echoed the key" + ); + } + assert_eq!( + keys_in(&kernel).len(), + 2, + "only the genesis key and the NFC key are held" + ); +} + +#[test] +fn a_lore_page_path_with_spaces_is_a_record_key() { + let (_dir, mut kernel) = keyed_world(); + let place = commons(&kernel); + let record = "Worldbuilding/Pre-Elysium/Factions/Powers/Minor/Ewan Hart"; + let declare = |kernel: &mut WorldKernel, handle: &str| { + submit_as( + kernel, + CallerId::Principal(owner()), + None, + patch_of(vec![mirror( + handle, + Some(key("aetheria.lore", record)), + place, + )]), + ) + }; + declare(&mut kernel, "ewan").expect("a path with interior spaces is admitted"); + assert_eq!(rejected(declare(&mut kernel, "again")), vec![held("again")]); +} + +#[test] +fn a_loaded_state_with_a_bad_import_key_is_refused() { + let (_dir, mut kernel) = keyed_world(); + let place = commons(&kernel); + submit_as( + &mut kernel, + CallerId::Principal(owner()), + None, + patch_of(vec![mirror( + "beta", + Some(key("aetheria.ship", "Beta")), + place, + )]), + ) + .unwrap(); + assert!(crate::journal::verify_state_shape(&kernel.state).is_ok()); + let corrupt = |edit: &dyn Fn(&mut ImportKey)| { + let mut state = kernel.state.clone(); + for subject in state.subjects.values_mut() { + if let Some(held) = subject.import_key.as_mut() { + edit(held); + } + } + crate::journal::verify_state_shape(&state) + }; + let shared = corrupt(&|held| *held = alpha()); + assert!( + matches!(&shared, Err(crate::journal::JournalError::Corrupt(why)) if why.contains("import key")), + "two subjects sharing one key: {shared:?}" + ); + assert!( + corrupt(&|held| *held = key("aetheria.ship", " Beta ")).is_err(), + "a key with edge spaces must not load" + ); + assert!( + corrupt(&|held| *held = key("", "")).is_err(), + "an empty key must not load" + ); + assert!( + corrupt(&|held| *held = key("aetheria.ship", "Be\u{200b}ta")).is_err(), + "a key with a format character must not load" + ); +} + +/// The admission backstop, reached with an effect resolution never produced: a +/// resolved patch whose two subjects carry one key. The control is the same +/// effect with distinct keys, admitted by the same function. +#[test] +fn admitting_a_resolved_effect_refuses_two_subjects_with_one_key() { + let (_dir, kernel) = keyed_world(); + let place = commons(&kernel); + let resolve = || { + crate::patch::resolve_patch( + &kernel.state, + CommandId::new(), + &patch_of(vec![ + mirror("first", Some(key("aetheria.ship", "Beta")), place), + mirror("second", Some(key("aetheria.ship", "Gamma")), place), + ]), + None, + None, + ) + .expect("two distinct keys resolve") + }; + let resolves_to = crate::resolution_revision(&kernel.state).unwrap(); + let mut control = kernel.state.clone(); + crate::admit_resolved(&mut control, &resolve(), resolves_to) + .expect("distinct keys are admitted"); + + let mut twinned = resolve(); + assert_eq!(twinned.subjects.len(), 2); + twinned.subjects[1].subject.import_key = twinned.subjects[0].subject.import_key.clone(); + let mut state = kernel.state.clone(); + let error = crate::admit_resolved(&mut state, &twinned, resolves_to) + .expect_err("one key on two resolved subjects is refused"); + assert!( + matches!(&error, KernelError::Invariant(why) if why.contains("import key")), + "{error:?}" + ); + assert!(!format!("{error:?}").contains("Beta"), "the refusal echoed the key"); +} + +/// A decomposable character at every position of a real-shaped key: the NFD +/// spelling is refused wherever it sits, the NFC spelling is admitted, so the +/// rule cannot be a prefix, suffix or first-character check. +#[test] +fn a_decomposable_character_is_refused_in_nfd_at_every_position() { + let (_dir, mut kernel) = keyed_world(); + let place = commons(&kernel); + let template: Vec<char> = "Worldbuilding/Pre-Elysium/Factions/Powers/Minor/Ewan Hart" + .chars() + .collect(); + let submit = |kernel: &mut WorldKernel, handle: &str, record: String| { + submit_as( + kernel, + CallerId::Principal(owner()), + None, + patch_of(vec![mirror( + handle, + Some(key("aetheria.lore", &record)), + place, + )]), + ) + }; + let spelled = |position: usize, inserted: &str| { + let mut record: String = template[..position].iter().collect(); + record.push_str(inserted); + record.extend(&template[position..]); + record + }; + for position in 0..=template.len() { + let nfd = spelled(position, "e\u{301}"); + assert!( + !unicode_normalization::is_nfc(&nfd), + "position {position} is not NFD" + ); + let set = rejected(submit(&mut kernel, "bad", nfd)); + assert_eq!(set, vec![malformed("bad")], "NFD at position {position}"); + } + for position in 0..=template.len() { + let nfc = spelled(position, "\u{e9}"); + submit(&mut kernel, &format!("good{position}"), nfc) + .unwrap_or_else(|_| panic!("NFC at position {position} was refused")); + } + assert_eq!( + keys_in(&kernel).len(), + 1 + template.len() + 1, + "the genesis key and one NFC key per position are held, no NFD key" + ); +} diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs new file mode 100644 index 000000000..a2d36fbb2 --- /dev/null +++ b/native/aetherlight/src/journal.rs @@ -0,0 +1,2990 @@ +use super::{ + COMMIT_SCHEMA, CommandId, CommittedCommand, KernelError, STATE_SCHEMA, WorldCommit, + WorldEffect, WorldId, WorldState, apply_effect, commit_digest, reduce, state_digest, +}; +use chrono::Utc; +use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore}; +use serde::{Serialize, de::DeserializeOwned}; +use std::{ + cell::Cell, + collections::{BTreeMap, BTreeSet}, + path::Path, +}; +use thiserror::Error; + +const STATE_ROW: &str = "world_state.elaboration.v1"; +const COMMIT_ROW: &str = "world_commit.elaboration.v1"; + +#[derive(Debug, Error)] +pub(super) enum JournalError { + #[error("opened store contains another world")] + WorldMismatch, + #[error("world ownership is uncertain after command {command_id:?}; drop and reopen")] + RecoveryRequired { command_id: CommandId }, + #[error("world store path no longer names the owned database")] + OwnershipLost, + #[error("world store operation failed: {0}")] + Store(String), + #[error("world journal is corrupt: {0}")] + Corrupt(String), +} + +pub(super) enum JournalOpen { + Empty(EmptyWorldJournal), + Live { + journal: WorldJournal, + state: WorldState, + }, +} + +pub(super) struct EmptyWorldJournal { + store: OwnedRedbMessagePackBackingStore, + #[cfg(test)] + fail_after_durable_initialize: bool, +} + +#[derive(Clone, Copy)] +enum JournalHealth { + Healthy, + RecoveryRequired(CommandId), + OwnershipLost, +} + +pub(super) struct WorldJournal { + store: OwnedRedbMessagePackBackingStore, + state_row: CultCacheEnvelope, + commits: BTreeMap<CommandId, WorldCommit>, + health: Cell<JournalHealth>, + #[cfg(test)] + fail_after_durable_commit: bool, +} + +impl WorldJournal { + pub(super) fn open_owner(path: &Path) -> Result<JournalOpen, JournalError> { + let store = OwnedRedbMessagePackBackingStore::new(path) + .map_err(|error| JournalError::Store(error.to_string()))?; + store + .validate_path_identity() + .map_err(|_| JournalError::OwnershipLost)?; + let rows = store + .pull_all() + .map_err(|error| JournalError::Store(error.to_string()))?; + store + .validate_path_identity() + .map_err(|_| JournalError::OwnershipLost)?; + if rows.is_empty() { + return Ok(JournalOpen::Empty(EmptyWorldJournal { + store, + #[cfg(test)] + fail_after_durable_initialize: false, + })); + } + let (state_row, state, commits) = recover(rows, None)?; + Ok(JournalOpen::Live { + journal: Self { + store, + state_row, + commits, + health: Cell::new(JournalHealth::Healthy), + #[cfg(test)] + fail_after_durable_commit: false, + }, + state, + }) + } + + pub(super) fn open( + path: &Path, + expected_world_id: WorldId, + ) -> Result<(Self, WorldState), JournalError> { + let store = OwnedRedbMessagePackBackingStore::new(path) + .map_err(|error| JournalError::Store(error.to_string()))?; + store + .validate_path_identity() + .map_err(|_| JournalError::OwnershipLost)?; + let rows = store + .pull_all() + .map_err(|error| JournalError::Store(error.to_string()))?; + store + .validate_path_identity() + .map_err(|_| JournalError::OwnershipLost)?; + let (state_row, state, commits) = recover(rows, Some(expected_world_id))?; + Ok(( + Self { + store, + state_row, + commits, + health: Cell::new(JournalHealth::Healthy), + #[cfg(test)] + fail_after_durable_commit: false, + }, + state, + )) + } + + pub(super) fn ensure_healthy(&self) -> Result<(), JournalError> { + match self.health.get() { + JournalHealth::RecoveryRequired(command_id) => { + return Err(JournalError::RecoveryRequired { command_id }); + } + JournalHealth::OwnershipLost => return Err(JournalError::OwnershipLost), + JournalHealth::Healthy => {} + } + if self.store.validate_path_identity().is_err() { + self.health.set(JournalHealth::OwnershipLost); + return Err(JournalError::OwnershipLost); + } + Ok(()) + } + + pub(super) fn commit( + &mut self, + next: &WorldState, + commit: &WorldCommit, + ) -> Result<(), JournalError> { + self.ensure_healthy()?; + let command_id = commit.command.id(); + if self.commits.contains_key(&command_id) { + return Err(JournalError::Corrupt( + "single-owner append attempted to duplicate a committed command".into(), + )); + } + let current: WorldState = decode(&self.state_row)?; + verify_append(¤t, next, commit)?; + let next_row = envelope(STATE_ROW, STATE_SCHEMA, next.world_id.key(), next)?; + let commit_row = envelope(COMMIT_ROW, COMMIT_SCHEMA, command_id.key(), commit)?; + self.health.set(JournalHealth::RecoveryRequired(command_id)); + let swapped = self.store.compare_and_swap_batch( + std::slice::from_ref(&self.state_row), + vec![next_row.clone(), commit_row], + ); + match swapped { + Ok(true) => {} + Ok(false) | Err(_) => { + return Err(JournalError::RecoveryRequired { command_id }); + } + } + #[cfg(test)] + if self.fail_after_durable_commit { + return Err(JournalError::RecoveryRequired { command_id }); + } + if self.store.validate_path_identity().is_err() { + return Err(JournalError::RecoveryRequired { command_id }); + } + self.state_row = next_row; + self.commits.insert(command_id, commit.clone()); + self.health.set(JournalHealth::Healthy); + Ok(()) + } + + pub(super) fn commit_for(&self, command_id: CommandId) -> Option<&WorldCommit> { + self.commits.get(&command_id) + } + + /// Every commit the journal holds, in no particular order. + pub(super) fn commits(&self) -> impl Iterator<Item = &WorldCommit> { + self.commits.values() + } + + #[cfg(test)] + pub(super) fn commit_count(&self) -> usize { + self.commits.len() + } + + /// PA.f40: a test outside this module needs the full commit map to forge + /// one commit's effect and route the forgery through `verify_history` + /// directly, the same way this module's own forgery tests already do via + /// `self.commits.clone()`. + #[cfg(test)] + pub(super) fn commits_for_test(&self) -> BTreeMap<CommandId, WorldCommit> { + self.commits.clone() + } + + #[cfg(test)] + pub(super) fn fail_after_durable_commit_for_test(&mut self) { + self.fail_after_durable_commit = true; + } +} + +impl EmptyWorldJournal { + #[cfg(test)] + pub(super) fn fail_after_durable_initialize_for_test(&mut self) { + self.fail_after_durable_initialize = true; + } + + pub(super) fn initialize( + self, + state: &WorldState, + genesis: &WorldCommit, + ) -> Result<WorldJournal, JournalError> { + self.store + .validate_path_identity() + .map_err(|_| JournalError::OwnershipLost)?; + let mut commits = BTreeMap::new(); + let command_id = genesis.command.id(); + commits.insert(command_id, genesis.clone()); + verify_history(state, &commits)?; + let state_row = envelope(STATE_ROW, STATE_SCHEMA, state.world_id.key(), state)?; + let commit_row = envelope(COMMIT_ROW, COMMIT_SCHEMA, command_id.key(), genesis)?; + let inserted = self + .store + .append_if_snapshot_unchanged(&[], vec![state_row.clone(), commit_row]); + if !matches!(inserted, Ok(true)) { + return Err(JournalError::RecoveryRequired { command_id }); + } + #[cfg(test)] + if self.fail_after_durable_initialize { + return Err(JournalError::RecoveryRequired { command_id }); + } + if self.store.validate_path_identity().is_err() { + return Err(JournalError::RecoveryRequired { command_id }); + } + Ok(WorldJournal { + store: self.store, + state_row, + commits, + health: Cell::new(JournalHealth::Healthy), + #[cfg(test)] + fail_after_durable_commit: false, + }) + } +} + +fn recover( + rows: Vec<CultCacheEnvelope>, + expected_world_id: Option<WorldId>, +) -> Result< + ( + CultCacheEnvelope, + WorldState, + BTreeMap<CommandId, WorldCommit>, + ), + JournalError, +> { + let mut state_rows = Vec::new(); + let mut commits = BTreeMap::new(); + for row in rows { + match row.r#type.as_str() { + STATE_ROW => { + require_schema(&row, STATE_SCHEMA)?; + state_rows.push(row); + } + COMMIT_ROW => { + require_schema(&row, COMMIT_SCHEMA)?; + let commit: WorldCommit = decode(&row)?; + let command_id = commit.command.id(); + if row.key != command_id.key() { + return Err(JournalError::Corrupt( + "commit row key does not match command ID".into(), + )); + } + if commits.insert(command_id, commit).is_some() { + return Err(JournalError::Corrupt("duplicate command commit".into())); + } + } + other => { + return Err(JournalError::Corrupt(format!( + "unadmitted row type {other}" + ))); + } + } + } + if state_rows.len() != 1 { + return Err(JournalError::Corrupt(format!( + "expected one state row, found {}", + state_rows.len() + ))); + } + let state_row = state_rows.pop().expect("length checked"); + let state: WorldState = decode(&state_row)?; + if state_row.key != state.world_id.key() { + return Err(JournalError::Corrupt( + "state row key does not match its world ID".into(), + )); + } + if expected_world_id.is_some_and(|expected| state.world_id != expected) { + return Err(JournalError::WorldMismatch); + } + verify_history(&state, &commits)?; + Ok((state_row, state, commits)) +} + +fn verify_append( + current: &WorldState, + next: &WorldState, + commit: &WorldCommit, +) -> Result<(), JournalError> { + verify_state_shape(current)?; + verify_state_shape(next)?; + if current.world_id != next.world_id + || commit.world_id != current.world_id + || commit.schema != COMMIT_SCHEMA + || commit.previous_revision != Some(current.revision) + || commit.resulting_revision != next.revision + || next.revision != current.revision.saturating_add(1) + || commit.previous_state_digest.as_deref() != Some(current.state_digest.as_str()) + || commit.resulting_state_digest != next.state_digest + || commit.previous_commit_digest != current.last_commit_digest + || next.last_commit_digest.as_deref() != Some(commit.digest.as_str()) + { + return Err(JournalError::Corrupt( + "commit does not bind the exact state transition".into(), + )); + } + if state_digest(current).map_err(kernel_error)? != current.state_digest + || state_digest(next).map_err(kernel_error)? != next.state_digest + || commit_digest(commit).map_err(kernel_error)? != commit.digest + { + return Err(JournalError::Corrupt("digest mismatch".into())); + } + let mut replay = current.clone(); + apply_committed_command(&mut replay, commit)?; + replay.revision = next.revision; + replay.state_digest = state_digest(&replay).map_err(kernel_error)?; + replay.last_commit_digest = Some(commit.digest.clone()); + if &replay != next { + return Err(JournalError::Corrupt( + "commit effect does not reproduce next state".into(), + )); + } + Ok(()) +} + +/// `pub(super)`, matching `verify_state_shape`: a Soul-style forgery test +/// outside this module routes its falsification through the same function +/// that actually judges a committed history, rather than through the +/// structural-only `verify_state_shape`. +pub(super) fn verify_history( + state: &WorldState, + commits: &BTreeMap<CommandId, WorldCommit>, +) -> Result<(), JournalError> { + verify_state_shape(state)?; + if commits + .iter() + .any(|(command_id, commit)| *command_id != commit.command.id()) + { + return Err(JournalError::Corrupt( + "commit index does not derive from the persisted command".into(), + )); + } + let expected_commits = usize::try_from(state.revision) + .map_err(|_| JournalError::Corrupt("revision does not fit this runtime".into()))?; + let expected_commits = expected_commits + .checked_add(1) + .ok_or_else(|| JournalError::Corrupt("commit count overflow".into()))?; + if commits.len() != expected_commits { + return Err(JournalError::Corrupt( + "commit count does not equal genesis plus head revision".into(), + )); + } + let mut ordered: Vec<_> = commits.values().collect(); + ordered.sort_by_key(|commit| commit.resulting_revision); + let genesis = ordered + .first() + .ok_or_else(|| JournalError::Corrupt("world has no genesis commit".into()))?; + let CommittedCommand::CreateWorld(genesis_command) = &genesis.command else { + return Err(JournalError::Corrupt( + "first commit does not contain the immutable creation command".into(), + )); + }; + let WorldEffect::WorldCreated { .. } = &genesis.effect else { + return Err(JournalError::Corrupt( + "first commit is not immutable world genesis".into(), + )); + }; + if genesis.schema != COMMIT_SCHEMA + || genesis.world_id != state.world_id + || genesis.previous_revision.is_some() + || genesis.resulting_revision != 0 + || genesis.previous_state_digest.is_some() + || genesis.previous_commit_digest.is_some() + || commit_digest(genesis).map_err(kernel_error)? != genesis.digest + { + return Err(JournalError::Corrupt( + "genesis commit is not canonical or verifiable".into(), + )); + } + let mut replay = WorldState::genesis(state.world_id, genesis_command, &genesis.effect) + .map_err(kernel_error)?; + verify_state_shape(&replay)?; + verify_commitments_are_future(&replay, &BTreeMap::new())?; + if replay.state_digest != genesis.resulting_state_digest { + return Err(JournalError::Corrupt( + "genesis resulting state digest is invalid".into(), + )); + } + replay.last_commit_digest = Some(genesis.digest.clone()); + + for commit in ordered.into_iter().skip(1) { + if commit.schema != COMMIT_SCHEMA + || commit.world_id != state.world_id + || commit.previous_revision != Some(replay.revision) + || commit.resulting_revision != replay.revision.saturating_add(1) + || commit.previous_state_digest.as_deref() != Some(replay.state_digest.as_str()) + || commit.previous_commit_digest != replay.last_commit_digest + || commit_digest(commit).map_err(kernel_error)? != commit.digest + { + return Err(JournalError::Corrupt( + "commit chain is not contiguous or verifiable".into(), + )); + } + let previous_now = replay.now; + let previous_commitments = replay.commitments.clone(); + // Authority is re-decided here for free: `apply_committed_command` + // re-runs `reduce` against the pre-commit state and requires effect + // equality, then `apply_effect`, and both of those call + // `require_patch_author` and `confine_to_jurisdiction`. A forged row + // claiming an elaborator caller for a patch outside its jurisdiction + // fails replay rather than being admitted by a reducer that trusts the + // recorded caller. A third statement of the same rule here would be a + // third owner of one decision. + apply_committed_command(&mut replay, commit)?; + // Two chain checks one state cannot make: the clock never runs + // backwards, and it advances only on a tick. + let advanced = matches!(commit.effect, WorldEffect::TimeAdvanced { .. }); + if replay.now < previous_now || (replay.now > previous_now) != advanced { + return Err(JournalError::Corrupt( + "the world clock moved without a time-advanced commit, or ran backwards".into(), + )); + } + verify_commitments_are_future(&replay, &previous_commitments)?; + replay.revision = commit.resulting_revision; + replay.state_digest = state_digest(&replay).map_err(kernel_error)?; + if replay.state_digest != commit.resulting_state_digest { + return Err(JournalError::Corrupt( + "commit resulting state digest is invalid".into(), + )); + } + replay.last_commit_digest = Some(commit.digest.clone()); + } + if &replay != state { + return Err(JournalError::Corrupt( + "head state does not equal replayed history".into(), + )); + } + Ok(()) +} + +/// The replay-side twin of `Mismatch::CommitmentDueInThePast`: every commitment +/// key this commit introduced is due after the post-commit clock. Replay already +/// reconstructs both sides, so this is a set difference over one partition. +fn verify_commitments_are_future( + state: &WorldState, + before: &BTreeMap<super::SubjectId, BTreeMap<super::CommitmentKey, super::Commitment>>, +) -> Result<(), JournalError> { + for (subject_id, held) in &state.commitments { + for (key, commitment) in held { + let existed = before + .get(subject_id) + .is_some_and(|previous| previous.contains_key(key)); + if !existed && commitment.due <= state.now { + return Err(JournalError::Corrupt( + "a commitment was born at or after its own due date".into(), + )); + } + } + } + Ok(()) +} + +pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> { + if state.schema != STATE_SCHEMA { + return Err(JournalError::Corrupt("invalid state schema".into())); + } + if state.title.trim().is_empty() || state.title.trim() != state.title { + return Err(JournalError::Corrupt( + "world title is empty or noncanonical".into(), + )); + } + if state.brief.trim() != state.brief { + return Err(JournalError::Corrupt("world brief is noncanonical".into())); + } + if state.brief.trim() != state.brief { + return Err(JournalError::Corrupt("world brief is noncanonical".into())); + } + super::validate_principal(&state.owner).map_err(kernel_error)?; + if state.subjects.is_empty() + || state.controller_assignments.len() != state.subjects.len() + || state.affordance_grants.is_empty() + { + return Err(JournalError::Corrupt( + "world ontology is empty or has split subject/controller ownership".into(), + )); + } + let is_place = |entity_id: &super::EntityId| { + state + .entities + .get(entity_id) + .is_some_and(|record| record.kind == super::EntityKind::Place) + }; + for (entity_id, entity) in &state.entities { + if !super::patch::is_canonical_text(&entity.label) { + return Err(JournalError::Corrupt( + "entity label is empty or noncanonical".into(), + )); + } + if let Some(container) = entity.container + && (entity.kind != super::EntityKind::Place || !is_place(&container)) + { + return Err(JournalError::Corrupt( + "entity container does not name a canonical place".into(), + )); + } + if !super::patch::containment_terminates(*entity_id, &state.entities) { + return Err(JournalError::Corrupt("place contains itself".into())); + } + } + for edge in state.edges.values() { + let (from, to) = edge.endpoints(); + if !is_place(&from) + || !is_place(&to) + || from == to + || !super::patch::is_valid_cost(edge.cost()) + { + return Err(JournalError::Corrupt( + "route does not join two distinct places at a valid cost".into(), + )); + } + } + for (subject_id, position) in &state.positions { + if !state.subjects.contains_key(subject_id) || !is_place(&position.place) { + return Err(JournalError::Corrupt( + "position does not name a canonical subject and place".into(), + )); + } + } + let is_resource = |entity_id: &super::EntityId| { + state + .entities + .get(entity_id) + .is_some_and(|record| record.kind == super::EntityKind::Resource) + }; + // Absence is zero and one slot holds one pair, so a store satisfying these + // clauses cannot carry a zero, an empty holder, a duplicate, or a dangling + // holding — with no scan for any of them. + for (subject_id, held) in &state.holdings { + if !state.subjects.contains_key(subject_id) + || held.is_empty() + || held + .iter() + .any(|(resource, quantity)| !is_resource(resource) || quantity.0 == 0) + { + return Err(JournalError::Corrupt( + "holding does not name a canonical subject and resource at a nonzero quantity" + .into(), + )); + } + } + for (subject_id, targets) in &state.dependencies { + let target_is_canonical = |target: &super::DependencyTarget| match target { + super::DependencyTarget::Resource(entity_id) => is_resource(entity_id), + super::DependencyTarget::Route(edge_id) => state.edges.contains_key(edge_id), + super::DependencyTarget::Subject(other) => { + other != subject_id && state.subjects.contains_key(other) + } + }; + if !state.subjects.contains_key(subject_id) + || targets.is_empty() + || !targets.iter().all(target_is_canonical) + { + return Err(JournalError::Corrupt( + "dependency does not name a canonical subject and a distinct canonical target" + .into(), + )); + } + } + // Facts, channels, and knowledge. The `facts`/`channels` bijections run both + // ways: a payload row without its entity, or an entity of that kind without + // its payload, is a referenceable half-thing. + for (entity_id, record) in &state.facts { + let standing_is_live = match &record.standing { + super::FactStanding::Canonical { evidence } => { + super::patch::is_canonical_text(evidence.text()) + } + super::FactStanding::Claimed { by } => state.subjects.contains_key(by), + super::FactStanding::Ruled => true, + }; + if !state + .entities + .get(entity_id) + .is_some_and(|entity| entity.kind == super::EntityKind::Fact) + || !super::patch::is_canonical_text(record.statement.as_str()) + || !standing_is_live + { + return Err(JournalError::Corrupt( + "a fact names no canonical entity, statement, or standing".into(), + )); + } + } + for (entity_id, record) in &state.channels { + let reach_is_live = match &record.reach { + super::Reach::Subjects(members) => members + .iter() + .all(|subject_id| state.subjects.contains_key(subject_id)), + super::Reach::Place(place) => is_place(place), + }; + if !state + .entities + .get(entity_id) + .is_some_and(|entity| entity.kind == super::EntityKind::Channel) + || !reach_is_live + || !record + .controller + .is_none_or(|subject_id| state.subjects.contains_key(&subject_id)) + { + return Err(JournalError::Corrupt( + "a channel names no canonical entity, reach, or controller".into(), + )); + } + } + for (entity_id, entity) in &state.entities { + let paired = match entity.kind { + super::EntityKind::Fact => state.facts.contains_key(entity_id), + super::EntityKind::Channel => state.channels.contains_key(entity_id), + super::EntityKind::Place | super::EntityKind::Resource => true, + }; + if !paired { + return Err(JournalError::Corrupt( + "a fact or channel entity carries no payload row".into(), + )); + } + } + for (subject_id, held) in &state.knowledge { + let entry_is_live = |entry: &super::Knowledge| { + entry.acquired_at <= state.revision + && match entry.source { + super::KnowledgeSource::Told { by, via } => { + state.subjects.contains_key(&by) + && via.is_none_or(|channel| state.channels.contains_key(&channel)) + } + super::KnowledgeSource::Seen { by } => state.subjects.contains_key(&by), + super::KnowledgeSource::Witnessed | super::KnowledgeSource::Evidenced => true, + } + }; + if !state.subjects.contains_key(subject_id) + || held.is_empty() + || held + .iter() + .any(|(fact, entry)| !state.facts.contains_key(fact) || !entry_is_live(entry)) + { + return Err(JournalError::Corrupt( + "knowledge does not name a canonical subject, fact, and source, or was acquired ahead of the world's revision" + .into(), + )); + } + } + // Commitments, pressures, attention stamps, and the authored scale target. + // Absence is the only spelling of nothing at every level, so a store + // satisfying these clauses carries no empty inner map, no zero magnitude, + // and no dangling row — with no scan for any of them. + for (subject_id, held) in &state.commitments { + let commitment_is_canonical = |commitment: &super::Commitment| { + (commitment.kind == super::CommitmentKind::Routine) == commitment.period.is_some() + && commitment.period.is_none_or(|period| { + (1..=super::patch::MAX_ROUTE_COST).contains(&period.minutes()) + }) + && (commitment.kind == super::CommitmentKind::Routine + || commitment.checks.is_empty()) + && match commitment.counterparty { + Some(counterparty) => { + counterparty != *subject_id + && state.subjects.contains_key(&counterparty) + && commitment.kind != super::CommitmentKind::Goal + } + None => true, + } + && commitment + .checks + .iter() + .all(|check| super::bound_precondition_is_live(state, check)) + }; + if !state.subjects.contains_key(subject_id) + || held.is_empty() + || !held.values().all(commitment_is_canonical) + { + return Err(JournalError::Corrupt( + "a commitment does not name a canonical promisor, counterparty, shape, or check" + .into(), + )); + } + } + for (target, held) in &state.pressures { + let source_is_live = |source: &super::PressureSource| match source { + super::PressureSource::Commitment { subject, key } => state + .commitments + .get(subject) + .is_some_and(|commitments| commitments.contains_key(key)), + super::PressureSource::Dependency(dependency) => state + .dependencies + .get(target) + .is_some_and(|targets| targets.contains(dependency)), + super::PressureSource::Subject(subject_id) => state.subjects.contains_key(subject_id), + }; + if !state.subjects.contains_key(target) + || held.is_empty() + || held + .iter() + .any(|(source, magnitude)| magnitude.0 == 0 || !source_is_live(source)) + { + return Err(JournalError::Corrupt( + "a pressure row does not name a canonical target, live source, and nonzero \ + magnitude" + .into(), + )); + } + } + if state + .last_opportunity_at + .iter() + .any(|(subject_id, stamp)| !state.subjects.contains_key(subject_id) || *stamp > state.now) + { + return Err(JournalError::Corrupt( + "an attention stamp names an unknown subject or a future minute".into(), + )); + } + if state + .scale_intent + .jurisdictions + .keys() + .any(|root| !is_place(root)) + || state + .scale_intent + .jurisdictions + .values() + .map(|weight| u64::from(*weight)) + .sum::<u64>() + > 1000 + { + return Err(JournalError::Corrupt( + "the scale intent names a non-place root or distributes more than the whole".into(), + )); + } + // The third statement of the draw rule, beside genesis and + // `SetLensWeights`: no stored world holds weights that never draw. + if !state.lens_weights.draws() { + return Err(JournalError::Corrupt("the lens weights never draw".into())); + } + // The civic subgraph, in the slot the deleted `authority_scope` check + // occupied: a jurisdiction names live ground under a canonical kind, an + // office sits on an institution and lends something to a person who holds + // no other office there, and a forum names a live subject. + let target_is_canonical = |target: &super::AuthorityTarget| match target { + super::AuthorityTarget::Subject(subject_id) => state.subjects.contains_key(subject_id), + super::AuthorityTarget::PlaceSubtree(entity_id) => is_place(entity_id), + }; + for (subject_id, grants) in &state.authority { + if !state.subjects.contains_key(subject_id) + || grants.is_empty() + || !grants.iter().all(|grant| { + super::patch::is_civic_name(&grant.kind.0) && target_is_canonical(&grant.over) + }) + { + return Err(JournalError::Corrupt( + "authority does not name a canonical subject and live ground under a canonical kind" + .into(), + )); + } + } + for (institution, offices) in &state.selection { + let mut incumbents = BTreeSet::new(); + if state.subjects.get(institution).map(|subject| subject.kind) + != Some(super::SubjectKind::Institution) + || offices.is_empty() + { + return Err(JournalError::Corrupt( + "an office register does not name a canonical institution".into(), + )); + } + for (name, office) in offices { + let incumbent_is_person = office.incumbent.is_none_or(|incumbent| { + state.subjects.get(&incumbent).map(|subject| subject.kind) + == Some(super::SubjectKind::Person) + && incumbents.insert(incumbent) + }); + if !super::patch::is_civic_name(&name.0) + || office.delegated.is_empty() + || !office + .delegated + .iter() + .all(|kind| super::patch::is_civic_name(&kind.0)) + || !incumbent_is_person + { + return Err(JournalError::Corrupt( + "an office lends nothing, is misnamed, or is held twice or by a non-person" + .into(), + )); + } + } + } + for (grievance, forum) in &state.redress { + if !super::patch::is_civic_name(&grievance.0) + || !state.subjects.contains_key(&forum.forum) + || !target_is_canonical(&forum.standing) + { + return Err(JournalError::Corrupt( + "a forum does not name a canonical grievance, subject, and standing".into(), + )); + } + } + if super::overlapping_holder(state).is_some() { + return Err(JournalError::Corrupt( + "one subject holds two overlapping jurisdictions of one kind".into(), + )); + } + let mut declared_keys = BTreeSet::new(); + let no_held = BTreeSet::new(); + for subject in state.subjects.values() { + if let Some(key) = &subject.import_key + && super::patch::import_key_fault(key, &no_held, &mut declared_keys).is_some() + { + return Err(JournalError::Corrupt( + "subject import key is malformed or held by two subjects".into(), + )); + } + } + let mut controller_ids = BTreeSet::new(); + for (subject_id, subject) in &state.subjects { + if !super::patch::is_canonical_text(&subject.label) { + return Err(JournalError::Corrupt( + "subject label is empty or noncanonical".into(), + )); + } + let scope = super::DecisionScope { + subject_id: *subject_id, + }; + let assignment = state + .controller_assignments + .get(&scope) + .ok_or_else(|| JournalError::Corrupt("decision subject has no controller".into()))?; + super::validate_assignment(assignment).map_err(kernel_error)?; + // A mirror has no controller id, so it joins no uniqueness set. + if let Some(controller_id) = assignment.id() + && !controller_ids.insert(controller_id) + { + return Err(JournalError::Corrupt( + "controller ID owns more than one canonical scope".into(), + )); + } + } + if state + .controller_assignments + .keys() + .any(|scope| !state.subjects.contains_key(&scope.subject_id)) + { + return Err(JournalError::Corrupt( + "controller assignment references an unknown subject".into(), + )); + } + for (scope, granted) in &state.affordance_grants { + if !state.controller_assignments.contains_key(scope) + || granted.is_empty() + || granted + .iter() + .any(|affordance_id| !state.affordance_catalog.contains_key(affordance_id)) + { + return Err(JournalError::Corrupt( + "affordance grant is empty, unscoped, or names no catalog entry".into(), + )); + } + } + // Both ways, the pairing `admit_resolved` decided: a mirror holds no grant, + // and every controller-bearing scope holds one. + if state + .controller_assignments + .iter() + .any(|(scope, assignment)| { + state.affordance_grants.contains_key(scope) != assignment.mode().is_some() + }) + { + return Err(JournalError::Corrupt( + "controller assignment and affordance grant do not pair".into(), + )); + } + // Every stored entry still passes the declaration validator, so a forged + // catalog row cannot install an entry the resolver would have refused. + for entry in state.affordance_catalog.values() { + if !super::patch::entry_is_admissible(entry) { + return Err(JournalError::Corrupt( + "stored affordance entry is not admissible".into(), + )); + } + } + // Approval shape holds only in Draft. Once the world is Active, the + // approvals that admitted it are frozen history: they are judged once by + // `reduce`'s `ActivateWorld` arm and after that by replay, not re-judged + // here against the present-day controller roster. Retiring the human + // (PA.f32) or adding a later human-controlled subject must not make a + // past activation retroactively corrupt. + if state.phase == super::WorldPhase::Draft { + let required = super::required_approvers(state); + if !state.draft_approvals.is_subset(&required) { + return Err(JournalError::Corrupt( + "draft approvals do not match canonical controller ownership".into(), + )); + } + } + let mut event_ids = BTreeSet::new(); + let mut claimed = BTreeSet::new(); + let mut previous_event_revision = 0; + for event in &state.events { + state + .controller_assignments + .get(&event.scope) + .ok_or_else(|| JournalError::Corrupt("event references an unknown scope".into()))?; + let entry = state + .affordance_catalog + .get(&event.affordance) + .ok_or_else(|| JournalError::Corrupt("event uses an unknown affordance".into()))?; + // A speech or display event names the claim it minted, and that claim + // is asserted by the acting subject and by no other event. + let mut minted_is_canonical = |fact: Option<super::EntityId>| { + fact.is_none_or(|fact| { + claimed.insert(fact) + && state.facts.get(&fact).is_some_and(|record| { + record.standing + == super::FactStanding::Claimed { + by: event.scope.subject_id, + } + }) + }) + }; + let speech_is_canonical = minted_is_canonical(event.speech); + let display_is_canonical = minted_is_canonical(event.display); + if !event_ids.insert(event.id) + || event.revision == 0 + || event.revision > state.revision + || event.revision <= previous_event_revision + // Present-tense controller identity and present-tense affordance + // grants are not judged here: retiring a subject or revoking a + // verb it once used must not corrupt the history of that use. + // Authority at commit time is judged once, by `reduce`, and after + // that by replay (`verify_history` re-runs `reduce` for every + // commit) and by the digest chain. This shape check only holds + // time-invariant facts: the event's scope resolves to a live + // assignment (checked above) and its affordance is a catalog + // entry (checked above). + || event.band >= entry.outcome_bands.len() + // Speech rides only a speech-carrying entry; such an entry always + // addresses someone, by words or by a visible act; a display may + // accompany any entry. + || (event.speech.is_some() && !entry.carries_speech) + || (entry.carries_speech && event.speech.is_none() && event.display.is_none()) + // One lowered operation per band effect, plus the two the speech + // lowering prepends and the two the display lowering adds. + || entry.outcome_bands[event.band].effects.len() + + if event.speech.is_some() { 2 } else { 0 } + + if event.display.is_some() { 2 } else { 0 } + != event.effects.len() + || !speech_is_canonical + || !display_is_canonical + { + return Err(JournalError::Corrupt( + "decision event is noncanonical or violates controller scope".into(), + )); + } + previous_event_revision = event.revision; + } + Ok(()) +} + +fn apply_committed_command( + state: &mut WorldState, + commit: &WorldCommit, +) -> Result<(), JournalError> { + let CommittedCommand::WorldCommand(command) = &commit.command else { + return Err(JournalError::Corrupt( + "creation command appears after world genesis".into(), + )); + }; + if command.world_id != state.world_id || command.expected_revision != state.revision { + return Err(JournalError::Corrupt( + "committed command does not target the exact replay state".into(), + )); + } + let expected_effect = reduce(state, command).map_err(kernel_error)?; + if expected_effect != commit.effect { + return Err(JournalError::Corrupt( + "committed effect is not the deterministic reduction of its command".into(), + )); + } + apply_effect( + state, + command.id, + &commit.command.caller(), + &expected_effect, + ) + .map_err(kernel_error) +} + +fn require_schema(row: &CultCacheEnvelope, schema: &str) -> Result<(), JournalError> { + if row.schema_id.as_deref() != Some(schema) { + Err(JournalError::Corrupt(format!( + "row {}/{} has the wrong schema", + row.r#type, row.key + ))) + } else { + Ok(()) + } +} + +fn envelope<T: Serialize>( + row_type: &str, + schema: &str, + key: String, + value: &T, +) -> Result<CultCacheEnvelope, JournalError> { + Ok(CultCacheEnvelope { + key, + r#type: row_type.into(), + payload: rmp_serde::to_vec_named(value) + .map_err(|error| JournalError::Store(error.to_string()))?, + stored_at: Utc::now().to_rfc3339(), + schema_id: Some(schema.into()), + }) +} + +fn decode<T: DeserializeOwned + Serialize>(row: &CultCacheEnvelope) -> Result<T, JournalError> { + let value: T = rmp_serde::from_slice(&row.payload).map_err(|error| { + JournalError::Corrupt(format!( + "could not decode row {}/{}: {error}", + row.r#type, row.key + )) + })?; + let canonical = rmp_serde::to_vec_named(&value) + .map_err(|error| JournalError::Corrupt(error.to_string()))?; + if canonical != row.payload { + return Err(JournalError::Corrupt(format!( + "row {}/{} is not canonical", + row.r#type, row.key + ))); + } + Ok(value) +} + +fn kernel_error(error: KernelError) -> JournalError { + JournalError::Corrupt(error.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::WorldScaleIntentRef; + use crate::patch::kernel_speak_grant; + use crate::tests::speak_entry; + use crate::{ + AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, CreateWorld, Declaration, + DraftHandle, EntityDeclaration, EntityId, EntityKind, NewController, Position, PrincipalId, + Ref, SubjectDeclaration, SubjectKind, WorldKernel, WorldPatch, + }; + + #[derive(serde::Serialize, serde::Deserialize)] + struct CanonicalFixture { + value: u8, + } + + fn owner_patch(subject: SubjectDeclaration) -> WorldPatch { + WorldPatch { + declarations: vec![Declaration::Subject(subject)], + operations: Vec::new(), + evidence: Vec::new(), + } + } + + #[test] + fn decode_rejects_an_alternate_messagepack_shape() { + let row = CultCacheEnvelope { + key: "fixture".into(), + r#type: "fixture".into(), + payload: rmp_serde::to_vec(&CanonicalFixture { value: 7 }).unwrap(), + stored_at: Utc::now().to_rfc3339(), + schema_id: Some("fixture.v0".into()), + }; + assert!(decode::<CanonicalFixture>(&row).is_err()); + } + + #[test] + fn replay_rejects_a_forged_command_or_effect_even_with_valid_hashes() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let owner = PrincipalId::new("owner@example.test"); + let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); + let creation = CreateWorld { + lens_weights: crate::tests::stock_weights(), + id: CommandId::new(), + owner: owner.clone(), + title: "Before".into(), + brief: String::new(), + patch: owner_patch(SubjectDeclaration { + handle: DraftHandle::new("owner"), + label: "Owner".into(), + kind: SubjectKind::Person, + controller: NewController::Human { + principal: owner.clone(), + }, + affordances: kernel_speak_grant(), + position: None, + import_key: None, + }), + scale_intent: WorldScaleIntentRef::default(), + grammar: None, + }; + let (mut kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap(); + let snapshot = kernel.snapshot().unwrap(); + let command_id = CommandId::new(); + kernel + .submit( + CommandEnvelope { + id: command_id, + world_id: snapshot.world_id, + expected_revision: snapshot.revision, + caller: CallerId::Principal(owner), + body: CommandBody::ApproveDraft, + }, + &authenticated, + ) + .unwrap(); + + let mut command_forged_head = kernel.state.clone(); + let mut command_forged_commits = kernel.journal.commits.clone(); + let command_forged = command_forged_commits.get_mut(&command_id).unwrap(); + let CommittedCommand::WorldCommand(command) = &mut command_forged.command else { + panic!("expected a world command"); + }; + command.body = CommandBody::ActivateWorld; + command_forged.digest = commit_digest(command_forged).unwrap(); + command_forged_head.last_commit_digest = Some(command_forged.digest.clone()); + + assert!(matches!( + verify_history(&command_forged_head, &command_forged_commits), + Err(JournalError::Corrupt(_)) + )); + + let mut caller_forged_head = kernel.state.clone(); + let mut caller_forged_commits = kernel.journal.commits.clone(); + let caller_forged = caller_forged_commits.get_mut(&command_id).unwrap(); + let CommittedCommand::WorldCommand(command) = &mut caller_forged.command else { + panic!("expected a world command"); + }; + command.caller = CallerId::Principal(PrincipalId::new("attacker@example.test")); + caller_forged.digest = commit_digest(caller_forged).unwrap(); + caller_forged_head.last_commit_digest = Some(caller_forged.digest.clone()); + + assert!(matches!( + verify_history(&caller_forged_head, &caller_forged_commits), + Err(JournalError::Corrupt(_)) + )); + + let mut effect_forged_head = kernel.state.clone(); + let mut effect_forged_commits = kernel.journal.commits.clone(); + let effect_forged = effect_forged_commits.get_mut(&command_id).unwrap(); + effect_forged.effect = WorldEffect::WorldActivated; + effect_forged.digest = commit_digest(effect_forged).unwrap(); + effect_forged_head.last_commit_digest = Some(effect_forged.digest.clone()); + + assert!(matches!( + verify_history(&effect_forged_head, &effect_forged_commits), + Err(JournalError::Corrupt(_)) + )); + } + + #[test] + fn a_forged_patch_effect_does_not_apply() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let owner = PrincipalId::new("owner@example.test"); + let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); + let creation = CreateWorld { + lens_weights: crate::tests::stock_weights(), + id: CommandId::new(), + owner: owner.clone(), + title: "Kharad".into(), + brief: String::new(), + patch: owner_patch(SubjectDeclaration { + handle: DraftHandle::new("owner"), + label: "Owner".into(), + kind: SubjectKind::Person, + controller: NewController::Human { + principal: owner.clone(), + }, + affordances: kernel_speak_grant(), + position: None, + import_key: None, + }), + scale_intent: WorldScaleIntentRef::default(), + grammar: None, + }; + let (mut kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap(); + let snapshot = kernel.snapshot().unwrap(); + let command_id = CommandId::new(); + kernel + .submit( + CommandEnvelope { + id: command_id, + world_id: snapshot.world_id, + expected_revision: snapshot.revision, + caller: CallerId::Principal(owner), + body: CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("rhythm-road"), + label: "The Rhythm Road".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("rhythm-authority"), + label: "The Rhythm Authority".into(), + kind: SubjectKind::Institution, + controller: NewController::OperationalAgent, + affordances: BTreeSet::from([speak_entry(&kernel)]), + position: Some(Ref::Draft(DraftHandle::new("rhythm-road"))), + import_key: None, + }), + ], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + }, + &authenticated, + ) + .unwrap(); + + let mut forged_head = kernel.state.clone(); + let mut forged_commits = kernel.journal.commits.clone(); + let forged = forged_commits.get_mut(&command_id).unwrap(); + let WorldEffect::PatchAdmitted { resolved, .. } = &mut forged.effect else { + panic!("expected an admitted patch effect"); + }; + resolved.subjects[0].position = Some(Position { + place: EntityId::issue(), + }); + forged.digest = commit_digest(forged).unwrap(); + forged_head.last_commit_digest = Some(forged.digest.clone()); + + assert!(matches!( + verify_history(&forged_head, &forged_commits), + Err(JournalError::Corrupt(_)) + )); + } + + /// A store written at the schema this pass replaced is refused outright. + /// There is no migration adapter, and the refusal is the behaviour. + #[test] + fn a_store_from_the_knowledge_schema_is_refused() { + let row = CultCacheEnvelope { + key: "state".into(), + r#type: "world_state.knowledge.v1".into(), + payload: Vec::new(), + stored_at: Utc::now().to_rfc3339(), + schema_id: Some("ghostlight.world_state.knowledge.v1".into()), + }; + let error = recover(vec![row], None).unwrap_err(); + let JournalError::Corrupt(message) = error else { + panic!("expected a corrupt store"); + }; + assert!( + message.contains("unadmitted row type"), + "unexpected refusal: {message}" + ); + } + + /// A `Witness` reaches the store through two rows — a commit carries the + /// admitted operations and the state row carries the event's effects — so + /// both schemas bumped and both prior versions are refused at open. There + /// is no migration adapter and no dual read. + #[test] + fn a_store_written_before_the_witness_schema_is_refused() { + for (row_type, schema) in [ + (STATE_ROW, "ghostlight.world_state.consumer.v1"), + (COMMIT_ROW, "ghostlight.world_commit.consumer.v1"), + ] { + let row = CultCacheEnvelope { + key: "state".into(), + r#type: row_type.into(), + payload: Vec::new(), + stored_at: Utc::now().to_rfc3339(), + schema_id: Some(schema.into()), + }; + let error = recover(vec![row], None).unwrap_err(); + let JournalError::Corrupt(message) = error else { + panic!("expected a corrupt store for {schema}"); + }; + assert!( + message.contains("has the wrong schema"), + "unexpected refusal for {schema}: {message}" + ); + } + } + + /// Lens weights entered both rows — the state row holds them and a commit + /// row carries `LensWeightsReplaced` — so both schemas bumped and both + /// `consumer.v4` strings are refused at open. No migration, no dual read. + #[test] + fn a_store_written_before_the_lens_schema_is_refused() { + for (row_type, schema) in [ + (STATE_ROW, "ghostlight.world_state.consumer.v4"), + (COMMIT_ROW, "ghostlight.world_commit.consumer.v4"), + ] { + let row = CultCacheEnvelope { + key: "state".into(), + r#type: row_type.into(), + payload: Vec::new(), + stored_at: Utc::now().to_rfc3339(), + schema_id: Some(schema.into()), + }; + let error = recover(vec![row], None).unwrap_err(); + let JournalError::Corrupt(message) = error else { + panic!("expected a corrupt store for {schema}"); + }; + assert!( + message.contains("has the wrong schema"), + "unexpected refusal for {schema}: {message}" + ); + } + } + + /// A world whose history includes an owner's `SetLensWeights`, reopened + /// from its own store rows. + fn lens_history() -> (tempfile::TempDir, WorldKernel, crate::LensWeights) { + use crate::tests::{auth_principal, creation, owner, submit_owner}; + use crate::{Lens, LensWeights}; + + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, _) = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "Lens History"), + &auth_principal(owner()), + ) + .unwrap(); + let replaced = LensWeights::new(BTreeMap::from([ + (Lens::Patina, 0), + (Lens::Charter, 4), + (Lens::Ledger, 1), + (Lens::Numen, 2), + ])); + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + CommandBody::SetLensWeights { + weights: replaced.clone(), + }, + ); + (directory, kernel, replaced) + } + + fn rows_of(state: &WorldState, commits: &[WorldCommit]) -> Vec<CultCacheEnvelope> { + let mut rows: Vec<CultCacheEnvelope> = commits + .iter() + .map(|commit| { + envelope(COMMIT_ROW, COMMIT_SCHEMA, commit.command.id().key(), commit).unwrap() + }) + .collect(); + rows.push(envelope(STATE_ROW, STATE_SCHEMA, state.world_id.key(), state).unwrap()); + rows + } + + /// Replay re-derives the owner's weight change: the honest history reopens + /// to the same state digest and weights, and the store on disk does too. + #[test] + fn a_history_with_a_lens_weight_change_replays_exactly() { + let (directory, kernel, replaced) = lens_history(); + let honest: Vec<WorldCommit> = kernel.journal.commits.values().cloned().collect(); + let (_, replayed, commits) = + recover(rows_of(&kernel.state, &honest), None).expect("the honest history replays"); + assert_eq!(commits.len(), honest.len()); + assert_eq!(replayed.state_digest, kernel.state.state_digest); + assert_eq!(replayed.lens_weights, replaced); + + let (world_id, digest) = (kernel.state.world_id, kernel.state.state_digest.clone()); + drop(kernel); + let reopened = WorldKernel::open(directory.path().join("world.cc"), world_id).unwrap(); + assert_eq!(reopened.state.state_digest, digest); + assert_eq!(reopened.state.lens_weights, replaced); + } + + /// A stored weight change is not believed about who made it or what it + /// wrote. Each forgery re-seals the whole store around its rewrite: the + /// head state takes the effect's weights, its state digest is recomputed, + /// the commit's resulting state digest and its own digest follow, and the + /// head's last commit digest names the re-sealed commit. No digest can + /// answer for the check, which the drawing control proves: the same + /// re-sealing around a set that draws replays. + #[test] + fn a_forged_lens_weights_row_fails_replay() { + use crate::tests::human_principal; + use crate::{Lens, LensWeights}; + + let (_directory, kernel, _) = lens_history(); + let honest: Vec<WorldCommit> = kernel.journal.commits.values().cloned().collect(); + let forge = |rewrite: &dyn Fn(&mut WorldCommit)| -> (WorldState, Vec<WorldCommit>) { + let mut head = kernel.state.clone(); + let mut forged: Vec<WorldCommit> = honest.clone(); + let lens_row = forged + .iter_mut() + .filter(|commit| matches!(commit.effect, WorldEffect::LensWeightsReplaced { .. })) + .collect::<Vec<_>>(); + let [commit] = <[&mut WorldCommit; 1]>::try_from(lens_row) + .expect("the history holds exactly one lens weights row"); + assert_eq!( + commit.resulting_revision, head.revision, + "the lens weights row is the head commit" + ); + rewrite(commit); + let WorldEffect::LensWeightsReplaced { weights } = &commit.effect else { + unreachable!("a lens weights row stays one"); + }; + head.lens_weights = weights.clone(); + head.state_digest = crate::state_digest(&head).unwrap(); + commit.resulting_state_digest = head.state_digest.clone(); + commit.digest = commit_digest(commit).unwrap(); + head.last_commit_digest = Some(commit.digest.clone()); + + // Every seal agrees with what it seals. + assert_eq!(crate::state_digest(&head).unwrap(), head.state_digest); + assert_eq!(commit_digest(commit).unwrap(), commit.digest); + assert_eq!(commit.resulting_state_digest, head.state_digest); + assert_eq!(head.last_commit_digest.as_deref(), Some(commit.digest.as_str())); + (head, forged) + }; + let set = |weights: LensWeights| { + move |commit: &mut WorldCommit| { + if let CommittedCommand::WorldCommand(command) = &mut commit.command { + command.body = CommandBody::SetLensWeights { + weights: weights.clone(), + }; + } + commit.effect = WorldEffect::LensWeightsReplaced { + weights: weights.clone(), + }; + } + }; + let refused = |(head, forged): (WorldState, Vec<WorldCommit>)| -> String { + let error = + recover(rows_of(&head, &forged), None).expect_err("a forged lens weights row replayed"); + let JournalError::Corrupt(detail) = error else { + panic!("unexpected refusal: {error:?}"); + }; + detail + }; + + // The control: a re-sealed store around a different set that draws + // replays, so the re-sealing leaves nothing for a digest to catch. + let drawing = LensWeights::new(BTreeMap::from([(Lens::Veil, 2), (Lens::Ember, 1)])); + let (head, forged) = forge(&set(drawing.clone())); + let (_, replayed, _) = + recover(rows_of(&head, &forged), None).expect("a consistent re-sealed store replays"); + assert_eq!(replayed.lens_weights, drawing); + + // A non-owner principal with a live approver role in this world. + let detail = refused(forge(&|commit| { + if let CommittedCommand::WorldCommand(command) = &mut commit.command { + command.caller = CallerId::Principal(human_principal()); + } + })); + assert!(detail.contains("Unauthorized") || detail.contains("does not own"), "{detail}"); + // The clock capability. + let detail = refused(forge(&|commit| { + if let CommittedCommand::WorldCommand(command) = &mut commit.command { + command.caller = CallerId::System(crate::SystemCapability::Clock); + } + })); + assert!(detail.contains("Unauthorized") || detail.contains("does not own"), "{detail}"); + // Every lens named, all at zero, in the command, its effect and the + // head: only the draw rule is left to refuse it. + let never = LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 0)).collect()); + let detail = refused(forge(&set(never))); + assert!( + detail.contains("never draw") || detail.contains("LensWeightsNeverDraw"), + "something other than the draw rule refused the all-zero row: {detail}" + ); + } + + /// The third statement of the draw rule: a state row whose weights never + /// draw is refused by the shape check itself, not only by replay. + #[test] + fn a_state_row_whose_lens_weights_never_draw_is_refused() { + use crate::{Lens, LensWeights}; + + let (_directory, kernel, _) = lens_history(); + let mut forged = kernel.state.clone(); + forged.lens_weights = + LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 0)).collect()); + let JournalError::Corrupt(detail) = + verify_state_shape(&forged).expect_err("an all-zero weight set passed the shape check") + else { + unreachable!("the shape check only reports corruption") + }; + assert!(detail.contains("lens weights"), "unexpected refusal: {detail}"); + + forged.lens_weights = LensWeights::default(); + assert!(verify_state_shape(&forged).is_err()); + assert!(verify_state_shape(&kernel.state).is_ok()); + + let commits: Vec<WorldCommit> = kernel.journal.commits.values().cloned().collect(); + let mut zeroed = kernel.state.clone(); + zeroed.lens_weights = + LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 0)).collect()); + assert!(matches!( + recover(rows_of(&zeroed, &commits), None), + Err(JournalError::Corrupt(_)) + )); + } + + /// The tick is re-derived at replay by the same function that produced it, + /// so a committed motion rewritten after the fact no longer reduces from + /// its command. The clock chain refuses a rewritten reading the same way. + #[test] + fn a_forged_motion_does_not_replay() { + use crate::tests::{activate, auth_principal, command, owner}; + use crate::{ + AuthenticatedCaller, CallerId, CommandBody, FictionalMinutes, SystemCapability, + TickMinutes, + }; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create( + &path, + crate::tests::creation(CommandId::new(), "Chronicle"), + &authenticated, + ) + .unwrap(); + let active = activate(&mut kernel); + let command_id = CommandId::new(); + let caller = CallerId::System(SystemCapability::Clock); + kernel + .submit( + command( + &active, + command_id, + caller.clone(), + CommandBody::AdvanceTime { + minutes: TickMinutes::new(30).unwrap(), + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap(); + + let mut forged_head = kernel.state.clone(); + let mut forged_commits = kernel.journal.commits.clone(); + let forged = forged_commits.get_mut(&command_id).unwrap(); + let WorldEffect::TimeAdvanced { to, .. } = &mut forged.effect else { + panic!("expected a time-advanced effect"); + }; + *to = FictionalMinutes(31); + forged.digest = commit_digest(forged).unwrap(); + forged_head.last_commit_digest = Some(forged.digest.clone()); + + assert!(matches!( + verify_history(&forged_head, &forged_commits), + Err(JournalError::Corrupt(_)) + )); + } + + /// Replay re-derives the operation half too: a committed relocation rewritten + /// to move a different subject no longer reduces from its command. + #[test] + fn a_forged_relocate_effect_does_not_apply() { + use crate::tests::{activate, admit_topology, auth_principal, command, owner}; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create( + &path, + crate::tests::creation(CommandId::new(), "Kharad"), + &authenticated, + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let active = activate(&mut kernel); + let command_id = CommandId::new(); + kernel + .submit( + command( + &active, + command_id, + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![crate::ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Existing(topology.ramp), + }], + evidence: Vec::new(), + }, + }, + ), + &authenticated, + ) + .unwrap(); + + let mut forged_head = kernel.state.clone(); + let mut forged_commits = kernel.journal.commits.clone(); + let forged = forged_commits.get_mut(&command_id).unwrap(); + let WorldEffect::PatchAdmitted { resolved, .. } = &mut forged.effect else { + panic!("expected an admitted patch effect"); + }; + let crate::ResolvedOp::Relocate { subject_id, .. } = &mut resolved.operations[0] + else { + panic!("expected a lowered relocation"); + }; + *subject_id = crate::SubjectId::issue(); + forged.digest = commit_digest(forged).unwrap(); + forged_head.last_commit_digest = Some(forged.digest.clone()); + + assert!(matches!( + verify_history(&forged_head, &forged_commits), + Err(JournalError::Corrupt(_)) + )); + } + + /// Soul: `a_forged_band_or_forged_effect_does_not_apply` proves the live + /// `apply_effect` arm re-derives. `verify_state_shape` does not re-derive a + /// band — it only bounds the index and refuses effects under an empty band — + /// so the layer that kills a persisted forgery is replay effect-equality. + /// This forges a committed decision inside the journal, re-digests it into a + /// contiguous chain, and asserts recovery refuses it. + #[test] + fn soul_a_forged_band_or_effect_in_the_journal_dies_at_replay() { + use crate::tests::{ + activate, admit_custody, admit_topology, affordance_named, auth_principal, command, + opportunity_for, owner, + }; + use crate::{ + AuthenticatedCaller, DecisionInvocation, Magnitude, ProposedEffect, Quantity, + RoleBinding, Target, + }; + + let forge = |kind: &str, mutate: &dyn Fn(&mut crate::DecisionEvent)| { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create( + &path, + crate::tests::creation(CommandId::new(), "ForgedDecision"), + &authenticated, + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + let active = activate(&mut kernel); + let entry = affordance_named(&active, kind); + let opportunity = opportunity_for(&active, custody.holder); + let caller = CallerId::Controller(opportunity.controller_id); + let command_id = CommandId::new(); + let role = |name: &str, target| RoleBinding { + role: crate::Role(name.into()), + target, + }; + kernel + .submit( + command( + &active, + command_id, + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation: DecisionInvocation { + affordance: entry, + bindings: vec![ + role("from", Target::Subject(custody.holder)), + role("recipient", Target::Subject(custody.counterparty)), + role("place", Target::Entity(topology.yard)), + role("resource", Target::Entity(custody.tithe)), + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(2)), + }], + speech: None, + display: None, + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap(); + + // The honest journal recovers. + assert!(verify_history(&kernel.state, &kernel.journal.commits).is_ok()); + + let mut forged_head = kernel.state.clone(); + let mut forged_commits = kernel.journal.commits.clone(); + let forged = forged_commits.get_mut(&command_id).unwrap(); + let WorldEffect::DecisionExercised { event, .. } = &mut forged.effect else { + panic!("expected an exercised decision effect"); + }; + mutate(event); + let forged_event = event.clone(); + *forged_head.events.last_mut().unwrap() = forged_event; + forged.digest = commit_digest(forged).unwrap(); + forged_head.last_commit_digest = Some(forged.digest.clone()); + forged_head.state_digest = String::new(); + forged_head.state_digest = crate::state_digest(&forged_head).unwrap(); + (forged_head, forged_commits) + }; + + // A band the seed did not draw, held inside a chain that verifies. + let (head, commits) = forge("carry_chance", &|event| { + event.band = (event.band + 1) % 3; + }); + assert!(matches!( + verify_history(&head, &commits), + Err(JournalError::Corrupt(_)) + )); + + // A magnitude the ceiling admitted but the lowering never produced. + let (head, commits) = forge("carry", &|event| { + let Some(crate::ResolvedOp::Transfer { qty, .. }) = event.effects.first_mut() + else { + panic!("expected a lowered transfer"); + }; + *qty = Quantity(1); + }); + assert!(matches!( + verify_history(&head, &commits), + Err(JournalError::Corrupt(_)) + )); + } + + #[test] + fn replay_rejects_genesis_that_does_not_derive_from_its_creation_command() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let owner = PrincipalId::new("owner@example.test"); + let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); + let creation_id = CommandId::new(); + let creation = CreateWorld { + lens_weights: crate::tests::stock_weights(), + id: creation_id, + owner: owner.clone(), + title: "Admitted".into(), + brief: String::new(), + patch: owner_patch(SubjectDeclaration { + handle: DraftHandle::new("owner"), + label: "Owner".into(), + kind: SubjectKind::Person, + controller: NewController::Human { principal: owner }, + affordances: kernel_speak_grant(), + position: None, + import_key: None, + }), + scale_intent: WorldScaleIntentRef::default(), + grammar: None, + }; + let (kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap(); + let mut forged_head = kernel.state.clone(); + let mut forged_commits = kernel.journal.commits.clone(); + let forged = forged_commits.get_mut(&creation_id).unwrap(); + let CommittedCommand::CreateWorld(command) = &mut forged.command else { + panic!("expected genesis creation command"); + }; + command.title = "Different command".into(); + forged.digest = commit_digest(forged).unwrap(); + forged_head.last_commit_digest = Some(forged.digest.clone()); + + assert!(matches!( + verify_history(&forged_head, &forged_commits), + Err(JournalError::Corrupt(_)) + )); + + let mut binding_forged_head = kernel.state.clone(); + let mut binding_forged_commits = kernel.journal.commits.clone(); + let binding_forged = binding_forged_commits.get_mut(&creation_id).unwrap(); + let WorldEffect::WorldCreated { resolved, .. } = &mut binding_forged.effect else { + panic!("expected genesis effect"); + }; + resolved.subjects[0].subject.label = "Not the creation subject".into(); + binding_forged.digest = commit_digest(binding_forged).unwrap(); + binding_forged_head.last_commit_digest = Some(binding_forged.digest.clone()); + + assert!(matches!( + verify_history(&binding_forged_head, &binding_forged_commits), + Err(JournalError::Corrupt(_)) + )); + } + + /// Soul falsification: the extended replay shape check is not decoration. + /// A forged store row carrying a self-loop, a cost out of range, a + /// non-place endpoint, or a position on a non-place is refused by + /// `recover`, which is the path `WorldJournal::open` takes. + #[test] + fn soul_forged_topology_store_rows_are_refused_on_recover() { + use crate::patch::{AccessKind, Cost, EdgeRecord, MAX_ROUTE_COST}; + use crate::tests::{admit_topology, auth_principal, owner}; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + crate::tests::creation(CommandId::new(), "Forged Rows"), + &auth_principal(owner()), + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let commits: Vec<CultCacheEnvelope> = kernel + .journal + .commits + .values() + .map(|commit| { + envelope(COMMIT_ROW, COMMIT_SCHEMA, commit.command.id().key(), commit).unwrap() + }) + .collect(); + let rows_for = |state: &WorldState, row_type: &str| { + let mut rows = commits.clone(); + rows.push(envelope(row_type, STATE_SCHEMA, state.world_id.key(), state).unwrap()); + rows + }; + + // The honest state recovers. + assert!(recover(rows_for(&kernel.state, STATE_ROW), None).is_ok()); + + let self_loop = { + let mut state = kernel.state.clone(); + state.edges.insert( + topology.ramp, + EdgeRecord::Route { + label: "The Yard Ramp".into(), + from: topology.yard, + to: topology.yard, + access: AccessKind::Public, + cost: Cost(12), + open: true, + }, + ); + state + }; + let bad_cost = { + let mut state = kernel.state.clone(); + state + .edges + .get_mut(&topology.ramp) + .unwrap() + .set_cost(Cost(MAX_ROUTE_COST + 1)); + state + }; + let non_place_endpoint = { + let mut state = kernel.state.clone(); + state.entities.get_mut(&topology.road).unwrap().kind = + crate::EntityKind::Resource; + state + }; + let stray_position = { + let mut state = kernel.state.clone(); + state.positions.insert( + topology.walker, + Position { + place: EntityId::issue(), + }, + ); + state + }; + for forged in [self_loop, bad_cost, non_place_endpoint, stray_position] { + let error = recover(rows_for(&forged, STATE_ROW), None).unwrap_err(); + assert!( + matches!(error, JournalError::Corrupt(_)), + "a forged topology row recovered: {error:?}" + ); + } + } + + /// Soul falsification: a store written before the topology partitions is + /// refused outright, with no migration adapter in the path. + #[test] + fn soul_a_pre_topology_store_row_is_refused() { + use crate::tests::{admit_topology, auth_principal, owner}; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + crate::tests::creation(CommandId::new(), "Old Store"), + &auth_principal(owner()), + ) + .unwrap(); + admit_topology(&mut kernel); + let mut rows: Vec<CultCacheEnvelope> = kernel + .journal + .commits + .values() + .map(|commit| { + envelope( + "world_commit.foundation.v2", + COMMIT_SCHEMA, + commit.command.id().key(), + commit, + ) + .unwrap() + }) + .collect(); + rows.push( + envelope( + "world_state.foundation.v1", + STATE_SCHEMA, + kernel.state.world_id.key(), + &kernel.state, + ) + .unwrap(), + ); + let error = recover(rows, None).unwrap_err(); + let JournalError::Corrupt(message) = error else { + panic!("expected a corrupt store, got {error:?}"); + }; + assert!( + message.contains("unadmitted row type"), + "unexpected refusal: {message}" + ); + } + + /// A committed levy survives a restart exactly: the snapshot, the band, the + /// lowered effects, and the re-derived authority verdict all come back, and + /// the same envelope is already applied. + #[test] + fn restart_replay_after_a_levy_is_exact() { + use crate::tests::{affordance_named, civic_world, command, opportunity_for, owner}; + use crate::{ + DecisionInvocation, Magnitude, ProposedEffect, Quantity, Role, RoleBinding, + SubmitReceipt, Target, + }; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + crate::tests::creation(CommandId::new(), "Replayed Levy"), + &crate::tests::auth_principal(owner()), + ) + .unwrap(); + let (_, civic, active) = civic_world(&mut kernel); + let opportunity = opportunity_for(&active, civic.treasury); + let caller = CallerId::Controller(opportunity.controller_id); + let envelope = command( + &active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation: DecisionInvocation { + affordance: affordance_named(&active, "levy"), + bindings: vec![ + RoleBinding { + role: Role("payer".into()), + target: Target::Subject(civic.farmer), + }, + RoleBinding { + role: Role("resource".into()), + target: Target::Entity(civic.grain), + }, + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(3)), + }], + speech: None, + display: None, + }, + }, + ); + kernel + .submit( + envelope.clone(), + &AuthenticatedCaller::fixture(caller.clone()), + ) + .unwrap(); + let committed = kernel.snapshot().unwrap(); + let event = kernel.state.events.last().expect("the levy event").clone(); + let world_id = committed.world_id; + drop(kernel); + + let mut reopened = WorldKernel::open(&path, world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), committed); + let replayed = reopened.state.events.last().expect("the replayed event"); + assert_eq!(replayed.band, event.band); + assert_eq!(replayed.effects, event.effects); + assert!(matches!( + reopened + .submit(envelope, &AuthenticatedCaller::fixture(caller)) + .unwrap(), + SubmitReceipt::AlreadyApplied(_) + )); + } + + /// Soul falsification: the civic shape checks are not decoration. A forged + /// store row that widens a jurisdiction, doubles an incumbency, seats an + /// institution, or empties a delegation is refused by `recover`. + #[test] + fn a_forged_authority_or_incumbency_is_corrupt() { + use crate::tests::{ + BAILIFF_OFFICE, LEVY_KIND, WARDEN_OFFICE, auth_principal, authority_kind, civic_world, + office, owner, + }; + use crate::{AuthorityGrant, AuthorityTarget, Office}; + use std::collections::BTreeSet; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + crate::tests::creation(CommandId::new(), "Forged Civics"), + &auth_principal(owner()), + ) + .unwrap(); + let (topology, civic, _) = civic_world(&mut kernel); + let commits: Vec<CultCacheEnvelope> = kernel + .journal + .commits + .values() + .map(|commit| { + envelope(COMMIT_ROW, COMMIT_SCHEMA, commit.command.id().key(), commit).unwrap() + }) + .collect(); + let rows_for = |state: &WorldState| { + let mut rows = commits.clone(); + rows.push(envelope(STATE_ROW, STATE_SCHEMA, state.world_id.key(), state).unwrap()); + rows + }; + assert!(recover(rows_for(&kernel.state), None).is_ok()); + + let widened = { + let mut state = kernel.state.clone(); + state.authority.insert( + civic.reeve, + BTreeSet::from([AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: AuthorityTarget::PlaceSubtree(civic.chamber), + }]), + ); + state + }; + let dangling = { + let mut state = kernel.state.clone(); + state.authority.insert( + civic.outsider, + BTreeSet::from([AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: AuthorityTarget::PlaceSubtree(EntityId::issue()), + }]), + ); + state + }; + let doubled = { + let mut state = kernel.state.clone(); + state + .selection + .get_mut(&civic.treasury) + .unwrap() + .get_mut(&office(BAILIFF_OFFICE)) + .unwrap() + .incumbent = Some(civic.reeve); + state + }; + let seated_institution = { + let mut state = kernel.state.clone(); + state + .selection + .get_mut(&civic.treasury) + .unwrap() + .get_mut(&office(WARDEN_OFFICE)) + .unwrap() + .incumbent = Some(civic.treasury); + state + }; + let inert_office = { + let mut state = kernel.state.clone(); + state.selection.get_mut(&civic.treasury).unwrap().insert( + office(WARDEN_OFFICE), + Office { + incumbent: Some(civic.reeve), + delegated: BTreeSet::new(), + }, + ); + state + }; + let office_on_person = { + let mut state = kernel.state.clone(); + state + .selection + .insert(topology.walker, state.selection[&civic.treasury].clone()); + state + }; + for forged in [ + widened, + dangling, + doubled, + seated_institution, + inert_office, + office_on_person, + ] { + let error = recover(rows_for(&forged), None).unwrap_err(); + assert!( + matches!(error, JournalError::Corrupt(_)), + "a forged civic row recovered: {error:?}" + ); + } + } + + /// Soul falsification: a store written before the civic partitions is + /// refused outright, with no migration adapter in the path. + #[test] + fn a_store_from_the_previous_schema_is_refused() { + use crate::tests::{auth_principal, civic_world, owner}; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + crate::tests::creation(CommandId::new(), "Pre-Authority"), + &auth_principal(owner()), + ) + .unwrap(); + civic_world(&mut kernel); + let mut rows: Vec<CultCacheEnvelope> = kernel + .journal + .commits + .values() + .map(|commit| { + envelope( + "world_commit.affordance.v1", + COMMIT_SCHEMA, + commit.command.id().key(), + commit, + ) + .unwrap() + }) + .collect(); + rows.push( + envelope( + "world_state.affordance.v1", + STATE_SCHEMA, + kernel.state.world_id.key(), + &kernel.state, + ) + .unwrap(), + ); + let error = recover(rows, None).unwrap_err(); + let JournalError::Corrupt(message) = error else { + panic!("expected a corrupt store, got {error:?}"); + }; + assert!( + message.contains("unadmitted row type"), + "unexpected refusal: {message}" + ); + } + + /// Soul falsification of the structural-overlap decision, updated for the + /// admission-time covering check: a `Subject` grant naming ground a + /// `PlaceSubtree` grant already covers is refused on arrival, but nothing + /// re-derives that check off of live position. Once the farmer walks out + /// from under the hall, the identical grant is unremarkable, and no + /// `Relocate` — in either direction — is ever asked to keep a shape + /// decision current. + #[test] + fn a_relocation_never_corrupts_a_civic_store() { + use crate::tests::{ + LEVY_KIND, auth_principal, civic_world, operations, over_subject, owner, reject_owner, + submit_owner, + }; + use crate::{ComponentOp, Mismatch, SubmitReceipt}; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + crate::tests::creation(CommandId::new(), "Moving Civics"), + &auth_principal(owner()), + ) + .unwrap(); + let (_, civic, _) = civic_world(&mut kernel); + + let admit = |kernel: &mut WorldKernel, ops: Vec<ComponentOp>| { + let before = kernel.snapshot().unwrap(); + assert!(matches!( + submit_owner(kernel, &before, operations(ops)), + SubmitReceipt::Applied(_) + )); + verify_state_shape(&kernel.state).expect("the committed store keeps its shape"); + assert!( + crate::overlapping_holder(&kernel.state).is_none(), + "a committed store never holds two overlapping jurisdictions" + ); + }; + let place_covers = |kernel: &WorldKernel| { + crate::covers( + &kernel.state, + crate::AuthorityTarget::PlaceSubtree(civic.hall), + crate::Target::Subject(civic.farmer), + ) + }; + let name_farmer = || { + vec![crate::tests::grant_to( + civic.treasury, + LEVY_KIND, + over_subject(civic.farmer), + )] + }; + + // The treasury's hall grant already covers the farmer standing in the + // chamber underneath it, so naming him directly is a second source + // for the same kind of act, and admission refuses it while he stands + // there. + assert!(place_covers(&kernel)); + let before = kernel.snapshot().unwrap(); + assert_eq!( + reject_owner(&mut kernel, &before, operations(name_farmer())), + vec![Mismatch::OverlappingJurisdiction { operation: 0 }] + ); + + // Out of the subtree, one route at a time. + for edge in [civic.passage, civic.causeway] { + admit( + &mut kernel, + vec![ComponentOp::Relocate { + subject: Ref::Existing(civic.farmer), + via: Ref::Existing(edge), + }], + ); + } + // The move dissolved the cover without any operation naming it, which + // is why the disjointness rule cannot be occupancy-sensitive: nothing + // reruns the covering check on a `Relocate`, in or out. + assert!(!place_covers(&kernel)); + + // Now that he stands outside it, the identical grant is unremarkable. + admit(&mut kernel, name_farmer()); + assert!(kernel.state.authority[&civic.treasury].len() >= 3); + + // The whole history replays, and the reopened world is identical. + let committed = kernel.snapshot().unwrap(); + drop(kernel); + let reopened = WorldKernel::open(&path, committed.world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), committed); + } +} + +#[cfg(test)] +mod custody_tests { + use super::*; + use crate::{ + CallerId, CommandBody, CommandId, ComponentOp, DependencyRef, EntityKind, Quantity, Ref, + SubmitReceipt, WorldKernel, WorldPatch, + tests::{admit_custody, admit_topology, auth_principal, command, creation, owner}, + }; + + /// Replay re-derives the custody partitions from the commit log alone: a + /// world reopened after a transfer is byte-identical, and the transfer's own + /// envelope is idempotent. + #[test] + fn restart_replay_after_a_transfer_is_exact() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let authenticated = auth_principal(owner()); + let (mut kernel, _) = + WorldKernel::create(&path, creation(CommandId::new(), "Replay"), &authenticated) + .unwrap(); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + let active = crate::tests::activate(&mut kernel); + + let envelope = command( + &active, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }], + evidence: Vec::new(), + }, + }, + ); + let SubmitReceipt::Applied(receipt) = + kernel.submit(envelope.clone(), &authenticated).unwrap() + else { + panic!("expected an applied transfer"); + }; + let accepted = kernel.snapshot().unwrap(); + let world_id = accepted.world_id; + drop(kernel); + + let mut reopened = WorldKernel::open(&path, world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), accepted); + assert_eq!( + reopened.submit(envelope, &authenticated).unwrap(), + SubmitReceipt::AlreadyApplied(receipt) + ); + } + + /// Replay recomputes `reduce`, so the band and the lowered operations are + /// re-derived rather than trusted: a stored event whose band or effects the + /// seed does not reproduce fails effect equality on the way back in. + #[test] + fn restart_replay_after_an_action_is_exact() { + use crate::tests::affordance_named; + use crate::{AuthenticatedCaller, Magnitude, ProposedEffect, RoleBinding, Target}; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "ActionReplay"), + &authenticated, + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + let active = crate::tests::activate(&mut kernel); + let carry = affordance_named(&active, "carry"); + let opportunity = crate::tests::opportunity_for(&active, custody.holder); + let caller = CallerId::Controller(opportunity.controller_id); + + let role = |name: &str, target| RoleBinding { + role: crate::Role(name.into()), + target, + }; + let envelope = command( + &active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity: opportunity.clone(), + invocation: crate::DecisionInvocation { + affordance: carry, + bindings: vec![ + role("from", Target::Subject(custody.holder)), + role("recipient", Target::Subject(custody.counterparty)), + role("place", Target::Entity(topology.yard)), + role("resource", Target::Entity(custody.tithe)), + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(2)), + }], + speech: None, + display: None, + }, + }, + ); + let authenticated_controller = AuthenticatedCaller::fixture(caller); + let SubmitReceipt::Applied(receipt) = kernel + .submit(envelope.clone(), &authenticated_controller) + .unwrap() + else { + panic!("expected an applied invocation"); + }; + let accepted = kernel.snapshot().unwrap(); + let committed = kernel + .state + .events + .last() + .expect("the committed event") + .clone(); + assert!(!committed.effects.is_empty()); + let world_id = accepted.world_id; + drop(kernel); + + let mut reopened = WorldKernel::open(&path, world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), accepted); + assert_eq!( + reopened.state.events.last().expect("the replayed event"), + &committed + ); + assert_eq!( + reopened + .submit(envelope, &authenticated_controller) + .unwrap(), + SubmitReceipt::AlreadyApplied(receipt) + ); + } + + /// A store written at the pass-2 schema is refused outright. There is no + /// migration adapter, and the refusal is the behaviour. + #[test] + fn a_store_from_the_previous_schema_is_refused() { + let row = CultCacheEnvelope { + key: "state".into(), + r#type: "world_state.topology.v1".into(), + payload: Vec::new(), + stored_at: Utc::now().to_rfc3339(), + schema_id: Some("ghostlight.world_state.topology.v1".into()), + }; + let error = recover(vec![row], None).unwrap_err(); + let JournalError::Corrupt(message) = error else { + panic!("expected a corrupt store"); + }; + assert!( + message.contains("unadmitted row type"), + "unexpected refusal: {message}" + ); + } + + /// PA.f39, M9: the Draft-only approval shape clause is defence in depth, + /// so it is pinned directly on `verify_state_shape` rather than only + /// through a full submit path. A fresh Draft world's approvals pass; a + /// forged principal outside `required_approvers` does not. + #[test] + fn draft_approvals_outside_required_approvers_is_corrupt() { + use crate::tests::{auth_principal, creation, owner}; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "PAf39ApprovalShape"), + &auth_principal(owner()), + ) + .unwrap(); + assert_eq!(kernel.state.phase, crate::WorldPhase::Draft); + verify_state_shape(&kernel.state) + .expect("a fresh Draft world has a canonical approval shape"); + + let mut forged = kernel.state.clone(); + forged + .draft_approvals + .insert(crate::PrincipalId::new("interloper@example.test")); + assert!( + matches!(verify_state_shape(&forged), Err(JournalError::Corrupt(_))), + "an approval outside the required set passed the shape check" + ); + } + + /// Absence is zero and one slot holds one pair, so a stored zero, an empty + /// holder, and a holding on something that is not a resource are each + /// corrupt at replay. + /// + /// Deviation from the spec's wording, decided here: the assertion is against + /// `verify_state_shape`, which owns these clauses. Routing through + /// `verify_history` would also fail on replay-equality, so it would pass + /// even if the shape clauses were deleted — which is the opposite of a + /// falsification. + #[test] + fn a_zero_or_dangling_holding_is_corrupt() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let authenticated = auth_principal(owner()); + let (mut kernel, _) = + WorldKernel::create(&path, creation(CommandId::new(), "Shape"), &authenticated) + .unwrap(); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + crate::tests::activate(&mut kernel); + verify_state_shape(&kernel.state).expect("the admitted world has a canonical shape"); + + let mut zero = kernel.state.clone(); + zero.holdings + .get_mut(&custody.holder) + .unwrap() + .insert(custody.tithe, Quantity(0)); + assert!(matches!( + verify_state_shape(&zero), + Err(JournalError::Corrupt(_)) + )); + + let mut emptied = kernel.state.clone(); + emptied.holdings.get_mut(&custody.holder).unwrap().clear(); + assert!(matches!( + verify_state_shape(&emptied), + Err(JournalError::Corrupt(_)) + )); + + let mut not_a_resource = kernel.state.clone(); + assert_eq!( + not_a_resource.entities[&topology.yard].kind, + EntityKind::Place + ); + not_a_resource + .holdings + .get_mut(&custody.holder) + .unwrap() + .insert(topology.yard, Quantity(1)); + assert!(matches!( + verify_state_shape(¬_a_resource), + Err(JournalError::Corrupt(_)) + )); + + let mut dangling = kernel.state.clone(); + dangling.dependencies.insert( + custody.holder, + BTreeSet::from([crate::DependencyTarget::Subject(custody.holder)]), + ); + assert!(matches!( + verify_state_shape(&dangling), + Err(JournalError::Corrupt(_)) + )); + } + + /// Soul: replay is exact after *every* custody and dependency operation, not + /// only after a transfer. The reopened world is byte-identical, the last + /// envelope is idempotent, and the whole chain still verifies. + #[test] + fn soul_replay_is_exact_after_every_custody_operation() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "EveryOperation"), + &authenticated, + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + // `Admit` and its evidence are Draft-only, so the opening balance is + // already on the log before activation. + let custody = admit_custody(&mut kernel, &topology); + let active = crate::tests::activate(&mut kernel); + + let envelope = command( + &active, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ + ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }, + ComponentOp::Transform { + holder: Ref::Existing(custody.holder), + from_resource: Ref::Existing(custody.tithe), + into_resource: Ref::Existing(custody.ingot), + qty: Quantity(2), + }, + ComponentOp::Consume { + holder: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(1), + }, + ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Route(Ref::Existing(topology.shutter)), + }, + ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Subject(Ref::Existing(custody.counterparty)), + }, + ], + evidence: Vec::new(), + }, + }, + ); + let SubmitReceipt::Applied(receipt) = + kernel.submit(envelope.clone(), &authenticated).unwrap() + else { + panic!("expected an applied custody patch"); + }; + let accepted = kernel.snapshot().unwrap(); + let holdings = kernel.state.holdings.clone(); + let dependencies = kernel.state.dependencies.clone(); + let digest = kernel.state.state_digest.clone(); + let world_id = accepted.world_id; + drop(kernel); + + let mut reopened = WorldKernel::open(&path, world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), accepted); + assert_eq!(reopened.state.holdings, holdings); + assert_eq!(reopened.state.dependencies, dependencies); + assert_eq!(reopened.state.state_digest, digest); + assert_eq!( + reopened.submit(envelope, &authenticated).unwrap(), + SubmitReceipt::AlreadyApplied(receipt) + ); + } + + /// Soul: a dependency naming a target of the wrong kind, or no canonical + /// target at all, is refused at replay. The shape clauses carry the + /// referential integrity the operation arm enforces at admission. + #[test] + fn soul_a_dependency_on_an_absent_or_wrong_kind_target_is_corrupt() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "DependencyShape"), + &authenticated, + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + crate::tests::activate(&mut kernel); + verify_state_shape(&kernel.state).expect("the admitted world has a canonical shape"); + + // A place is not a resource, so a resource dependency naming one dangles. + let mut wrong_kind = kernel.state.clone(); + wrong_kind.dependencies.insert( + custody.holder, + BTreeSet::from([crate::DependencyTarget::Resource(topology.yard)]), + ); + assert!(matches!( + verify_state_shape(&wrong_kind), + Err(JournalError::Corrupt(_)) + )); + + // An empty target set is the second representation of nothing, and there + // is only supposed to be one. + let mut emptied = kernel.state.clone(); + emptied.dependencies.insert(custody.holder, BTreeSet::new()); + assert!(matches!( + verify_state_shape(&emptied), + Err(JournalError::Corrupt(_)) + )); + + // A holder key that names no canonical subject. + let mut orphan = kernel.state.clone(); + let absent = *orphan.subjects.keys().next().unwrap(); + orphan.dependencies.insert( + absent, + BTreeSet::from([crate::DependencyTarget::Resource(custody.tithe)]), + ); + orphan.subjects.remove(&absent); + assert!(matches!( + verify_state_shape(&orphan), + Err(JournalError::Corrupt(_)) + )); + } + + /// A world with one routine, one past-due goal, and a commit chain that + /// reaches them: the fixture the two clock-forgery checks below need. + fn ticking_world(path: &std::path::Path) -> (WorldKernel, super::super::SubjectId, CommandId) { + use crate::tests::{activate, auth_principal, command, operations, owner}; + use crate::{ + AuthenticatedCaller, CallerId, CommandBody, CommitmentKind, ComponentOp, + FictionalMinutes, Ref, SystemCapability, TickMinutes, + }; + + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create( + path, + crate::tests::creation(CommandId::new(), "Ticking"), + &authenticated, + ) + .unwrap(); + let active = activate(&mut kernel); + let subject = active.subjects.first().expect("a seeded subject").id; + let snapshot = kernel.snapshot().unwrap(); + kernel + .submit( + command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + operations(vec![ + ComponentOp::CreateCommitment { + subject: Ref::Existing(subject), + counterparty: None, + kind: CommitmentKind::Routine, + due: FictionalMinutes(10), + period: Some(TickMinutes::new(10).unwrap()), + checks: Vec::new(), + statement: crate::Statement::new("What was promised, as the promisor would say it.").unwrap(), + }, + ComponentOp::CreateCommitment { + subject: Ref::Existing(subject), + counterparty: None, + kind: CommitmentKind::Goal, + due: FictionalMinutes(20), + period: None, + checks: Vec::new(), + statement: crate::Statement::new("What was promised, as the promisor would say it.").unwrap(), + }, + ]), + ), + &authenticated, + ) + .unwrap(); + + let tick_id = CommandId::new(); + let caller = CallerId::System(SystemCapability::Clock); + let snapshot = kernel.snapshot().unwrap(); + kernel + .submit( + command( + &snapshot, + tick_id, + caller.clone(), + CommandBody::AdvanceTime { + minutes: TickMinutes::new(30).unwrap(), + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap(); + (kernel, subject, tick_id) + } + + /// Soul falsification: the replay gate and the `apply_effect` gate are two + /// independent re-derivations. This one exercises the replay side over a + /// motion that actually moved commitments and pressure — a rewritten + /// magnitude, a rewritten roll, and a fabricated row each stop replaying. + #[test] + fn soul_a_forged_tick_motion_does_not_replay() { + use crate::{FictionalMinutes, PressureMagnitude, PressureSource}; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (kernel, subject, tick_id) = ticking_world(&path); + let WorldEffect::TimeAdvanced { motion, .. } = &kernel + .journal + .commits + .get(&tick_id) + .expect("the tick's commit") + .effect + else { + panic!("expected a time-advanced effect"); + }; + assert!(!motion.fulfilled.is_empty(), "the routine rolled"); + assert!(!motion.pressed.is_empty(), "the past-due goal pressed"); + + let forge = |rewrite: fn(&mut crate::Motion)| { + let mut forged_head = kernel.state.clone(); + let mut forged_commits = kernel.journal.commits.clone(); + let forged = forged_commits.get_mut(&tick_id).unwrap(); + let WorldEffect::TimeAdvanced { motion, .. } = &mut forged.effect else { + panic!("expected a time-advanced effect"); + }; + rewrite(motion); + forged.digest = commit_digest(forged).unwrap(); + forged_head.last_commit_digest = Some(forged.digest.clone()); + verify_history(&forged_head, &forged_commits) + }; + + let rewrites: [fn(&mut crate::Motion); 4] = [ + // A magnitude the tick never wrote. + |motion| motion.pressed[0].magnitude = PressureMagnitude(42), + // A roll to a date the period does not reach. + |motion| motion.fulfilled[0].next_due = FictionalMinutes(9_999), + // A row for a source nothing derived. + |motion| { + let mut row = motion.pressed[0].clone(); + row.source = PressureSource::Subject(row.target); + motion.pressed.push(row); + }, + // A fulfilment dropped on the floor. + |motion| motion.fulfilled.clear(), + ]; + for rewrite in rewrites { + assert!( + matches!(forge(rewrite), Err(JournalError::Corrupt(_))), + "a forged motion replayed" + ); + } + let _ = subject; + } + + /// `TickMinutes` is `#[serde(transparent)]`, so a hand-written store row + /// can carry a period of zero — a routine that re-arms on the same minute + /// forever — without ever passing through `TickMinutes::new`. The shape + /// check now enforces the same `1..=MAX_ROUTE_COST` span bound the + /// constructor enforces, so the forged row is refused directly. + #[test] + fn soul_a_zero_period_is_refused_by_the_shape_check() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (kernel, subject, _) = ticking_world(&path); + + // The forgery an in-crate caller cannot write: `TickMinutes::new` + // refuses zero, and the field is private, so the only door is serde. + assert!(crate::TickMinutes::new(0).is_none()); + let zero: crate::TickMinutes = + rmp_serde::from_slice(&rmp_serde::to_vec(&0u32).unwrap()).expect("a transparent span"); + + let mut forged = kernel.state.clone(); + let key = *forged.commitments[&subject] + .iter() + .find(|(_, commitment)| commitment.period.is_some()) + .expect("the routine") + .0; + forged + .commitments + .get_mut(&subject) + .unwrap() + .get_mut(&key) + .unwrap() + .period = Some(zero); + + // The shape check refuses the forged span bound directly. + assert!( + matches!(verify_state_shape(&forged), Err(JournalError::Corrupt(_))), + "verify_state_shape admitted a period outside 1..=MAX_ROUTE_COST" + ); + + // The commit chain refuses it too. + let commits: Vec<CultCacheEnvelope> = kernel + .journal + .commits + .values() + .map(|commit| { + envelope(COMMIT_ROW, COMMIT_SCHEMA, commit.command.id().key(), commit).unwrap() + }) + .collect(); + let mut rows = commits; + rows.push(envelope(STATE_ROW, STATE_SCHEMA, forged.world_id.key(), &forged).unwrap()); + assert!(matches!(recover(rows, None), Err(JournalError::Corrupt(_)))); + } + + /// Replay re-decides authority, so a stored row is not believed about who + /// authored it. An honest elaborator commit is rewritten to claim a + /// jurisdiction that does not cover its answer, and the history it belongs + /// to stops recovering. + #[test] + fn soul_a_forged_elaborator_commit_row_fails_replay() { + use crate::tests::{activate, submit_owner}; + use crate::{ + AuthenticatedCaller, CausalBoundary, Declaration, DraftHandle, EntityDeclaration, + JurisdictionKey, PatchAnswer, RouteDeclaration, SystemCapability, + }; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Forged Authorship"), + &auth_principal(owner()), + ) + .unwrap(); + let seed = kernel.snapshot().unwrap(); + let commons = seed.places[0].id; + submit_owner( + &mut kernel, + &seed, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("road"), + label: "The Unwalked Road".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(commons)), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("lane"), + label: "The Long Lane".into(), + from: Ref::Existing(commons), + to: Ref::Draft(DraftHandle::new("road")), + access: crate::AccessKind::Public, + cost: crate::Cost(1), + }), + ], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + activate(&mut kernel); + + let boundary = crate::derive_boundaries(&kernel.state) + .unwrap() + .into_iter() + .find(|boundary| matches!(boundary, CausalBoundary::UnelaboratedDestination { .. })) + .expect("the road is a dead end"); + let CausalBoundary::UnelaboratedDestination { place: road, .. } = boundary else { + unreachable!("the boundary was matched above") + }; + let caller = CallerId::System(SystemCapability::Elaborator { + jurisdiction: JurisdictionKey::PlaceSubtree(road), + }); + let snapshot = kernel.snapshot().unwrap(); + kernel + .submit( + command( + &snapshot, + CommandId::new(), + caller.clone(), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(boundary)), + patch: WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("shed"), + label: "The Roadside Shed".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(road)), + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .expect("the honest elaboration commits"); + + let state_row = || { + envelope( + STATE_ROW, + STATE_SCHEMA, + kernel.state.world_id.key(), + &kernel.state, + ) + .unwrap() + }; + let rows_of = |commits: Vec<crate::WorldCommit>| { + let mut rows: Vec<CultCacheEnvelope> = commits + .iter() + .map(|commit| { + envelope(COMMIT_ROW, COMMIT_SCHEMA, commit.command.id().key(), commit).unwrap() + }) + .collect(); + rows.push(state_row()); + rows + }; + + let honest: Vec<crate::WorldCommit> = + kernel.journal.commits.values().cloned().collect(); + recover(rows_of(honest.clone()), None).expect("the honest history replays"); + + // Rewrite only the recorded caller, to a jurisdiction that does not + // cover the answer the same row carries. + let mut forged_one = false; + let forged: Vec<crate::WorldCommit> = honest + .into_iter() + .map(|mut commit| { + if let crate::CommittedCommand::WorldCommand(command) = &mut commit.command + && matches!( + command.caller, + CallerId::System(SystemCapability::Elaborator { .. }) + ) + { + command.caller = CallerId::System(SystemCapability::Elaborator { + jurisdiction: JurisdictionKey::PlaceSubtree(commons), + }); + // Re-seal the row, so the chain digest cannot answer for + // the authority check. The elaborator commit is the last + // one, so no successor's `previous_commit_digest` moves. + commit.digest = commit_digest(&commit).unwrap(); + forged_one = true; + } + commit + }) + .collect(); + assert!(forged_one, "no elaborator row was found to forge"); + let error = recover(rows_of(forged), None).expect_err("a forged authorship replayed"); + let JournalError::Corrupt(detail) = &error else { + panic!("unexpected refusal: {error:?}"); + }; + assert!( + !detail.contains("commit chain is not contiguous"), + "the chain digest answered for the authority check: {detail}" + ); + } +} diff --git a/native/aetherlight/src/lens.rs b/native/aetherlight/src/lens.rs new file mode 100644 index 000000000..c14de9d8e --- /dev/null +++ b/native/aetherlight/src/lens.rs @@ -0,0 +1,379 @@ +//! The stock lenses. A lens is the flavor an elaborator session reaches for: +//! prompt emphasis over the one fixed tool catalog, never admission, authority, +//! or quota. This module owns the stock table, each lens's instruction text, +//! and the draw recipe; it reads no world state and writes nothing. + +use super::{CommandId, KernelError, WorldId, digest}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +/// The sentence every lens's instructions begin with. +const ELABORATION_INSTRUCTIONS: &str = "Use only the supplied tools to author structure inside your jurisdiction. Answer the boundary or deficit you were given, then submit. Recording a gap changes nothing."; + +/// The library's stock lens set. Serialized by snake_case name, so a name the +/// library does not know cannot be represented at any deserialization boundary. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Lens { + Patina, + Charter, + Ledger, + Hearth, + Tangle, + Veil, + Ember, + Numen, +} + +impl Lens { + /// Every lens, in declaration order. The draw walks this order. + pub const ALL: [Lens; 8] = [ + Lens::Patina, + Lens::Charter, + Lens::Ledger, + Lens::Hearth, + Lens::Tangle, + Lens::Veil, + Lens::Ember, + Lens::Numen, + ]; + + pub fn name(self) -> &'static str { + match self { + Lens::Patina => "Patina", + Lens::Charter => "Charter", + Lens::Ledger => "Ledger", + Lens::Hearth => "Hearth", + Lens::Tangle => "Tangle", + Lens::Veil => "Veil", + Lens::Ember => "Ember", + Lens::Numen => "Numen", + } + } + + /// What kind of structure the lens reaches for. + pub(crate) fn reaches_for(self) -> &'static str { + match self { + Lens::Patina => "ordinary objects, customs, nicknames, local jokes", + Lens::Charter => "government, law, offices, selection, succession, redress", + Lens::Ledger => "resources, labor, trade, infrastructure, scarcity, class pressure", + Lens::Hearth => "kinship, daily life, care, obligation, belonging", + Lens::Tangle => "factions, alliances, rivalries, leverage", + Lens::Veil => "secrets, rumors, misinformation, taboos, unevenly held knowledge", + Lens::Ember => "disputes, hazards, instability, escalation, urgent pressure", + Lens::Numen => "religion, magic, ritual, awe, cosmology, the genuinely strange", + } + } + + /// Existing `PATCH_TOOLS` names in emphasis order. Emphasis is prompt text + /// only: the catalog, its order, and its schemas are the same for every lens. + pub(crate) fn leads_with(self) -> &'static [&'static str] { + match self { + Lens::Patina => &[ + "set_persona_material", + "declare_affordance", + "declare_resource", + "declare_place", + ], + Lens::Charter => &[ + "grant_authority", + "open_office", + "install_incumbent", + "open_forum", + "declare_subject", + ], + Lens::Ledger => &[ + "transfer", + "bind", + "declare_resource", + "alter_cost", + "declare_route", + ], + Lens::Hearth => &[ + "create_commitment", + "set_persona_material", + "declare_subject", + ], + Lens::Tangle => &[ + "advance_pressure", + "create_commitment", + "grant_authority", + "declare_subject", + "bind", + ], + Lens::Veil => &[ + "acquire_knowledge", + "communicate", + "declare_channel", + "set_reach", + "declare_fact", + "forget", + ], + Lens::Ember => &[ + "advance_pressure", + "create_commitment", + "close_route", + "consume", + ], + Lens::Numen => &[ + "declare_fact", + "declare_affordance", + "set_persona_material", + "witness", + ], + } + } + + /// The elaborator's instructions under this lens: the shared sentence, then + /// the lens clause. Read once, when a session is first built; the session + /// then carries the text, and nothing rebuilds it from here. + pub(crate) fn instructions(self) -> String { + format!( + "{ELABORATION_INSTRUCTIONS} Lens: {}. Reach for {}. Lead with {}; every supplied tool remains available.", + self.name(), + self.reaches_for(), + self.leads_with().join(", "), + ) + } +} + +/// A world's lens weights. Validity is decided where weights are admitted; +/// `Default` is the empty map a world holds before genesis writes its weights, +/// and it never draws. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(transparent)] +pub struct LensWeights(BTreeMap<Lens, u32>); + +impl LensWeights { + pub fn new(weights: BTreeMap<Lens, u32>) -> Self { + Self(weights) + } + + /// A lens the map does not name weighs zero. + pub fn get(&self, lens: Lens) -> u32 { + self.0.get(&lens).copied().unwrap_or(0) + } + + pub fn iter(&self) -> impl Iterator<Item = (Lens, u32)> + '_ { + self.0.iter().map(|(lens, weight)| (*lens, *weight)) + } + + /// Some weight is nonzero, so a draw has somewhere to land. + pub(crate) fn draws(&self) -> bool { + self.0.values().any(|weight| *weight > 0) + } + + /// Every stock lens weighs the same in both sets. A lens a map does not + /// name weighs zero, so `{charter: 3}` and `{patina: 0, charter: 3}` are + /// one set spelled two ways: they draw identically and neither replaces + /// the other. + pub(crate) fn weighs_the_same_as(&self, other: &LensWeights) -> bool { + Lens::ALL + .into_iter() + .all(|lens| self.get(lens) == other.get(lens)) + } +} + +/// The draw's whole input: the world and the session's fixed identity. The +/// weights select over it; they are not part of it. +#[derive(Serialize)] +struct LensPreimage { + world_id: WorldId, + command_id: CommandId, +} + +/// One digest, one modulo, one cumulative walk over `Lens::ALL` — the recipe +/// `select_band` uses, not a second entropy shape. The same world, session +/// identity, and weights draw the same lens. Modulo rather than rejection +/// sampling: the bias is bounded by `total_weight / 2^64`. +pub(crate) fn draw( + weights: &LensWeights, + world_id: WorldId, + command_id: CommandId, +) -> Result<Lens, KernelError> { + // The guard is on the divisor itself, as `select_band`'s is: no other + // statement of "these weights draw" can let the modulo below divide by zero. + let total: u128 = Lens::ALL + .iter() + .map(|lens| u128::from(weights.get(*lens))) + .sum(); + if total == 0 { + return Err(KernelError::Invariant("lens weights never draw".into())); + } + let preimage = digest(&LensPreimage { + world_id, + command_id, + })?; + let head = preimage + .strip_prefix("sha256:") + .and_then(|hex| hex.get(..16)) + .and_then(|head| u64::from_str_radix(head, 16).ok()) + .ok_or_else(|| KernelError::Invariant("lens draw digest is not hex".into()))?; + let mut position = u128::from(head) % total; + for lens in Lens::ALL { + let weight = u128::from(weights.get(lens)); + if position < weight { + return Ok(lens); + } + position -= weight; + } + Err(KernelError::Invariant( + "lens weights did not cover the draw".into(), + )) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::patch::PATCH_TOOLS; + use crate::tests::stock_weights; + use std::collections::BTreeSet; + + fn ids() -> Vec<CommandId> { + (0..200) + .map(|i| CommandId::derived("l1-probe", &[&i.to_string()])) + .collect() + } + + fn tally(weights: &LensWeights) -> BTreeMap<Lens, usize> { + let mut counts = BTreeMap::new(); + for id in ids() { + let lens = draw(weights, WorldId::nil_for_test(), id).unwrap(); + *counts.entry(lens).or_insert(0) += 1; + } + counts + } + + #[test] + fn every_lead_names_a_patch_tool() { + let catalog: BTreeSet<&str> = PATCH_TOOLS.iter().map(|entry| entry.name).collect(); + for lens in Lens::ALL { + let leads = lens.leads_with(); + assert!(!leads.is_empty(), "{lens:?} leads with nothing"); + let distinct: BTreeSet<&str> = leads.iter().copied().collect(); + assert_eq!(distinct.len(), leads.len(), "{lens:?} repeats a lead"); + for name in leads { + assert!( + catalog.contains(name), + "{lens:?} leads with unknown tool {name}" + ); + } + } + } + + #[test] + fn the_draw_is_a_function_of_world_and_session() { + let weights = stock_weights(); + let world = WorldId::nil_for_test(); + for id in ids() { + assert_eq!( + draw(&weights, world, id).unwrap(), + draw(&weights, world, id).unwrap() + ); + } + let expected: BTreeMap<Lens, usize> = BTREE_STOCK_TALLY.into_iter().collect(); + assert_eq!(tally(&weights), expected); + } + + /// Computed at Cut 1 and pinned: the replay proof for 200 derived ids under + /// stock weights. + const BTREE_STOCK_TALLY: [(Lens, usize); 8] = [ + (Lens::Patina, 22), + (Lens::Charter, 37), + (Lens::Ledger, 26), + (Lens::Hearth, 19), + (Lens::Tangle, 23), + (Lens::Veil, 29), + (Lens::Ember, 18), + (Lens::Numen, 26), + ]; + + #[test] + fn a_zero_weight_never_draws() { + let weights = LensWeights::new(BTreeMap::from([ + (Lens::Patina, 0), + (Lens::Charter, 3), + (Lens::Ledger, 1), + ])); + let counts = tally(&weights); + assert_eq!(counts.get(&Lens::Patina), None, "a zero weight drew"); + let expected: BTreeMap<Lens, usize> = ZERO_WEIGHT_TALLY.into_iter().collect(); + assert_eq!(counts, expected); + } + + /// Computed at Cut 1 and pinned; near 3:1 over the same 200 ids. + const ZERO_WEIGHT_TALLY: [(Lens, usize); 2] = [(Lens::Charter, 155), (Lens::Ledger, 45)]; + + #[test] + fn all_zero_weights_are_an_error() { + let world = WorldId::nil_for_test(); + let id = CommandId::derived("l1-probe", &["0"]); + let all_zero = LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 0)).collect()); + assert_eq!(all_zero.iter().count(), 8); + for weights in [LensWeights::default(), all_zero] { + assert!(matches!( + draw(&weights, world, id), + Err(KernelError::Invariant(_)) + )); + } + } + + #[test] + fn an_unknown_lens_name_does_not_deserialize() { + for refused in [ + r#"{"Patina":1}"#, + r#"{"patina ":1}"#, + r#"{"patinaa":1}"#, + r#"{"patina":1,"tribunal":1}"#, + ] { + assert!( + serde_json::from_str::<LensWeights>(refused).is_err(), + "{refused} deserialized" + ); + } + let accepted = serde_json::from_str::<LensWeights>(r#"{"patina":1}"#).unwrap(); + assert_eq!(accepted.get(Lens::Patina), 1); + assert_eq!(accepted.iter().count(), 1); + + let stock = stock_weights(); + let bytes = rmp_serde::to_vec_named(&stock).unwrap(); + let back: LensWeights = rmp_serde::from_slice(&bytes).unwrap(); + assert_eq!(back, stock); + assert_eq!(rmp_serde::to_vec_named(&back).unwrap(), bytes); + } + + #[test] + fn each_lens_text_names_its_own_leads() { + let mut texts = BTreeSet::new(); + for lens in Lens::ALL { + let text = lens.instructions(); + assert!(text.contains(lens.name()), "{lens:?} text omits its name"); + for name in lens.leads_with() { + assert!(text.contains(name), "{lens:?} text omits {name}"); + } + texts.insert(text); + } + assert_eq!(texts.len(), 8, "two lenses share a text"); + } + + #[test] + fn lenses_serialize_as_snake_case_names() { + let names: Vec<String> = Lens::ALL + .iter() + .map(|lens| serde_json::to_string(lens).unwrap()) + .collect(); + assert_eq!( + names, + [ + r#""patina""#, + r#""charter""#, + r#""ledger""#, + r#""hearth""#, + r#""tangle""#, + r#""veil""#, + r#""ember""#, + r#""numen""#, + ] + ); + } +} diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs new file mode 100644 index 000000000..3f64965c6 --- /dev/null +++ b/native/aetherlight/src/lib.rs @@ -0,0 +1,19173 @@ +//! The Ghostlight world library. +//! +//! The world owner is one deterministic authority: authenticated commands enter, +//! one reducer decides, and one journal atomically commits the resulting state. +//! Controllers may use models, but models never own lifecycle, scope, affordances, +//! opportunities, reduction, or persistence. +//! +//! A consumer reaches this crate through create/open, immutable snapshots, +//! command submission, typed receipts, and the runner and port entry points +//! below. The kernel itself is sealed: there is no mutable state, no canonical +//! ID allocator, no reducer entry, no journal writer, and no authenticated-caller +//! constructor on the public surface, under every configuration. This crate +//! declares no cargo features, so no build can lift the seal. +//! +//! The negative proofs are doc-tests, which compile as an external crate and so +//! stand exactly where a consumer stands. +//! +//! ```compile_fail,E0603 +//! use ghostlight::WorldKernel; +//! ``` +//! +//! ```compile_fail,E0603 +//! use ghostlight::reduce; +//! ``` +//! +//! ```compile_fail,E0603 +//! use ghostlight::WorldState; +//! ``` +//! +//! ```compile_fail,E0603 +//! use ghostlight::CommandEnvelope; +//! ``` +//! +//! ```compile_fail,E0603 +//! use ghostlight::AuthenticatedCaller; +//! ``` +//! +//! ```compile_fail,E0603 +//! use ghostlight::journal::WorldJournal; +//! ``` +//! +//! ```compile_fail,E0599 +//! let _ = ghostlight::SubjectId::issue(); +//! ``` +//! +//! ```compile_fail,E0603 +//! let _ = ghostlight::ScopeDigest::fixture("x"); +//! ``` +//! +//! ```compile_fail,E0425 +//! let _ = ghostlight::fixture_controller_opportunities(&[]); +//! ``` +//! +//! ```compile_fail,E0425 +//! let _ = ghostlight::fixture_inference_output("prose", "receipt"); +//! ``` + +mod action; +mod aetheria; +mod clock; +mod consumer; +mod controllers; +mod cover; +mod elaboration; +mod grammar; +#[cfg(test)] +mod import_key_tests; +mod journal; +mod lens; +mod local_inference; +mod mailbox; +mod patch; +mod sdk_inference; +mod table; +mod tool_schema; +mod vault; +mod verse; + +pub(crate) use action::ActionMismatch; +pub(crate) use clock::Motion; +pub use clock::{FictionalMinutes, TickMinutes}; +pub use consumer::{ + CONSUMER_BODY_LIMIT, CONSUMER_CREDENTIALS_ENVIRONMENT, CONSUMER_PATCH_SCHEMA, + CONSUMER_RECEIPT_SCHEMA, ConsumerRegistry, admit_document, encode_receipt, +}; +pub use controllers::{ + CONTROLLER_WORK_SCHEMA, CellRun, ConnectorBinding, ControllerError, ControllerModels, + ControllerOpenError, + ControllerNeed, ControllerPendingReason, ControllerRunner, ControllerWork, + ControllerWorkCustody, ControllerWorkLookup, ControllerWorkStore, ControllerWorkStoreError, + ControllerWorkWrite, + GroupedCheckpoint, InferenceEvent, InferenceFault, InferenceFaultClass, InferenceFaultDisposition, InferenceOutput, + InferencePort, + InferencePurpose, InferenceRequest, NarrativeCheckpoint, NarrativeRun, OperationalCheckpoint, + OperationalRun, PersonaLane, PreparedInference, SubmissionDisposition, TokenUsage, ToolResultOracle, + TracingInferencePort, open_controller_work, open_inference, +}; +pub(crate) use cover::{CellId, Constituent, Resolution}; +pub use aetheria::{ + AetheriaCatalog, AetheriaFaction, CatalogReadError, VerbRule, read_aetheria_catalog, +}; +pub use cover::{AgencyGraph, Cell, Cover, CoverBudget, CoverBudgetError, TickIndex, derive_cover}; +pub use elaboration::{ + ElaborationCheckpoint, ElaborationRunner, ElaboratorSession, EvidenceError, EvidenceQuery, + EvidenceReceipt, EvidenceSource, SeedCheckpoint, SeedOutcome, SeedRunner, select_row, +}; +pub use grammar::{ + GrammarBinding, GrammarError, GrammarIdentity, GrammarReferentKind, GrammarRole, GrammarVerb, + RenderPath, +}; +pub use lens::{Lens, LensWeights}; +pub use local_inference::{DEFAULT_HOSTED_MODEL_PREFIX, DEFAULT_LOCAL_MODEL_PREFIX, HostedBinding, LocalBinding}; +#[cfg(feature = "test-support")] +pub use local_inference::open_local_port_with_timeout; +pub(crate) use mailbox::ElaborationPort; +pub use mailbox::{ConsumerPort, ControllerPort, MailboxError, PlayPort, SeedPort, WorldMailbox}; +pub use patch::{ + CommitmentKey, DraftHandle, JurisdictionKey, Mismatch, PatchAnswer, Ref, RefKind, RefName, Role, + Site, Statement, WorldPatch, +}; +pub(crate) use patch::{ + AccessKind, Affordance, Audience, AuthoredSource, AuthorityGrant, AuthorityTarget, + BoundPrecondition, Bounds, ChannelRecord, Commitment, CommitmentKind, Confidence, Cost, + Declaration, DependencyTarget, EntityDeclaration, EntityKind, EvidenceRef, FactRecord, + FactStanding, Forum, GrievanceKindName, Knowledge, KnowledgeSource, Office, OfficeName, + PersonaMaterial, Position, PressureMagnitude, PressureSource, Quantity, Reach, + SubjectDeclaration, WorldScaleIntent, WorldScaleIntentRef, +}; +pub use patch::ImportKey; +#[cfg(test)] +use patch::{ + AffordanceDeclaration, AudienceRef, AudienceSpec, ChannelDeclaration, ComponentOp, + DependencyRef, FactDeclaration, FactStandingRef, ReachRef, RouteDeclaration, +}; +#[cfg(test)] +pub(crate) use patch::{ + AffordanceKindName, AuthorityGrantRef, AuthorityKindName, AuthorityTargetRef, ComponentOpKind, + EffectSlot, OutcomeBand, Precondition, RoleSpec, +}; +pub use sdk_inference::{DEFAULT_SDK_MODEL_PREFIX, SdkBinding}; +pub use table::{ + DecodedBatch, PatchSite, TableError, actor_tools, authoring_tools, decode_actor_call, + decode_authoring_call, decode_authoring_calls, describe_refusal, describe_refusal_to_actor, + id_text, id_text_matches, table_view, +}; +pub use vault::{VaultError, VaultEvidenceSource}; +pub use verse::{ + CALL_RECORD_SCHEMA, CallRecordError, CallRecordStore, CreateVerseWorldIntent, ProviderCallRecord, + RUN_RECORD_SCHEMA, RecordedCoverBudget, RecordingInferencePort, Refusal, RefusalReason, RunClaim, + ReplayInferencePort, RunField, RunId, RunOutcome, RunStart, RunStatus, TickCheckpoint, + TickReport, UnattributedCall, VerseGenesisError, VerseRunConfig, VerseRunError, VerseRunRecord, VerseRunStore, + call_run_id, run_manual, +}; +use patch::{EdgeRecord, EntityRecord, LedgerDelta, ResolvedOp, ResolvedPatch}; + +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, BTreeSet}; +#[cfg(test)] +use std::path::Path; +use thiserror::Error; +use uuid::Uuid; + +/// Proof that the consumer verified a live principal, and the moment that +/// proof stops being worth anything. +/// +/// The consumer verifies; this library only bounds. `valid_until` is the +/// consumer's own session expiry, not a fresh clock read at construction, and +/// [`WorldMailbox::submit_principal`] refuses evidence presented after it — so +/// a long-lived holder such as [`SeedPort`] is bounded by the session that +/// vouched for it rather than by one request's lifetime. +/// +/// Keeping this type here, rather than taking the consumer's own session type, +/// is what keeps the consumer's principal format out of the kernel. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VerifiedPrincipalEvidence { + account_subject_hash: String, + valid_until: DateTime<Utc>, +} + +impl VerifiedPrincipalEvidence { + pub fn new(account_subject_hash: impl Into<String>, valid_until: DateTime<Utc>) -> Self { + Self { + account_subject_hash: account_subject_hash.into(), + valid_until, + } + } + + pub fn account_subject_hash(&self) -> &str { + &self.account_subject_hash + } + + pub fn valid_until(&self) -> DateTime<Utc> { + self.valid_until + } + + #[cfg(test)] + pub(crate) fn fixture( + account_subject_hash: impl Into<String>, + valid_until: DateTime<Utc>, + ) -> Self { + Self::new(account_subject_hash, valid_until) + } +} + +pub const STATE_SCHEMA: &str = "ghostlight.world_state.consumer.v6"; +pub(crate) const COMMIT_SCHEMA: &str = "ghostlight.world_commit.consumer.v6"; + +/// Compatibility tag derived from [`STATE_SCHEMA`]: the trailing +/// `<family>-<version>` pair (e.g. `foundation-v1`). Callers that publish a +/// compatibility marker alongside the schema string must derive it from here +/// rather than hand-copying a second literal that can drift from the schema. +pub fn state_schema_compatibility_tag() -> String { + let mut segments = STATE_SCHEMA.rsplit('.'); + let version = segments.next().unwrap_or_default(); + let family = segments.next().unwrap_or_default(); + format!("{family}-{version}") +} + +/// The visibility argument is the whole boundary decision for an ID type: the +/// ones a consumer names by value are `pub`, the rest stay `pub(crate)`, and no +/// `issue()` impl is emitted here at all — issuance is private in every case. +macro_rules! opaque_uuid { + ($name:ident, $vis:vis) => { + #[derive( + Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, + )] + #[serde(transparent)] + $vis struct $name(Uuid); + }; + ($name:ident) => { + opaque_uuid!($name, pub(crate)); + }; +} + +opaque_uuid!(WorldId, pub); +opaque_uuid!(CommandId, pub); +opaque_uuid!(SubjectId, pub); +opaque_uuid!(EntityId, pub); +opaque_uuid!(EdgeId, pub); +opaque_uuid!(ControllerId); +opaque_uuid!(AffordanceId, pub); +opaque_uuid!(EventId); + +impl CommandId { + fn issue() -> Self { + Self(Uuid::new_v4()) + } + + pub fn new() -> Self { + Self::issue() + } + + pub fn parse_uuid(value: &str) -> Result<Self, KernelError> { + Uuid::parse_str(value) + .map(Self) + .map_err(|_| KernelError::InvalidCommandId) + } + + /// The cell's own controller-work key. One row per cell per tick, derived so + /// a resumed tick reopens the row it wrote rather than starting a second + /// cognition chain over the same opportunities. + pub(crate) fn for_cell(world: WorldId, cell: cover::CellId, tick: cover::TickIndex) -> Self { + Self(cover::cell_work_uuid(world, cell, tick)) + } + + /// One constituent's submission id. Deterministic over + /// `(world, cell, subject, tick)`, so a resumed cell re-submits the same id + /// and the kernel's idempotency ledger answers with the original receipt + /// instead of committing a second time. + pub(crate) fn for_cell_constituent( + world: WorldId, + cell: cover::CellId, + subject: SubjectId, + tick: cover::TickIndex, + ) -> Self { + Self(cover::cell_constituent_uuid(world, cell, subject, tick)) + } + + /// sha256 over a namespace and its ordered, length-prefixed parts, first + /// sixteen bytes. A command key, not a referent id: `patch::derive_id` + /// still has exactly two call sites. No `uuid/v5`. + pub(crate) fn derived(namespace: &str, parts: &[&str]) -> Self { + let mut hasher = Sha256::new(); + hasher.update(namespace.as_bytes()); + for part in parts { + hasher.update((part.len() as u64).to_be_bytes()); + hasher.update(part.as_bytes()); + } + let bytes: [u8; 16] = hasher.finalize()[..16] + .try_into() + .expect("sha256 yields at least sixteen bytes"); + Self(Uuid::from_bytes(bytes)) + } + + fn key(self) -> String { + self.0.to_string() + } +} + +impl WorldId { + /// Canonical text, for the key derivations that hash a world identity. + pub(crate) fn text(self) -> String { + self.0.to_string() + } + + /// A named zero for tests that need a world identity and no world. + #[cfg(test)] + pub(crate) fn nil_for_test() -> Self { + Self(Uuid::nil()) + } + + fn issue() -> Self { + Self(Uuid::new_v4()) + } + + fn key(self) -> String { + self.0.to_string() + } +} + +// Subject, entity, controller, and affordance IDs are derived, never drawn. +// `patch::derive_id` is the only allocator, and it is called from exactly two +// sites: `patch::resolve_patch` and `action::exercise`. The action lane mints +// exactly one referent per invocation — always an `EntityKind::Fact`, always +// `Claimed` by the acting subject, never caller-named, never any other kind. +// These fixtures exist so tests can name an ID that no partition holds. +#[cfg(test)] +impl SubjectId { + fn issue() -> Self { + Self(Uuid::new_v4()) + } +} + +#[cfg(test)] +impl EntityId { + fn issue() -> Self { + Self(Uuid::new_v4()) + } +} + +#[cfg(test)] +impl ControllerId { + fn issue() -> Self { + Self(Uuid::new_v4()) + } +} + +#[cfg(test)] +impl AffordanceId { + fn issue() -> Self { + Self(Uuid::new_v4()) + } +} + +impl EventId { + fn for_command(command_id: CommandId) -> Self { + Self(command_id.0) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub struct PrincipalId(String); + +impl PrincipalId { + pub fn new(value: impl Into<String>) -> Self { + Self(value.into()) + } +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum WorldPhase { + Draft, + Active, +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum SubjectKind { + Person, + Institution, + Population, +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum ControllerMode { + Human, + NarrativePersona, + OperationalAgent, +} + +/// A configured external consumer. Opaque inside the kernel: derived from the +/// consumer's configured name at the ingress registry and never spelled back +/// out, so no consumer name can reach a match arm. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[serde(transparent)] +pub(crate) struct ConsumerId(Uuid); + +/// The one namespace a configured consumer name lowers through. +const CONSUMER_ID_NAMESPACE: &str = "ghostlight.consumer.id.v0"; + +impl ConsumerId { + /// The one lowering from a configured name, through `CommandId::derived`'s + /// recipe over its own namespace. Called only by the ingress registry. + pub(crate) fn of_name(name: &str) -> Self { + Self(CommandId::derived(CONSUMER_ID_NAMESPACE, &[name]).0) + } + + /// Canonical text, for the command-key derivation that hashes it. + pub(crate) fn text(self) -> String { + self.0.to_string() + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", rename_all = "snake_case")] +pub(crate) enum NewController { + Human { + principal: PrincipalId, + }, + NarrativePersona, + OperationalAgent, + /// Declared as a mirror of state this world does not own. Mints no + /// controller, no mode, and no opportunity. + External { + consumer: ConsumerId, + }, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +struct CreateWorld { + id: CommandId, + owner: PrincipalId, + title: String, + /// The world's authored premise, in the owner's words. Every lane reads it + /// as its guidance; nothing derives it and nothing writes it later. + brief: String, + patch: WorldPatch, + /// Authored once, here, and never mutated: `CommandBody::AdmitPatch` carries + /// no intent, so write-once is the command shape rather than a check. + scale_intent: WorldScaleIntentRef, + /// The world's flavor as genesis writes it. `SetLensWeights` may replace + /// it later; this command carries what the world began with. + lens_weights: LensWeights, + /// The grammar the world is bound to for its whole life, or none for an + /// open-catalog world. Authored here and nowhere else: genesis installs it. + #[serde(default, skip_serializing_if = "Option::is_none")] + grammar: Option<GrammarBinding>, +} + +/// Unattributed creation intent. World ingress derives ownership, controller +/// identity, handles, kinds, and affordances from verified principal evidence. +#[derive(Clone, Debug)] +pub struct CreateWorldIntent { + pub id: CommandId, + pub title: String, + /// The premise, verbatim from the owner. May be empty: a world with no + /// brief is a deliberate choice, and its lanes then get no guidance. + pub brief: String, + pub human_subject_label: String, + pub narrative_persona_label: Option<String>, + pub operational_agent_label: Option<String>, + /// World-wide target of goal-bearing subjects per kind. Required, and may + /// be empty: a world with no target is a deliberate choice, not a default + /// that arrives because nobody said anything. + pub targets: BTreeMap<SubjectKind, u32>, + /// The jurisdiction roots genesis declares beside the commons, because + /// `resolve_patch` only resolves roots the same patch declares. + pub jurisdictions: Vec<CreateJurisdictionIntent>, + /// Required. The library holds no default weights; a consumer states the + /// world's flavor or is refused. + pub lens_weights: LensWeights, +} + +/// One jurisdiction root as ingress states it. The handle is a string here and +/// a `DraftHandle` inside the world subtree, which is the one lowering: the +/// handle constructor is not reachable from runtime ingress. +#[derive(Clone, Debug)] +pub struct CreateJurisdictionIntent { + pub handle: String, + pub label: String, + pub permille: u32, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", content = "id", rename_all = "snake_case")] +enum CallerId { + Principal(PrincipalId), + Controller(ControllerId), + /// An internal capability. Never derived from session evidence, never + /// minted by ingress, and admitted for exactly one command body. + System(SystemCapability), +} + +/// Internally tagged, because a data-carrying variant cannot join a bare-string +/// encoding without silently changing every commit that already carries +/// `Clock`. The tag is part of the commit digest, so the schema bumps with it. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "capability", rename_all = "snake_case")] +enum SystemCapability { + Clock, + /// Authors structure inside one jurisdiction. Never derived from session + /// evidence, never minted by ingress, never held by a subject. + Elaborator { + jurisdiction: JurisdictionKey, + }, + /// One external consumer, authoring only the subjects this world has + /// admitted as its mirrors. Minted by exactly one mailbox method, after the + /// ingress has authenticated the document; never derived from session + /// evidence. + Consumer { + consumer: ConsumerId, + }, + /// The play table. Admitted for unanswered, unconfined Active patches, the + /// only author of `Ruled` facts and `Mint`, and for the clock. Minted only + /// by `PlayPort`. + Play, +} + +/// What a confined patch author may write. `None` from `require_patch_author` +/// still means unconfined: the owner. +/// +/// Deliberately not `AuthorityTarget`. That is in-world grant vocabulary read +/// by `covers` and `targets_overlap`; this names a caller's write scope, and +/// its consumer arm names a caller rather than a subject — the subject set is +/// derived from `controller_assignments` at decision time. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum PatchGround { + /// A place subtree. The elaborator's shape, unchanged in meaning. + Jurisdiction(JurisdictionKey), + /// Every subject bound to this consumer. + Consumer(ConsumerId), +} + +#[derive(Clone, Debug)] +struct AuthenticatedCaller { + caller: CallerId, +} + +impl AuthenticatedCaller { + fn verified_principal(principal: PrincipalId) -> Self { + Self { + caller: CallerId::Principal(principal), + } + } + + fn verified_controller(controller: ControllerId) -> Self { + Self { + caller: CallerId::Controller(controller), + } + } + + /// Visible only inside the `world` subtree and called only by + /// `WorldMailbox::submit_clock`. Runtime ingress cannot reach it. + fn verified_system(capability: SystemCapability) -> Self { + Self { + caller: CallerId::System(capability), + } + } + + #[cfg(test)] + fn fixture(caller: CallerId) -> Self { + Self { caller } + } +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub struct DecisionScope { + pub subject_id: SubjectId, +} + +/// The digest of exactly the components a proposal's verification reads: the +/// scope's controller assignment, its affordance grants, its subject's Position, +/// and the routes incident to that place. Built through the one `digest()` +/// helper over ordered containers, so it is a pure function of committed state. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub struct ScopeDigest(String); + +impl ScopeDigest { + fn as_str(&self) -> &str { + &self.0 + } + + #[cfg(test)] + pub(crate) fn fixture(value: &str) -> Self { + Self(value.into()) + } +} + +#[derive(Serialize)] +struct ScopePreimage<'a> { + world_id: WorldId, + subject_id: SubjectId, + controller: &'a ControllerAssignment, + /// The granted entries *and their definitions*: preconditions and ceilings + /// are what admission reads, so a change to a granted entry must change the + /// digest. + affordances: BTreeMap<AffordanceId, &'a Affordance>, + components: &'a ScopeComponents, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct DecisionOpportunity { + pub world_id: WorldId, + pub(crate) revision: u64, + pub(crate) scope_digest: ScopeDigest, + pub scope: DecisionScope, + pub(crate) controller_id: ControllerId, + pub controller_mode: ControllerMode, + pub affordance_ids: Vec<AffordanceId>, +} + +impl DecisionOpportunity { + pub(crate) fn digest(&self) -> Result<String, KernelError> { + digest(self) + } +} + +/// The referent a role is bound to. Canonical IDs only: an invocation happens +/// in Active, where no declaration exists, so a draft reference is +/// unrepresentable here and the action lane runs no draft resolution. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "target", content = "id", rename_all = "snake_case")] +pub(crate) enum Target { + Subject(SubjectId), + Entity(EntityId), + Edge(EdgeId), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub struct RoleBinding { + pub(crate) role: Role, + pub(crate) target: Target, +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "magnitude", content = "value", rename_all = "snake_case")] +pub(crate) enum Magnitude { + None, + Quantity(Quantity), + Cost(Cost), +} + +/// One proposal against one effect slot. It carries no referents: they all come +/// from the slot's roles resolved through the invocation's bindings, so an +/// invocation cannot name a target its affordance declared no role for and the +/// ceiling check is a comparison rather than a graph walk. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct ProposedEffect { + pub(crate) slot: usize, + pub(crate) magnitude: Magnitude, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct DecisionInvocation { + pub affordance: AffordanceId, + pub bindings: Vec<RoleBinding>, + /// Exactly one entry per slot in the entry, in any order. + pub proposed: Vec<ProposedEffect>, + /// Command input, and the only place an utterance's text enters the kernel. + /// The committed home of those bytes is `facts[fact].statement`. + pub speech: Option<Statement>, + /// A visible act in the actor's own words, and the only place it enters + /// the kernel. It accompanies any invocation: a body is visible whatever + /// it is doing. Its audience is the actor's place, never the entry's. + pub display: Option<Statement>, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +struct CommandEnvelope { + id: CommandId, + world_id: WorldId, + expected_revision: u64, + caller: CallerId, + body: CommandBody, +} + +/// Unattributed human command intent. The mailbox derives the caller from +/// live app-session evidence before the reducer sees an envelope. +#[derive(Clone, Debug)] +pub struct PrincipalCommandIntent { + pub id: CommandId, + pub world_id: WorldId, + pub expected_revision: u64, + pub body: CommandBody, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum CommandBody { + ApproveDraft, + ActivateWorld, + ExerciseDecision { + opportunity: DecisionOpportunity, + invocation: DecisionInvocation, + }, + DeclineDecision { + opportunity: DecisionOpportunity, + }, + AdmitPatch { + /// Draft answers nothing. Active must answer a currently derived + /// boundary or a jurisdiction whose deficit is nonzero, and the commit + /// must satisfy what it answered. + answers: Option<PatchAnswer>, + patch: WorldPatch, + }, + /// The world's only clock advance. Owner or the clock capability, and the + /// clock capability may do nothing else. + AdvanceTime { + minutes: TickMinutes, + }, + /// Replaces the world's whole lens weight set. Owner only, in any phase, + /// under genesis admission: a set that never draws is refused, and a zero + /// weight is admitted and never draws. A set that weighs every lens as + /// the current one does, however its map is spelled, changes nothing + /// canonical and is refused with `NoCanonicalChange` after admission, so + /// nothing commits. A session that already drew keeps its recorded lens. + SetLensWeights { + weights: LensWeights, + }, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +struct SubjectState { + label: String, + kind: SubjectKind, + /// Written only when a subject declaration is resolved; absent from a + /// subject nobody imported, so its digests are unchanged. + #[serde(default, skip_serializing_if = "Option::is_none")] + import_key: Option<ImportKey>, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", rename_all = "snake_case")] +enum ControllerAssignment { + Human { + controller_id: ControllerId, + principal: PrincipalId, + }, + NarrativePersona { + controller_id: ControllerId, + }, + OperationalAgent { + controller_id: ControllerId, + }, + /// A mirror of state this world does not own. It has no controller id and + /// no mode, because the kernel will not keep a fictional one so an accessor + /// can stay infallible. + ExternallyControlled { + consumer: ConsumerId, + }, + /// A subject `Retire` ended for good. Not a second partition: + /// `controller_assignments` stays the sole answer to who may call, and + /// this is one of its values. It has no controller id, no mode, and no + /// caller, so it mints no opportunity and is never an audience. + Retired, +} + +impl ControllerAssignment { + fn id(&self) -> Option<ControllerId> { + match self { + Self::Human { controller_id, .. } + | Self::NarrativePersona { controller_id } + | Self::OperationalAgent { controller_id } => Some(*controller_id), + Self::ExternallyControlled { .. } | Self::Retired => None, + } + } + + fn mode(&self) -> Option<ControllerMode> { + match self { + Self::Human { .. } => Some(ControllerMode::Human), + Self::NarrativePersona { .. } => Some(ControllerMode::NarrativePersona), + Self::OperationalAgent { .. } => Some(ControllerMode::OperationalAgent), + Self::ExternallyControlled { .. } | Self::Retired => None, + } + } + + /// `None` for a retired subject: no caller may ever act for it again. A + /// mirror still returns `Some`, the one caller that could ever act for + /// its scope; the controller lane cannot mint it either, but that caller + /// exists and is comparable. + fn expected_caller(&self) -> Option<CallerId> { + match self { + Self::Human { principal, .. } => Some(CallerId::Principal(principal.clone())), + Self::NarrativePersona { controller_id } | Self::OperationalAgent { controller_id } => { + Some(CallerId::Controller(*controller_id)) + } + Self::ExternallyControlled { consumer } => Some(CallerId::System( + SystemCapability::Consumer { consumer: *consumer }, + )), + Self::Retired => None, + } + } + + fn consumer(&self) -> Option<ConsumerId> { + match self { + Self::ExternallyControlled { consumer } => Some(*consumer), + Self::Human { .. } + | Self::NarrativePersona { .. } + | Self::OperationalAgent { .. } + | Self::Retired => None, + } + } + + fn human_principal(&self) -> Option<&PrincipalId> { + match self { + Self::Human { principal, .. } => Some(principal), + Self::NarrativePersona { .. } + | Self::OperationalAgent { .. } + | Self::ExternallyControlled { .. } + | Self::Retired => None, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(crate) struct DecisionEvent { + pub(crate) id: EventId, + pub(crate) revision: u64, + pub(crate) scope: DecisionScope, + pub(crate) controller_id: ControllerId, + /// The entry exercised. The invocation itself lives on the effect: the + /// invocation is what the caller said, the event is what the world recorded. + pub(crate) affordance: AffordanceId, + /// The claim this act asserted, if it carried speech. Never the text: the + /// event is the world's record and every reader reads it, so it carries the + /// fact id and the statement lives in `facts` alone. + pub(crate) speech: Option<EntityId>, + /// The claim this act displayed, if it carried a visible act. Same rule. + pub(crate) display: Option<EntityId>, + /// Index into the entry's `outcome_bands`. Re-derived and compared at apply + /// and at replay, never trusted. + pub(crate) band: usize, + /// The selected band's slots, lowered through the invocation's bindings. + /// Empty when the selected band names no effects. + pub(crate) effects: Vec<ResolvedOp>, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +struct WorldState { + schema: String, + world_id: WorldId, + revision: u64, + phase: WorldPhase, + owner: PrincipalId, + title: String, + /// Authored at creation and never mutated; the one prose the world says + /// about itself, projected as guidance to every lane. + brief: String, + /// Bound by genesis and never written again; absent from a world with no + /// grammar, so such a world's state and digests are what they were before + /// grammars existed. + #[serde(default, skip_serializing_if = "Option::is_none")] + grammar: Option<GrammarBinding>, + draft_approvals: BTreeSet<PrincipalId>, + subjects: BTreeMap<SubjectId, SubjectState>, + entities: BTreeMap<EntityId, EntityRecord>, + edges: BTreeMap<EdgeId, EdgeRecord>, + positions: BTreeMap<SubjectId, Position>, + /// What each subject holds. Absence is zero at both levels: no stored + /// `Quantity(0)` and no empty inner map, so a duplicate holding is + /// unrepresentable and "nothing" has one shape. + holdings: BTreeMap<SubjectId, BTreeMap<EntityId, Quantity>>, + /// What each subject depends on. Never empty for a present key. + dependencies: BTreeMap<SubjectId, BTreeSet<DependencyTarget>>, + /// One row per `EntityKind::Fact` entity, and no orphan either way. Facts + /// are write-once: declaration and `AssertClaim` are the only writers, and + /// standing never changes after admission. + facts: BTreeMap<EntityId, FactRecord>, + /// One row per `EntityKind::Channel` entity, and no orphan either way. + channels: BTreeMap<EntityId, ChannelRecord>, + /// What each subject knows. The sole owner of who-heard-what: `events` + /// records what was done, and this decides what a subject may act on and + /// what its projection may contain. Never empty for a present key, and + /// absence is "knows nothing of it" — forgetting removes the key. + knowledge: BTreeMap<SubjectId, BTreeMap<EntityId, Knowledge>>, + /// What ground each subject has jurisdiction over, and under which + /// world-declared kind. Never empty for a present key. No subject holds two + /// grants of one kind over overlapping ground, so nothing ever arbitrates + /// between two sources of one permission. + authority: BTreeMap<SubjectId, BTreeSet<AuthorityGrant>>, + /// The offices each institution constitutes, and who sits in them. An + /// incumbent never exercises its institution's opportunity: + /// `controller_assignments` stays the sole answer to who may call, and an + /// office answers the different question of what its incumbent has + /// jurisdiction over. + selection: BTreeMap<SubjectId, BTreeMap<OfficeName, Office>>, + /// Where each kind of grievance goes, and who may bring it. Keyed by + /// neither a subject nor a referent, so it enters no scope digest and is + /// admission-only state. + redress: BTreeMap<GrievanceKindName, Forum>, + /// What each subject has promised. Never empty for a present key. + commitments: BTreeMap<SubjectId, BTreeMap<CommitmentKey, Commitment>>, + /// Lived meaning per subject. Read by projection and by nothing that + /// decides, so it enters `state_digest` and no `ScopePreimage`. + persona_material: BTreeMap<SubjectId, PersonaMaterial>, + /// Pressure *on* each subject, keyed target-major then source. Never empty + /// for a present key; no stored zero magnitude. + pressures: BTreeMap<SubjectId, BTreeMap<PressureSource, PressureMagnitude>>, + /// When each subject was last given a decision opportunity it consumed. + /// Absence means never. The debt term of the attention order and nothing + /// else. + last_opportunity_at: BTreeMap<SubjectId, FictionalMinutes>, + /// Minutes since genesis. The world's only clock, advanced by exactly one + /// command body and read by no wall clock. It enters `state_digest` and no + /// `ScopePreimage`: it is world truth, and it is read by no precondition, so + /// a tick that only advances pressure moves no proposal's binding. + now: FictionalMinutes, + /// The authored scale target, written once by genesis and never mutated. + scale_intent: WorldScaleIntent, + /// Written by genesis and replaced only by `SetLensWeights`; read by the + /// elaborator's draw and by nothing that admits. It enters `state_digest` + /// and no `ScopePreimage`. + lens_weights: LensWeights, + controller_assignments: BTreeMap<DecisionScope, ControllerAssignment>, + /// What an affordance *is*. World-authored, Draft-only, written by + /// `admit_resolved` alone. + affordance_catalog: BTreeMap<AffordanceId, Affordance>, + /// Who may exercise which entry. A grant carries no payload, so a duplicate + /// grant is unrepresentable rather than checked. + affordance_grants: BTreeMap<DecisionScope, BTreeSet<AffordanceId>>, + events: Vec<DecisionEvent>, + state_digest: String, + last_commit_digest: Option<String>, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", rename_all = "snake_case")] +enum WorldEffect { + WorldCreated { + owner: PrincipalId, + title: String, + brief: String, + resolved: ResolvedPatch, + }, + PatchAdmitted { + /// What this commit answered, so `apply_effect` re-decides the same + /// rule `reduce` decided and then proves the answer was satisfied. + answers: Option<PatchAnswer>, + resolved: ResolvedPatch, + }, + DraftApproved { + principal: PrincipalId, + }, + WorldActivated, + DecisionExercised { + opportunity: DecisionOpportunity, + /// The command's own input, kept beside the event rather than inside it: + /// the invocation is what the caller said, the event is what the world + /// recorded, and only the first carries text. + invocation: DecisionInvocation, + event: DecisionEvent, + }, + DecisionDeclined { + opportunity: DecisionOpportunity, + }, + /// The first effect that mutates state for subjects other than one scope. + /// Its gate is the clock capability or the owner, and `apply_effect` + /// re-derives the whole motion, so a forged fulfilment, magnitude, row, or + /// target is one comparison rather than a clause apiece. + TimeAdvanced { + minutes: TickMinutes, + to: FictionalMinutes, + motion: Motion, + }, + /// The owner replaced the world's lens weights. `apply_effect` re-decides + /// the owner and the draw rule. + LensWeightsReplaced { + weights: LensWeights, + }, +} + +/// The exact raw command admitted by the world owner. This is the sole +/// persistent command authority: IDs, callers, retry identity, and effects are +/// derived from this value rather than copied into independently forgeable +/// commit fields. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", content = "command", rename_all = "snake_case")] +enum CommittedCommand { + CreateWorld(CreateWorld), + WorldCommand(CommandEnvelope), +} + +impl CommittedCommand { + fn id(&self) -> CommandId { + match self { + Self::CreateWorld(command) => command.id, + Self::WorldCommand(command) => command.id, + } + } + + fn caller(&self) -> CallerId { + match self { + Self::CreateWorld(command) => CallerId::Principal(command.owner.clone()), + Self::WorldCommand(command) => command.caller.clone(), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +struct WorldCommit { + schema: String, + world_id: WorldId, + command: CommittedCommand, + previous_revision: Option<u64>, + resulting_revision: u64, + previous_state_digest: Option<String>, + resulting_state_digest: String, + previous_commit_digest: Option<String>, + effect: WorldEffect, + committed_at: DateTime<Utc>, + digest: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SubjectSnapshot { + pub id: SubjectId, + pub label: String, + pub kind: SubjectKind, + /// The Aetheria record this subject was imported from, if it was. + pub import_key: Option<ImportKey>, + /// Absent for an externally controlled mirror, which has no controller and + /// no turn. Every reader fails closed on `None`; none gets a default. + pub(crate) controller_id: Option<ControllerId>, + pub controller_mode: Option<ControllerMode>, + pub human_controller: Option<PrincipalId>, + pub affordances: BTreeSet<AffordanceId>, + pub(crate) position: Option<EntityId>, + /// Set for a subject `Retire` ended: no opportunity, no position, no + /// audience, its history kept. The agent's view and the surface read this + /// rather than inferring retirement from an absent position, which a + /// merely unplaced live subject also has. + pub retired: bool, + /// Exactly what the scope digest binds for this subject, carried whole + /// rather than lowered into projections that then have to be diffed back + /// together: its own position, incident routes, holdings, dependencies, + /// grants, delegated offices, known fact keys, controlled channels, and + /// commitments. A counterparty's components never enter. The narrative lane + /// persists this as the "before" an interruption is measured against. + pub(crate) components: ScopeComponents, + pub(crate) offices_held: Vec<OfficeSnapshot>, + /// View-only, and covered by no digest: an institution's own offices, so + /// its controller can see what it lends and to whom. No precondition reads + /// it, and installing a warden therefore does not reject the institution's + /// in-flight proposals — what an institution lends is not what it may do. + pub(crate) offices_granted: Vec<OfficeSnapshot>, + /// View-only: the forums whose standing covers this subject, through the + /// same covering predicate `HasStanding` uses. + pub(crate) redress: Vec<ForumSnapshot>, + /// Every fact this subject holds, with the statement resolved. The sole + /// perception surface: a subject perceives a speech act if and only if it + /// holds `Knowledge` of that act's fact. Ordered by `minted_at` then `fact`. + pub(crate) knowledge: Vec<KnowledgeSnapshot>, + /// Digest-bound, lowered from the one `scope_components` call `snapshot` + /// already makes, so view and digest cannot drift. Carries `past_due`, + /// which the components do not. + pub(crate) commitments: Vec<CommitmentSnapshot>, + /// Pressure on self. View-only: read by no precondition, so covered by no + /// digest. Pressure this subject *sources* is excluded — it is another + /// subject's state, and the actor already sees the commitment that produced + /// it. + pub(crate) pressures: Vec<PressureSnapshot>, + /// This subject's own dependencies, lowered from `components.dependencies` + /// (private to this module) so the play table's omniscient view can print + /// what a `release` may name without reaching into `ScopeComponents` + /// itself. View-only, covered by no digest of its own: it is already bound + /// through `components`. + pub(crate) dependencies: Vec<DependencyTarget>, + /// What the subject carries as lived meaning, if anything was authored. + pub(crate) material: Option<PersonaMaterial>, + /// A projection of `qualifies`, not a stored flag and not a second count: + /// whether this subject already reduces its jurisdiction's scale deficit. + /// The seed brief needs to say which subjects count; recomputing the + /// conjunction outside the kernel would be a second definition of alive. + pub qualified: bool, + /// The greatest `DecisionEvent.revision` whose scope is this subject, or + /// `None` if the subject never acted. Derived from `state.events` alone: + /// no new state, no schema change. The recency marker `projector_knowledge` + /// stamps onto each knowledge row is `acquired_at > last_acted_at`. + pub(crate) last_acted_at: Option<u64>, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct CommitmentSnapshot { + pub(crate) key: CommitmentKey, + pub(crate) kind: CommitmentKind, + pub(crate) counterparty: Option<SubjectId>, + pub(crate) due: FictionalMinutes, + pub(crate) period: Option<TickMinutes>, + pub(crate) statement: Statement, + /// Derived in `snapshot` so a controller does not recompute it against a + /// clock it must be handed anyway. + pub(crate) past_due: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct PressureSnapshot { + pub(crate) source: PressureSource, + pub(crate) magnitude: PressureMagnitude, +} + +/// What a subject knows of one fact. `standing` carries no `EvidenceRef`: a +/// receipt is non-fictional provenance and never enters a subject-facing +/// surface, so a subject learns *that* a fact is canonical and never which +/// receipt admitted it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct KnowledgeSnapshot { + pub(crate) fact: EntityId, + pub(crate) statement: Statement, + pub(crate) standing: FactStandingView, + pub(crate) confidence: Confidence, + /// The speaker a subject sees is `Told { by }`. A subject holding a fact it + /// was never told sees the statement with no speaker, which is correct: it + /// knows the thing, not the telling. + pub(crate) source: KnowledgeSource, + /// The revision of the act that minted this claim, spoken or displayed, + /// when some committed event asserted it. + pub(crate) minted_at: Option<u64>, + /// The revision at which this subject acquired this row, from `Knowledge` + /// directly: always present, unlike `minted_at`, so the recency marker can + /// see a row a patch, a seed, or a ruling landed with no minting event. + pub(crate) acquired_at: u64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum FactStandingView { + Canonical, + Claimed { by: SubjectId }, + /// Stated by the play table. Never produced for a subject-facing knowledge + /// row (`snapshot`'s per-subject projection still collapses it into + /// `Canonical`, because a subject's own perception cannot tell a ruled + /// fact from an ordinarily canonical one); produced only for the + /// omniscient `WorldSnapshot::facts` row the play table's own `table_view` + /// reads. + Ruled, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct OfficeSnapshot { + pub(crate) institution: SubjectId, + pub(crate) office: OfficeName, + pub(crate) incumbent: Option<SubjectId>, + /// What the office actually lends: the institution's live grants whose kind + /// the office delegates. + pub(crate) authority: BTreeSet<AuthorityGrant>, +} + +/// A forum a subject may petition. It carries no standing: a subject learns +/// that it may bring a grievance, not the boundary of everyone else's standing. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct ForumSnapshot { + pub(crate) grievance: GrievanceKindName, + pub(crate) forum: SubjectId, +} + +/// One catalog entry as consumers read it. The whole entry, because every +/// derived surface — tool schemas, signature prose, the typed view's permission +/// block — is a projection of it and a narrower snapshot would be a second +/// vocabulary to keep in step. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub struct AffordanceSnapshot { + pub id: AffordanceId, + pub entry: Affordance, + /// Derived from the world's grammar by this entry's kind; none when the + /// world has no grammar. + pub render_path: Option<RenderPath>, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct ResourceSnapshot { + pub(crate) id: EntityId, + pub(crate) label: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PlaceSnapshot { + pub id: EntityId, + pub label: String, + pub(crate) container: Option<EntityId>, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct RouteSnapshot { + pub(crate) id: EdgeId, + pub(crate) label: String, + pub(crate) from: EntityId, + pub(crate) to: EntityId, + pub(crate) access: AccessKind, + pub(crate) cost: Cost, + pub(crate) open: bool, +} + +/// A declared channel, standing rather than per-subject: `ChannelRecord` +/// carries no label (only `reach` and `controller`), so this is exactly that +/// record plus the canonical id, an omniscient row for the play table's own +/// view. No subject-facing surface reads it; a subject sees only the channels +/// it controls, through its own `components`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct ChannelSnapshot { + pub(crate) id: EntityId, + pub(crate) reach: Reach, + pub(crate) controller: Option<SubjectId>, +} + +/// Every fact the world holds, canonical or not, with its real standing — +/// including `Ruled`, which every subject-facing knowledge row collapses to +/// `Canonical` — and who currently holds it. Built straight from +/// `state.facts` and `state.knowledge`, not from any subject's own knowledge +/// projection, so a fact nobody has been told or shown is still a row here: +/// `mint`, `transfer`, `witness`, and `acquire_knowledge` all take a fact id, +/// and the play table's omniscient view must be able to name one nobody +/// perceives yet. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct FactSnapshot { + pub(crate) id: EntityId, + pub(crate) statement: Statement, + pub(crate) standing: FactStandingView, + pub(crate) known_by: Vec<SubjectId>, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct WorldSnapshot { + pub world_id: WorldId, + pub revision: u64, + pub phase: WorldPhase, + pub owner: PrincipalId, + pub title: String, + pub brief: String, + /// The bound grammar's identity; none for a world with an open catalog. + pub grammar: Option<GrammarIdentity>, + pub draft_approvals: BTreeSet<PrincipalId>, + pub required_approvers: BTreeSet<PrincipalId>, + pub subjects: Vec<SubjectSnapshot>, + pub affordances: Vec<AffordanceSnapshot>, + pub places: Vec<PlaceSnapshot>, + pub(crate) resources: Vec<ResourceSnapshot>, + pub(crate) routes: Vec<RouteSnapshot>, + /// Every declared channel, omniscient: no subject-facing surface reads + /// this field. `communicate`'s audience may name one by id. + pub(crate) channels: Vec<ChannelSnapshot>, + /// Every fact the world holds, omniscient and including facts nobody + /// currently perceives: no subject-facing surface reads this field, which + /// exists for the play table's own `table_view` alone. + pub(crate) facts: Vec<FactSnapshot>, + /// Already ordered by pressure, then attention debt, then id: one owner, so + /// an operator interface, the mesh projection, and any future driver read + /// the same order and + /// none computes its own. + pub opportunities: Vec<DecisionOpportunity>, + /// Everyone in a world shares the clock, and no controller can read a `due` + /// without it. + pub now: FictionalMinutes, + /// The elaborator's surface. There is no global pressure register and no + /// commitment gazetteer. + pub boundaries: Vec<CausalBoundary>, + pub scale_deficit: Vec<ScaleDeficitRow>, + pub lens_weights: LensWeights, + pub state_digest: String, + pub last_commit_digest: Option<String>, +} + +/// One committed act as the human operator's story feed reads it. It is the +/// operator surface, not a perception surface: no subject-facing lane receives +/// it, and `SelectedDecision` never sees an event log at all. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OperatorEvent { + pub revision: u64, + pub speaker: SubjectId, + pub speaker_label: String, + pub speech: Option<Statement>, + pub display: Option<Statement>, + /// The affordance kind the act exercised. + pub verb: String, + /// How the world's grammar renders that verb; none in a world with no + /// grammar. + pub render_path: Option<RenderPath>, + /// What the act bound each of the verb's roles to, in the invocation's + /// order. + pub roles: Vec<BoundRole>, +} + +/// One role an act bound, with the label of what it was bound to. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BoundRole { + pub role: String, + pub target: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CommitReceipt { + pub command_id: CommandId, + pub resulting_revision: u64, + pub resulting_state_digest: String, + pub commit_digest: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CreationReceipt { + pub command_id: CommandId, + pub world_id: WorldId, + pub resulting_state_digest: String, + pub commit_digest: String, +} + +impl CreationReceipt { + fn from_commit(commit: &WorldCommit) -> Result<Self, KernelError> { + let CommittedCommand::CreateWorld(command) = &commit.command else { + return Err(KernelError::Invariant( + "world genesis receipt does not point to a creation command".into(), + )); + }; + let WorldEffect::WorldCreated { .. } = &commit.effect else { + return Err(KernelError::Invariant( + "world genesis receipt does not point to genesis".into(), + )); + }; + Ok(Self { + command_id: command.id, + world_id: commit.world_id, + resulting_state_digest: commit.resulting_state_digest.clone(), + commit_digest: commit.digest.clone(), + }) + } +} + +impl From<&WorldCommit> for CommitReceipt { + fn from(commit: &WorldCommit) -> Self { + Self { + command_id: commit.command.id(), + resulting_revision: commit.resulting_revision, + resulting_state_digest: commit.resulting_state_digest.clone(), + commit_digest: commit.digest.clone(), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum SubmitReceipt { + Applied(CommitReceipt), + AlreadyApplied(CommitReceipt), +} + +#[derive(Debug, Error)] +pub enum KernelError { + #[error("command ID must be a UUID")] + InvalidCommandId, + #[error("world title must not be empty")] + EmptyTitle, + #[error("world owner or human controller principal must be canonical and nonempty")] + EmptyPrincipal, + #[error("patch rejected: {0:?}")] + PatchRejected(Vec<Mismatch>), + #[error("action rejected: {0:?}")] + ActionRejected(Vec<ActionMismatch>), + #[error("command targets another world")] + WorldMismatch, + #[error("authenticated caller does not match the command")] + AuthenticationMismatch, + #[error("caller does not own this world")] + Unauthorized, + #[error("command requires phase {expected:?}, current phase is {actual:?}")] + WrongPhase { + expected: WorldPhase, + actual: WorldPhase, + }, + #[error("caller is not a required draft approver")] + NotDraftApprover, + #[error("caller has already approved this draft")] + DraftAlreadyApproved, + #[error("draft is missing required approvals: {0:?}")] + MissingApprovals(Vec<PrincipalId>), + #[error("this world derives no such decision opportunity")] + OpportunityMismatch, + #[error("decision scope changed since the proposal was bound")] + ScopeChanged { + scope: DecisionScope, + expected: ScopeDigest, + actual: ScopeDigest, + }, + #[error("caller does not control this decision scope")] + ControllerMismatch, + #[error("decision affordance is not granted by the opportunity")] + AffordanceDenied, + #[error("expected revision {expected}, current revision {actual}")] + RevisionMismatch { expected: u64, actual: u64 }, + #[error("command ID was reused with different content")] + CommandIdConflict, + #[error("world creation ID was reused with different content")] + CreationConflict, + #[error("world creation target already contains another world")] + CreationTargetOccupied, + #[error("world has not been created")] + WorldNotCreated, + #[error("opened store contains another world")] + OpenedWorldMismatch, + #[error("world ownership is uncertain after command {command_id:?}; drop and reopen")] + RecoveryRequired { command_id: CommandId }, + #[error("world store path no longer names the owned database; drop and reopen explicitly")] + OwnershipLost, + #[error("canonical serialization failed: {0}")] + Serialization(String), + #[error("world store operation failed: {0}")] + Store(String), + #[error("world journal is corrupt: {0}")] + CorruptJournal(String), + #[error("private reducer invariant failed: {0}")] + Invariant(String), + #[error("an active patch must answer a derived boundary or a nonzero deficit")] + AnswerRequired, + #[error("this world derives no such boundary or deficit")] + AnswerNotDerived, + #[error("the admitted patch does not satisfy the boundary or deficit it answered")] + AnswerNotSatisfied, +} + +impl KernelError { + fn requires_owner_restart(&self) -> bool { + matches!( + self, + Self::RecoveryRequired { .. } + | Self::OwnershipLost + | Self::Store(_) + | Self::CorruptJournal(_) + | Self::Invariant(_) + ) + } +} + +impl From<journal::JournalError> for KernelError { + fn from(error: journal::JournalError) -> Self { + match error { + journal::JournalError::WorldMismatch => Self::OpenedWorldMismatch, + journal::JournalError::RecoveryRequired { command_id } => { + Self::RecoveryRequired { command_id } + } + journal::JournalError::OwnershipLost => Self::OwnershipLost, + journal::JournalError::Store(detail) => Self::Store(detail), + journal::JournalError::Corrupt(detail) => Self::CorruptJournal(detail), + } + } +} + +struct WorldKernel { + state: WorldState, + journal: journal::WorldJournal, +} + +struct PreparedCreation { + command: CreateWorld, + world_id: WorldId, + owner: PrincipalId, + title: String, + brief: String, + resolved: ResolvedPatch, +} + +fn prepare_creation( + input: CreateWorld, + authenticated: &AuthenticatedCaller, +) -> Result<PreparedCreation, KernelError> { + let CallerId::Principal(authenticated_principal) = &authenticated.caller else { + return Err(KernelError::AuthenticationMismatch); + }; + validate_principal(&input.owner)?; + if &input.owner != authenticated_principal { + return Err(KernelError::AuthenticationMismatch); + } + let title = normalize_title(&input.title)?; + let brief = input.brief.trim().to_owned(); + // The world's own identity is not world structure, and it feeds every + // derived ID, so it is minted before resolution rather than by it. + let world_id = WorldId::issue(); + let resolved = patch::resolve_patch( + &WorldState::empty( + world_id, + input.owner.clone(), + title.clone(), + input.grammar.clone(), + ), + input.id, + &input.patch, + Some(&input.scale_intent), + Some(&input.lens_weights), + ) + .map_err(KernelError::PatchRejected)?; + require_ruler(&CallerId::Principal(input.owner.clone()), &resolved) + .map_err(KernelError::PatchRejected)?; + Ok(PreparedCreation { + world_id, + owner: input.owner.clone(), + title, + brief, + resolved, + command: input, + }) +} + +impl WorldKernel { + fn initialize( + empty: journal::EmptyWorldJournal, + prepared: PreparedCreation, + ) -> Result<(Self, CreationReceipt), KernelError> { + let world_id = prepared.world_id; + let effect = WorldEffect::WorldCreated { + owner: prepared.owner, + title: prepared.title, + brief: prepared.brief, + resolved: prepared.resolved, + }; + let mut state = WorldState::genesis(world_id, &prepared.command, &effect)?; + let mut genesis = WorldCommit { + schema: COMMIT_SCHEMA.into(), + world_id, + command: CommittedCommand::CreateWorld(prepared.command), + previous_revision: None, + resulting_revision: 0, + previous_state_digest: None, + resulting_state_digest: state.state_digest.clone(), + previous_commit_digest: None, + effect, + committed_at: Utc::now(), + digest: String::new(), + }; + genesis.digest = commit_digest(&genesis)?; + state.last_commit_digest = Some(genesis.digest.clone()); + let receipt = CreationReceipt::from_commit(&genesis)?; + let journal = empty.initialize(&state, &genesis)?; + Ok((Self { state, journal }, receipt)) + } + + fn retry_creation(&self, prepared: &PreparedCreation) -> Result<CreationReceipt, KernelError> { + self.journal.ensure_healthy()?; + let Some(commit) = self.journal.commit_for(prepared.command.id) else { + return Err(KernelError::CreationTargetOccupied); + }; + if commit.command != CommittedCommand::CreateWorld(prepared.command.clone()) + || !matches!(&commit.effect, WorldEffect::WorldCreated { .. }) + { + return Err(KernelError::CreationConflict); + } + CreationReceipt::from_commit(commit) + } + + #[cfg(test)] + fn create( + path: impl AsRef<Path>, + input: CreateWorld, + authenticated: &AuthenticatedCaller, + ) -> Result<(Self, CreationReceipt), KernelError> { + let prepared = prepare_creation(input, authenticated)?; + match journal::WorldJournal::open_owner(path.as_ref())? { + journal::JournalOpen::Empty(empty) => Self::initialize(empty, prepared), + journal::JournalOpen::Live { journal, state } => { + let kernel = Self { state, journal }; + let receipt = kernel.retry_creation(&prepared)?; + Ok((kernel, receipt)) + } + } + } + + #[cfg(test)] + fn open(path: impl AsRef<Path>, expected_world_id: WorldId) -> Result<Self, KernelError> { + let (journal, state) = journal::WorldJournal::open(path.as_ref(), expected_world_id)?; + Ok(Self { state, journal }) + } + + fn snapshot(&self) -> Result<WorldSnapshot, KernelError> { + self.journal.ensure_healthy()?; + snapshot(&self.state) + } + + /// The human operator's story feed. Separate from `snapshot` so that no + /// controller lane can reach an unscoped event log: a `WorldSnapshot` field + /// no consumer may read in full would be a loaded gun with a comment on it. + fn operator_log(&self) -> Result<Vec<OperatorEvent>, KernelError> { + self.journal.ensure_healthy()?; + // An event records what the world did; the invocation, which names the + // bound roles, lives on the commit that produced it. + let invocations: BTreeMap<EventId, &DecisionInvocation> = self + .journal + .commits() + .filter_map(|commit| match &commit.effect { + WorldEffect::DecisionExercised { + invocation, event, .. + } => Some((event.id, invocation)), + _ => None, + }) + .collect(); + operator_log(&self.state, &invocations) + } + + /// The tick driver's opportunity list, in the same order a snapshot + /// carries it. Separate from `snapshot` for the reason `agency_graph` is: + /// only the tick driver reads it. + fn opportunities(&self) -> Result<Vec<DecisionOpportunity>, KernelError> { + self.journal.ensure_healthy()?; + Ok(order_opportunities( + &self.state, + derive_opportunities(&self.state)?, + )) + } + + /// How many clock advances the world has committed: the next tick's + /// ordinal, held by the world and read from its journal. Separate from + /// `snapshot` for the reason `opportunities` is: only the tick driver + /// reads it. + fn clock_advances(&self) -> Result<u64, KernelError> { + self.journal.ensure_healthy()?; + Ok(self + .journal + .commits() + .filter(|commit| matches!(commit.effect, WorldEffect::TimeAdvanced { .. })) + .count() as u64) + } + + /// The scheduler's adjacency projection. Separate from `snapshot` for the + /// same reason `operator_log` is: it is wider than any subject view, so a + /// `WorldSnapshot` field carrying it would be reachable from every prompt + /// builder in the process. + fn agency_graph(&self) -> Result<AgencyGraph, KernelError> { + self.journal.ensure_healthy()?; + Ok(agency_graph(&self.state)) + } + + fn submit( + &mut self, + command: CommandEnvelope, + authenticated: &AuthenticatedCaller, + ) -> Result<SubmitReceipt, KernelError> { + let committed_at = Utc::now(); + self.journal.ensure_healthy()?; + if command.world_id != self.state.world_id { + return Err(KernelError::WorldMismatch); + } + if command.caller != authenticated.caller { + return Err(KernelError::AuthenticationMismatch); + } + // Retry identity is caller plus body. The expected revision is stamped by + // the mailbox owner rather than supplied by the caller, so it is not part + // of what makes a command the same command. + if let Some(commit) = self.committed_command(command.id) { + let CommittedCommand::WorldCommand(committed) = &commit.command else { + return Err(KernelError::CommandIdConflict); + }; + return if committed.caller == command.caller && committed.body == command.body { + Ok(SubmitReceipt::AlreadyApplied(CommitReceipt::from(commit))) + } else { + Err(KernelError::CommandIdConflict) + }; + } + if command.expected_revision != self.state.revision { + return Err(KernelError::RevisionMismatch { + expected: command.expected_revision, + actual: self.state.revision, + }); + } + + let effect = reduce(&self.state, &command)?; + let mut candidate = self.state.clone(); + apply_effect(&mut candidate, command.id, &command.caller, &effect)?; + candidate.revision = candidate + .revision + .checked_add(1) + .ok_or_else(|| KernelError::Serialization("world revision overflow".into()))?; + candidate.state_digest = state_digest(&candidate)?; + + let mut commit = WorldCommit { + schema: COMMIT_SCHEMA.into(), + world_id: self.state.world_id, + command: CommittedCommand::WorldCommand(command), + previous_revision: Some(self.state.revision), + resulting_revision: candidate.revision, + previous_state_digest: Some(self.state.state_digest.clone()), + resulting_state_digest: candidate.state_digest.clone(), + previous_commit_digest: self.state.last_commit_digest.clone(), + effect, + committed_at, + digest: String::new(), + }; + commit.digest = commit_digest(&commit)?; + candidate.last_commit_digest = Some(commit.digest.clone()); + + self.journal.commit(&candidate, &commit)?; + self.state = candidate; + Ok(SubmitReceipt::Applied(CommitReceipt::from(&commit))) + } + + fn committed_command(&self, command_id: CommandId) -> Option<&WorldCommit> { + self.journal.commit_for(command_id) + } + + fn controller_receipt( + &self, + command_id: CommandId, + opportunity: &DecisionOpportunity, + invocation: &DecisionInvocation, + ) -> Result<Option<CommitReceipt>, KernelError> { + self.journal.ensure_healthy()?; + let Some(commit) = self.committed_command(command_id) else { + return Ok(None); + }; + let CommittedCommand::WorldCommand(CommandEnvelope { + body: + CommandBody::ExerciseDecision { + opportunity: committed_opportunity, + invocation: committed_invocation, + }, + .. + }) = &commit.command + else { + return Err(KernelError::CommandIdConflict); + }; + if committed_opportunity != opportunity || committed_invocation != invocation { + return Err(KernelError::CommandIdConflict); + } + Ok(Some(CommitReceipt::from(commit))) + } + + fn controller_decline_receipt( + &self, + command_id: CommandId, + opportunity: &DecisionOpportunity, + ) -> Result<Option<CommitReceipt>, KernelError> { + self.journal.ensure_healthy()?; + let Some(commit) = self.committed_command(command_id) else { + return Ok(None); + }; + let CommittedCommand::WorldCommand(CommandEnvelope { + body: + CommandBody::DeclineDecision { + opportunity: committed_opportunity, + }, + .. + }) = &commit.command + else { + return Err(KernelError::CommandIdConflict); + }; + if committed_opportunity != opportunity { + return Err(KernelError::CommandIdConflict); + } + Ok(Some(CommitReceipt::from(commit))) + } +} + +fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result<WorldEffect, KernelError> { + // The one admission rule for internal capabilities, stated here and again + // at the top of `apply_effect`: `reduce` decides and `apply_effect` + // re-decides, which is how every gate in this file is written. + require_system_capability(&command.caller, &command.body)?; + match &command.body { + CommandBody::ApproveDraft => { + require_phase(state, WorldPhase::Draft)?; + let CallerId::Principal(principal) = &command.caller else { + return Err(KernelError::NotDraftApprover); + }; + if !required_approvers(state).contains(principal) { + return Err(KernelError::NotDraftApprover); + } + if state.draft_approvals.contains(principal) { + return Err(KernelError::DraftAlreadyApproved); + } + Ok(WorldEffect::DraftApproved { + principal: principal.clone(), + }) + } + CommandBody::ActivateWorld => { + require_owner(state, &command.caller)?; + require_phase(state, WorldPhase::Draft)?; + let missing: Vec<_> = required_approvers(state) + .difference(&state.draft_approvals) + .cloned() + .collect(); + if !missing.is_empty() { + return Err(KernelError::MissingApprovals(missing)); + } + Ok(WorldEffect::WorldActivated) + } + CommandBody::ExerciseDecision { + opportunity, + invocation, + } => { + require_phase(state, WorldPhase::Active)?; + let current = exact_opportunity(state, opportunity)?; + let assignment = state + .controller_assignments + .get(¤t.scope) + .ok_or(KernelError::OpportunityMismatch)?; + if assignment.expected_caller().as_ref() != Some(&command.caller) { + return Err(KernelError::ControllerMismatch); + } + let granted = require_granted(state, ¤t, invocation.affordance)?; + let event = action::exercise(state, command.id, ¤t, &granted, invocation)?; + Ok(WorldEffect::DecisionExercised { + opportunity: current, + invocation: invocation.clone(), + event, + }) + } + CommandBody::DeclineDecision { opportunity } => { + require_phase(state, WorldPhase::Active)?; + let current = exact_opportunity(state, opportunity)?; + let assignment = state + .controller_assignments + .get(¤t.scope) + .ok_or(KernelError::OpportunityMismatch)?; + if assignment.expected_caller().as_ref() != Some(&command.caller) { + return Err(KernelError::ControllerMismatch); + } + Ok(WorldEffect::DecisionDeclined { + opportunity: current, + }) + } + CommandBody::AdvanceTime { minutes } => { + // There is no time in Draft: a world under construction has no due + // dates to cross. + require_phase(state, WorldPhase::Active)?; + require_clock_caller(state, &command.caller)?; + let to = state + .now + .checked_add(*minutes) + .ok_or_else(|| KernelError::Serialization("world clock overflow".into()))?; + // A tick with an empty motion is still a commit: the clock moved, + // which is a canonical change. That is why the clock is a state + // field rather than a patch operation. + Ok(WorldEffect::TimeAdvanced { + minutes: *minutes, + to, + motion: clock::derive_motion(state, to), + }) + } + CommandBody::AdmitPatch { answers, patch } => { + // Answer before authority, because the jurisdiction check reads the + // answer and a missing one must read as `AnswerRequired` rather + // than `Unauthorized`. Resolution before confinement, because + // confinement reads draft-resolved referents and a structurally + // broken patch should return its complete mismatch set rather than + // a jurisdiction complaint about a reference that does not resolve. + require_answer( + state, + &command.caller, + answers.as_ref(), + !(patch.declarations.is_empty() && patch.evidence.is_empty()), + )?; + let confinement = require_patch_author(state, &command.caller, answers.as_ref())?; + let resolved = patch::resolve_patch(state, command.id, patch, None, None) + .map_err(KernelError::PatchRejected)?; + require_ruler(&command.caller, &resolved).map_err(KernelError::PatchRejected)?; + if let Some(ground) = confinement { + confine_to_ground(state, &resolved, ground).map_err(KernelError::PatchRejected)?; + } + Ok(WorldEffect::PatchAdmitted { + answers: answers.clone(), + resolved, + }) + } + CommandBody::SetLensWeights { weights } => { + require_owner(state, &command.caller)?; + if !weights.draws() { + return Err(KernelError::PatchRejected(vec![ + Mismatch::LensWeightsNeverDraw, + ])); + } + // Admission first, then effect: a caller who may not set weights, + // or a set that never draws, is refused as such even when it + // equals the current set. Only an admitted set can be a no-op. + if weights.weighs_the_same_as(&state.lens_weights) { + return Err(KernelError::PatchRejected(vec![ + Mismatch::NoCanonicalChange, + ])); + } + Ok(WorldEffect::LensWeightsReplaced { + weights: weights.clone(), + }) + } + } +} + +/// A system capability is admitted for exactly one command body and nothing +/// else. Stated once here, reached by `reduce` and by `apply_effect`. +fn require_system_capability(caller: &CallerId, body: &CommandBody) -> Result<(), KernelError> { + let CallerId::System(capability) = caller else { + return Ok(()); + }; + let admitted = matches!( + (capability, body), + (SystemCapability::Clock, CommandBody::AdvanceTime { .. }) + | (SystemCapability::Play, CommandBody::AdvanceTime { .. }) + | ( + SystemCapability::Elaborator { .. } + | SystemCapability::Consumer { .. } + | SystemCapability::Play, + CommandBody::AdmitPatch { .. } + ) + ); + if admitted { + Ok(()) + } else { + Err(KernelError::Unauthorized) + } +} + +/// The owner may tick from an interface; the tick task may tick with no +/// session. Nothing +/// else may tick. +fn require_clock_caller(state: &WorldState, caller: &CallerId) -> Result<(), KernelError> { + if matches!( + caller, + CallerId::System(SystemCapability::Clock) | CallerId::System(SystemCapability::Play) + ) { + Ok(()) + } else { + require_owner(state, caller) + } +} + +/// Answering is what lets an Active patch declare. Draft answers nothing: +/// `SeedRequest` — the ontology's draft-phase answer — is not inhabited, so +/// genesis and draft elaboration answer nothing. In Active, a patch that only +/// changes components of existing structure is the operator's hand and answers +/// nothing; a patch that declares or admits evidence is elaboration, and +/// elaboration answers a boundary the kernel currently derives or a +/// jurisdiction whose deficit is nonzero. +fn require_answer( + state: &WorldState, + caller: &CallerId, + answers: Option<&PatchAnswer>, + declares: bool, +) -> Result<(), KernelError> { + if caller == &CallerId::System(SystemCapability::Play) && state.phase == WorldPhase::Draft { + return Err(KernelError::WrongPhase { + expected: WorldPhase::Active, + actual: state.phase, + }); + } + match (state.phase, answers) { + (WorldPhase::Draft, None) => Ok(()), + (WorldPhase::Draft, Some(_)) => Err(KernelError::AnswerNotDerived), + (WorldPhase::Active, None) if declares => { + if caller == &CallerId::System(SystemCapability::Play) { + Ok(()) + } else { + Err(KernelError::AnswerRequired) + } + } + (WorldPhase::Active, None) => Ok(()), + (WorldPhase::Active, Some(PatchAnswer::Boundary(claimed))) => { + exact_boundary(state, claimed).map(|_| ()) + } + (WorldPhase::Active, Some(PatchAnswer::Deficit(jurisdiction))) => { + if jurisdiction_deficit(state, *jurisdiction)? > 0 { + Ok(()) + } else { + Err(KernelError::AnswerNotDerived) + } + } + } +} + +/// The total deficit of one jurisdiction, which is what an answer must strictly +/// reduce. +fn jurisdiction_deficit( + state: &WorldState, + jurisdiction: JurisdictionKey, +) -> Result<u64, KernelError> { + Ok(derive_scale_deficit(state)? + .into_iter() + .filter(|row| row.jurisdiction == jurisdiction) + .map(|row| u64::from(row.deficit)) + .sum()) +} + +/// A human principal joins `required_approvers`, so only the lane that builds +/// revision 0 from nothing may bind one. The predicate reads state, never the +/// caller. It takes the two fields it inspects rather than a whole +/// `WorldState` so the genesis lane, which resolves declarations before any +/// `WorldState` exists, can call the same owner instead of hand-copying the +/// literal it would otherwise always evaluate to. +fn admits_human(revision: u64, subjects: &BTreeMap<SubjectId, SubjectState>) -> bool { + revision == 0 && subjects.is_empty() +} + +impl WorldState { + /// The world before any structure. Genesis resolves its own patch against + /// this value, so the genesis lane and `AdmitPatch` share one resolver + /// signature instead of hand-passing empty partitions. + fn empty( + world_id: WorldId, + owner: PrincipalId, + title: String, + grammar: Option<GrammarBinding>, + ) -> Self { + Self { + schema: STATE_SCHEMA.into(), + world_id, + revision: 0, + phase: WorldPhase::Draft, + owner, + title, + brief: String::new(), + grammar, + draft_approvals: BTreeSet::new(), + subjects: BTreeMap::new(), + entities: BTreeMap::new(), + edges: BTreeMap::new(), + positions: BTreeMap::new(), + holdings: BTreeMap::new(), + dependencies: BTreeMap::new(), + facts: BTreeMap::new(), + channels: BTreeMap::new(), + knowledge: BTreeMap::new(), + authority: BTreeMap::new(), + selection: BTreeMap::new(), + redress: BTreeMap::new(), + commitments: BTreeMap::new(), + persona_material: BTreeMap::new(), + pressures: BTreeMap::new(), + last_opportunity_at: BTreeMap::new(), + now: FictionalMinutes::default(), + scale_intent: WorldScaleIntent::default(), + // Never persisted: genesis overwrites it, and `verify_state_shape` + // refuses a stored set that never draws. + lens_weights: LensWeights::default(), + controller_assignments: BTreeMap::new(), + affordance_catalog: BTreeMap::new(), + affordance_grants: BTreeMap::new(), + events: Vec::new(), + state_digest: String::new(), + last_commit_digest: None, + } + } + + fn genesis( + world_id: WorldId, + command: &CreateWorld, + effect: &WorldEffect, + ) -> Result<Self, KernelError> { + let WorldEffect::WorldCreated { + owner, + title, + brief, + resolved, + } = effect + else { + return Err(KernelError::Invariant( + "genesis state requires a world-created effect".into(), + )); + }; + validate_principal(&command.owner)?; + let expected_title = normalize_title(&command.title)?; + if owner != &command.owner || title != &expected_title { + return Err(KernelError::Invariant( + "genesis effect does not match the admitted creation command".into(), + )); + } + // The same re-derive-and-compare that `apply_committed_command` runs for + // every other command. Deterministic allocation is what lets one + // equality replace a field-by-field binding zip. + let mut state = Self::empty(world_id, owner.clone(), title.clone(), command.grammar.clone()); + state.brief = brief.clone(); + let expected = patch::resolve_patch( + &state, + command.id, + &command.patch, + Some(&command.scale_intent), + Some(&command.lens_weights), + ) + .map_err(KernelError::PatchRejected)?; + if &expected != resolved { + return Err(KernelError::Invariant( + "genesis effect does not derive from its creation command".into(), + )); + } + require_ruler(&CallerId::Principal(command.owner.clone()), resolved).map_err(|_| { + KernelError::Invariant( + "genesis effect rules or mints without the play authority".into(), + ) + })?; + // Genesis resolves to revision 0 itself: `state.revision` never + // advances past 0 for the creating commit (`resulting_revision: 0`), + // unlike every later commit, which resolves to `state.revision + 1`. + let genesis_revision = state.revision; + admit_resolved(&mut state, resolved, genesis_revision)?; + state.state_digest = state_digest(&state)?; + Ok(state) + } +} + +/// The only writer of every ontology partition. Both admission lanes mutate +/// through it in one fixed order — entities, routes, subjects, operations — so a +/// patch may relocate along a route it declares. It re-derives every structural +/// claim from `state`, so an effect that skipped resolution dies here. +fn admit_resolved( + state: &mut WorldState, + resolved: &ResolvedPatch, + resolves_to: u64, +) -> Result<(), KernelError> { + if resolved.declares_nothing() && resolved.operations.is_empty() { + return Err(KernelError::Invariant( + "admitted patch carries no canonical change".into(), + )); + } + let humans_admitted = admits_human(state.revision, &state.subjects); + for entity in &resolved.entities { + if !patch::is_canonical_text(&entity.entity.label) { + return Err(KernelError::Invariant( + "admitted entity label is not canonical".into(), + )); + } + if let Some(container) = entity.entity.container + && (entity.entity.kind != EntityKind::Place + || state + .entities + .get(&container) + .is_none_or(|record| record.kind != EntityKind::Place)) + { + return Err(KernelError::Invariant( + "admitted container does not name a canonical place".into(), + )); + } + if state + .entities + .insert(entity.entity_id, entity.entity.clone()) + .is_some() + { + return Err(KernelError::Invariant( + "admitted entity ID collision".into(), + )); + } + if !patch::containment_terminates(entity.entity_id, &state.entities) { + return Err(KernelError::Invariant( + "admitted place contains itself".into(), + )); + } + } + for route in &resolved.routes { + let (from, to) = route.edge.endpoints(); + let endpoint_is_place = |entity_id: &EntityId| { + state + .entities + .get(entity_id) + .is_some_and(|record| record.kind == EntityKind::Place) + }; + if !patch::is_canonical_text(route.edge.label()) + || !endpoint_is_place(&from) + || !endpoint_is_place(&to) + || from == to + || !patch::is_valid_cost(route.edge.cost()) + { + return Err(KernelError::Invariant( + "admitted route is noncanonical or does not join two places".into(), + )); + } + if state + .edges + .insert(route.edge_id, route.edge.clone()) + .is_some() + { + return Err(KernelError::Invariant("admitted route ID collision".into())); + } + } + let mut controller_ids: BTreeSet<ControllerId> = state + .controller_assignments + .values() + .filter_map(ControllerAssignment::id) + .collect(); + for entry in &resolved.affordances { + // The catalog's only writer holds the same grammar check the resolver + // runs, so an effect resolved elsewhere cannot install an entry the + // bound grammar refuses. + if state.grammar.as_ref().is_some_and(|grammar| { + grammar + .refusal(&entry.affordance.kind, &entry.affordance.roles) + .is_some() + }) { + return Err(KernelError::Invariant( + "admitted affordance is outside the bound grammar".into(), + )); + } + if state + .affordance_catalog + .insert(entry.affordance_id, entry.affordance.clone()) + .is_some() + { + return Err(KernelError::Invariant( + "admitted affordance ID collision".into(), + )); + } + } + // The subjects map's only writer holds the same injectivity the resolver + // checks, decided by the same function. + { + let held = patch::held_import_keys(state.subjects.values()); + let mut declared = BTreeSet::new(); + for subject in &resolved.subjects { + if let Some(key) = &subject.subject.import_key + && patch::import_key_fault(key, &held, &mut declared).is_some() + { + return Err(KernelError::Invariant( + "admitted subject's import key is malformed, held or repeated".into(), + )); + } + } + } + for subject in &resolved.subjects { + let scope = DecisionScope { + subject_id: subject.subject_id, + }; + if !patch::is_canonical_text(&subject.subject.label) { + return Err(KernelError::Invariant( + "admitted subject label is not canonical".into(), + )); + } + validate_assignment(&subject.controller)?; + if matches!(subject.controller, ControllerAssignment::Human { .. }) && !humans_admitted { + return Err(KernelError::Invariant( + "only world genesis may bind a human controller".into(), + )); + } + // Controller-shaped, both ways: a mirror receives no affordance, and + // every other controller must receive one. That is what makes the + // mirror's exclusion from opportunity derivation consistent rather than + // merely enforced. + if matches!( + subject.controller, + ControllerAssignment::ExternallyControlled { .. } + ) != subject.affordances.is_empty() + { + return Err(KernelError::Invariant( + "admitted subject's controller and affordance grant do not pair".into(), + )); + } + if let Some(position) = subject.position + && state + .entities + .get(&position.place) + .is_none_or(|entity| entity.kind != EntityKind::Place) + { + return Err(KernelError::Invariant( + "admitted position does not name a canonical place".into(), + )); + } + if let Some(controller_id) = subject.controller.id() + && !controller_ids.insert(controller_id) + { + return Err(KernelError::Invariant( + "admitted controller ID collision".into(), + )); + } + if state + .subjects + .insert(subject.subject_id, subject.subject.clone()) + .is_some() + || state + .controller_assignments + .insert(scope, subject.controller.clone()) + .is_some() + { + return Err(KernelError::Invariant( + "admitted subject or scope ID collision".into(), + )); + } + if let Some(position) = subject.position + && state + .positions + .insert(subject.subject_id, position) + .is_some() + { + return Err(KernelError::Invariant( + "admitted position collides with an existing one".into(), + )); + } + for affordance_id in &subject.affordances { + if !state.affordance_catalog.contains_key(affordance_id) { + return Err(KernelError::Invariant( + "admitted grant names no catalog entry".into(), + )); + } + state + .affordance_grants + .entry(scope) + .or_default() + .insert(*affordance_id); + } + } + // Facts and channels: one `entities` row and one payload row per + // declaration, written together so the bijection has one writer. + for declared in &resolved.facts { + let claimed_by_a_stranger = match &declared.fact.standing { + FactStanding::Canonical { evidence } => { + !(patch::is_canonical_text(evidence.text()) && resolved.evidence.contains(evidence)) + } + FactStanding::Claimed { by } => !state.subjects.contains_key(by), + FactStanding::Ruled => false, + }; + if !patch::is_canonical_text(&declared.entity.label) + || !patch::is_canonical_text(declared.fact.statement.as_str()) + || declared.entity.kind != EntityKind::Fact + || claimed_by_a_stranger + { + return Err(KernelError::Invariant( + "admitted fact is noncanonical, unevidenced, or asserted by no live subject".into(), + )); + } + if state + .entities + .insert(declared.entity_id, declared.entity.clone()) + .is_some() + || state + .facts + .insert(declared.entity_id, declared.fact.clone()) + .is_some() + { + return Err(KernelError::Invariant("admitted fact ID collision".into())); + } + } + for declared in &resolved.channels { + if !patch::is_canonical_text(&declared.entity.label) + || declared.entity.kind != EntityKind::Channel + || !channel_referents_exist(state, &declared.channel) + { + return Err(KernelError::Invariant( + "admitted channel is noncanonical or names no live reach".into(), + )); + } + if state + .entities + .insert(declared.entity_id, declared.entity.clone()) + .is_some() + || state + .channels + .insert(declared.entity_id, declared.channel.clone()) + .is_some() + { + return Err(KernelError::Invariant( + "admitted channel ID collision".into(), + )); + } + } + if let Some(intent) = &resolved.scale_intent { + state.scale_intent = intent.clone(); + } + if let Some(weights) = &resolved.lens_weights { + state.lens_weights = weights.clone(); + } + apply_operations(state, &resolved.operations, &resolved.evidence, resolves_to) +} + +/// The component writer for every lane: snapshot the before-totals for every +/// resource the operations name, apply each operation, accumulate the ledger +/// deltas, and prove conservation once. Declaration admission calls it after its +/// declaration loops; an exercised affordance's lowered effects call it +/// directly. One writer, one conservation statement. +/// +/// A forged effect reaches this function without ever passing the resolver, so +/// conservation is re-derived over the committed partitions, against the same +/// equation, with `before` read from state rather than from anything the effect +/// asserts. +fn apply_operations( + state: &mut WorldState, + operations: &[ResolvedOp], + evidence: &[EvidenceRef], + resolves_to: u64, +) -> Result<(), KernelError> { + let mut deltas: BTreeMap<EntityId, LedgerDelta> = BTreeMap::new(); + for operation in operations { + for resource in operation_resources(operation) { + deltas.entry(resource).or_default().before = resource_total(state, resource); + } + } + for operation in operations { + apply_operation(state, operation, evidence, resolves_to)?; + match operation { + ResolvedOp::Transform { + from_resource, + into_resource, + qty, + .. + } => { + deltas.entry(*from_resource).or_default().spent += u128::from(qty.0); + deltas.entry(*into_resource).or_default().gained += u128::from(qty.0); + } + ResolvedOp::Consume { resource, qty, .. } => { + deltas.entry(*resource).or_default().consumed += u128::from(qty.0); + } + ResolvedOp::Admit { resource, qty, .. } => { + deltas.entry(*resource).or_default().admitted += u128::from(qty.0); + } + ResolvedOp::Mint { resource, qty, .. } => { + deltas.entry(*resource).or_default().admitted += u128::from(qty.0); + } + _ => {} + } + } + for (resource, delta) in &mut deltas { + delta.after = resource_total(state, *resource); + } + if patch::check_ledger(&deltas).is_some() { + return Err(KernelError::Invariant("custody does not conserve".into())); + } + // Disjointness, re-derived over the committed partitions for the same + // reason conservation is: a forged effect reaches this function without + // passing the resolver. + if operations.iter().any(|operation| { + matches!( + operation, + ResolvedOp::GrantAuthority { .. } + | ResolvedOp::OpenOffice { .. } + | ResolvedOp::InstallIncumbent { .. } + ) + }) && overlapping_holder(state).is_some() + { + return Err(KernelError::Invariant( + "one subject holds two overlapping jurisdictions of one kind".into(), + )); + } + Ok(()) +} + +/// Every resource an operation names, so `admit_resolved` can read its committed +/// total before touching it. +fn operation_resources(operation: &ResolvedOp) -> Vec<EntityId> { + match operation { + ResolvedOp::Transfer { resource, .. } + | ResolvedOp::Consume { resource, .. } + | ResolvedOp::Admit { resource, .. } + | ResolvedOp::Mint { resource, .. } => vec![*resource], + ResolvedOp::Transform { + from_resource, + into_resource, + .. + } => vec![*from_resource, *into_resource], + _ => Vec::new(), + } +} + +fn resource_total(state: &WorldState, resource: EntityId) -> u128 { + state + .holdings + .values() + .filter_map(|held| held.get(&resource)) + .map(|quantity| u128::from(quantity.0)) + .sum() +} + +/// What a holder holds. Absence is zero. +fn held(state: &WorldState, holder: SubjectId, resource: EntityId) -> u64 { + state + .holdings + .get(&holder) + .and_then(|held| held.get(&resource)) + .map_or(0, |quantity| quantity.0) +} + +/// Zero removes the resource key, and an emptied holder removes the holder key, +/// so `holdings` has exactly one representation of nothing. +fn set_held(state: &mut WorldState, holder: SubjectId, resource: EntityId, value: u64) { + if value == 0 { + let empty = if let Some(held) = state.holdings.get_mut(&holder) { + held.remove(&resource); + held.is_empty() + } else { + false + }; + if empty { + state.holdings.remove(&holder); + } + } else { + state + .holdings + .entry(holder) + .or_default() + .insert(resource, Quantity(value)); + } +} + +/// Whether a subject and a resource are both canonical and of the right kind. +fn custody_referents_exist(state: &WorldState, holder: SubjectId, resource: EntityId) -> bool { + state.subjects.contains_key(&holder) + && state + .entities + .get(&resource) + .is_some_and(|record| record.kind == EntityKind::Resource) +} + +fn dependency_target_exists(state: &WorldState, target: DependencyTarget) -> bool { + match target { + DependencyTarget::Resource(entity_id) => state + .entities + .get(&entity_id) + .is_some_and(|record| record.kind == EntityKind::Resource), + DependencyTarget::Route(edge_id) => state.edges.contains_key(&edge_id), + DependencyTarget::Subject(subject_id) => state.subjects.contains_key(&subject_id), + } +} + +/// The component half of admission. Every precondition is re-derived from the +/// partitions, so a forged operation cannot assert a move the topology refuses. +fn apply_operation( + state: &mut WorldState, + operation: &ResolvedOp, + evidence: &[EvidenceRef], + resolves_to: u64, +) -> Result<(), KernelError> { + let insufficient = || KernelError::Invariant("holder does not hold enough".into()); + let overflow = || KernelError::Invariant("holding would overflow".into()); + let unknown = || KernelError::Invariant("custody operation names no canonical referent".into()); + let zero = || KernelError::Invariant("custody operation moves nothing".into()); + match operation { + ResolvedOp::Relocate { + subject_id, + edge_id, + } => { + let route = state + .edges + .get(edge_id) + .ok_or_else(|| KernelError::Invariant("relocation names no route".into()))?; + let (from, to) = route.endpoints(); + let open = route.is_open(); + let access = route.access().clone(); + if !open + || state.positions.get(subject_id) != Some(&Position { place: from }) + || !patch::route_admits(state, &subject_authority(state, *subject_id), &access, to) + { + return Err(KernelError::Invariant( + "relocation does not traverse an open route the subject may take from its place" + .into(), + )); + } + state.positions.insert(*subject_id, Position { place: to }); + } + ResolvedOp::OpenRoute { edge_id } | ResolvedOp::CloseRoute { edge_id } => { + let open = matches!(operation, ResolvedOp::OpenRoute { .. }); + let route = state + .edges + .get_mut(edge_id) + .ok_or_else(|| KernelError::Invariant("route operation names no route".into()))?; + if route.is_open() == open { + return Err(KernelError::Invariant( + "route operation changes nothing".into(), + )); + } + route.set_open(open); + } + ResolvedOp::AlterCost { edge_id, cost } => { + if !patch::is_valid_cost(*cost) { + return Err(KernelError::Invariant( + "admitted cost is out of range".into(), + )); + } + let route = state + .edges + .get_mut(edge_id) + .ok_or_else(|| KernelError::Invariant("route operation names no route".into()))?; + if route.cost() == *cost { + return Err(KernelError::Invariant( + "route operation changes nothing".into(), + )); + } + route.set_cost(*cost); + } + ResolvedOp::Transfer { + from, + to, + resource, + qty, + } => { + if !custody_referents_exist(state, *from, *resource) || !state.subjects.contains_key(to) + { + return Err(unknown()); + } + if qty.0 == 0 || from == to { + return Err(zero()); + } + let remaining = held(state, *from, *resource) + .checked_sub(qty.0) + .ok_or_else(insufficient)?; + let credited = held(state, *to, *resource) + .checked_add(qty.0) + .ok_or_else(overflow)?; + set_held(state, *from, *resource, remaining); + set_held(state, *to, *resource, credited); + } + ResolvedOp::Transform { + holder, + from_resource, + into_resource, + qty, + } => { + if !custody_referents_exist(state, *holder, *from_resource) + || !custody_referents_exist(state, *holder, *into_resource) + { + return Err(unknown()); + } + if qty.0 == 0 || from_resource == into_resource { + return Err(zero()); + } + let remaining = held(state, *holder, *from_resource) + .checked_sub(qty.0) + .ok_or_else(insufficient)?; + let gained = held(state, *holder, *into_resource) + .checked_add(qty.0) + .ok_or_else(overflow)?; + set_held(state, *holder, *from_resource, remaining); + set_held(state, *holder, *into_resource, gained); + } + ResolvedOp::Consume { + holder, + resource, + qty, + } => { + if !custody_referents_exist(state, *holder, *resource) { + return Err(unknown()); + } + if qty.0 == 0 { + return Err(zero()); + } + let remaining = held(state, *holder, *resource) + .checked_sub(qty.0) + .ok_or_else(insufficient)?; + set_held(state, *holder, *resource, remaining); + } + ResolvedOp::Admit { + holder, + resource, + qty, + evidence: cited, + } => { + if !custody_referents_exist(state, *holder, *resource) { + return Err(unknown()); + } + if qty.0 == 0 { + return Err(zero()); + } + if !evidence.contains(cited) { + return Err(KernelError::Invariant( + "admitted quantity cites no evidence in its patch".into(), + )); + } + let admitted = held(state, *holder, *resource) + .checked_add(qty.0) + .ok_or_else(overflow)?; + set_held(state, *holder, *resource, admitted); + } + ResolvedOp::Mint { + holder, + resource, + qty, + } => { + if !custody_referents_exist(state, *holder, *resource) { + return Err(unknown()); + } + if qty.0 == 0 { + return Err(zero()); + } + let minted = held(state, *holder, *resource) + .checked_add(qty.0) + .ok_or_else(overflow)?; + set_held(state, *holder, *resource, minted); + } + ResolvedOp::Bind { subject, target } | ResolvedOp::Release { subject, target } => { + let bind = matches!(operation, ResolvedOp::Bind { .. }); + if !state.subjects.contains_key(subject) || !dependency_target_exists(state, *target) { + return Err(unknown()); + } + if *target == DependencyTarget::Subject(*subject) { + return Err(KernelError::Invariant( + "a subject cannot depend on itself".into(), + )); + } + let bound = state + .dependencies + .get(subject) + .is_some_and(|targets| targets.contains(target)); + if bound == bind { + return Err(KernelError::Invariant( + "dependency operation changes nothing".into(), + )); + } + if bind { + state + .dependencies + .entry(*subject) + .or_default() + .insert(*target); + } else { + let empty = if let Some(targets) = state.dependencies.get_mut(subject) { + targets.remove(target); + targets.is_empty() + } else { + false + }; + if empty { + state.dependencies.remove(subject); + } + } + } + ResolvedOp::GrantAuthority { holder, grant } + | ResolvedOp::RevokeAuthority { holder, grant } => { + let granting = matches!(operation, ResolvedOp::GrantAuthority { .. }); + if !state.subjects.contains_key(holder) + || !authority_referent_exists(state, grant.over) + || !patch::is_civic_name(&grant.kind.0) + { + return Err(unknown()); + } + let held = state + .authority + .get(holder) + .is_some_and(|grants| grants.contains(grant)); + if held == granting { + return Err(KernelError::Invariant( + "authority operation changes nothing".into(), + )); + } + if granting { + state + .authority + .entry(*holder) + .or_default() + .insert(grant.clone()); + } else { + let empty = if let Some(grants) = state.authority.get_mut(holder) { + grants.remove(grant); + grants.is_empty() + } else { + false + }; + if empty { + state.authority.remove(holder); + } + } + } + ResolvedOp::OpenOffice { + institution, + office, + delegated, + } => { + require_institution(state, *institution, office)?; + if delegated.is_empty() || delegated.iter().any(|kind| !patch::is_civic_name(&kind.0)) { + return Err(KernelError::Invariant( + "an office lends no canonical authority kind".into(), + )); + } + let current = state + .selection + .get(institution) + .and_then(|offices| offices.get(office)); + if current.is_some_and(|seat| &seat.delegated == delegated) { + return Err(KernelError::Invariant( + "office operation changes nothing".into(), + )); + } + // A sitting incumbent survives a reconstitution: clipping an + // office's powers under its holder is a political act, not a + // vacancy. + let incumbent = current.and_then(|seat| seat.incumbent); + state.selection.entry(*institution).or_default().insert( + office.clone(), + Office { + incumbent, + delegated: delegated.clone(), + }, + ); + } + ResolvedOp::CloseOffice { + institution, + office, + } + | ResolvedOp::VacateOffice { + institution, + office, + } => { + let closing = matches!(operation, ResolvedOp::CloseOffice { .. }); + require_institution(state, *institution, office)?; + let no_office = || KernelError::Invariant("office operation names no office".into()); + let offices = state.selection.get_mut(institution).ok_or_else(no_office)?; + let occupied = offices + .get(office) + .map(|seat| seat.incumbent.is_some()) + .ok_or_else(no_office)?; + if closing { + offices.remove(office); + let empty = offices.is_empty(); + if empty { + state.selection.remove(institution); + } + } else if !occupied { + return Err(KernelError::Invariant( + "office operation changes nothing".into(), + )); + } else { + offices.get_mut(office).ok_or_else(no_office)?.incumbent = None; + } + } + ResolvedOp::InstallIncumbent { + institution, + office, + incumbent, + } => { + require_institution(state, *institution, office)?; + if state.subjects.get(incumbent).map(|subject| subject.kind) + != Some(SubjectKind::Person) + { + return Err(KernelError::Invariant( + "an office holder is not a person subject".into(), + )); + } + let offices = state + .selection + .get_mut(institution) + .ok_or_else(|| KernelError::Invariant("office operation names no office".into()))?; + if offices + .iter() + .any(|(name, seat)| name != office && seat.incumbent == Some(*incumbent)) + { + return Err(KernelError::Invariant( + "one person holds two offices of one institution".into(), + )); + } + let seat = offices + .get_mut(office) + .ok_or_else(|| KernelError::Invariant("office operation names no office".into()))?; + if seat.incumbent == Some(*incumbent) { + return Err(KernelError::Invariant( + "office operation changes nothing".into(), + )); + } + seat.incumbent = Some(*incumbent); + } + ResolvedOp::OpenForum { + grievance, + forum, + standing, + } => { + if !state.subjects.contains_key(forum) + || !authority_referent_exists(state, *standing) + || !patch::is_civic_name(&grievance.0) + { + return Err(unknown()); + } + let seat = Forum { + forum: *forum, + standing: *standing, + }; + if state.redress.get(grievance) == Some(&seat) { + return Err(KernelError::Invariant( + "forum operation changes nothing".into(), + )); + } + state.redress.insert(grievance.clone(), seat); + } + ResolvedOp::CloseForum { grievance } => { + if state.redress.remove(grievance).is_none() { + return Err(KernelError::Invariant( + "forum operation names no forum".into(), + )); + } + } + ResolvedOp::AssertClaim { + fact, + statement, + by, + } => { + if !state.subjects.contains_key(by) || !patch::is_canonical_text(statement.as_str()) { + return Err(KernelError::Invariant( + "a claim names no live asserter or no canonical statement".into(), + )); + } + if state + .entities + .insert( + *fact, + EntityRecord { + label: CLAIM_LABEL.into(), + kind: EntityKind::Fact, + container: None, + }, + ) + .is_some() + || state + .facts + .insert( + *fact, + FactRecord { + statement: statement.clone(), + standing: FactStanding::Claimed { by: *by }, + }, + ) + .is_some() + { + return Err(KernelError::Invariant("minted claim ID collision".into())); + } + } + ResolvedOp::AcquireKnowledge { + subject, + fact, + source, + confidence, + } => { + let Some(record) = state.facts.get(fact) else { + return Err(KernelError::Invariant( + "knowledge operation names no canonical fact".into(), + )); + }; + if !state.subjects.contains_key(subject) + || (*source == AuthoredSource::Evidenced + && !matches!(record.standing, FactStanding::Canonical { .. })) + { + return Err(KernelError::Invariant( + "knowledge operation names no live subject, or evidences a claim".into(), + )); + } + let source = match source { + AuthoredSource::Witnessed => KnowledgeSource::Witnessed, + AuthoredSource::Evidenced => KnowledgeSource::Evidenced, + }; + // Compared on `confidence` and `source` alone: `acquired_at` is + // this write's own revision, not part of what the author asserts, + // so a re-assertion identical in everything the author controls + // still refuses as a no-op even though it would land a later + // `acquired_at`. + if state + .knowledge + .get(subject) + .and_then(|held| held.get(fact)) + .is_some_and(|held| held.confidence == *confidence && held.source == source) + { + return Err(KernelError::Invariant( + "knowledge operation changes nothing".into(), + )); + } + // Matches `DecisionEvent.revision` and the `minted_at` scan built + // from it (`action::exercise`, `snapshot`): both name the revision + // this commit resolves to. `resolves_to` is `state.revision` itself + // at genesis, which never advances past 0, and `state.revision + 1` + // everywhere else, since `state` still holds the *previous* + // revision until `submit` bumps it. One value, one caller-computed + // source, so a genesis-seeded row cannot land one revision ahead of + // the state it was written into. + let acquired_at = resolves_to; + let entry = Knowledge { + confidence: *confidence, + source, + acquired_at, + }; + state + .knowledge + .entry(*subject) + .or_default() + .insert(*fact, entry); + } + ResolvedOp::Forget { subject, fact } => { + let (removed, emptied) = state + .knowledge + .get_mut(subject) + .map(|held| { + let removed = held.remove(fact).is_some(); + (removed, held.is_empty()) + }) + .unwrap_or((false, false)); + if !removed { + return Err(KernelError::Invariant( + "knowledge operation changes nothing".into(), + )); + } + if emptied { + state.knowledge.remove(subject); + } + } + ResolvedOp::Communicate { speaker, fact, to } => { + if !state.subjects.contains_key(speaker) || !state.facts.contains_key(fact) { + return Err(KernelError::Invariant( + "a telling names no live speaker or fact".into(), + )); + } + if !can_broadcast(state, *speaker, to) { + return Err(KernelError::Invariant( + "a speaker is outside its own audience".into(), + )); + } + // An empty fan-out is legal: the delta of a telling is a property of + // the world — an empty room, a silenced channel — not a defect in + // the proposal. Speaking alone commits the claim and lands nothing. + // `acquired_at` matches `minted_at` (PA.f44): both name the + // revision this commit resolves to, `resolves_to` (PA.f49) — + // `state.revision` itself at genesis, `state.revision + 1` + // otherwise. + let acquired_at = resolves_to; + for listener in fan_out(state, *speaker, *fact, to) { + state.knowledge.entry(listener).or_default().insert( + *fact, + Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Told { + by: *speaker, + via: to.channel(), + }, + acquired_at, + }, + ); + } + } + ResolvedOp::Display { actor, fact } => { + if !state.subjects.contains_key(actor) || !state.facts.contains_key(fact) { + return Err(KernelError::Invariant( + "a display names no live actor or fact".into(), + )); + } + // The room is the audience, re-derived here: the same derivation + // co-located speech uses, so a body and a voice cannot disagree + // about who is in the room. A placeless actor is refused as a + // placeless speaker is; an empty room is a legal no-op, as + // speaking alone is. `Believed` is fixed by the kernel: a + // displayer cannot choose how much a viewer believes its body. + let room = Audience::Colocated; + if !can_broadcast(state, *actor, &room) { + return Err(KernelError::Invariant( + "an actor displays from no place".into(), + )); + } + // The revision the caller's own commit resolves to: `state.revision` + // itself at genesis, which never advances past 0, and + // `state.revision + 1` everywhere else, since `state` still holds + // the *previous* revision until `submit` bumps it. One value, one + // caller-computed source, so a genesis-seeded row cannot land one + // revision ahead of the state it was written into. + let acquired_at = resolves_to; + for viewer in fan_out(state, *actor, *fact, &room) { + state.knowledge.entry(viewer).or_default().insert( + *fact, + Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Seen { by: *actor }, + acquired_at, + }, + ); + } + } + ResolvedOp::Witness { + fact, + place, + confidence, + } => { + if !state.facts.contains_key(fact) + || !state + .entities + .get(place) + .is_some_and(|record| record.kind == EntityKind::Place) + { + return Err(KernelError::Invariant( + "a witness names no live fact or place".into(), + )); + } + // Recipients are derived here and never stored: everyone standing + // under the place, less everyone who already holds the fact. A + // witness that reaches nobody is refused, because a witnessed event + // is only its reception — `resolve_patch` refuses the same case over + // the candidate graph, so the two layers cannot disagree. + let recipients = unheld(state, *fact, under_place(state, *place)); + if recipients.is_empty() { + return Err(KernelError::Invariant( + "a witness reaches nobody who does not already hold the fact".into(), + )); + } + // The revision the caller's own commit resolves to: `state.revision` + // itself at genesis, which never advances past 0, and + // `state.revision + 1` everywhere else, since `state` still holds + // the *previous* revision until `submit` bumps it. One value, one + // caller-computed source, so a genesis-seeded row cannot land one + // revision ahead of the state it was written into. + let acquired_at = resolves_to; + for witness in recipients { + state.knowledge.entry(witness).or_default().insert( + *fact, + Knowledge { + confidence: *confidence, + source: KnowledgeSource::Witnessed, + acquired_at, + }, + ); + } + } + ResolvedOp::SetPersonaMaterial { subject, material } => { + if !state.subjects.contains_key(subject) + || material + .reads + .keys() + .any(|other| !state.subjects.contains_key(other)) + { + return Err(unknown()); + } + if state.persona_material.get(subject) == Some(material) { + return Err(KernelError::Invariant( + "persona material changes nothing".into(), + )); + } + state.persona_material.insert(*subject, material.clone()); + } + ResolvedOp::SetReach { channel, reach } => { + let current = state + .channels + .get(channel) + .ok_or_else(|| KernelError::Invariant("channel operation names no channel".into()))? + .clone(); + let record = ChannelRecord { + reach: reach.clone(), + controller: current.controller, + }; + if !channel_referents_exist(state, &record) { + return Err(KernelError::Invariant( + "a reach names no live subject or place".into(), + )); + } + if current.reach == *reach { + return Err(KernelError::Invariant( + "channel operation changes nothing".into(), + )); + } + state.channels.insert(*channel, record); + } + ResolvedOp::SetController { + channel, + controller, + } => { + if controller.is_some_and(|subject_id| !state.subjects.contains_key(&subject_id)) { + return Err(unknown()); + } + let seat = state.channels.get_mut(channel).ok_or_else(|| { + KernelError::Invariant("channel operation names no channel".into()) + })?; + if seat.controller == *controller { + return Err(KernelError::Invariant( + "channel operation changes nothing".into(), + )); + } + seat.controller = *controller; + } + ResolvedOp::CreateCommitment { + subject, + key, + commitment, + } => { + if !state.subjects.contains_key(subject) + || !commitment_is_live(state, *subject, commitment) + { + return Err(KernelError::Invariant( + "a commitment names no live promisor, counterparty, or check".into(), + )); + } + if state + .commitments + .entry(*subject) + .or_default() + .insert(*key, commitment.clone()) + .is_some() + { + return Err(KernelError::Invariant("commitment key collision".into())); + } + } + ResolvedOp::DischargeCommitment { subject, key } => { + // One removal, two writes, one owner: the commitment and every + // pressure row it sourced. + let discharged = || KernelError::Invariant("discharge names no live commitment".into()); + let held = state.commitments.get_mut(subject).ok_or_else(discharged)?; + held.remove(key).ok_or_else(discharged)?; + let empty = held.is_empty(); + if empty { + state.commitments.remove(subject); + } + let sourced = PressureSource::Commitment { + subject: *subject, + key: *key, + }; + state.pressures.retain(|_, held| { + held.remove(&sourced); + !held.is_empty() + }); + } + ResolvedOp::AdvancePressure { source, target, by } + | ResolvedOp::ReducePressure { source, target, by } => { + let advancing = matches!(operation, ResolvedOp::AdvancePressure { .. }); + if !state.subjects.contains_key(target) || !pressure_source_is_live(state, source) { + return Err(unknown()); + } + let current = state + .pressures + .get(target) + .and_then(|held| held.get(source)) + .map_or(0, |magnitude| magnitude.0); + let next = if advancing { + current.saturating_add(by.0) + } else { + current.saturating_sub(by.0) + }; + if next == current { + return Err(KernelError::Invariant( + "pressure operation changes nothing".into(), + )); + } + set_pressure(state, *target, *source, next); + } + ResolvedOp::ResolvePressure { source, target } => { + if state + .pressures + .get(target) + .is_none_or(|held| !held.contains_key(source)) + { + return Err(KernelError::Invariant( + "pressure operation changes nothing".into(), + )); + } + set_pressure(state, *target, *source, 0); + } + ResolvedOp::Retire { subject } => { + let scope = DecisionScope { + subject_id: *subject, + }; + let assignment = state.controller_assignments.get(&scope).ok_or_else(unknown)?; + match assignment { + ControllerAssignment::Retired => { + return Err(KernelError::Invariant( + "retire operation names an already retired subject".into(), + )); + } + ControllerAssignment::ExternallyControlled { .. } => { + return Err(KernelError::Invariant( + "retire operation names a mirror this world does not own".into(), + )); + } + // A human's Draft approval cannot be removed by removing the + // human: re-decided here beside the resolver's + // `RetiresAnApprover`, since resolution is speculative and + // this is the actual commit. Active retires the human freely; + // its approval is frozen history by then, judged by replay. + ControllerAssignment::Human { .. } if state.phase == WorldPhase::Draft => { + return Err(KernelError::Invariant( + "retire operation would remove a Draft approver".into(), + )); + } + ControllerAssignment::Human { .. } + | ControllerAssignment::NarrativePersona { .. } + | ControllerAssignment::OperationalAgent { .. } => {} + } + state + .controller_assignments + .insert(scope, ControllerAssignment::Retired); + state.positions.remove(subject); + state.affordance_grants.remove(&scope); + } + ResolvedOp::GrantAffordance { subject, affordance } + | ResolvedOp::RevokeAffordance { subject, affordance } => { + let granting = matches!(operation, ResolvedOp::GrantAffordance { .. }); + let scope = DecisionScope { + subject_id: *subject, + }; + let assignment = state.controller_assignments.get(&scope).ok_or_else(unknown)?; + if assignment.mode().is_none() || !state.affordance_catalog.contains_key(affordance) { + return Err(unknown()); + } + let granted = state + .affordance_grants + .get_mut(&scope) + .ok_or_else(unknown)?; + let held = granted.contains(affordance); + if held == granting { + return Err(KernelError::Invariant( + "affordance grant operation changes nothing".into(), + )); + } + if granting { + granted.insert(*affordance); + } else { + if granted.len() == 1 { + return Err(KernelError::Invariant( + "revoke would leave a controlled subject with no affordance".into(), + )); + } + granted.remove(affordance); + } + } + } + Ok(()) +} + +/// Zero removes the source key, and an emptied target removes the target key, +/// so `pressures` has exactly one representation of nothing. +fn set_pressure(state: &mut WorldState, target: SubjectId, source: PressureSource, value: u32) { + if value == 0 { + let empty = if let Some(held) = state.pressures.get_mut(&target) { + held.remove(&source); + held.is_empty() + } else { + false + }; + if empty { + state.pressures.remove(&target); + } + } else { + state + .pressures + .entry(target) + .or_default() + .insert(source, PressureMagnitude(value)); + } +} + +/// Whether every referent a commitment names is live and its shape holds. +/// Re-derived over the committed partitions, because a forged effect reaches +/// `apply_operation` without ever passing the resolver. +fn commitment_is_live(state: &WorldState, subject: SubjectId, commitment: &Commitment) -> bool { + let counterparty_is_live = match commitment.counterparty { + Some(counterparty) => { + counterparty != subject + && state.subjects.contains_key(&counterparty) + && commitment.kind != CommitmentKind::Goal + } + None => true, + }; + counterparty_is_live + && (commitment.kind == CommitmentKind::Routine) == commitment.period.is_some() + && (commitment.kind == CommitmentKind::Routine || commitment.checks.is_empty()) + && commitment.due > state.now + && commitment + .checks + .iter() + .all(|check| bound_precondition_is_live(state, check)) +} + +fn bound_precondition_is_live(state: &WorldState, check: &BoundPrecondition) -> bool { + let is_kind = |entity_id: &EntityId, kind: EntityKind| { + state + .entities + .get(entity_id) + .is_some_and(|record| record.kind == kind) + }; + let audience_is_live = |via: &Audience| match via { + Audience::Colocated => true, + Audience::Channel(entity_id) => state.channels.contains_key(entity_id), + }; + match check { + BoundPrecondition::Present { at } => is_kind(at, EntityKind::Place), + BoundPrecondition::Reachable { to, within } => { + is_kind(to, EntityKind::Place) && patch::is_valid_cost(*within) + } + BoundPrecondition::Holds { resource, .. } => is_kind(resource, EntityKind::Resource), + BoundPrecondition::Authorized { over, kind } => { + patch::is_civic_name(&kind.0) + && match over { + Target::Subject(subject_id) => state.subjects.contains_key(subject_id), + Target::Entity(entity_id) => is_kind(entity_id, EntityKind::Place), + Target::Edge(edge_id) => state.edges.contains_key(edge_id), + } + } + BoundPrecondition::HasStanding { grievance } => patch::is_civic_name(&grievance.0), + BoundPrecondition::Knows { fact, .. } => is_kind(fact, EntityKind::Fact), + BoundPrecondition::CanBroadcast { via } => audience_is_live(via), + BoundPrecondition::CanReach { subject, via } => { + state.subjects.contains_key(subject) && audience_is_live(via) + } + BoundPrecondition::Committed { to, .. } => state.subjects.contains_key(to), + } +} + +fn pressure_source_is_live(state: &WorldState, source: &PressureSource) -> bool { + match source { + PressureSource::Commitment { subject, key } => state + .commitments + .get(subject) + .is_some_and(|held| held.contains_key(key)), + PressureSource::Dependency(target) => dependency_target_exists(state, *target), + PressureSource::Subject(subject_id) => state.subjects.contains_key(subject_id), + } +} + +/// The label every minted claim carries. A label is a name, not a transcript: +/// the statement is never copied into it and the label is never derived from +/// it. Labels resolve no references, so identical labels across every claim +/// are unremarkable. The statement itself lives in `facts[fact].statement` +/// and is also carried inside the committed `AssertClaim` effect on the +/// event that minted it; `facts` is the one readable home a projection may +/// consult, and the event copy is the replay witness, never a second read +/// surface. +const CLAIM_LABEL: &str = "claim"; + +/// Whether a channel's reach and controller name live structure. +fn channel_referents_exist(state: &WorldState, record: &ChannelRecord) -> bool { + let reach = match &record.reach { + Reach::Subjects(members) => members + .iter() + .all(|subject_id| state.subjects.contains_key(subject_id)), + Reach::Place(place) => state + .entities + .get(place) + .is_some_and(|entity| entity.kind == EntityKind::Place), + }; + reach + && record + .controller + .is_none_or(|subject_id| state.subjects.contains_key(&subject_id)) +} + +/// Whether a subject's controller assignment is `Retired`. The one statement +/// of retirement read by anything downstream of it (audience derivation, +/// preconditions, resolvers): a mirror's assignment is `ExternallyControlled` +/// and is never retired by this check, only an actual `Retire` sets it. +pub(crate) fn is_retired(state: &WorldState, subject_id: SubjectId) -> bool { + matches!( + state.controller_assignments.get(&DecisionScope { subject_id }), + Some(ControllerAssignment::Retired) + ) +} + +/// Everyone standing anywhere under one place. The one downward-facing read of +/// `positions`: `audience`'s `Reach::Place` arm and `ResolvedOp::Witness` are +/// its two callers, so what "under a place" means cannot drift between a +/// declared broadcast area and a witnessed event. A subject with no position is +/// under nothing. +fn under_place(state: &WorldState, root: EntityId) -> BTreeSet<SubjectId> { + state + .positions + .iter() + .filter(|(_, position)| patch::covers_place(&state.entities, root, position.place)) + .map(|(subject_id, _)| *subject_id) + .collect() +} + +/// The one statement of reach. Called by both speech preconditions, by a +/// `Communicate`'s admission, and by its apply. Nothing else computes an +/// audience. +/// +/// Co-location is the actor's exact place, not its subtree: a voice fills a +/// room, not the district containing it. A channel's `Reach::Place` is +/// deliberately wider, because a declared broadcast area is a declared choice. +fn audience(state: &WorldState, actor: SubjectId, of: &Audience) -> BTreeSet<SubjectId> { + match of { + Audience::Colocated => { + let Some(here) = state.positions.get(&actor).copied() else { + return BTreeSet::new(); + }; + state + .positions + .iter() + .filter(|(_, position)| **position == here) + .map(|(subject_id, _)| *subject_id) + .collect() + } + Audience::Channel(channel) => { + let Some(record) = state.channels.get(channel) else { + return BTreeSet::new(); + }; + match &record.reach { + // Audience derivation is the one owner of who is reachable, so + // a channel may still *declare* a retired member (PA.f33); + // retirement is filtered here, at the single read site, not at + // declaration time. + Reach::Subjects(members) => members + .iter() + .copied() + .filter(|member| !is_retired(state, *member)) + .collect(), + Reach::Place(root) => under_place(state, *root), + } + } + } +} + +/// Whether an actor may broadcast into an audience: either the actor stands +/// inside the declared reach, or — for a channel — the actor is that +/// channel's controller. The controller's privilege is narrow: it lets the +/// horn sound from outside the room, but it does not admit the controller to +/// the audience itself. A controller outside its channel's reach gains no +/// knowledge from its own telling and is not a target another actor can +/// reach through that channel; `audience()` stays the one statement of who is +/// inside, and this is the one statement of who may speak. +fn can_broadcast(state: &WorldState, actor: SubjectId, of: &Audience) -> bool { + if audience(state, actor, of).contains(&actor) { + return true; + } + match of { + Audience::Channel(channel) => state + .channels + .get(channel) + .is_some_and(|record| record.controller == Some(actor)), + Audience::Colocated => false, + } +} + +/// A knowledge landing never overwrites and never downgrades a holder: whoever +/// already holds the fact is dropped, whatever it holds and however it came by +/// it. The knower owns its own credence, and a landing that could reset it by +/// repeating itself would own another subject's mind through an effect nobody +/// checked. `fan_out` and `ResolvedOp::Witness` are the two callers, so a +/// telling and a witnessed event cannot disagree about who is already a knower. +fn unheld( + state: &WorldState, + fact: EntityId, + listeners: BTreeSet<SubjectId>, +) -> BTreeSet<SubjectId> { + listeners + .into_iter() + .filter(|listener| { + !state + .knowledge + .get(listener) + .is_some_and(|held| held.contains_key(&fact)) + }) + .collect() +} + +/// Who gains knowledge from one telling: the audience, less the speaker, less +/// anyone who already holds the fact. `Believed` is fixed by the kernel and is +/// not a field on the operation, so a speaker cannot choose how much a listener +/// believes it. +fn fan_out( + state: &WorldState, + speaker: SubjectId, + fact: EntityId, + to: &Audience, +) -> BTreeSet<SubjectId> { + let mut listeners = audience(state, speaker, to); + listeners.remove(&speaker); + unheld(state, fact, listeners) +} + +/// Whether an authority target names a live subject or a live place. +fn authority_referent_exists(state: &WorldState, target: AuthorityTarget) -> bool { + match target { + AuthorityTarget::Subject(subject_id) => state.subjects.contains_key(&subject_id), + AuthorityTarget::PlaceSubtree(entity_id) => state + .entities + .get(&entity_id) + .is_some_and(|record| record.kind == EntityKind::Place), + } +} + +/// The shared half of every office operation: a canonical office name on a live +/// institution subject. +fn require_institution( + state: &WorldState, + institution: SubjectId, + office: &OfficeName, +) -> Result<(), KernelError> { + if !patch::is_civic_name(&office.0) { + return Err(KernelError::Invariant( + "office name is not canonical".into(), + )); + } + if state.subjects.get(&institution).map(|subject| subject.kind) + != Some(SubjectKind::Institution) + { + return Err(KernelError::Invariant( + "an office was opened on a subject that is not an institution".into(), + )); + } + Ok(()) +} + +/// The subject, if any, whose effective authority holds two grants of one kind +/// over overlapping ground. Re-derived over the committed partitions after every +/// batch that could widen a jurisdiction, so a forged effect cannot install the +/// split-brained state the resolver refuses. +fn overlapping_holder(state: &WorldState) -> Option<SubjectId> { + let holders: BTreeSet<SubjectId> = state + .authority + .keys() + .copied() + .chain( + state + .selection + .values() + .flat_map(|offices| offices.values()) + .filter_map(|office| office.incumbent), + ) + .collect(); + holders.into_iter().find(|holder| { + let effective: Vec<AuthorityGrant> = + subject_authority(state, *holder).into_iter().collect(); + effective.iter().enumerate().any(|(index, one)| { + effective[index + 1..].iter().any(|other| { + one.kind == other.kind + && patch::targets_overlap(&state.entities, one.over, other.over) + }) + }) + }) +} + +/// Exactly the components a subject's verification reads. One owner, consumed by +/// the scope digest and by the snapshot, so the two cannot drift. `routes` is +/// every edge whose `from` or `to` is the subject's place: an inbound route +/// decides who can arrive, and reading too little is a correctness hole while +/// reading too much only costs an extra rejection. `holdings` and `dependencies` +/// are the acting subject's own; a counterparty's holdings do not enter, because +/// a transfer changes both subjects' components and so changes both digests. +/// It also holds what the actor *is* authorized over, and nothing about the +/// world the actor reaches: the target's position, the target's container +/// chain, the forum's state, and any subordinate's components stay out. A +/// realm-wide authority whose preimage held its jurisdiction's occupancy would +/// conflict with every commit in the realm, which is whole-world binding +/// restored by the front door. A target that walks out of a jurisdiction +/// mid-flight therefore fails at `Authorized` rather than rebinding, while a +/// revoked grant is a `ScopeChanged`. +/// +/// `Deserialize` is here so the narrative lane can persist a subject's own +/// components as the "before" an interruption is measured against. No field +/// changes with it, so `ScopePreimage`'s serialization — and therefore every +/// scope digest — is byte-identical. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct ScopeComponents { + position: Option<Position>, + routes: BTreeMap<EdgeId, EdgeRecord>, + holdings: BTreeMap<EntityId, Quantity>, + dependencies: BTreeSet<DependencyTarget>, + /// This subject's own grants. + authority: BTreeSet<AuthorityGrant>, + /// What each held office lends: for every office whose incumbent is this + /// subject, the institution's live grants whose kind that office delegates. + /// The institution's authority is copied in through the office link, so one + /// scope digest covers the grant, the office, and the institution's + /// jurisdiction, and only delegated kinds enter — an institution's `judge` + /// jurisdiction never churns a `levy`-only incumbent's proposals. + delegated: BTreeMap<SubjectId, BTreeMap<OfficeName, BTreeSet<AuthorityGrant>>>, + /// The keys of this subject's own knowledge. Keys, not payloads: a statement + /// is immutable, so it cannot change without the key changing, and + /// confidence is admission-only — a re-appraisal that lowers a subject's own + /// confidence does not reject its own in-flight proposal, because `Knows` + /// re-checks at commit and fails closed with `FactUnknown`. + knows: BTreeSet<EntityId>, + /// The channels this subject controls, with their records. Membership of a + /// channel it merely hears never enters: a 1,000-member channel would churn + /// a thousand digests per membership change, which is whole-world binding by + /// the front door. + controls: BTreeMap<EntityId, ChannelRecord>, + /// This subject's own commitments. `Precondition::Committed` reads them, so + /// the digest must bind them. Pressure, the clock, and the attention stamp + /// stay out: no precondition reads any of the three, so a tick that only + /// advances pressure invalidates no in-flight proposal. + commitments: BTreeMap<CommitmentKey, Commitment>, +} + +/// Whether an authority target covers a referent. The one statement of +/// jurisdictional membership, reached by `Authorized`, `HasStanding`, +/// `route_admits`, the delegation monotonicity rule, and the snapshot's redress +/// projection. +/// +/// A place subtree covers a subject standing anywhere under it, a place under +/// it, and a route with either endpoint under it — a city must be able to close +/// its own gate, and a gate's far end is outside the city by construction. A +/// resource, fact, or channel is covered by nothing; `RoleKindUnfit` refuses an +/// `Authorized` over such a role at declaration. +fn covers(state: &WorldState, target: AuthorityTarget, of: Target) -> bool { + let under = |place: EntityId, root: EntityId| patch::covers_place(&state.entities, root, place); + match (target, of) { + (AuthorityTarget::Subject(holder), Target::Subject(subject_id)) => holder == subject_id, + (AuthorityTarget::Subject(_), _) => false, + (AuthorityTarget::PlaceSubtree(root), Target::Subject(subject_id)) => state + .positions + .get(&subject_id) + .is_some_and(|position| under(position.place, root)), + (AuthorityTarget::PlaceSubtree(root), Target::Entity(entity_id)) => state + .entities + .get(&entity_id) + .is_some_and(|record| record.kind == EntityKind::Place && under(entity_id, root)), + (AuthorityTarget::PlaceSubtree(root), Target::Edge(edge_id)) => { + state.edges.get(&edge_id).is_some_and(|record| { + let (from, to) = record.endpoints(); + under(from, root) || under(to, root) + }) + } + } +} + +/// Own grants plus what every held office lends. The single statement of what a +/// subject may invoke authority over. There is no precedence between a direct +/// grant and a delegated one, because `OverlappingJurisdiction` makes it +/// impossible for both to answer for one kind over overlapping ground. +fn effective_authority( + own: &BTreeSet<AuthorityGrant>, + delegated: &BTreeMap<SubjectId, BTreeMap<OfficeName, BTreeSet<AuthorityGrant>>>, +) -> BTreeSet<AuthorityGrant> { + let mut effective = own.clone(); + for lent in delegated.values().flat_map(|offices| offices.values()) { + effective.extend(lent.iter().cloned()); + } + effective +} + +/// Every office this subject occupies, keyed by institution, with what each one +/// lends of that institution's live grants. +fn delegated_authority( + state: &WorldState, + subject_id: SubjectId, +) -> BTreeMap<SubjectId, BTreeMap<OfficeName, BTreeSet<AuthorityGrant>>> { + let mut held: BTreeMap<SubjectId, BTreeMap<OfficeName, BTreeSet<AuthorityGrant>>> = + BTreeMap::new(); + for (institution, offices) in &state.selection { + // A retired institution lends nothing: `Retire` does not vacate + // offices, so the incumbency stays on record, but a dissolved + // institution's grants stop reaching its office-holders here, the one + // site that turns an office into effective authority. + if is_retired(state, *institution) { + continue; + } + for (name, office) in offices { + if office.incumbent != Some(subject_id) { + continue; + } + let lent: BTreeSet<AuthorityGrant> = state + .authority + .get(institution) + .into_iter() + .flatten() + .filter(|grant| office.delegated.contains(&grant.kind)) + .cloned() + .collect(); + held.entry(*institution) + .or_default() + .insert(name.clone(), lent); + } + } + held +} + +/// The effective authority of one subject read straight from the partitions, +/// for the reducer paths that do not already hold a `ScopeComponents`. +fn subject_authority(state: &WorldState, subject_id: SubjectId) -> BTreeSet<AuthorityGrant> { + let empty = BTreeSet::new(); + effective_authority( + state.authority.get(&subject_id).unwrap_or(&empty), + &delegated_authority(state, subject_id), + ) +} + +fn scope_components(state: &WorldState, subject_id: SubjectId) -> ScopeComponents { + let position = state.positions.get(&subject_id).copied(); + let routes = position + .map(|position| { + state + .edges + .iter() + .filter(|(_, record)| { + let (from, to) = record.endpoints(); + from == position.place || to == position.place + }) + .map(|(edge_id, record)| (*edge_id, record.clone())) + .collect() + }) + .unwrap_or_default(); + ScopeComponents { + position, + routes, + holdings: state.holdings.get(&subject_id).cloned().unwrap_or_default(), + dependencies: state + .dependencies + .get(&subject_id) + .cloned() + .unwrap_or_default(), + authority: state + .authority + .get(&subject_id) + .cloned() + .unwrap_or_default(), + delegated: delegated_authority(state, subject_id), + knows: state + .knowledge + .get(&subject_id) + .into_iter() + .flat_map(BTreeMap::keys) + .copied() + .collect(), + controls: state + .channels + .iter() + .filter(|(_, record)| record.controller == Some(subject_id)) + .map(|(entity_id, record)| (*entity_id, record.clone())) + .collect(), + commitments: state + .commitments + .get(&subject_id) + .cloned() + .unwrap_or_default(), + } +} + +/// The human operator's story feed, derived from the causal record. The events +/// log is not a perception surface: `knowledge` is the sole answer to what a +/// subject may act on and what its projection may contain. +fn operator_log( + state: &WorldState, + invocations: &BTreeMap<EventId, &DecisionInvocation>, +) -> Result<Vec<OperatorEvent>, KernelError> { + state + .events + .iter() + .map(|event| { + let speaker = state + .subjects + .get(&event.scope.subject_id) + .ok_or_else(|| KernelError::Invariant("event names no live subject".into()))?; + let invocation = invocations.get(&event.id).ok_or_else(|| { + KernelError::Invariant("event has no committed invocation".into()) + })?; + let entry = state + .affordance_catalog + .get(&event.affordance) + .ok_or_else(|| KernelError::Invariant("event names no catalog entry".into()))?; + let roles = invocation + .bindings + .iter() + .map(|binding| { + let label = match binding.target { + Target::Subject(id) => state.subjects.get(&id).map(|s| s.label.clone()), + Target::Entity(id) => state.entities.get(&id).map(|e| e.label.clone()), + Target::Edge(id) => state.edges.contains_key(&id).then(|| "edge".to_owned()), + }; + label + .map(|target| BoundRole { + role: binding.role.0.clone(), + target, + }) + .ok_or_else(|| KernelError::Invariant("event binds no live referent".into())) + }) + .collect::<Result<Vec<_>, _>>()?; + Ok(OperatorEvent { + revision: event.revision, + speaker: event.scope.subject_id, + speaker_label: speaker.label.clone(), + speech: event + .speech + .and_then(|fact| state.facts.get(&fact)) + .map(|record| record.statement.clone()), + display: event + .display + .and_then(|fact| state.facts.get(&fact)) + .map(|record| record.statement.clone()), + verb: entry.kind.0.clone(), + render_path: state + .grammar + .as_ref() + .and_then(|grammar| grammar.verb(&entry.kind.0)) + .map(|verb| verb.render_path), + roles, + }) + }) + .collect() +} + +/// The scheduler's adjacency projection. It is deliberately wider than any +/// subject view — channel reach and place containment are in no subject's +/// snapshot at all — which is exactly why it is derived here, beside +/// `operator_log`, and handed to the cover rather than assembled by a +/// controller organ out of the union of what subjects can see. +/// +/// Nothing here is authority. Two subjects are adjacent when a decision by one +/// can plausibly land on the other, and adjacency only decides which prompt +/// they share. +fn agency_graph(state: &WorldState) -> AgencyGraph { + let active: BTreeSet<SubjectId> = state + .controller_assignments + .iter() + .filter(|(_, controller)| { + matches!(controller.mode(), Some(mode) if mode != ControllerMode::Human) + }) + .map(|(scope, _)| scope.subject_id) + .collect(); + let mut graph = AgencyGraph { + subjects: active.iter().copied().collect(), + edges: BTreeSet::new(), + }; + if active.len() < 2 { + return graph; + } + let live = |subject: &SubjectId| active.contains(subject); + + // Place containment, which subsumes "standing in the same room": a place + // covers itself, so one closure states both. + let mut in_place: BTreeMap<EntityId, BTreeSet<SubjectId>> = BTreeMap::new(); + for (place, record) in &state.entities { + if record.kind != EntityKind::Place { + continue; + } + let occupants: BTreeSet<SubjectId> = state + .positions + .iter() + .filter(|(subject, position)| { + live(subject) && patch::covers_place(&state.entities, *place, position.place) + }) + .map(|(subject, _)| *subject) + .collect(); + if occupants.len() >= 2 { + graph.relate(&occupants); + } + if !occupants.is_empty() { + in_place.insert(*place, occupants); + } + } + + // An open route makes two rooms one neighbourhood. One representative per + // side is enough: each side is already related internally. + for edge in state.edges.values() { + let EdgeRecord::Route { from, to, open, .. } = edge; + if !open { + continue; + } + if let (Some(here), Some(there)) = (in_place.get(from), in_place.get(to)) + && let (Some(one), Some(other)) = (here.first(), there.first()) + { + graph.link(*one, *other); + } + } + + // Dependencies: a named subject is a direct edge, a shared resource or + // route is a star over everyone leaning on it. + let mut shared: BTreeMap<DependencyTarget, BTreeSet<SubjectId>> = BTreeMap::new(); + for (subject, targets) in &state.dependencies { + if !live(subject) { + continue; + } + for target in targets { + match target { + DependencyTarget::Subject(other) if live(other) => graph.link(*subject, *other), + DependencyTarget::Subject(_) => {} + other => { + shared.entry(*other).or_default().insert(*subject); + } + } + } + } + for group in shared.values() { + graph.relate(group); + } + + // Authority and office: an institution and the people who hold its seats, + // and a jurisdiction that names one subject as its ground. + for (institution, offices) in &state.selection { + let mut seated: BTreeSet<SubjectId> = offices + .values() + .filter_map(|office| office.incumbent) + .filter(live) + .collect(); + if live(institution) { + seated.insert(*institution); + } + graph.relate(&seated); + } + for (holder, grants) in &state.authority { + if !live(holder) { + continue; + } + for grant in grants { + if let AuthorityTarget::Subject(over) = grant.over + && live(&over) + { + graph.link(*holder, over); + } + } + } + + // Channel reach. This is the edge no union of subject views could produce: + // a subject sees the channels it controls, never who else is in earshot. + for record in state.channels.values() { + let mut reached: BTreeSet<SubjectId> = match &record.reach { + Reach::Subjects(subjects) => subjects.iter().copied().filter(live).collect(), + Reach::Place(place) => in_place.get(place).cloned().unwrap_or_default(), + }; + if let Some(controller) = record.controller.filter(live) { + reached.insert(controller); + } + graph.relate(&reached); + } + + // Pressure, and the promises that raise it. + for (target, sources) in &state.pressures { + if !live(target) { + continue; + } + for source in sources.keys() { + let other = match source { + PressureSource::Commitment { subject, .. } => Some(*subject), + PressureSource::Dependency(DependencyTarget::Subject(subject)) => Some(*subject), + PressureSource::Subject(subject) => Some(*subject), + PressureSource::Dependency(_) => None, + }; + if let Some(other) = other.filter(live) { + graph.link(*target, other); + } + } + } + for (subject, promises) in &state.commitments { + if !live(subject) { + continue; + } + for commitment in promises.values() { + if let Some(counterparty) = commitment.counterparty.filter(live) { + graph.link(*subject, counterparty); + } + } + } + + graph +} + +fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> { + // One pass over the causal record so each subject's own knowledge map can be + // stamped with the revision that minted each claim it holds. + let minted_at: BTreeMap<EntityId, u64> = state + .events + .iter() + .flat_map(|event| { + event + .speech + .into_iter() + .chain(event.display) + .map(move |fact| (fact, event.revision)) + }) + .collect(); + // One pass over the causal record so each subject can be stamped with the + // revision of its own last exercised decision. `None` for a subject that + // never acted. + let last_acted_at: BTreeMap<SubjectId, u64> = + state + .events + .iter() + .fold(BTreeMap::new(), |mut acc, event| { + let entry = acc.entry(event.scope.subject_id).or_insert(event.revision); + if event.revision > *entry { + *entry = event.revision; + } + acc + }); + let subjects = state + .subjects + .iter() + .map(|(subject_id, subject)| { + let scope = DecisionScope { + subject_id: *subject_id, + }; + let controller = state.controller_assignments.get(&scope).ok_or_else(|| { + KernelError::Invariant("subject has no controller assignment".into()) + })?; + let affordances = state + .affordance_grants + .get(&scope) + .cloned() + .unwrap_or_default(); + let components = scope_components(state, *subject_id); + let offices_held = components + .delegated + .iter() + .flat_map(|(institution, offices)| { + offices + .iter() + .map(move |(office, authority)| OfficeSnapshot { + institution: *institution, + office: office.clone(), + incumbent: Some(*subject_id), + authority: authority.clone(), + }) + }) + .collect(); + let offices_granted = state + .selection + .get(subject_id) + .into_iter() + .flatten() + .map(|(office, seat)| OfficeSnapshot { + institution: *subject_id, + office: office.clone(), + incumbent: seat.incumbent, + authority: state + .authority + .get(subject_id) + .into_iter() + .flatten() + .filter(|grant| seat.delegated.contains(&grant.kind)) + .cloned() + .collect(), + }) + .collect(); + let redress = state + .redress + .iter() + .filter(|(_, forum)| covers(state, forum.standing, Target::Subject(*subject_id))) + .map(|(grievance, forum)| ForumSnapshot { + grievance: grievance.clone(), + forum: forum.forum, + }) + .collect(); + // The sole perception surface, derived here rather than in a + // controller: a controller that recomputed perception would be a + // second answer to who heard what. + let mut knowledge: Vec<KnowledgeSnapshot> = state + .knowledge + .get(subject_id) + .into_iter() + .flatten() + .map(|(fact, held)| { + let record = state.facts.get(fact).ok_or_else(|| { + KernelError::Invariant("knowledge names no canonical fact".into()) + })?; + Ok(KnowledgeSnapshot { + fact: *fact, + statement: record.statement.clone(), + standing: match &record.standing { + FactStanding::Canonical { .. } => FactStandingView::Canonical, + FactStanding::Claimed { by } => FactStandingView::Claimed { by: *by }, + FactStanding::Ruled => FactStandingView::Canonical, + }, + confidence: held.confidence, + source: held.source, + minted_at: minted_at.get(fact).copied(), + acquired_at: held.acquired_at, + }) + }) + .collect::<Result<Vec<_>, KernelError>>()?; + knowledge.sort_by_key(|entry| (entry.minted_at, entry.fact)); + Ok(SubjectSnapshot { + id: *subject_id, + label: subject.label.clone(), + kind: subject.kind, + import_key: subject.import_key.clone(), + controller_id: controller.id(), + controller_mode: controller.mode(), + human_controller: controller.human_principal().cloned(), + affordances, + position: components.position.map(|position| position.place), + retired: matches!(controller, ControllerAssignment::Retired), + offices_held, + offices_granted, + redress, + knowledge, + commitments: components + .commitments + .iter() + .map(|(key, commitment)| CommitmentSnapshot { + key: *key, + kind: commitment.kind, + counterparty: commitment.counterparty, + due: commitment.due, + period: commitment.period, + statement: commitment.statement.clone(), + past_due: commitment.due <= state.now, + }) + .collect(), + dependencies: components.dependencies.iter().copied().collect(), + components, + material: state.persona_material.get(subject_id).cloned(), + pressures: state + .pressures + .get(subject_id) + .into_iter() + .flatten() + .map(|(source, magnitude)| PressureSnapshot { + source: *source, + magnitude: *magnitude, + }) + .collect(), + qualified: qualifies(state, *subject_id), + last_acted_at: last_acted_at.get(subject_id).copied(), + }) + }) + .collect::<Result<Vec<_>, KernelError>>()?; + let places = state + .entities + .iter() + .filter(|(_, record)| record.kind == EntityKind::Place) + .map(|(entity_id, record)| PlaceSnapshot { + id: *entity_id, + label: record.label.clone(), + container: record.container, + }) + .collect(); + let resources = state + .entities + .iter() + .filter(|(_, record)| record.kind == EntityKind::Resource) + .map(|(entity_id, record)| ResourceSnapshot { + id: *entity_id, + label: record.label.clone(), + }) + .collect(); + let routes = state + .edges + .iter() + .map(|(edge_id, record)| { + let (from, to) = record.endpoints(); + RouteSnapshot { + id: *edge_id, + label: record.label().to_owned(), + from, + to, + access: record.access().clone(), + cost: record.cost(), + open: record.is_open(), + } + }) + .collect(); + let channels = state + .channels + .iter() + .map(|(entity_id, record)| ChannelSnapshot { + id: *entity_id, + reach: record.reach.clone(), + controller: record.controller, + }) + .collect(); + // Omniscient and independent of any subject's own knowledge projection: + // a fact nobody has been told or shown is still a row here, and a + // `Ruled` fact keeps its real standing rather than the `Canonical` + // collapse every subject-facing knowledge row applies. + let facts = state + .facts + .iter() + .map(|(fact_id, record)| FactSnapshot { + id: *fact_id, + statement: record.statement.clone(), + standing: match &record.standing { + FactStanding::Canonical { .. } => FactStandingView::Canonical, + FactStanding::Claimed { by } => FactStandingView::Claimed { by: *by }, + FactStanding::Ruled => FactStandingView::Ruled, + }, + known_by: state + .knowledge + .iter() + .filter(|(_, held)| held.contains_key(fact_id)) + .map(|(subject_id, _)| *subject_id) + .collect(), + }) + .collect(); + Ok(WorldSnapshot { + world_id: state.world_id, + revision: state.revision, + phase: state.phase, + owner: state.owner.clone(), + title: state.title.clone(), + brief: state.brief.clone(), + grammar: state.grammar.as_ref().map(GrammarBinding::identity), + draft_approvals: state.draft_approvals.clone(), + required_approvers: required_approvers(state), + subjects, + affordances: state + .affordance_catalog + .iter() + .map(|(affordance_id, entry)| AffordanceSnapshot { + id: *affordance_id, + entry: entry.clone(), + render_path: state + .grammar + .as_ref() + .and_then(|grammar| grammar.verb(&entry.kind.0)) + .map(|verb| verb.render_path), + }) + .collect(), + places, + resources, + routes, + channels, + facts, + opportunities: order_opportunities(state, derive_opportunities(state)?), + now: state.now, + boundaries: derive_boundaries(state)?, + scale_deficit: derive_scale_deficit(state)?, + lens_weights: state.lens_weights.clone(), + state_digest: state.state_digest.clone(), + last_commit_digest: state.last_commit_digest.clone(), + }) +} + +/// A place in the world's causal reach that the world has not yet grown into. +/// Derived, never stored, and cleared by no writer: a boundary stops being +/// derived when its predicate stops holding. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "boundary", rename_all = "snake_case")] +pub enum CausalBoundary { + UnelaboratedDestination { + route: EdgeId, + place: EntityId, + scope: BoundaryDigest, + }, + MissingStructure { + subject: SubjectId, + key: CommitmentKey, + scope: BoundaryDigest, + }, + /// Declared, never derived: no relations partition exists. Answering one is + /// `AnswerNotDerived`. + PolityInCausalRange { + subject: SubjectId, + scope: BoundaryDigest, + }, + /// Declared, never derived: no population membership and no slice concept + /// exists. Answering one is `AnswerNotDerived`. + IndividuationRequired { + population: SubjectId, + scope: BoundaryDigest, + }, +} + +/// The digest of exactly the components that derive one boundary, produced by +/// the one `digest()` owner, in the `ScopeDigest` idiom. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub struct BoundaryDigest(String); + +impl BoundaryDigest { + /// The digest text, for the one command-key derivation that hashes it. + pub(crate) fn text(&self) -> &str { + &self.0 + } + + /// The deficit lane's answer has no preimage of its own: its digest is the + /// session's, produced by the same `sha256:` spelling. + pub(crate) fn from_digest(value: String) -> Self { + Self(value) + } +} + +#[derive(Serialize)] +struct UnelaboratedDestinationPreimage<'a> { + world_id: WorldId, + route: &'a EdgeRecord, + place: &'a EntityRecord, + contained: BTreeSet<EntityId>, + occupants: BTreeSet<SubjectId>, + incident: BTreeSet<EdgeId>, +} + +#[derive(Serialize)] +struct MissingStructurePreimage<'a> { + world_id: WorldId, + subject: SubjectId, + key: CommitmentKey, + commitment: &'a Commitment, + counterparty_authority: BTreeSet<AuthorityGrant>, + redress: &'a BTreeMap<GrievanceKindName, Forum>, +} + +/// Beside `derive_opportunities`, and reached from `snapshot` and from +/// `reduce`'s `AdmitPatch` arm. The same shape as the opportunity derivation, +/// not the same function: the inputs and the consumers differ, and a shared +/// derivation returning a sum type would be a generic helper wearing a name. +fn derive_boundaries(state: &WorldState) -> Result<Vec<CausalBoundary>, KernelError> { + let mut boundaries = Vec::new(); + for (edge_id, record) in &state.edges { + let (from, to) = record.endpoints(); + for place in [from, to] { + let contained: BTreeSet<EntityId> = state + .entities + .iter() + .filter(|(_, entity)| entity.container == Some(place)) + .map(|(entity_id, _)| *entity_id) + .collect(); + let occupants: BTreeSet<SubjectId> = state + .positions + .iter() + .filter(|(_, position)| position.place == place) + .map(|(subject_id, _)| *subject_id) + .collect(); + let incident: BTreeSet<EdgeId> = state + .edges + .iter() + .filter(|(_, candidate)| { + let (candidate_from, candidate_to) = candidate.endpoints(); + candidate_from == place || candidate_to == place + }) + .map(|(candidate_id, _)| *candidate_id) + .collect(); + if !contained.is_empty() + || !occupants.is_empty() + || incident.len() != 1 + || !incident.contains(edge_id) + { + continue; + } + let entity = state + .entities + .get(&place) + .ok_or_else(|| KernelError::Invariant("a route names no canonical place".into()))?; + boundaries.push(CausalBoundary::UnelaboratedDestination { + route: *edge_id, + place, + scope: BoundaryDigest(digest(&UnelaboratedDestinationPreimage { + world_id: state.world_id, + route: record, + place: entity, + contained, + occupants, + incident, + })?), + }); + } + } + // A commitment the counterparty can neither command nor litigate. Both + // clauses read the civic partitions through their own predicates, so + // jurisdiction lent by an office counts and no second covering rule exists. + // A `Goal` derives nothing: a promise to oneself needs no forum. + for (subject, held) in &state.commitments { + for (key, commitment) in held { + let Some(counterparty) = commitment.counterparty else { + continue; + }; + let counterparty_authority = subject_authority(state, counterparty); + let commandable = counterparty_authority + .iter() + .any(|grant| covers(state, grant.over, Target::Subject(*subject))); + let litigable = state + .redress + .values() + .any(|forum| covers(state, forum.standing, Target::Subject(counterparty))); + if commandable || litigable { + continue; + } + boundaries.push(CausalBoundary::MissingStructure { + subject: *subject, + key: *key, + scope: BoundaryDigest(digest(&MissingStructurePreimage { + world_id: state.world_id, + subject: *subject, + key: *key, + commitment, + counterparty_authority, + redress: &state.redress, + })?), + }); + } + } + Ok(boundaries) +} + +/// The sole validator of a claimed boundary, mirroring `exact_opportunity`. +fn exact_boundary( + state: &WorldState, + claimed: &CausalBoundary, +) -> Result<CausalBoundary, KernelError> { + derive_boundaries(state)? + .into_iter() + .find(|current| current == claimed) + .ok_or(KernelError::AnswerNotDerived) +} + +/// One region's count for one subject kind. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct ScaleDeficitRow { + pub jurisdiction: JurisdictionKey, + pub kind: SubjectKind, + pub target: u32, + pub qualified: u32, + pub deficit: u32, +} + +/// Whether a subject counts toward the world's scale target. Aliveness is +/// structural and phase-free: a controller, a non-empty grant set, and a held +/// `Goal`. A Draft world's deficit is what the seed lane has left to author; an +/// Active world's is what the elaborator has left to answer. +/// +/// There is no phase clause here because `require_answer` already owns the +/// Draft-answer refusal: it refuses every Draft answer outright, so a phase +/// clause in this predicate would protect nothing and would only pin a Draft +/// world's deficit at the authored intent forever, leaving the seed lane no +/// derived termination. +/// +/// The conjunction is written once, because retirement and grant revocation +/// make the first two clauses live later and a scattered count would then be +/// wrong in three places. "Executable" is structural, never "preconditions +/// currently hold": evaluating them per subject per snapshot would make the +/// deficit flicker as routes open and close. +fn qualifies(state: &WorldState, subject_id: SubjectId) -> bool { + let scope = DecisionScope { subject_id }; + state.controller_assignments.contains_key(&scope) + && state + .affordance_grants + .get(&scope) + .is_some_and(|granted| !granted.is_empty()) + && state.commitments.get(&subject_id).is_some_and(|held| { + held.values() + .any(|commitment| commitment.kind == CommitmentKind::Goal) + }) +} + +/// Derived in `snapshot`, never stored. `snapshot` is the recount: it already +/// re-derives everything, and a second after-every-commit step would be a +/// second owner. Only admitted subjects reduce it, so a rejected patch leaves +/// it visible, which is free — a rejection mutates nothing. +fn derive_scale_deficit(state: &WorldState) -> Result<Vec<ScaleDeficitRow>, KernelError> { + let mut counted: BTreeMap<(JurisdictionKey, SubjectKind), u32> = BTreeMap::new(); + for (subject_id, subject) in &state.subjects { + if !qualifies(state, *subject_id) { + continue; + } + match state.positions.get(subject_id) { + // A subject under nested roots counts toward both: layered + // jurisdiction applied to counting. A subject standing somewhere + // no declared root covers still counts, in `Uncovered`, so the + // deficit stays total over every qualifying subject. + Some(position) => { + let mut covered = false; + for root in state.scale_intent.jurisdictions.keys() { + if patch::covers_place(&state.entities, *root, position.place) { + covered = true; + *counted + .entry((JurisdictionKey::PlaceSubtree(*root), subject.kind)) + .or_default() += 1; + } + } + if !covered { + *counted + .entry((JurisdictionKey::Uncovered, subject.kind)) + .or_default() += 1; + } + } + // Counted, visible, and reducing no target. + None => { + *counted + .entry((JurisdictionKey::Uncovered, subject.kind)) + .or_default() += 1; + } + } + } + let mut rows: BTreeMap<(JurisdictionKey, SubjectKind), ScaleDeficitRow> = BTreeMap::new(); + for (kind, world_target) in &state.scale_intent.targets { + for (root, permille) in &state.scale_intent.jurisdictions { + let jurisdiction = JurisdictionKey::PlaceSubtree(*root); + let target = u32::try_from( + u64::from(*world_target) + .checked_mul(u64::from(*permille)) + .ok_or_else(|| KernelError::Invariant("scale target overflow".into()))? + / 1000, + ) + .map_err(|_| KernelError::Invariant("scale target overflow".into()))?; + let qualified = counted + .get(&(jurisdiction, *kind)) + .copied() + .unwrap_or_default(); + rows.insert( + (jurisdiction, *kind), + ScaleDeficitRow { + jurisdiction, + kind: *kind, + target, + qualified, + deficit: target.saturating_sub(qualified), + }, + ); + } + } + for ((jurisdiction, kind), qualified) in counted { + rows.entry((jurisdiction, kind)) + .or_insert(ScaleDeficitRow { + jurisdiction, + kind, + target: 0, + qualified, + deficit: 0, + }) + .qualified = qualified; + } + Ok(rows + .into_values() + .filter(|row| row.target > 0 || row.qualified > 0) + .collect()) +} + +/// A pure re-ordering of `derive_opportunities`' output: same values, same +/// length, same set. Never a filter — filtering by readiness would drag +/// precondition reads into `ScopePreimage`, and a tick could then withdraw an +/// opportunity a controller is mid-inference on, which `exact_opportunity` +/// would report as `OpportunityMismatch` rather than the honest `ScopeChanged`. +/// +/// A subject never attended sorts ahead of every subject that has, and a +/// subject with no pressure still climbs one tick at a time, so the order +/// starves nobody. `SubjectId` is the final tiebreak, so the order is total and +/// identical on every machine. +fn order_opportunities( + state: &WorldState, + mut opportunities: Vec<DecisionOpportunity>, +) -> Vec<DecisionOpportunity> { + opportunities.sort_by_key(|opportunity| { + let subject_id = opportunity.scope.subject_id; + ( + std::cmp::Reverse(pressure_total(state, subject_id)), + std::cmp::Reverse(attention_debt(state, subject_id)), + subject_id, + ) + }); + opportunities +} + +fn pressure_total(state: &WorldState, subject_id: SubjectId) -> u64 { + state + .pressures + .get(&subject_id) + .into_iter() + .flat_map(BTreeMap::values) + .fold(0u64, |total, magnitude| { + total.saturating_add(u64::from(magnitude.0)) + }) +} + +/// Minutes since this subject last consumed an opportunity. Absence is +/// `u64::MAX`: never attended outranks every subject that has. +fn attention_debt(state: &WorldState, subject_id: SubjectId) -> u64 { + state + .last_opportunity_at + .get(&subject_id) + .map_or(u64::MAX, |stamp| state.now.since(*stamp)) +} + +fn derive_opportunities(state: &WorldState) -> Result<Vec<DecisionOpportunity>, KernelError> { + if state.phase != WorldPhase::Active { + return Ok(Vec::new()); + } + state + .controller_assignments + .iter() + // World truth, not a scheduling preference: a mirror has no turn, so it + // never mints an opportunity and never trips the empty-grant invariant. + .filter(|(_, controller)| controller.mode().is_some()) + .map(|(scope, controller)| { + let (Some(controller_id), Some(controller_mode)) = (controller.id(), controller.mode()) + else { + return Err(KernelError::Invariant( + "decision scope has no controller turn".into(), + )); + }; + let affordance_ids: Vec<_> = state + .affordance_grants + .get(scope) + .into_iter() + .flatten() + .copied() + .collect(); + if affordance_ids.is_empty() { + return Err(KernelError::Invariant( + "active decision scope has no affordances".into(), + )); + } + Ok(DecisionOpportunity { + world_id: state.world_id, + revision: state.revision, + scope_digest: scope_digest(state, *scope)?, + scope: *scope, + controller_id, + controller_mode, + affordance_ids, + }) + }) + .collect() +} + +/// The entries one scope is granted, paired with their definitions. A grant +/// naming no catalog entry is a corrupt kernel rather than a rejection: one +/// owner writes both partitions in one commit. +fn granted_entries( + state: &WorldState, + scope: DecisionScope, +) -> Result<BTreeMap<AffordanceId, &Affordance>, KernelError> { + state + .affordance_grants + .get(&scope) + .into_iter() + .flatten() + .map(|affordance_id| { + state + .affordance_catalog + .get(affordance_id) + .map(|entry| (*affordance_id, entry)) + .ok_or_else(|| KernelError::Invariant("granted affordance has no entry".into())) + }) + .collect() +} + +/// One affordance the kernel has already gated: the opportunity offers this +/// entry, the scope holds it, and `entry` is its catalog definition. It is the +/// only way to name an affordance to `action::exercise`, so a caller cannot +/// reach the invocation pipeline without passing the grant check first. +pub(crate) struct GrantedAffordance<'a> { + pub(crate) id: AffordanceId, + pub(crate) entry: &'a Affordance, +} + +/// The membership half of the affordance check, shared by `reduce` and +/// `apply_effect`: the opportunity offers the entry and the scope holds it. It +/// returns the entry rather than a unit, so the gate and the lookup are one act. +fn require_granted<'a>( + state: &'a WorldState, + current: &DecisionOpportunity, + affordance: AffordanceId, +) -> Result<GrantedAffordance<'a>, KernelError> { + if current.affordance_ids.contains(&affordance) + && state + .affordance_grants + .get(¤t.scope) + .is_some_and(|granted| granted.contains(&affordance)) + { + let entry = state + .affordance_catalog + .get(&affordance) + .ok_or_else(|| KernelError::Invariant("granted affordance has no entry".into()))?; + Ok(GrantedAffordance { + id: affordance, + entry, + }) + } else { + Err(KernelError::AffordanceDenied) + } +} + +/// The sole producer of a `ScopeDigest`. The components it reads come from +/// `scope_components`, which the snapshot reads too. +fn scope_digest(state: &WorldState, scope: DecisionScope) -> Result<ScopeDigest, KernelError> { + let controller = state + .controller_assignments + .get(&scope) + .ok_or_else(|| KernelError::Invariant("decision scope has no controller".into()))?; + let affordances = granted_entries(state, scope)?; + let components = scope_components(state, scope.subject_id); + digest(&ScopePreimage { + world_id: state.world_id, + subject_id: scope.subject_id, + controller, + affordances, + components: &components, + }) + .map(ScopeDigest) +} + +/// Binding, which is one of the two checks a committed invocation passes. +/// Binding is scope-digest equality: has what the proposal was made against +/// moved? Admission — preconditions, effect ceilings, and the band draw, all in +/// `action::exercise` — is the other, and it runs at commit against the same +/// revision the digest was verified at. A component that admission reads but +/// binding does not is therefore fail-closed by re-check at commit rather than +/// by rejecting the proposal when it changes. +fn exact_opportunity( + state: &WorldState, + claimed: &DecisionOpportunity, +) -> Result<DecisionOpportunity, KernelError> { + if claimed.world_id != state.world_id { + return Err(KernelError::OpportunityMismatch); + } + let current = derive_opportunities(state)? + .into_iter() + .find(|current| current.scope == claimed.scope) + .ok_or(KernelError::OpportunityMismatch)?; + if claimed.revision > state.revision { + return Err(KernelError::OpportunityMismatch); + } + if current.scope_digest != claimed.scope_digest { + return Err(KernelError::ScopeChanged { + scope: claimed.scope, + expected: claimed.scope_digest.clone(), + actual: current.scope_digest, + }); + } + Ok(current) +} + +fn required_approvers(state: &WorldState) -> BTreeSet<PrincipalId> { + std::iter::once(state.owner.clone()) + .chain( + state + .controller_assignments + .values() + .filter_map(ControllerAssignment::human_principal) + .cloned(), + ) + .collect() +} + +/// Who may admit a patch, and inside what. `None` means unconfined: the owner. +/// Reached from `reduce`'s `AdmitPatch` arm and re-reached from `apply_effect`'s +/// `PatchAdmitted` arm, per the file's idiom that `reduce` decides and +/// `apply_effect` re-decides. +fn require_patch_author( + state: &WorldState, + caller: &CallerId, + answers: Option<&PatchAnswer>, +) -> Result<Option<PatchGround>, KernelError> { + match caller { + CallerId::Principal(principal) if principal == &state.owner => Ok(None), + CallerId::System(SystemCapability::Play) => Ok(None), + CallerId::System(SystemCapability::Elaborator { jurisdiction }) => { + let answer = answers.ok_or(KernelError::Unauthorized)?; + let ground = PatchGround::Jurisdiction(*jurisdiction); + if !ground_covers(state, ground, answer) { + return Err(KernelError::Unauthorized); + } + Ok(Some(ground)) + } + CallerId::System(SystemCapability::Consumer { consumer }) => { + // Authority over its own mirrors is not jurisdictional and does not + // depend on an answer. An answer, when present, must name a subject + // this consumer is bound to, so a consumer cannot claim credit for + // structure it is confined out of writing. + let ground = PatchGround::Consumer(*consumer); + if let Some(answer) = answers + && !ground_covers(state, ground, answer) + { + return Err(KernelError::Unauthorized); + } + Ok(Some(ground)) + } + _ => Err(KernelError::Unauthorized), + } +} + +/// Does the caller's jurisdiction cover the thing the answer names? +/// +/// Two coverings, deliberately asymmetric. A boundary is covered +/// **transitively** through `covers_place`, so a parent jurisdiction's +/// elaborator may answer a boundary in a nested child. A deficit is covered by +/// **exact key equality**: a subject under nested roots counts toward both +/// roots' targets, so a parent answering a child's row would reduce two targets +/// with one subject and drain a child's queue while its own row stays red. +/// Boundaries name a thing; deficits name a row. +/// A consumer's arm is narrower on purpose: it may answer only a +/// `MissingStructure` boundary on one of its own mirrors. A deficit is +/// jurisdictional and a consumer holds no jurisdiction; a boundary about a +/// foreign subject is not its business. +fn ground_covers(state: &WorldState, held: PatchGround, answer: &PatchAnswer) -> bool { + let held = match held { + PatchGround::Jurisdiction(jurisdiction) => jurisdiction, + PatchGround::Consumer(consumer) => { + let PatchAnswer::Boundary(CausalBoundary::MissingStructure { subject, .. }) = answer + else { + return false; + }; + return bound_to_consumer(state, *subject, consumer); + } + }; + match answer { + PatchAnswer::Boundary(CausalBoundary::UnelaboratedDestination { place, .. }) => { + place_in(state, held, *place) + } + // The two never-derived variants join this clause only so the match is + // total; `exact_boundary` refuses them before authority is read. + PatchAnswer::Boundary( + CausalBoundary::MissingStructure { subject, .. } + | CausalBoundary::PolityInCausalRange { subject, .. } + | CausalBoundary::IndividuationRequired { + population: subject, + .. + }, + ) => match state.positions.get(subject) { + Some(position) => place_in(state, held, position.place), + None => held == JurisdictionKey::Uncovered, + }, + PatchAnswer::Deficit(key) => *key == held, + } +} + +/// Is this committed subject one of that consumer's mirrors? The consumer's +/// ground is derived here, at decision time, and never carried on the wire: a +/// binding a later commit revoked shrinks the consumer's authority with no +/// ingress change. +fn bound_to_consumer(state: &WorldState, subject: SubjectId, consumer: ConsumerId) -> bool { + state + .controller_assignments + .get(&DecisionScope { + subject_id: subject, + }) + .and_then(ControllerAssignment::consumer) + == Some(consumer) +} + +fn place_in(state: &WorldState, held: JurisdictionKey, place: EntityId) -> bool { + match held { + JurisdictionKey::PlaceSubtree(root) => patch::covers_place(&state.entities, root, place), + JurisdictionKey::Uncovered => false, + } +} + +/// The ground a patch writes on, as one map over `state ∪ patch`, so a place +/// declared and built on in the same patch confines through the chain it +/// declares. +fn candidate_places( + state: &WorldState, + resolved: &ResolvedPatch, +) -> BTreeMap<EntityId, EntityRecord> { + let mut entities = state.entities.clone(); + for declared in &resolved.entities { + entities.insert(declared.entity_id, declared.entity.clone()); + } + for declared in &resolved.facts { + entities.insert(declared.entity_id, declared.entity.clone()); + } + for declared in &resolved.channels { + entities.insert(declared.entity_id, declared.entity.clone()); + } + entities +} + +/// Every place-or-subject referent a jurisdictional author writes must sit under +/// its jurisdiction. Returns the complete set, like every other check. +/// +/// Placeless referents — resource kinds, catalog entries, canonical facts — +/// name no ground and are not confined. A place declared with no container is a +/// new jurisdiction root and is the owner's act. There is no relevance test: a +/// patch that satisfies its answer may also declare unrelated structure inside +/// its jurisdiction, because "the minimum the boundary needs" is a semantic +/// verdict the kernel must not hold. +fn confine_to_ground( + state: &WorldState, + resolved: &ResolvedPatch, + held: PatchGround, +) -> Result<(), Vec<Mismatch>> { + let entities = candidate_places(state, resolved); + // A consumer names no ground, so every place, every route, and every + // place-shaped reach is refused with no extra rule: relocation, route + // opening and closing, cost changes, and place-subtree grants are + // unrepresentable for it because they carry a place or a route. + let inside = |place: EntityId| match held { + PatchGround::Jurisdiction(JurisdictionKey::PlaceSubtree(root)) => { + patch::covers_place(&entities, root, place) + } + PatchGround::Jurisdiction(JurisdictionKey::Uncovered) | PatchGround::Consumer(_) => false, + }; + // Every subject's consumer binding over `state ∪ patch`, so a consumer's + // first document can declare its own mirror and write it in one patch. + let mut bindings: BTreeMap<SubjectId, Option<ConsumerId>> = state + .controller_assignments + .iter() + .map(|(scope, assignment)| (scope.subject_id, assignment.consumer())) + .collect(); + for declared in &resolved.subjects { + bindings.insert(declared.subject_id, declared.controller.consumer()); + } + let mut positions: BTreeMap<SubjectId, Option<EntityId>> = state + .positions + .iter() + .map(|(subject, position)| (*subject, Some(position.place))) + .collect(); + for declared in &resolved.subjects { + positions.insert( + declared.subject_id, + declared.position.map(|position| position.place), + ); + } + let mut edges: BTreeMap<EdgeId, (EntityId, EntityId)> = state + .edges + .iter() + .map(|(edge_id, record)| (*edge_id, record.endpoints())) + .collect(); + for declared in &resolved.routes { + edges.insert(declared.edge_id, declared.edge.endpoints()); + } + + let mut mismatches = Vec::new(); + let mut confine_subject = |site: &Site, subject: SubjectId, mismatches: &mut Vec<Mismatch>| { + let admitted = match held { + PatchGround::Jurisdiction(jurisdiction) => { + match positions.get(&subject).copied().flatten() { + Some(place) => inside(place), + None => jurisdiction == JurisdictionKey::Uncovered, + } + } + // Position is unconfined for a consumer: what binds a mirror is who + // controls it, not where it stands. + PatchGround::Consumer(consumer) => { + bindings.get(&subject).copied().flatten() == Some(consumer) + } + }; + if !admitted { + mismatches.push(Mismatch::OutsideJurisdiction { site: site.clone() }); + } + }; + let mut confine_place = |site: &Site, place: EntityId, mismatches: &mut Vec<Mismatch>| { + if !inside(place) { + mismatches.push(Mismatch::OutsideJurisdiction { site: site.clone() }); + } + }; + + for declared in &resolved.subjects { + let site = Site::Declaration(declared.handle.clone()); + confine_subject(&site, declared.subject_id, &mut mismatches); + } + for declared in &resolved.entities { + if declared.entity.kind != EntityKind::Place { + continue; + } + let site = Site::Declaration(declared.handle.clone()); + match declared.entity.container { + Some(container) => confine_place(&site, container, &mut mismatches), + // A root is the owner's act. An elaborator elaborates inside one. + None => mismatches.push(Mismatch::OutsideJurisdiction { site }), + } + } + for declared in &resolved.routes { + let site = Site::Declaration(declared.handle.clone()); + let (from, to) = declared.edge.endpoints(); + confine_place(&site, from, &mut mismatches); + confine_place(&site, to, &mut mismatches); + } + for declared in &resolved.facts { + let site = Site::Declaration(declared.handle.clone()); + match declared.fact.standing { + FactStanding::Claimed { by } => confine_subject(&site, by, &mut mismatches), + // A consumer's citation is its own provenance claim, and that claim + // buys an `Admit` into its own custody and a claimed fact. It + // cannot canonize. + FactStanding::Canonical { .. } => { + if matches!(held, PatchGround::Consumer(_)) { + mismatches.push(Mismatch::OutsideJurisdiction { site }); + } + } + // Redundant with `require_ruler`, which refuses a confined caller's + // `Ruled` fact outright; kept so this match stays total. + FactStanding::Ruled => { + mismatches.push(Mismatch::OutsideJurisdiction { site }); + } + } + } + for declared in &resolved.channels { + let site = Site::Declaration(declared.handle.clone()); + match &declared.channel.reach { + Reach::Place(place) => confine_place(&site, *place, &mut mismatches), + Reach::Subjects(subjects) => { + for subject in subjects { + confine_subject(&site, *subject, &mut mismatches); + } + } + } + if let Some(controller) = declared.channel.controller { + confine_subject(&site, controller, &mut mismatches); + } + } + for (index, operation) in resolved.operations.iter().enumerate() { + let site = Site::Operation(index); + // Retirement and an affordance grant are authority over the subject's + // standing, not structure over ground: a confined author is refused + // whatever place the subject stands under, exactly as `require_ruler` + // refuses a `Ruled` fact or a `Mint` outright. The owner is unconfined + // and never reaches this clause. + if matches!( + operation, + ResolvedOp::Retire { .. } + | ResolvedOp::GrantAffordance { .. } + | ResolvedOp::RevokeAffordance { .. } + ) { + mismatches.push(Mismatch::OutsideJurisdiction { site: site.clone() }); + continue; + } + let (subjects, places, routes) = operation_ground(operation, &entities); + for subject in subjects { + confine_subject(&site, subject, &mut mismatches); + } + for place in places { + confine_place(&site, place, &mut mismatches); + } + for route in routes { + match edges.get(&route) { + Some((from, to)) => { + confine_place(&site, *from, &mut mismatches); + confine_place(&site, *to, &mut mismatches); + } + None => mismatches.push(Mismatch::OutsideJurisdiction { site: site.clone() }), + } + } + } + mismatches.sort(); + mismatches.dedup(); + if mismatches.is_empty() { + Ok(()) + } else { + Err(mismatches) + } +} + +/// The one author of a `Ruled` fact and a `Mint`. `Ok` when the caller is +/// `System(Play)`. Otherwise, one `Mismatch::RuledWithoutAuthority` per +/// `Ruled` fact and per `Mint`, and `Ok` if there are none. Called in +/// `reduce`'s `AdmitPatch` arm right after `resolve_patch` and before +/// confinement, and re-decided in `apply_effect`'s `PatchAdmitted` arm. The +/// resolver stays actor-blind: this runs after resolution, never inside it. +fn require_ruler(caller: &CallerId, resolved: &ResolvedPatch) -> Result<(), Vec<Mismatch>> { + if caller == &CallerId::System(SystemCapability::Play) { + return Ok(()); + } + let mut mismatches = Vec::new(); + for declared in &resolved.facts { + if matches!(declared.fact.standing, FactStanding::Ruled) { + mismatches.push(Mismatch::RuledWithoutAuthority { + site: Site::Declaration(declared.handle.clone()), + }); + } + } + for (index, operation) in resolved.operations.iter().enumerate() { + if matches!(operation, ResolvedOp::Mint { .. }) { + mismatches.push(Mismatch::RuledWithoutAuthority { + site: Site::Operation(index), + }); + } + } + if mismatches.is_empty() { + Ok(()) + } else { + Err(mismatches) + } +} + +/// The ground one lowered operation touches: the subjects whose position it +/// must sit under, the places it names directly, and the routes whose endpoints +/// it must sit under. Total over `ResolvedOp`, so a new operation cannot ship +/// without saying where it lands. +fn operation_ground( + operation: &ResolvedOp, + entities: &BTreeMap<EntityId, EntityRecord>, +) -> (Vec<SubjectId>, Vec<EntityId>, Vec<EdgeId>) { + // A resource, a fact, and a channel are placeless referents: they name no + // ground, so only a place among the named entities confines. + let places = |candidates: Vec<EntityId>| { + candidates + .into_iter() + .filter(|entity_id| { + entities + .get(entity_id) + .is_some_and(|record| record.kind == EntityKind::Place) + }) + .collect() + }; + match operation { + ResolvedOp::Relocate { + subject_id, + edge_id, + } => (vec![*subject_id], Vec::new(), vec![*edge_id]), + ResolvedOp::OpenRoute { edge_id } | ResolvedOp::CloseRoute { edge_id } => { + (Vec::new(), Vec::new(), vec![*edge_id]) + } + ResolvedOp::AlterCost { edge_id, .. } => (Vec::new(), Vec::new(), vec![*edge_id]), + ResolvedOp::Transfer { + from, to, resource, .. + } => (vec![*from, *to], places(vec![*resource]), Vec::new()), + ResolvedOp::Transform { + holder, + from_resource, + into_resource, + .. + } => ( + vec![*holder], + places(vec![*from_resource, *into_resource]), + Vec::new(), + ), + ResolvedOp::Consume { + holder, resource, .. + } + | ResolvedOp::Admit { + holder, resource, .. + } + | ResolvedOp::Mint { + holder, resource, .. + } => (vec![*holder], places(vec![*resource]), Vec::new()), + ResolvedOp::Bind { subject, target } | ResolvedOp::Release { subject, target } => { + match target { + DependencyTarget::Subject(other) => { + (vec![*subject, *other], Vec::new(), Vec::new()) + } + DependencyTarget::Route(edge_id) => (vec![*subject], Vec::new(), vec![*edge_id]), + DependencyTarget::Resource(resource) => { + (vec![*subject], places(vec![*resource]), Vec::new()) + } + } + } + ResolvedOp::GrantAuthority { holder, grant } + | ResolvedOp::RevokeAuthority { holder, grant } => match grant.over { + AuthorityTarget::Subject(other) => (vec![*holder, other], Vec::new(), Vec::new()), + AuthorityTarget::PlaceSubtree(root) => (vec![*holder], vec![root], Vec::new()), + }, + ResolvedOp::OpenOffice { institution, .. } + | ResolvedOp::CloseOffice { institution, .. } + | ResolvedOp::VacateOffice { institution, .. } => { + (vec![*institution], Vec::new(), Vec::new()) + } + ResolvedOp::InstallIncumbent { + institution, + incumbent, + .. + } => (vec![*institution, *incumbent], Vec::new(), Vec::new()), + ResolvedOp::OpenForum { + forum, standing, .. + } => match standing { + AuthorityTarget::Subject(other) => (vec![*forum, *other], Vec::new(), Vec::new()), + AuthorityTarget::PlaceSubtree(root) => (vec![*forum], vec![*root], Vec::new()), + }, + ResolvedOp::CloseForum { .. } => (Vec::new(), Vec::new(), Vec::new()), + ResolvedOp::AcquireKnowledge { subject, .. } | ResolvedOp::Forget { subject, .. } => { + (vec![*subject], Vec::new(), Vec::new()) + } + ResolvedOp::Communicate { speaker, .. } | ResolvedOp::Display { actor: speaker, .. } => { + (vec![*speaker], Vec::new(), Vec::new()) + } + // The place is the whole ground. Confining by it is not weaker than + // confining by the recipients: `covers_place` is transitive, so every + // subject the fan-out selects stands under the place, and a place + // admitted under a root puts all of them under that root. Naming the + // recipients here would be a second statement of the same rule, + // computed from state this function does not read. + ResolvedOp::Witness { place, .. } => (Vec::new(), places(vec![*place]), Vec::new()), + ResolvedOp::SetPersonaMaterial { subject, material } => ( + std::iter::once(*subject) + .chain(material.reads.keys().copied()) + .collect(), + Vec::new(), + Vec::new(), + ), + ResolvedOp::SetReach { channel, reach } => { + let mut subjects = Vec::new(); + let mut named = Vec::new(); + match reach { + Reach::Place(place) => named.push(*place), + Reach::Subjects(members) => subjects.extend(members.iter().copied()), + } + named.push(*channel); + (subjects, places(named), Vec::new()) + } + ResolvedOp::SetController { + channel, + controller, + } => ( + controller.iter().copied().collect(), + places(vec![*channel]), + Vec::new(), + ), + // Kernel-synthesized by `action::exercise` and by nothing a patch may + // carry; it is confined by its speaker all the same. + ResolvedOp::AssertClaim { by, .. } => (vec![*by], Vec::new(), Vec::new()), + ResolvedOp::CreateCommitment { + subject, + commitment, + .. + } => ( + std::iter::once(*subject) + .chain(commitment.counterparty) + .collect(), + Vec::new(), + Vec::new(), + ), + ResolvedOp::DischargeCommitment { subject, .. } => (vec![*subject], Vec::new(), Vec::new()), + ResolvedOp::AdvancePressure { source, target, .. } + | ResolvedOp::ReducePressure { source, target, .. } + | ResolvedOp::ResolvePressure { source, target } => { + let mut subjects = vec![*target]; + let mut named = Vec::new(); + let mut routes = Vec::new(); + match source { + PressureSource::Commitment { subject, .. } | PressureSource::Subject(subject) => { + subjects.push(*subject); + } + PressureSource::Dependency(DependencyTarget::Subject(subject)) => { + subjects.push(*subject); + } + PressureSource::Dependency(DependencyTarget::Route(edge_id)) => { + routes.push(*edge_id); + } + PressureSource::Dependency(DependencyTarget::Resource(resource)) => { + named.push(*resource); + } + } + (subjects, places(named), routes) + } + // Confinement never reaches these through the ordinary ground check: + // `confine_to_ground` refuses `Retire`, `GrantAffordance`, and + // `RevokeAffordance` unconditionally for every confined author before + // this function is called for them. The subject is named here so the + // match stays total and correct if that clause is ever bypassed. + ResolvedOp::Retire { subject } + | ResolvedOp::GrantAffordance { subject, .. } + | ResolvedOp::RevokeAffordance { subject, .. } => (vec![*subject], Vec::new(), Vec::new()), + } +} + +fn require_owner(state: &WorldState, caller: &CallerId) -> Result<(), KernelError> { + if caller == &CallerId::Principal(state.owner.clone()) { + Ok(()) + } else { + Err(KernelError::Unauthorized) + } +} + +fn require_phase(state: &WorldState, expected: WorldPhase) -> Result<(), KernelError> { + if state.phase == expected { + Ok(()) + } else { + Err(KernelError::WrongPhase { + expected, + actual: state.phase, + }) + } +} + +fn normalize_title(value: &str) -> Result<String, KernelError> { + let value = value.trim(); + if value.is_empty() { + Err(KernelError::EmptyTitle) + } else { + Ok(value.to_owned()) + } +} + +fn validate_principal(value: &PrincipalId) -> Result<(), KernelError> { + if value.0.trim().is_empty() || value.0.trim() != value.0 { + Err(KernelError::EmptyPrincipal) + } else { + Ok(()) + } +} + +fn validate_assignment(value: &ControllerAssignment) -> Result<(), KernelError> { + if let ControllerAssignment::Human { principal, .. } = value { + validate_principal(principal)?; + } + Ok(()) +} + +/// The revision a non-genesis commit resolves to: one past `state.revision`, +/// which still holds the *previous* revision here, since `submit` only bumps +/// it after `apply_effect` returns. Genesis is not a caller: it resolves to +/// `state.revision` itself and computes that directly (PA.f49). +fn resolution_revision(state: &WorldState) -> Result<u64, KernelError> { + state + .revision + .checked_add(1) + .ok_or_else(|| KernelError::Serialization("world revision overflow".into())) +} + +/// `command_id` is the band draw's only per-command term, so the arm that +/// re-derives an exercised decision needs the same one `reduce` drew from. +fn apply_effect( + state: &mut WorldState, + command_id: CommandId, + caller: &CallerId, + effect: &WorldEffect, +) -> Result<(), KernelError> { + // The capability rule `reduce` decided, re-decided here against the effect + // the command produced. + if let CallerId::System(capability) = caller { + let admitted = matches!( + (capability, effect), + (SystemCapability::Clock, WorldEffect::TimeAdvanced { .. }) + | (SystemCapability::Play, WorldEffect::TimeAdvanced { .. }) + | ( + SystemCapability::Elaborator { .. } + | SystemCapability::Consumer { .. } + | SystemCapability::Play, + WorldEffect::PatchAdmitted { .. } + ) + ); + if !admitted { + return Err(KernelError::Unauthorized); + } + } + match effect { + WorldEffect::WorldCreated { .. } => { + return Err(KernelError::Invariant( + "world genesis cannot be applied as a mutable effect".into(), + )); + } + WorldEffect::PatchAdmitted { answers, resolved } => { + require_answer(state, caller, answers.as_ref(), !resolved.declares_nothing())?; + require_ruler(caller, resolved).map_err(|_| { + KernelError::Invariant( + "admitted patch rules or mints without the play authority".into(), + ) + })?; + let confinement = + require_patch_author(state, caller, answers.as_ref()).map_err(|_| { + KernelError::Invariant( + "admitted patch does not satisfy admission authority".into(), + ) + })?; + if let Some(ground) = confinement { + confine_to_ground(state, resolved, ground).map_err(|_| { + KernelError::Invariant( + "admitted patch wrote outside its author's ground".into(), + ) + })?; + } + // The deficit before the write, so "strictly decreased" is a + // comparison rather than a claim the effect makes. + let before = match answers { + Some(PatchAnswer::Deficit(jurisdiction)) => { + jurisdiction_deficit(state, *jurisdiction)? + } + _ => 0, + }; + let resolves_to = resolution_revision(state)?; + admit_resolved(state, resolved, resolves_to)?; + // What makes "a commit clears exactly the boundary it answers" + // structural rather than hoped for. "Nothing else clears one" is + // true by construction: boundaries are derived and no writer + // clears one. + match answers { + Some(PatchAnswer::Boundary(answered)) => { + if exact_boundary(state, answered).is_ok() { + return Err(KernelError::AnswerNotSatisfied); + } + } + Some(PatchAnswer::Deficit(jurisdiction)) => { + if jurisdiction_deficit(state, *jurisdiction)? >= before { + return Err(KernelError::AnswerNotSatisfied); + } + } + None => {} + } + } + WorldEffect::DraftApproved { principal } => { + if state.phase != WorldPhase::Draft + || caller != &CallerId::Principal(principal.clone()) + || !required_approvers(state).contains(principal) + || !state.draft_approvals.insert(principal.clone()) + { + return Err(KernelError::Invariant( + "draft-approval effect is unauthorized or duplicate".into(), + )); + } + } + WorldEffect::WorldActivated => { + if caller != &CallerId::Principal(state.owner.clone()) + || state.phase != WorldPhase::Draft + || !required_approvers(state).is_subset(&state.draft_approvals) + { + return Err(KernelError::Invariant( + "activation does not satisfy lifecycle authority".into(), + )); + } + state.phase = WorldPhase::Active; + } + WorldEffect::DecisionExercised { + opportunity, + invocation, + event, + } => { + let current = exact_opportunity(state, opportunity)?; + let assignment = state + .controller_assignments + .get(¤t.scope) + .ok_or_else(|| { + KernelError::Invariant("decision scope lost its controller".into()) + })?; + if state.phase != WorldPhase::Active + || assignment.expected_caller().as_ref() != Some(caller) + { + return Err(KernelError::Invariant( + "decision effect does not match exact opportunity authority".into(), + )); + } + let granted = require_granted(state, ¤t, invocation.affordance)?; + // The whole event is re-derived by the function that produced the + // honest one, so a forged band, operation, magnitude, minted claim, + // or utterance is one comparison rather than a clause apiece. + let derived = action::exercise(state, command_id, ¤t, &granted, invocation)?; + if derived != *event { + return Err(KernelError::Invariant( + "decision effect does not derive from its opportunity".into(), + )); + } + state.events.push(event.clone()); + if !event.effects.is_empty() { + // `derived != *event` above already proved `event.revision` is + // exactly what `resolution_revision(state)` would compute right + // now; read it back rather than computing it a second time. + apply_operations(state, &event.effects, &[], event.revision)?; + } + state + .last_opportunity_at + .insert(current.scope.subject_id, state.now); + } + WorldEffect::DecisionDeclined { opportunity } => { + let current = exact_opportunity(state, opportunity)?; + let assignment = state + .controller_assignments + .get(¤t.scope) + .ok_or_else(|| { + KernelError::Invariant("decision scope lost its controller".into()) + })?; + if state.phase != WorldPhase::Active + || assignment.expected_caller().as_ref() != Some(caller) + { + return Err(KernelError::Invariant( + "decline effect does not match exact opportunity authority".into(), + )); + } + // A decline consumed the turn: a controller that keeps declining + // must not keep the head of the queue. + state + .last_opportunity_at + .insert(current.scope.subject_id, state.now); + } + WorldEffect::TimeAdvanced { + minutes, + to, + motion, + } => { + require_phase(state, WorldPhase::Active)?; + require_clock_caller(state, caller)?; + let derived_to = state + .now + .checked_add(*minutes) + .ok_or_else(|| KernelError::Serialization("world clock overflow".into()))?; + // The whole motion is re-derived rather than trusted field by + // field, so a forged fulfilment, magnitude, row, and target are one + // comparison. + if derived_to != *to || clock::derive_motion(state, derived_to) != *motion { + return Err(KernelError::Invariant( + "time effect does not derive from the world clock".into(), + )); + } + state.now = *to; + for rolled in &motion.fulfilled { + let commitment = state + .commitments + .get_mut(&rolled.subject) + .and_then(|held| held.get_mut(&rolled.key)) + .ok_or_else(|| { + KernelError::Invariant("a fulfilled routine has no commitment".into()) + })?; + commitment.due = rolled.next_due; + } + // No inner map is ever left empty, because `derive_motion` emits no + // zero magnitude. + for written in &motion.pressed { + state + .pressures + .entry(written.target) + .or_default() + .insert(written.source, written.magnitude); + } + } + WorldEffect::LensWeightsReplaced { weights } => { + if caller != &CallerId::Principal(state.owner.clone()) || !weights.draws() { + return Err(KernelError::Invariant( + "lens weights effect does not satisfy owner admission".into(), + )); + } + state.lens_weights = weights.clone(); + } + } + Ok(()) +} + +fn digest<T: Serialize>(value: &T) -> Result<String, KernelError> { + let bytes = rmp_serde::to_vec_named(value) + .map_err(|error| KernelError::Serialization(error.to_string()))?; + Ok(format!("sha256:{:x}", Sha256::digest(bytes))) +} + +fn state_digest(state: &WorldState) -> Result<String, KernelError> { + let mut value = state.clone(); + value.state_digest.clear(); + value.last_commit_digest = None; + digest(&value) +} + +fn commit_digest(commit: &WorldCommit) -> Result<String, KernelError> { + let mut value = commit.clone(); + value.digest.clear(); + digest(&value) +} + +#[cfg(test)] +mod tests { + use super::patch::kernel_speak_grant; + use super::*; + + /// What a committed event actually asserted, read from the one readable + /// home of an utterance: `facts[fact].statement`. The committed event's + /// own `AssertClaim` effect carries the same bytes as the replay witness, + /// but no projection reads that copy; `facts` is the surface. + pub(crate) fn spoken<'a>(state: &'a WorldState, event: &DecisionEvent) -> Option<&'a str> { + event + .speech + .and_then(|fact| state.facts.get(&fact)) + .map(|record| record.statement.as_str()) + } + + pub(crate) fn owner() -> PrincipalId { + PrincipalId::new("owner@example.test") + } + + pub(crate) fn human_principal() -> PrincipalId { + PrincipalId::new("human@example.test") + } + + pub(crate) fn auth_principal(principal: PrincipalId) -> AuthenticatedCaller { + AuthenticatedCaller::fixture(CallerId::Principal(principal)) + } + + pub(crate) fn subject( + handle: &str, + label: &str, + kind: SubjectKind, + controller: NewController, + ) -> Declaration { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind, + controller, + affordances: kernel_speak_grant(), + // The fixture world is one room. Co-located speech needs a place to + // fill, so every fixture subject stands in the commons. + position: Some(Ref::Draft(DraftHandle::new(COMMONS))), + import_key: None, + }) + } + + /// The one place the base fixture world declares. + pub(crate) const COMMONS: &str = "commons"; + + /// How many entities the base fixture world admits at genesis: the commons + /// and nothing else. A patch-lane test that proves a rejection allocated + /// nothing compares against this rather than against zero. + pub(crate) const FIXTURE_ENTITIES: usize = 1; + + /// The committed Speak entry. A post-genesis declaration grants it by + /// canonical reference, like every other structure a previous commit + /// allocated: the kernel synthesizes the entry once, at genesis. + pub(crate) fn speak_entry(kernel: &WorldKernel) -> Ref<AffordanceId> { + Ref::Existing( + *kernel + .state + .affordance_catalog + .iter() + .find(|(_, entry)| entry.kind.0 == "speak") + .map(|(affordance_id, _)| affordance_id) + .expect("genesis admits the kernel Speak entry"), + ) + } + + /// A catalog entry by kind name. An affordance id names an entry, not a + /// subject's copy of one, so a test that needs an entry a scope does not + /// hold asks for it by name rather than by list position. + pub(crate) fn affordance_named(snapshot: &WorldSnapshot, kind: &str) -> AffordanceId { + snapshot + .affordances + .iter() + .find(|entry| entry.entry.kind.0 == kind) + .map(|entry| entry.id) + .expect("the fixture world declares this affordance") + } + + /// Every stock lens at weight one. + pub(crate) fn stock_weights() -> LensWeights { + LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 1)).collect()) + } + + pub(crate) fn creation(id: CommandId, title: &str) -> CreateWorld { + CreateWorld { + id, + owner: owner(), + title: title.into(), + brief: String::new(), + patch: WorldPatch { + operations: Vec::new(), + evidence: Vec::new(), + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(COMMONS), + label: "The Commons".into(), + kind: EntityKind::Place, + container: None, + }), + // A second, world-declared entry granted to exactly one + // subject, so the fixture world has more than one verb and + // grant sets differ between scopes. + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("convene"), + kind: AffordanceKindName("convene".into()), + roles: Vec::new(), + // A speech-carrying entry must name exactly one + // audience for the lowering to read. + preconditions: vec![Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + }), + subject( + "human", + "The Human", + SubjectKind::Person, + NewController::Human { + principal: human_principal(), + }, + ), + subject( + "persona", + "The Witness", + SubjectKind::Person, + NewController::NarrativePersona, + ), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("operator"), + label: "The Council".into(), + kind: SubjectKind::Institution, + controller: NewController::OperationalAgent, + affordances: kernel_speak_grant() + .into_iter() + .chain(std::iter::once(Ref::Draft(DraftHandle::new("convene")))) + .collect(), + position: Some(Ref::Draft(DraftHandle::new(COMMONS))), + import_key: None, + }), + ], + }, + scale_intent: WorldScaleIntentRef::default(), + lens_weights: stock_weights(), + grammar: None, + } + } + + pub(crate) fn command( + snapshot: &WorldSnapshot, + id: CommandId, + caller: CallerId, + body: CommandBody, + ) -> CommandEnvelope { + CommandEnvelope { + id, + world_id: snapshot.world_id, + expected_revision: snapshot.revision, + caller, + body, + } + } + + pub(crate) fn submit_owner( + kernel: &mut WorldKernel, + snapshot: &WorldSnapshot, + body: CommandBody, + ) -> SubmitReceipt { + kernel + .submit( + command( + snapshot, + CommandId::new(), + CallerId::Principal(owner()), + body, + ), + &auth_principal(owner()), + ) + .unwrap() + } + + pub(crate) fn activate(kernel: &mut WorldKernel) -> WorldSnapshot { + let genesis = kernel.snapshot().unwrap(); + submit_owner(kernel, &genesis, CommandBody::ApproveDraft); + let after_owner = kernel.snapshot().unwrap(); + kernel + .submit( + command( + &after_owner, + CommandId::new(), + CallerId::Principal(human_principal()), + CommandBody::ApproveDraft, + ), + &auth_principal(human_principal()), + ) + .unwrap(); + let approved = kernel.snapshot().unwrap(); + submit_owner(kernel, &approved, CommandBody::ActivateWorld); + kernel.snapshot().unwrap() + } + + /// The canonical IDs of the shared topology fixture: three places, four + /// routes with every access and open combination the operations read, and one + /// subject standing in the yard. + pub(crate) struct Topology { + pub(crate) yard: EntityId, + pub(crate) road: EntityId, + pub(crate) gate: EntityId, + pub(crate) ramp: EdgeId, + pub(crate) shutter: EdgeId, + pub(crate) toll: EdgeId, + pub(crate) span: EdgeId, + pub(crate) walker: SubjectId, + } + + fn place(handle: &str, label: &str) -> Declaration { + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: EntityKind::Place, + container: None, + }) + } + + fn way( + handle: &str, + label: &str, + from: &str, + to: &str, + access: AccessKind, + cost: u32, + ) -> Declaration { + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + from: Ref::Draft(DraftHandle::new(from)), + to: Ref::Draft(DraftHandle::new(to)), + access, + cost: Cost(cost), + }) + } + + pub(crate) fn topology_patch(speak: Ref<AffordanceId>) -> WorldPatch { + WorldPatch { + declarations: vec![ + place("yard", "The Cavity Yard"), + place("road", "The Rhythm Road"), + place("gate", "The Rain Gate"), + way( + "ramp", + "The Yard Ramp", + "yard", + "road", + AccessKind::Public, + 12, + ), + way( + "shutter", + "The Yard Shutter", + "yard", + "gate", + AccessKind::Public, + 5, + ), + way( + "toll", + "The Toll Stair", + "yard", + "gate", + AccessKind::Restricted { + requires: AuthorityKindName(ADMIT_KIND.into()), + }, + 4, + ), + way( + "span", + "The Western Span", + "road", + "gate", + AccessKind::Public, + 7, + ), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("walker"), + label: "The Walker".into(), + kind: SubjectKind::Person, + controller: NewController::OperationalAgent, + affordances: BTreeSet::from([speak]), + position: Some(Ref::Draft(DraftHandle::new("yard"))), + import_key: None, + }), + ], + // A route that should start closed is declared and closed in one + // patch, so `open` keeps a single writer family. + operations: vec![ComponentOp::CloseRoute { + route: Ref::Draft(DraftHandle::new("shutter")), + }], + evidence: Vec::new(), + } + } + + pub(crate) fn admit_topology(kernel: &mut WorldKernel) -> Topology { + let before = kernel.snapshot().unwrap(); + let receipt = submit_owner( + kernel, + &before, + CommandBody::AdmitPatch { + answers: None, + patch: topology_patch(speak_entry(kernel)), + }, + ); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + let entity = |label: &str| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared place") + .0 + }; + let edge = |label: &str| { + *kernel + .state + .edges + .iter() + .find(|(_, record)| record.label() == label) + .expect("a declared route") + .0 + }; + Topology { + yard: entity("The Cavity Yard"), + road: entity("The Rhythm Road"), + gate: entity("The Rain Gate"), + ramp: edge("The Yard Ramp"), + shutter: edge("The Yard Shutter"), + toll: edge("The Toll Stair"), + span: edge("The Western Span"), + walker: *kernel + .state + .subjects + .iter() + .find(|(_, subject)| subject.label == "The Walker") + .expect("the walker is admitted") + .0, + } + } + + /// The canonical IDs of the custody fixture: two resources and two holder + /// subjects standing in the topology, with the first holder carrying an + /// evidenced opening balance. + pub(crate) struct Custody { + pub(crate) tithe: EntityId, + pub(crate) ingot: EntityId, + pub(crate) holder: SubjectId, + pub(crate) counterparty: SubjectId, + } + + /// The seed world's authority kinds, offices, and grievance. They are world + /// data: the kernel compares these strings and reads them no other way. + pub(crate) const LEVY_KIND: &str = "levy"; + pub(crate) const ADMIT_KIND: &str = "admit"; + pub(crate) const COMMAND_KIND: &str = "command"; + pub(crate) const JUDGE_KIND: &str = "judge"; + pub(crate) const WARDEN_OFFICE: &str = "warden"; + pub(crate) const BAILIFF_OFFICE: &str = "bailiff"; + pub(crate) const SEIZURE_GRIEVANCE: &str = "seizure"; + + pub(crate) const TITHE_RECEIPT: &str = "receipt:rhythm-tithe-census"; + pub(crate) const OPENING_BALANCE: u64 = 7; + + pub(crate) fn resource(handle: &str, label: &str) -> Declaration { + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: EntityKind::Resource, + container: None, + }) + } + + fn holder(handle: &str, label: &str, place: EntityId, speak: Ref<AffordanceId>) -> Declaration { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: SubjectKind::Institution, + controller: NewController::OperationalAgent, + affordances: std::iter::once(speak) + .chain(carry_affordances().into_iter().map(|declaration| { + let Declaration::Affordance(entry) = declaration else { + unreachable!("carry_affordances declares only affordances") + }; + Ref::Draft(entry.handle) + })) + .collect(), + position: Some(Ref::Existing(place)), + import_key: None, + }) + } + + pub(crate) const CARRY_HANDLE: &str = "carry"; + + /// The worked affordances for the action lane. Every one carries the same + /// four roles and the same bounded `Transfer` slot, so a test varies exactly + /// one thing — a precondition or a band table — by naming a different entry + /// rather than by reaching into a committed catalog. The catalog is + /// Draft-only, so authoring it is how a world gets a verb. + fn carry_roles() -> Vec<RoleSpec> { + vec![ + RoleSpec { + role: Role("from".into()), + kind: RefKind::Subject(None), + }, + RoleSpec { + role: Role("recipient".into()), + kind: RefKind::Subject(None), + }, + RoleSpec { + role: Role("place".into()), + kind: RefKind::Entity(EntityKind::Place), + }, + RoleSpec { + role: Role("resource".into()), + kind: RefKind::Entity(EntityKind::Resource), + }, + ] + } + + /// Two slots on disjoint bands: band 0 names only the transfer, band 1 only + /// the consume. Both slots are proposed on every invocation, so the entry + /// separates what a proposer offered from what a draw admitted. + fn split_variant() -> Declaration { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("carry-split"), + kind: AffordanceKindName("carry_split".into()), + roles: carry_roles(), + preconditions: Vec::new(), + effect_slots: vec![ + EffectSlot { + op_kind: ComponentOpKind::Transfer, + roles: vec![ + Role("from".into()), + Role("recipient".into()), + Role("resource".into()), + ], + bounds: Bounds::Quantity(Quantity(3)), + }, + EffectSlot { + op_kind: ComponentOpKind::Consume, + roles: vec![Role("from".into()), Role("resource".into())], + bounds: Bounds::Quantity(Quantity(3)), + }, + ], + outcome_bands: vec![ + OutcomeBand { + weight: 1, + effects: vec![0], + }, + OutcomeBand { + weight: 1, + effects: vec![1], + }, + ], + carries_speech: false, + }) + } + + fn carry_variant( + handle: &str, + kind: &str, + preconditions: Vec<Precondition>, + outcome_bands: Vec<OutcomeBand>, + ) -> Declaration { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new(handle), + kind: AffordanceKindName(kind.into()), + roles: carry_roles(), + preconditions, + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::Transfer, + roles: vec![ + Role("from".into()), + Role("recipient".into()), + Role("resource".into()), + ], + bounds: Bounds::Quantity(Quantity(3)), + }], + outcome_bands, + carries_speech: false, + }) + } + + fn certain_band() -> Vec<OutcomeBand> { + vec![OutcomeBand { + weight: 1, + effects: vec![0], + }] + } + + fn place_role() -> Role { + Role("place".into()) + } + + /// Carry, and five variants that each move one dial: a holding demand above + /// the opening balance, a reach budget short of the two-hop path, one that + /// covers it, a band that names no effect, and three equally weighted bands. + pub(crate) fn carry_affordances() -> Vec<Declaration> { + vec![ + carry_variant( + CARRY_HANDLE, + "carry", + vec![ + Precondition::Present { at: place_role() }, + Precondition::Holds { + resource: Role("resource".into()), + at_least: Quantity(1), + }, + ], + certain_band(), + ), + carry_variant( + "carry-greedy", + "carry_greedy", + vec![ + Precondition::Present { at: place_role() }, + Precondition::Holds { + resource: Role("resource".into()), + at_least: Quantity(OPENING_BALANCE + 1), + }, + ], + certain_band(), + ), + carry_variant( + "carry-holds", + "carry_holds", + vec![Precondition::Holds { + resource: Role("resource".into()), + at_least: Quantity(1), + }], + certain_band(), + ), + carry_variant( + "carry-near", + "carry_near", + vec![Precondition::Reachable { + to: place_role(), + within: Cost(NEAR_REACH), + }], + certain_band(), + ), + carry_variant( + "carry-far", + "carry_far", + vec![Precondition::Reachable { + to: place_role(), + within: Cost(FAR_REACH), + }], + certain_band(), + ), + carry_variant( + "carry-idle", + "carry_idle", + Vec::new(), + vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + ), + carry_variant( + "carry-chance", + "carry_chance", + Vec::new(), + vec![ + OutcomeBand { + weight: 1, + effects: vec![0], + }, + OutcomeBand { + weight: 1, + effects: Vec::new(), + }, + OutcomeBand { + weight: 1, + effects: Vec::new(), + }, + ], + ), + split_variant(), + ] + } + + /// Yard to gate over the open shutter alone. + pub(crate) const NEAR_REACH: u32 = 5; + /// Yard to gate over the ramp and the span, which is the only open public + /// path while the shutter is closed. + pub(crate) const FAR_REACH: u32 = 19; + + /// Declarations and evidence are Draft-only, so the resources, the holders, + /// and the one evidenced `Admit` that creates the opening balance all land + /// before activation. There is no holdings declaration field: quantity is + /// created by `Admit` and by nothing else, in this lane as in every other. + pub(crate) fn custody_patch(topology: &Topology, speak: Ref<AffordanceId>) -> WorldPatch { + WorldPatch { + declarations: carry_affordances() + .into_iter() + .chain([ + resource("tithe", "The Rhythm Tithe"), + resource("ingot", "The Cut Ingot"), + holder("clerk", "The Ledger Clerk", topology.yard, speak.clone()), + holder("keeper", "The Gate Keeper", topology.gate, speak), + ]) + .collect(), + operations: vec![ComponentOp::Admit { + holder: Ref::Draft(DraftHandle::new("clerk")), + resource: Ref::Draft(DraftHandle::new("tithe")), + qty: Quantity(OPENING_BALANCE), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }], + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], + } + } + + pub(crate) fn admit_custody(kernel: &mut WorldKernel, topology: &Topology) -> Custody { + let before = kernel.snapshot().unwrap(); + let receipt = submit_owner( + kernel, + &before, + CommandBody::AdmitPatch { + answers: None, + patch: custody_patch(topology, speak_entry(kernel)), + }, + ); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + let entity = |label: &str| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared resource") + .0 + }; + let subject = |label: &str| { + *kernel + .state + .subjects + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared holder") + .0 + }; + Custody { + tithe: entity("The Rhythm Tithe"), + ingot: entity("The Cut Ingot"), + holder: subject("The Ledger Clerk"), + counterparty: subject("The Gate Keeper"), + } + } + + /// Topology, custody, then activation: everything a custody test needs, in + /// the one order the phase rules allow. + pub(crate) fn custody_world(kernel: &mut WorldKernel) -> (Topology, Custody, WorldSnapshot) { + let topology = admit_topology(kernel); + let custody = admit_custody(kernel, &topology); + let active = activate(kernel); + (topology, custody, active) + } + + /// The canonical IDs of the civic fixture: a hall containing a chamber, an + /// institution holding jurisdiction over the hall, a person who holds that + /// jurisdiction only through an office, a person and a resource inside the + /// hall, and a person standing outside it. + pub(crate) struct Civic { + pub(crate) hall: EntityId, + pub(crate) chamber: EntityId, + pub(crate) passage: EdgeId, + pub(crate) causeway: EdgeId, + pub(crate) postern: EdgeId, + pub(crate) treasury: SubjectId, + pub(crate) reeve: SubjectId, + pub(crate) farmer: SubjectId, + pub(crate) outsider: SubjectId, + pub(crate) grain: EntityId, + } + + pub(crate) fn authority_kind(name: &str) -> AuthorityKindName { + AuthorityKindName(name.into()) + } + + pub(crate) fn office(name: &str) -> OfficeName { + OfficeName(name.into()) + } + + pub(crate) fn grievance(name: &str) -> GrievanceKindName { + GrievanceKindName(name.into()) + } + + pub(crate) fn over_place(place: EntityId) -> AuthorityTargetRef { + AuthorityTargetRef::PlaceSubtree(Ref::Existing(place)) + } + + pub(crate) fn over_subject(subject_id: SubjectId) -> AuthorityTargetRef { + AuthorityTargetRef::Subject(Ref::Existing(subject_id)) + } + + pub(crate) fn grant_of(kind: &str, over: AuthorityTargetRef) -> AuthorityGrantRef { + AuthorityGrantRef { + kind: authority_kind(kind), + over, + } + } + + pub(crate) fn grant_to(holder: SubjectId, kind: &str, over: AuthorityTargetRef) -> ComponentOp { + ComponentOp::GrantAuthority { + holder: Ref::Existing(holder), + grant: grant_of(kind, over), + } + } + + /// Seven world-authored civic entries. The kernel builds none of them; + /// each is a worked example of what a seed author writes to make the + /// political layer playable rather than administratively imposed. + fn civic_affordances() -> Vec<Declaration> { + let entry = |handle: &str, + kind: &str, + roles: Vec<RoleSpec>, + preconditions: Vec<Precondition>, + effect_slots: Vec<EffectSlot>, + outcome_bands: Vec<OutcomeBand>, + carries_speech: bool| { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new(handle), + kind: AffordanceKindName(kind.into()), + roles, + preconditions, + effect_slots, + outcome_bands, + carries_speech, + }) + }; + let role = |name: &str, kind: RefKind| RoleSpec { + role: Role(name.into()), + kind, + }; + let slot = |op_kind: ComponentOpKind, roles: Vec<&str>, bounds: Bounds| EffectSlot { + op_kind, + roles: roles.into_iter().map(|name| Role(name.into())).collect(), + bounds, + }; + let authorized = |over: &str, kind: &str| Precondition::Authorized { + over: Role(over.into()), + kind: authority_kind(kind), + }; + vec![ + // The payee is the reserved `actor` role, so an authorized + // collector cannot lawfully take a tax and send it to a friend. + entry( + "levy", + "levy", + vec![ + role("payer", RefKind::Subject(None)), + role("resource", RefKind::Entity(EntityKind::Resource)), + ], + vec![authorized("payer", LEVY_KIND)], + vec![slot( + ComponentOpKind::Transfer, + vec!["payer", "actor", "resource"], + Bounds::Quantity(Quantity(10)), + )], + certain_band(), + false, + ), + entry( + "delegate", + "delegate", + vec![ + role("deputy", RefKind::Subject(None)), + role("ground", RefKind::Entity(EntityKind::Place)), + ], + // The precondition names one kind and the slot grants another, + // so the monotonicity rule is the check that decides whether + // the granted authority is one the granter holds. + vec![authorized("ground", COMMAND_KIND)], + vec![slot( + ComponentOpKind::GrantAuthority { + kind: authority_kind(LEVY_KIND), + }, + vec!["deputy", "ground"], + Bounds::None, + )], + certain_band(), + false, + ), + // Isolates the action-lane's revocation envelope: no separate + // precondition, so a rejection here can only be + // `DelegationNotMonotone`. + entry( + "revoke", + "revoke", + vec![ + role("holder", RefKind::Subject(None)), + role("ground", RefKind::Entity(EntityKind::Place)), + ], + Vec::new(), + vec![slot( + ComponentOpKind::RevokeAuthority { + kind: authority_kind(LEVY_KIND), + }, + vec!["holder", "ground"], + Bounds::None, + )], + certain_band(), + false, + ), + entry( + "deploy", + "deploy", + vec![ + role("subordinate", RefKind::Subject(None)), + role("via", RefKind::Edge(patch::EdgeKind::Route)), + ], + vec![authorized("subordinate", COMMAND_KIND)], + vec![slot( + ComponentOpKind::Relocate, + vec!["subordinate", "via"], + Bounds::None, + )], + certain_band(), + false, + ), + // The first affordance whose effect changes shared topology under a + // legitimacy check; the second band is the interdiction that fails. + entry( + "sanction", + "sanction", + vec![role("road", RefKind::Edge(patch::EdgeKind::Route))], + vec![authorized("road", COMMAND_KIND)], + vec![slot( + ComponentOpKind::CloseRoute, + vec!["road"], + Bounds::None, + )], + vec![ + OutcomeBand { + weight: 3, + effects: vec![0], + }, + OutcomeBand { + weight: 1, + effects: Vec::new(), + }, + ], + false, + ), + // Succession is an act someone performs under authority, not a + // declared method string. + entry( + "appoint", + "appoint", + vec![ + role("institution", RefKind::Subject(None)), + role("candidate", RefKind::Subject(None)), + ], + vec![authorized("institution", COMMAND_KIND)], + vec![slot( + ComponentOpKind::InstallIncumbent { + office: office(BAILIFF_OFFICE), + }, + vec!["institution", "candidate"], + Bounds::None, + )], + certain_band(), + false, + ), + // The reader that keeps `Redress` from being decorative. + entry( + "petition", + "petition", + Vec::new(), + vec![ + Precondition::HasStanding { + grievance: grievance(SEIZURE_GRIEVANCE), + }, + // A petition is spoken, so the entry names where it lands. + Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }, + ], + Vec::new(), + vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + true, + ), + ] + } + + fn civic_grants(handles: &[&str], speak: &Ref<AffordanceId>) -> BTreeSet<Ref<AffordanceId>> { + std::iter::once(speak.clone()) + .chain( + handles + .iter() + .map(|handle| Ref::Draft(DraftHandle::new(*handle))), + ) + .collect() + } + + pub(crate) fn civic_patch(topology: &Topology, speak: Ref<AffordanceId>) -> WorldPatch { + let person = |handle: &str, label: &str, place: Ref<EntityId>, handles: &[&str]| { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: SubjectKind::Person, + controller: NewController::OperationalAgent, + affordances: civic_grants(handles, &speak), + position: Some(place), + import_key: None, + }) + }; + let declarations = civic_affordances() + .into_iter() + .chain([ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("hall"), + label: "The Tithe Hall".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("chamber"), + label: "The Counting Chamber".into(), + kind: EntityKind::Place, + container: Some(Ref::Draft(DraftHandle::new("hall"))), + }), + resource("grain", "The Winter Grain"), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("passage"), + label: "The Hall Passage".into(), + from: Ref::Draft(DraftHandle::new("chamber")), + to: Ref::Draft(DraftHandle::new("hall")), + access: AccessKind::Public, + cost: Cost(3), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("causeway"), + label: "The Hall Causeway".into(), + from: Ref::Draft(DraftHandle::new("hall")), + to: Ref::Existing(topology.road), + access: AccessKind::Public, + cost: Cost(6), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("postern"), + label: "The Hall Postern".into(), + from: Ref::Existing(topology.yard), + to: Ref::Draft(DraftHandle::new("chamber")), + access: AccessKind::Restricted { + requires: authority_kind(ADMIT_KIND), + }, + cost: Cost(2), + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("treasury"), + label: "The Tithe Treasury".into(), + kind: SubjectKind::Institution, + controller: NewController::OperationalAgent, + affordances: civic_grants( + &[ + "levy", "delegate", "deploy", "sanction", "appoint", "revoke", + ], + &speak, + ), + position: Some(Ref::Draft(DraftHandle::new("hall"))), + import_key: None, + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("reeve"), + label: "The Hall Reeve".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: civic_grants( + &["levy", "delegate", "petition", "sanction"], + &speak, + ), + position: Some(Ref::Draft(DraftHandle::new("chamber"))), + import_key: None, + }), + person( + "farmer", + "The Winter Farmer", + Ref::Draft(DraftHandle::new("chamber")), + &["levy", "petition", "revoke"], + ), + person( + "outsider", + "The Road Pedlar", + Ref::Existing(topology.road), + &["levy", "petition"], + ), + // Deliberately unplaced: a place-subtree jurisdiction covers a + // subject through its position, so a subject with none is + // covered by nothing. + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("nowhere"), + label: "The Unhoused".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: civic_grants(&["levy", "petition"], &speak), + position: None, + import_key: None, + }), + ]) + .collect(); + WorldPatch { + declarations, + operations: vec![ + ComponentOp::Admit { + holder: Ref::Draft(DraftHandle::new("farmer")), + resource: Ref::Draft(DraftHandle::new("grain")), + qty: Quantity(OPENING_BALANCE), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }, + ComponentOp::Admit { + holder: Ref::Draft(DraftHandle::new("outsider")), + resource: Ref::Draft(DraftHandle::new("grain")), + qty: Quantity(OPENING_BALANCE), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }, + ComponentOp::GrantAuthority { + holder: Ref::Draft(DraftHandle::new("treasury")), + grant: AuthorityGrantRef { + kind: authority_kind(LEVY_KIND), + over: AuthorityTargetRef::PlaceSubtree(Ref::Draft(DraftHandle::new( + "hall", + ))), + }, + }, + ComponentOp::GrantAuthority { + holder: Ref::Draft(DraftHandle::new("treasury")), + grant: AuthorityGrantRef { + kind: authority_kind(COMMAND_KIND), + over: AuthorityTargetRef::PlaceSubtree(Ref::Draft(DraftHandle::new( + "hall", + ))), + }, + }, + ComponentOp::OpenOffice { + institution: Ref::Draft(DraftHandle::new("treasury")), + office: office(WARDEN_OFFICE), + delegated: BTreeSet::from([authority_kind(LEVY_KIND)]), + }, + ComponentOp::OpenOffice { + institution: Ref::Draft(DraftHandle::new("treasury")), + office: office(BAILIFF_OFFICE), + delegated: BTreeSet::from([authority_kind(JUDGE_KIND)]), + }, + ComponentOp::InstallIncumbent { + institution: Ref::Draft(DraftHandle::new("treasury")), + office: office(WARDEN_OFFICE), + incumbent: Ref::Draft(DraftHandle::new("reeve")), + }, + ComponentOp::OpenForum { + grievance: grievance(SEIZURE_GRIEVANCE), + forum: Ref::Draft(DraftHandle::new("treasury")), + standing: AuthorityTargetRef::PlaceSubtree(Ref::Draft(DraftHandle::new( + "chamber", + ))), + }, + ], + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], + } + } + + pub(crate) fn admit_civic(kernel: &mut WorldKernel, topology: &Topology) -> Civic { + let before = kernel.snapshot().unwrap(); + let receipt = submit_owner( + kernel, + &before, + CommandBody::AdmitPatch { + answers: None, + patch: civic_patch(topology, speak_entry(kernel)), + }, + ); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + let entity = |label: &str| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared entity") + .0 + }; + let edge = |label: &str| { + *kernel + .state + .edges + .iter() + .find(|(_, record)| record.label() == label) + .expect("a declared route") + .0 + }; + let subject = |label: &str| { + *kernel + .state + .subjects + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared subject") + .0 + }; + Civic { + hall: entity("The Tithe Hall"), + chamber: entity("The Counting Chamber"), + grain: entity("The Winter Grain"), + passage: edge("The Hall Passage"), + causeway: edge("The Hall Causeway"), + postern: edge("The Hall Postern"), + treasury: subject("The Tithe Treasury"), + reeve: subject("The Hall Reeve"), + farmer: subject("The Winter Farmer"), + outsider: subject("The Road Pedlar"), + } + } + + /// Topology, the civic subgraph, then activation. + pub(crate) fn civic_world(kernel: &mut WorldKernel) -> (Topology, Civic, WorldSnapshot) { + let topology = admit_topology(kernel); + let civic = admit_civic(kernel, &topology); + let active = activate(kernel); + (topology, civic, active) + } + + /// The speech bench: a hall containing a yard, a speaker and a listener in + /// the hall, a bystander in the yard, a stranger nowhere, one evidenced + /// canonical fact, and a horn that carries over the hall subtree. + pub(crate) struct Speech { + pub(crate) hall: EntityId, + pub(crate) yard: EntityId, + pub(crate) speaker: SubjectId, + pub(crate) listener: SubjectId, + pub(crate) bystander: SubjectId, + pub(crate) stranger: SubjectId, + pub(crate) flood: EntityId, + pub(crate) horn: EntityId, + pub(crate) whisper: AffordanceId, + pub(crate) proclaim: AffordanceId, + pub(crate) recant: AffordanceId, + pub(crate) stair: EdgeId, + } + + pub(crate) const FLOOD_STATEMENT: &str = "The lower hinge is flooding."; + pub(crate) const FLOOD_EVIDENCE: &str = "vault:flood-survey"; + + /// A world with one room inside another, four subjects, a fact, and a + /// channel. Two world-declared speaking entries exercise both audiences: an + /// addressed co-located `whisper` and a channel-bound `proclaim`. + pub(crate) fn speech_world(kernel: &mut WorldKernel) -> (Speech, WorldSnapshot) { + let before = kernel.snapshot().unwrap(); + let speak = speak_entry(kernel); + let person = |handle: &str, label: &str, place: Option<&str>| { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([ + speak.clone(), + Ref::Draft(DraftHandle::new("whisper")), + Ref::Draft(DraftHandle::new("proclaim")), + Ref::Draft(DraftHandle::new("recant")), + ]), + position: place.map(|place| Ref::Draft(DraftHandle::new(place))), + import_key: None, + }) + }; + submit_owner( + kernel, + &before, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + evidence: vec![EvidenceRef::new(FLOOD_EVIDENCE)], + operations: Vec::new(), + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("hall"), + label: "The Long Hall".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("yard"), + label: "The Cavity Yard".into(), + kind: EntityKind::Place, + container: Some(Ref::Draft(DraftHandle::new("hall"))), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("stair"), + label: "The Yard Stair".into(), + from: Ref::Draft(DraftHandle::new("yard")), + to: Ref::Draft(DraftHandle::new("hall")), + access: AccessKind::Public, + cost: Cost(1), + }), + Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("flood"), + label: "the flooding of the lower hinge".into(), + statement: Statement::new(FLOOD_STATEMENT).unwrap(), + standing: FactStandingRef::Canonical { + evidence: EvidenceRef::new(FLOOD_EVIDENCE), + }, + }), + // Addressed speech: the audience is still the room. + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("whisper"), + kind: AffordanceKindName("whisper".into()), + roles: vec![RoleSpec { + role: Role("target".into()), + kind: RefKind::Subject(None), + }], + preconditions: vec![Precondition::CanReach { + subject: Role("target".into()), + via: AudienceSpec::Colocated, + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + }), + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("proclaim"), + kind: AffordanceKindName("proclaim".into()), + roles: vec![RoleSpec { + role: Role("channel".into()), + kind: RefKind::Entity(EntityKind::Channel), + }], + preconditions: vec![Precondition::CanBroadcast { + via: AudienceSpec::Channel(Role("channel".into())), + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + }), + // `Knows` plus the one knowledge operation an affordance + // may propose: a subject may only unremember what it + // holds with certainty. + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("recant"), + kind: AffordanceKindName("recant".into()), + roles: vec![RoleSpec { + role: Role("fact".into()), + kind: RefKind::Entity(EntityKind::Fact), + }], + preconditions: vec![Precondition::Knows { + fact: Role("fact".into()), + at_least: Confidence::Certain, + }], + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::Forget, + roles: vec![Role("actor".into()), Role("fact".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }), + person("speaker", "The Hall Speaker", Some("hall")), + person("listener", "The Hall Listener", Some("hall")), + person("bystander", "The Yard Bystander", Some("yard")), + person("stranger", "The Placeless Stranger", None), + Declaration::Channel(ChannelDeclaration { + handle: DraftHandle::new("horn"), + label: "The Temple Horn".into(), + reach: ReachRef::Place(Ref::Draft(DraftHandle::new("hall"))), + controller: Some(Ref::Draft(DraftHandle::new("speaker"))), + }), + ], + }, + }, + ); + let active = activate(kernel); + let place = |label: &str| { + active + .places + .iter() + .find(|place| place.label == label) + .expect("the declared place") + .id + }; + let who = |label: &str| { + active + .subjects + .iter() + .find(|subject| subject.label == label) + .expect("the declared subject") + .id + }; + let fact = *kernel + .state + .facts + .iter() + .find(|(_, record)| record.statement.as_str() == FLOOD_STATEMENT) + .expect("the declared fact") + .0; + let horn = *kernel + .state + .channels + .keys() + .next() + .expect("the declared channel"); + ( + Speech { + hall: place("The Long Hall"), + yard: place("The Cavity Yard"), + speaker: who("The Hall Speaker"), + listener: who("The Hall Listener"), + bystander: who("The Yard Bystander"), + stranger: who("The Placeless Stranger"), + flood: fact, + horn, + whisper: affordance_named(&active, "whisper"), + proclaim: affordance_named(&active, "proclaim"), + recant: affordance_named(&active, "recant"), + stair: active.routes[0].id, + }, + active, + ) + } + + /// Submits as owner and returns the complete mismatch set. + pub(crate) fn reject_owner( + kernel: &mut WorldKernel, + snapshot: &WorldSnapshot, + body: CommandBody, + ) -> Vec<Mismatch> { + let error = kernel + .submit( + command( + snapshot, + CommandId::new(), + CallerId::Principal(owner()), + body, + ), + &auth_principal(owner()), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch, got {error:?}"); + }; + mismatches + } + + pub(crate) fn operations(operations: Vec<ComponentOp>) -> CommandBody { + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations, + evidence: Vec::new(), + }, + } + } + + pub(crate) fn opportunity_for( + snapshot: &WorldSnapshot, + subject_id: SubjectId, + ) -> DecisionOpportunity { + snapshot + .opportunities + .iter() + .find(|value| value.scope.subject_id == subject_id) + .expect("the subject has an opportunity") + .clone() + } + + fn opportunity(snapshot: &WorldSnapshot, mode: ControllerMode) -> DecisionOpportunity { + snapshot + .opportunities + .iter() + .find(|value| value.controller_mode == mode) + .unwrap() + .clone() + } + + fn speak(opportunity: &DecisionOpportunity, text: &str) -> DecisionInvocation { + DecisionInvocation { + affordance: opportunity.affordance_ids[0], + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new(text).unwrap()), + display: None, + } + } + + #[test] + fn external_opportunities_reject_nested_authority_claims() { + let opportunity = DecisionOpportunity { + world_id: WorldId::issue(), + revision: 4, + scope_digest: ScopeDigest::fixture("sha256:fixture"), + scope: DecisionScope { + subject_id: SubjectId::issue(), + }, + controller_id: ControllerId::issue(), + controller_mode: ControllerMode::NarrativePersona, + affordance_ids: vec![AffordanceId::issue()], + }; + let mut nested = serde_json::to_value(&opportunity).unwrap(); + nested["scope"]["caller"] = serde_json::json!("legacy-owner"); + assert!(serde_json::from_value::<DecisionOpportunity>(nested).is_err()); + + let mut outer = serde_json::to_value(&opportunity).unwrap(); + outer["callerId"] = serde_json::json!("legacy-controller"); + assert!(serde_json::from_value::<DecisionOpportunity>(outer).is_err()); + } + + /// A commit elsewhere in the world does not discard a bound proposal: the + /// binding is the scope digest, and this scope did not change. + #[test] + fn an_unchanged_scope_commits_at_a_later_revision() { + let dir = tempfile::tempdir().unwrap(); + let (mut kernel, _) = WorldKernel::create( + dir.path().join("world.cc"), + creation(CommandId::new(), "Unchanged"), + &auth_principal(owner()), + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let active = activate(&mut kernel); + let bound = opportunity_for(&active, topology.walker); + + let persona = opportunity(&active, ControllerMode::NarrativePersona); + let persona_caller = CallerId::Controller(persona.controller_id); + kernel + .submit( + command( + &active, + CommandId::new(), + persona_caller.clone(), + CommandBody::ExerciseDecision { + invocation: speak(&persona, "The yard is quiet."), + opportunity: persona, + }, + ), + &AuthenticatedCaller::fixture(persona_caller), + ) + .unwrap(); + let later = kernel.snapshot().unwrap(); + assert_eq!(later.revision, active.revision + 1); + + let walker_caller = CallerId::Controller(bound.controller_id); + let receipt = kernel + .submit( + command( + &later, + CommandId::new(), + walker_caller.clone(), + CommandBody::ExerciseDecision { + invocation: speak(&bound, "I take the ramp."), + opportunity: bound.clone(), + }, + ), + &AuthenticatedCaller::fixture(walker_caller), + ) + .unwrap(); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + let after = kernel.state.events.clone(); + assert_eq!(after.len(), 2); + assert_eq!(after[1].revision, bound.revision + 2); + } + + /// Closing a route incident to the subject's place changes exactly what the + /// proposal's verification reads, so the bound proposal dies at the digest. + #[test] + fn a_changed_scope_is_rejected_with_scope_changed() { + let dir = tempfile::tempdir().unwrap(); + let (mut kernel, _) = WorldKernel::create( + dir.path().join("world.cc"), + creation(CommandId::new(), "Changed"), + &auth_principal(owner()), + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let active = activate(&mut kernel); + let bound = opportunity_for(&active, topology.walker); + + submit_owner( + &mut kernel, + &active, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::CloseRoute { + route: Ref::Existing(topology.ramp), + }], + evidence: Vec::new(), + }, + }, + ); + let closed = kernel.snapshot().unwrap(); + let walker_caller = CallerId::Controller(bound.controller_id); + let error = kernel + .submit( + command( + &closed, + CommandId::new(), + walker_caller.clone(), + CommandBody::ExerciseDecision { + invocation: speak(&bound, "I take the ramp."), + opportunity: bound.clone(), + }, + ), + &AuthenticatedCaller::fixture(walker_caller), + ) + .unwrap_err(); + let KernelError::ScopeChanged { + scope, + expected, + actual, + } = error + else { + panic!("expected a changed scope"); + }; + assert_eq!(scope, bound.scope); + assert_eq!(expected, bound.scope_digest); + assert_ne!(expected, actual); + assert_eq!(kernel.snapshot().unwrap(), closed); + } + + /// The digest covers the scope's controller, its grants, its Position, and + /// its incident routes, and nothing else in the world. + #[test] + fn scope_digest_reads_exactly_its_components() { + let dir = tempfile::tempdir().unwrap(); + let (mut kernel, _) = WorldKernel::create( + dir.path().join("world.cc"), + creation(CommandId::new(), "Components"), + &auth_principal(owner()), + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + activate(&mut kernel); + let scope = DecisionScope { + subject_id: topology.walker, + }; + let base = scope_digest(&kernel.state, scope).unwrap(); + + let mut changed_controller = kernel.state.clone(); + let assignment = changed_controller + .controller_assignments + .get_mut(&scope) + .unwrap(); + *assignment = ControllerAssignment::NarrativePersona { + controller_id: assignment.id().expect("the fixture scope has a controller"), + }; + assert_ne!(scope_digest(&changed_controller, scope).unwrap(), base); + + let mut changed_grants = kernel.state.clone(); + let extra = AffordanceId::issue(); + changed_grants + .affordance_catalog + .insert(extra, patch::kernel_speak_entry()); + changed_grants + .affordance_grants + .entry(scope) + .or_default() + .insert(extra); + assert_ne!(scope_digest(&changed_grants, scope).unwrap(), base); + + // The digest reads the granted entries' definitions, not only their + // ids: admission reads preconditions and ceilings, so altering an entry + // must move the digest. + let mut changed_entry = kernel.state.clone(); + let granted = *kernel.state.affordance_grants[&scope].first().unwrap(); + changed_entry + .affordance_catalog + .get_mut(&granted) + .unwrap() + .carries_speech = false; + assert_ne!(scope_digest(&changed_entry, scope).unwrap(), base); + + let mut changed_position = kernel.state.clone(); + changed_position.positions.insert( + topology.walker, + Position { + place: topology.road, + }, + ); + assert_ne!(scope_digest(&changed_position, scope).unwrap(), base); + + let mut changed_route = kernel.state.clone(); + changed_route + .edges + .get_mut(&topology.ramp) + .unwrap() + .set_cost(Cost(99)); + assert_ne!(scope_digest(&changed_route, scope).unwrap(), base); + + // The span joins road and gate, so it is incident to neither the walker's + // place nor its scope; an unrelated subject's decision is invisible too. + let mut unrelated_route = kernel.state.clone(); + unrelated_route + .edges + .get_mut(&topology.span) + .unwrap() + .set_cost(Cost(99)); + assert_eq!(scope_digest(&unrelated_route, scope).unwrap(), base); + + let active = kernel.snapshot().unwrap(); + let persona = opportunity(&active, ControllerMode::NarrativePersona); + let persona_caller = CallerId::Controller(persona.controller_id); + kernel + .submit( + command( + &active, + CommandId::new(), + persona_caller.clone(), + CommandBody::ExerciseDecision { + invocation: speak(&persona, "Unrelated."), + opportunity: persona, + }, + ), + &AuthenticatedCaller::fixture(persona_caller), + ) + .unwrap(); + assert_eq!(scope_digest(&kernel.state, scope).unwrap(), base); + } + + #[test] + fn draft_activation_human_and_autonomous_actions_share_one_reducer() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), " Delvehold "), + &auth_principal(owner()), + ) + .unwrap(); + let genesis = kernel.snapshot().unwrap(); + assert_eq!(genesis.title, "Delvehold"); + assert_eq!(genesis.phase, WorldPhase::Draft); + assert!(genesis.opportunities.is_empty()); + + let active = activate(&mut kernel); + assert_eq!(active.phase, WorldPhase::Active); + assert_eq!(active.opportunities.len(), 3); + + let human_opportunity = opportunity(&active, ControllerMode::Human); + kernel + .submit( + command( + &active, + CommandId::new(), + CallerId::Principal(human_principal()), + CommandBody::ExerciseDecision { + invocation: speak(&human_opportunity, "I open the door."), + opportunity: human_opportunity, + }, + ), + &auth_principal(human_principal()), + ) + .unwrap(); + let after_human = kernel.snapshot().unwrap(); + assert_eq!(kernel.state.events.len(), 1); + assert_eq!( + spoken(&kernel.state, &kernel.state.events[0]), + Some("I open the door.") + ); + + let persona_opportunity = opportunity(&after_human, ControllerMode::NarrativePersona); + let persona_caller = CallerId::Controller(persona_opportunity.controller_id); + kernel + .submit( + command( + &after_human, + CommandId::new(), + persona_caller.clone(), + CommandBody::ExerciseDecision { + invocation: speak(&persona_opportunity, "Then mind the hinge."), + opportunity: persona_opportunity, + }, + ), + &AuthenticatedCaller::fixture(persona_caller), + ) + .unwrap(); + let after_persona = kernel.snapshot().unwrap(); + assert_eq!(kernel.state.events.len(), 2); + assert!( + after_persona + .opportunities + .iter() + .all(|value| value.revision == after_persona.revision) + ); + } + + #[test] + fn lifecycle_and_controller_authority_fail_closed_without_commits() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Held"), + &auth_principal(owner()), + ) + .unwrap(); + let genesis = kernel.snapshot().unwrap(); + assert!(matches!( + kernel.submit( + command( + &genesis, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::ActivateWorld, + ), + &auth_principal(owner()) + ), + Err(KernelError::MissingApprovals(_)) + )); + assert_eq!(kernel.journal.commit_count(), 1); + + submit_owner(&mut kernel, &genesis, CommandBody::ApproveDraft); + let owner_approved = kernel.snapshot().unwrap(); + assert!(matches!( + kernel.submit( + command( + &owner_approved, + CommandId::new(), + CallerId::Principal(human_principal()), + CommandBody::ActivateWorld, + ), + &auth_principal(human_principal()) + ), + Err(KernelError::Unauthorized) + )); + assert!(matches!( + kernel.submit( + command( + &owner_approved, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::ApproveDraft, + ), + &auth_principal(owner()) + ), + Err(KernelError::DraftAlreadyApproved) + )); + assert_eq!(kernel.journal.commit_count(), 2); + + kernel + .submit( + command( + &owner_approved, + CommandId::new(), + CallerId::Principal(human_principal()), + CommandBody::ApproveDraft, + ), + &auth_principal(human_principal()), + ) + .unwrap(); + let approved = kernel.snapshot().unwrap(); + submit_owner(&mut kernel, &approved, CommandBody::ActivateWorld); + let active = kernel.snapshot().unwrap(); + let persona = opportunity(&active, ControllerMode::NarrativePersona); + let commits_before_forgery = kernel.journal.commit_count(); + assert!(matches!( + kernel.submit( + command( + &active, + CommandId::new(), + CallerId::Principal(human_principal()), + CommandBody::ExerciseDecision { + invocation: speak(&persona, "Puppet"), + opportunity: persona, + }, + ), + &auth_principal(human_principal()) + ), + Err(KernelError::ControllerMismatch) + )); + assert_eq!(kernel.journal.commit_count(), commits_before_forgery); + assert_eq!(kernel.snapshot().unwrap(), active); + } + + #[test] + fn a_tampered_or_unknown_opportunity_never_commits() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Exact"), + &auth_principal(owner()), + ) + .unwrap(); + let active = activate(&mut kernel); + let original = opportunity(&active, ControllerMode::Human); + // An entry only the operational subject is granted: the human's scope + // does not hold it, which is what denial means now that an affordance id + // names a catalog entry rather than one subject's copy of one. + let denied_invocation = DecisionInvocation { + affordance: affordance_named(&active, "convene"), + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("No grant").unwrap()), + display: None, + }; + assert!(matches!( + kernel.submit( + command( + &active, + CommandId::new(), + CallerId::Principal(human_principal()), + CommandBody::ExerciseDecision { + invocation: denied_invocation, + opportunity: original.clone(), + }, + ), + &auth_principal(human_principal()) + ), + Err(KernelError::AffordanceDenied) + )); + // A claimed affordance the world did not grant carries no authority: the + // kernel exercises the opportunity it derives, never the one submitted. + let forged_affordance = AffordanceId::issue(); + let mut tampered = original.clone(); + tampered.affordance_ids.push(forged_affordance); + assert!(matches!( + kernel.submit( + command( + &active, + CommandId::new(), + CallerId::Principal(human_principal()), + CommandBody::ExerciseDecision { + invocation: DecisionInvocation { + affordance: forged_affordance, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("Forged").unwrap()), + display: None, + }, + opportunity: tampered, + }, + ), + &auth_principal(human_principal()) + ), + Err(KernelError::AffordanceDenied) + )); + assert_eq!(kernel.snapshot().unwrap(), active); + + let mut forged_scope = original.clone(); + forged_scope.scope_digest = ScopeDigest::fixture("sha256:not-this-scope"); + assert!(matches!( + kernel.submit( + command( + &active, + CommandId::new(), + CallerId::Principal(human_principal()), + CommandBody::ExerciseDecision { + invocation: speak(&original, "No"), + opportunity: forged_scope, + }, + ), + &auth_principal(human_principal()) + ), + Err(KernelError::ScopeChanged { .. }) + )); + assert_eq!(kernel.snapshot().unwrap(), active); + + let unknown_scope = DecisionOpportunity { + scope: DecisionScope { + subject_id: SubjectId::issue(), + }, + ..original.clone() + }; + assert!(matches!( + kernel.submit( + command( + &active, + CommandId::new(), + CallerId::Principal(human_principal()), + CommandBody::ExerciseDecision { + invocation: speak(&original, "No"), + opportunity: unknown_scope, + }, + ), + &auth_principal(human_principal()) + ), + Err(KernelError::OpportunityMismatch) + )); + assert_eq!(kernel.snapshot().unwrap(), active); + } + + #[test] + fn create_submit_restart_and_replay_are_exact() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let creation = creation(CommandId::new(), "First"); + let (mut kernel, creation_receipt) = + WorldKernel::create(&path, creation.clone(), &auth_principal(owner())).unwrap(); + let active = activate(&mut kernel); + let decision = opportunity(&active, ControllerMode::OperationalAgent); + let caller = CallerId::Controller(decision.controller_id); + let command = command( + &active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + invocation: speak(&decision, "The vote carries."), + opportunity: decision, + }, + ); + let applied = kernel + .submit( + command.clone(), + &AuthenticatedCaller::fixture(caller.clone()), + ) + .unwrap(); + let SubmitReceipt::Applied(receipt) = applied else { + panic!("expected applied receipt") + }; + let accepted = kernel.snapshot().unwrap(); + drop(kernel); + + let (mut reopened, retried_creation_receipt) = + WorldKernel::create(&path, creation, &auth_principal(owner())).unwrap(); + assert_eq!(retried_creation_receipt, creation_receipt); + assert_eq!(reopened.snapshot().unwrap(), accepted); + assert_eq!( + reopened + .submit(command, &AuthenticatedCaller::fixture(caller)) + .unwrap(), + SubmitReceipt::AlreadyApplied(receipt) + ); + drop(reopened); + let reopened = WorldKernel::open(&path, accepted.world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), accepted); + } + + #[test] + fn controller_receipt_is_bound_to_the_exact_opportunity_and_invocation() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Receipt Scope"), + &auth_principal(owner()), + ) + .unwrap(); + let active = activate(&mut kernel); + let decision = opportunity(&active, ControllerMode::OperationalAgent); + let other = opportunity(&active, ControllerMode::NarrativePersona); + let command_id = CommandId::new(); + let caller = CallerId::Controller(decision.controller_id); + let invocation = speak(&decision, "The record is exact."); + kernel + .submit( + command( + &active, + command_id, + caller.clone(), + CommandBody::ExerciseDecision { + invocation: invocation.clone(), + opportunity: decision.clone(), + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap(); + + let receipt = kernel + .controller_receipt(command_id, &decision, &invocation) + .unwrap() + .expect("committed controller command has a receipt"); + assert_eq!(receipt.command_id, command_id); + assert!( + kernel + .controller_receipt(CommandId::new(), &decision, &invocation) + .unwrap() + .is_none() + ); + assert!(matches!( + kernel.controller_receipt(command_id, &other, &invocation), + Err(KernelError::CommandIdConflict) + )); + let altered_invocation = speak(&decision, "A different proposal."); + assert!(matches!( + kernel.controller_receipt(command_id, &decision, &altered_invocation), + Err(KernelError::CommandIdConflict) + )); + } + + #[test] + fn controller_decline_consumes_only_its_exact_opportunity() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Decline Scope"), + &auth_principal(owner()), + ) + .unwrap(); + let active = activate(&mut kernel); + let decision = opportunity(&active, ControllerMode::OperationalAgent); + let other = opportunity(&active, ControllerMode::NarrativePersona); + let caller = CallerId::Controller(decision.controller_id); + + assert!(matches!( + kernel.submit( + command( + &active, + CommandId::new(), + CallerId::Controller(other.controller_id), + CommandBody::DeclineDecision { + opportunity: decision.clone(), + }, + ), + &AuthenticatedCaller::fixture(CallerId::Controller(other.controller_id)), + ), + Err(KernelError::ControllerMismatch) + )); + assert_eq!(kernel.snapshot().unwrap(), active); + + let command_id = CommandId::new(); + let decline = command( + &active, + command_id, + caller.clone(), + CommandBody::DeclineDecision { + opportunity: decision.clone(), + }, + ); + let SubmitReceipt::Applied(receipt) = kernel + .submit( + decline.clone(), + &AuthenticatedCaller::fixture(caller.clone()), + ) + .unwrap() + else { + panic!("exact decline was not applied") + }; + let after = kernel.snapshot().unwrap(); + assert_eq!(after.revision, active.revision + 1); + assert!(kernel.state.events.is_empty()); + let refreshed = opportunity(&after, ControllerMode::OperationalAgent); + assert_ne!(refreshed, decision); + assert_eq!( + kernel + .controller_decline_receipt(command_id, &decision) + .unwrap(), + Some(receipt.clone()) + ); + assert!(matches!( + kernel.controller_decline_receipt(command_id, &other), + Err(KernelError::CommandIdConflict) + )); + assert!(matches!( + kernel.controller_receipt( + command_id, + &decision, + &speak(&decision, "A decline is not speech."), + ), + Err(KernelError::CommandIdConflict) + )); + assert_eq!( + kernel + .submit(decline, &AuthenticatedCaller::fixture(caller.clone())) + .unwrap(), + SubmitReceipt::AlreadyApplied(receipt.clone()) + ); + assert_eq!(kernel.snapshot().unwrap(), after); + drop(kernel); + let reopened = WorldKernel::open(&path, after.world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), after); + assert_eq!( + reopened + .controller_decline_receipt( + command_id, + &opportunity(&active, ControllerMode::OperationalAgent), + ) + .unwrap(), + Some(receipt) + ); + } + + #[test] + fn duplicate_and_stale_commands_do_not_commit() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Still"), + &auth_principal(owner()), + ) + .unwrap(); + let genesis = kernel.snapshot().unwrap(); + assert!(matches!( + submit_owner(&mut kernel, &genesis, CommandBody::ApproveDraft), + SubmitReceipt::Applied(_) + )); + let after = kernel.snapshot().unwrap(); + assert!(matches!( + kernel.submit( + command( + &after, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::ApproveDraft, + ), + &auth_principal(owner()) + ), + Err(KernelError::DraftAlreadyApproved) + )); + let stale = command( + &genesis, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::ApproveDraft, + ); + assert!(matches!( + kernel.submit(stale, &auth_principal(owner())), + Err(KernelError::RevisionMismatch { .. }) + )); + assert_eq!(kernel.snapshot().unwrap(), after); + assert_eq!(kernel.journal.commit_count(), 2); + } + + #[test] + fn durable_idempotency_precedes_revision_and_detects_conflicts() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "A"), + &auth_principal(owner()), + ) + .unwrap(); + let genesis = kernel.snapshot().unwrap(); + let id = CommandId::new(); + let first = command( + &genesis, + id, + CallerId::Principal(owner()), + CommandBody::ApproveDraft, + ); + let first_receipt = kernel + .submit(first.clone(), &auth_principal(owner())) + .unwrap(); + let second_snapshot = kernel.snapshot().unwrap(); + kernel + .submit( + command( + &second_snapshot, + CommandId::new(), + CallerId::Principal(human_principal()), + CommandBody::ApproveDraft, + ), + &auth_principal(human_principal()), + ) + .unwrap(); + let after_second = kernel.snapshot().unwrap(); + assert_eq!( + kernel.submit(first, &auth_principal(owner())).unwrap(), + match first_receipt { + SubmitReceipt::Applied(value) => SubmitReceipt::AlreadyApplied(value), + _ => unreachable!(), + } + ); + let conflict = command( + &genesis, + id, + CallerId::Principal(owner()), + CommandBody::ActivateWorld, + ); + assert!(matches!( + kernel.submit(conflict, &auth_principal(owner())), + Err(KernelError::CommandIdConflict) + )); + assert_eq!(kernel.snapshot().unwrap(), after_second); + } + + #[test] + fn creation_retry_is_bound_to_the_exact_raw_command() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let id = CommandId::new(); + let raw = creation(id, " Canonical Result "); + let (kernel, first) = + WorldKernel::create(&path, raw.clone(), &auth_principal(owner())).unwrap(); + assert_eq!(kernel.snapshot().unwrap().title, "Canonical Result"); + drop(kernel); + + let (kernel, retry) = + WorldKernel::create(&path, raw.clone(), &auth_principal(owner())).unwrap(); + assert_eq!(retry, first); + drop(kernel); + + let mut merely_equivalent = raw; + merely_equivalent.title = "Canonical Result".into(); + assert!(matches!( + WorldKernel::create(&path, merely_equivalent, &auth_principal(owner())), + Err(KernelError::CreationConflict) + )); + } + + #[test] + fn invalid_seed_never_allocates_a_world() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let mut invalid = creation(CommandId::new(), "Nope"); + invalid.patch.declarations[3] = invalid.patch.declarations[2].clone(); + let Err(KernelError::PatchRejected(rejected)) = + WorldKernel::create(&path, invalid, &auth_principal(owner())) + else { + panic!("expected a rejected creation patch"); + }; + assert_eq!( + rejected, + vec![Mismatch::DuplicateHandle { + handle: DraftHandle::new("human") + }] + ); + assert!( + WorldKernel::create( + &path, + creation(CommandId::new(), "Valid"), + &auth_principal(owner()) + ) + .is_ok() + ); + } + + #[test] + fn a_second_live_owner_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let creation = creation(CommandId::new(), "Held"); + let (kernel, _) = + WorldKernel::create(&path, creation.clone(), &auth_principal(owner())).unwrap(); + let world_id = kernel.snapshot().unwrap().world_id; + assert!(matches!( + WorldKernel::open(&path, world_id), + Err(KernelError::Store(_)) + )); + assert!(matches!( + WorldKernel::create(&path, creation.clone(), &auth_principal(owner())), + Err(KernelError::Store(_)) + )); + drop(kernel); + let kernel = WorldKernel::open(&path, world_id).unwrap(); + drop(kernel); + assert!(matches!( + WorldKernel::open(&path, WorldId::issue()), + Err(KernelError::OpenedWorldMismatch) + )); + } + + #[test] + fn lost_post_commit_ack_poisons_until_reopen_and_exact_retry() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Certain"), + &auth_principal(owner()), + ) + .unwrap(); + let genesis = kernel.snapshot().unwrap(); + let uncertain = CommandId::new(); + let attempted = command( + &genesis, + uncertain, + CallerId::Principal(owner()), + CommandBody::ApproveDraft, + ); + kernel.journal.fail_after_durable_commit_for_test(); + assert!(matches!( + kernel.submit(attempted.clone(), &auth_principal(owner())), + Err(KernelError::RecoveryRequired { command_id }) if command_id == uncertain + )); + assert!(matches!( + kernel.snapshot(), + Err(KernelError::RecoveryRequired { command_id }) if command_id == uncertain + )); + drop(kernel); + + let mut reopened = WorldKernel::open(&path, genesis.world_id).unwrap(); + let durable = reopened.snapshot().unwrap(); + assert_eq!(durable.revision, 1); + assert_eq!(durable.draft_approvals, BTreeSet::from([owner()])); + assert!(matches!( + reopened + .submit(attempted, &auth_principal(owner())) + .unwrap(), + SubmitReceipt::AlreadyApplied(_) + )); + } + + #[test] + fn lost_genesis_ack_reopens_as_the_same_world_and_exact_receipt() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let command_id = CommandId::new(); + let input = creation(command_id, "Durable Genesis"); + let authenticated = auth_principal(owner()); + let mut empty = match journal::WorldJournal::open_owner(&path).unwrap() { + journal::JournalOpen::Empty(empty) => empty, + journal::JournalOpen::Live { .. } => panic!("fixture store must be empty"), + }; + empty.fail_after_durable_initialize_for_test(); + let prepared = prepare_creation(input.clone(), &authenticated).unwrap(); + assert!(matches!( + WorldKernel::initialize(empty, prepared), + Err(KernelError::RecoveryRequired { command_id: uncertain }) + if uncertain == command_id + )); + + let (reopened, receipt) = WorldKernel::create(&path, input, &authenticated).unwrap(); + let snapshot = reopened.snapshot().unwrap(); + assert_eq!(receipt.command_id, command_id); + assert_eq!(receipt.world_id, snapshot.world_id); + assert_eq!(snapshot.revision, 0); + assert_eq!(snapshot.title, "Durable Genesis"); + } + + #[test] + fn replacing_the_store_path_revokes_the_live_owner() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let displaced = dir.path().join("displaced.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Pinned"), + &auth_principal(owner()), + ) + .unwrap(); + let snapshot = kernel.snapshot().unwrap(); + std::fs::rename(&path, &displaced).unwrap(); + std::fs::File::create(&path).unwrap(); + assert!(matches!(kernel.snapshot(), Err(KernelError::OwnershipLost))); + assert!(matches!( + kernel.submit( + command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::ApproveDraft, + ), + &auth_principal(owner()) + ), + Err(KernelError::OwnershipLost) + )); + std::fs::remove_file(&path).unwrap(); + std::fs::rename(&displaced, &path).unwrap(); + assert!(matches!(kernel.snapshot(), Err(KernelError::OwnershipLost))); + drop(kernel); + let reopened = WorldKernel::open(&path, snapshot.world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), snapshot); + } + + #[test] + fn sealed_authentication_cannot_be_replaced_by_a_command_claim() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Owned"), + &auth_principal(owner()), + ) + .unwrap(); + let snapshot = kernel.snapshot().unwrap(); + let forged = command( + &snapshot, + CommandId::new(), + CallerId::Principal(human_principal()), + CommandBody::ApproveDraft, + ); + assert!(matches!( + kernel.submit(forged, &auth_principal(owner())), + Err(KernelError::AuthenticationMismatch) + )); + assert_eq!(kernel.snapshot().unwrap(), snapshot); + } + + /// Soul falsification: the preimage must exclude the revision, the phase, + /// and every component outside the scope. Each step below is a real commit + /// that moves the world, not a hand-edited state. + #[test] + fn soul_scope_digest_excludes_revision_phase_and_everything_outside_the_scope() { + let dir = tempfile::tempdir().unwrap(); + let (mut kernel, _) = WorldKernel::create( + dir.path().join("world.cc"), + creation(CommandId::new(), "Preimage"), + &auth_principal(owner()), + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let scope = DecisionScope { + subject_id: topology.walker, + }; + let base = scope_digest(&kernel.state, scope).unwrap(); + let start_revision = kernel.state.revision; + + // A new place elsewhere, a route that touches neither the walker's + // place nor it, and a second placed subject: all outside the scope. + let speak = speak_entry(&kernel); + let before = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &before, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("annex"), + label: "The Annex".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("annexway"), + label: "The Annex Way".into(), + from: Ref::Existing(topology.road), + to: Ref::Draft(DraftHandle::new("annex")), + access: AccessKind::Public, + cost: Cost(3), + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("runner"), + label: "The Runner".into(), + kind: SubjectKind::Person, + controller: NewController::OperationalAgent, + affordances: BTreeSet::from([speak.clone()]), + position: Some(Ref::Existing(topology.road)), + import_key: None, + }), + ], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + assert_ne!(kernel.state.revision, start_revision); + assert_eq!(scope_digest(&kernel.state, scope).unwrap(), base); + + // Activation changes the phase, the approvals, and the revision. + let active = activate(&mut kernel); + assert_eq!(active.phase, WorldPhase::Active); + assert_eq!(scope_digest(&kernel.state, scope).unwrap(), base); + + // Another subject's Position moving is not this scope's business. + let annexway = *kernel + .state + .edges + .iter() + .find(|(_, record)| record.label() == "The Annex Way") + .expect("the declared route") + .0; + let runner = *kernel + .state + .subjects + .iter() + .find(|(_, subject)| subject.label == "The Runner") + .expect("the declared subject") + .0; + let active = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &active, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Relocate { + subject: Ref::Existing(runner), + via: Ref::Existing(annexway), + }], + evidence: Vec::new(), + }, + }, + ); + assert_eq!( + kernel.state.positions.get(&runner), + Some(&Position { + place: kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "The Annex") + .map(|(id, _)| *id) + .unwrap() + }) + ); + assert_eq!(scope_digest(&kernel.state, scope).unwrap(), base); + + // A route incident to the walker's own place is inside the scope. + let moved = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &moved, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::CloseRoute { + route: Ref::Existing(topology.ramp), + }], + evidence: Vec::new(), + }, + }, + ); + assert_ne!(scope_digest(&kernel.state, scope).unwrap(), base); + } + + /// Soul falsification: a claimed opportunity whose `affordance_ids` name + /// grants this scope does not hold cannot widen authority. The kernel reads + /// the derived list, so the forged one is ignored and the invocation is + /// denied on the real grants. + #[test] + fn soul_a_forged_affordance_list_cannot_widen_authority() { + let dir = tempfile::tempdir().unwrap(); + let (mut kernel, _) = WorldKernel::create( + dir.path().join("world.cc"), + creation(CommandId::new(), "Affordances"), + &auth_principal(owner()), + ) + .unwrap(); + let active = activate(&mut kernel); + let persona = opportunity(&active, ControllerMode::NarrativePersona); + let operator = opportunity(&active, ControllerMode::OperationalAgent); + + // The persona claims the operator's entry and lists it as its own. + let convened = affordance_named(&active, "convene"); + assert!(operator.affordance_ids.contains(&convened)); + assert!(!persona.affordance_ids.contains(&convened)); + let mut forged = persona.clone(); + forged.affordance_ids = vec![convened, persona.affordance_ids[0]]; + let caller = CallerId::Controller(persona.controller_id); + let error = kernel + .submit( + command( + &active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity: forged, + invocation: DecisionInvocation { + affordance: convened, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("Not my grant.").unwrap()), + display: None, + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap_err(); + assert!(matches!(error, KernelError::AffordanceDenied)); + assert_eq!(kernel.snapshot().unwrap(), active); + } + + /// Soul: an `AffordanceId` now names a catalog entry, not a subject's copy + /// of one — the three genesis subjects share Speak's single id. So the id + /// cannot be what gates: grant membership for the invoking scope is. The + /// same `convene` id commits for the scope that holds it and is denied for + /// one that does not. + #[test] + fn soul_a_shared_catalog_id_is_gated_by_the_scope_grant() { + let dir = tempfile::tempdir().unwrap(); + let (mut kernel, _) = WorldKernel::create( + dir.path().join("world.cc"), + creation(CommandId::new(), "SharedCatalogIds"), + &auth_principal(owner()), + ) + .unwrap(); + let active = activate(&mut kernel); + let speak = affordance_named(&active, "speak"); + let convened = affordance_named(&active, "convene"); + + // One entry, one id, every genesis subject a grantee. + assert_eq!(active.subjects.len(), 3); + assert!( + active + .subjects + .iter() + .all(|subject| subject.affordances.contains(&speak)) + ); + assert!( + active + .opportunities + .iter() + .all(|opportunity| opportunity.affordance_ids.contains(&speak)) + ); + let holders: Vec<SubjectId> = active + .subjects + .iter() + .filter(|subject| subject.affordances.contains(&convened)) + .map(|subject| subject.id) + .collect(); + assert_eq!(holders.len(), 1); + + let invoke = |kernel: &mut WorldKernel, snapshot: &WorldSnapshot, subject: SubjectId| { + let opportunity = opportunity_for(snapshot, subject); + let caller = CallerId::Controller(opportunity.controller_id); + kernel.submit( + command( + snapshot, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation: DecisionInvocation { + affordance: convened, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("The council convenes.").unwrap()), + display: None, + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + }; + + // The grantee's scope commits with that id. + assert!(matches!( + invoke(&mut kernel, &active, holders[0]).unwrap(), + SubmitReceipt::Applied(_) + )); + + // A scope that does not hold the entry is denied the very same id, and + // nothing commits. + let after = kernel.snapshot().unwrap(); + // A controller-driven scope, so the denial is the grant check rather + // than the human lane's caller check reached first. + let stranger = after + .subjects + .iter() + .find(|subject| { + !subject.affordances.contains(&convened) && subject.human_controller.is_none() + }) + .expect("a controller-driven subject without the grant") + .id; + assert!(matches!( + invoke(&mut kernel, &after, stranger).unwrap_err(), + KernelError::AffordanceDenied + )); + assert_eq!(kernel.snapshot().unwrap(), after); + } + + #[test] + fn a_stale_grant_rejects_but_a_distant_route_reaches_admission_instead() { + let dir = tempfile::tempdir().unwrap(); + let (mut kernel, _) = WorldKernel::create( + dir.path().join("world.cc"), + creation(CommandId::new(), "BindingAndAdmission"), + &auth_principal(owner()), + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let active = activate(&mut kernel); + let bound = opportunity_for(&active, topology.walker); + let speak = affordance_named(&active, "speak"); + + // Binding is scope-digest equality, and the digest reads the granted + // entries' definitions: altering one moves the digest, so a proposal + // bound before that change no longer binds. + let mut altered = kernel.state.clone(); + altered + .affordance_catalog + .get_mut(&speak) + .expect("the Speak entry") + .carries_speech = false; + assert_ne!( + scope_digest(&altered, bound.scope).unwrap(), + scope_digest(&kernel.state, bound.scope).unwrap() + ); + + // A route the actor does not stand beside is outside the digest, so + // closing it leaves the binding intact. That is deliberate: admission + // re-reads the live graph at commit, so nothing commits on stale + // topology and a proposal is not invalidated by distant traffic. + let before_digest = scope_digest(&kernel.state, bound.scope).unwrap(); + let before = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &before, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(topology.span), + }]), + ); + assert_eq!( + scope_digest(&kernel.state, bound.scope).unwrap(), + before_digest, + "a route outside the actor's incident set does not rebind the proposal" + ); + + let snapshot = kernel.snapshot().unwrap(); + let receipt = kernel + .submit( + command( + &snapshot, + CommandId::new(), + CallerId::Controller(bound.controller_id), + CommandBody::ExerciseDecision { + opportunity: bound.clone(), + invocation: DecisionInvocation { + affordance: speak, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("Still here.").unwrap()), + display: None, + }, + }, + ), + &AuthenticatedCaller::fixture(CallerId::Controller(bound.controller_id)), + ) + .expect("a distant route closing does not rebind this proposal"); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + } + + /// The mvp doc's disjointness requirement: an institution with an + /// operational organ and a person-shaped voice is two subjects joined by an + /// office, not one subject with two controllers. + #[test] + fn an_institution_and_its_voice_are_two_subjects_joined_by_an_office() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "Two"); + let (_, civic, active) = civic_world(&mut kernel); + + let treasury = opportunity_for(&active, civic.treasury); + let reeve = opportunity_for(&active, civic.reeve); + assert_ne!(treasury.controller_id, reeve.controller_id); + assert_eq!( + active + .opportunities + .iter() + .filter(|value| value.scope.subject_id == civic.treasury) + .count(), + 1 + ); + assert_eq!( + active + .opportunities + .iter() + .filter(|value| value.scope.subject_id == civic.reeve) + .count(), + 1 + ); + + // Both are authorized over the hall — one directly, one by delegation — + // and neither appears in the other's components. + let over_hall = AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: AuthorityTarget::PlaceSubtree(civic.hall), + }; + assert!(subject_authority(&kernel.state, civic.treasury).contains(&over_hall)); + assert!(subject_authority(&kernel.state, civic.reeve).contains(&over_hall)); + assert!(kernel.state.authority.get(&civic.reeve).is_none()); + assert!( + scope_components(&kernel.state, civic.treasury) + .delegated + .is_empty() + ); + assert!( + scope_components(&kernel.state, civic.reeve) + .authority + .is_empty() + ); + } + + /// A levy from catalog to conservation: one lowered `Transfer`, the ledger + /// total unchanged, and no other partition touched. + #[test] + fn a_levy_round_trips_from_catalog_to_conservation() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "Levy"); + let (_, civic, active) = civic_world(&mut kernel); + let before_total: u64 = kernel + .state + .holdings + .values() + .filter_map(|held| held.get(&civic.grain)) + .map(|quantity| quantity.0) + .sum(); + let positions = kernel.state.positions.clone(); + let edges = kernel.state.edges.clone(); + let entities = kernel.state.entities.clone(); + + let opportunity = opportunity_for(&active, civic.treasury); + let caller = CallerId::Controller(opportunity.controller_id); + let receipt = kernel + .submit( + command( + &active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation: DecisionInvocation { + affordance: affordance_named(&active, "levy"), + bindings: vec![ + RoleBinding { + role: Role("payer".into()), + target: Target::Subject(civic.farmer), + }, + RoleBinding { + role: Role("resource".into()), + target: Target::Entity(civic.grain), + }, + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(3)), + }], + speech: None, + display: None, + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap(); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + + let held = |holder: SubjectId| { + kernel + .state + .holdings + .get(&holder) + .and_then(|held| held.get(&civic.grain)) + .map_or(0, |quantity| quantity.0) + }; + assert_eq!(held(civic.farmer), OPENING_BALANCE - 3); + assert_eq!(held(civic.treasury), 3); + let after_total: u64 = kernel + .state + .holdings + .values() + .filter_map(|held| held.get(&civic.grain)) + .map(|quantity| quantity.0) + .sum(); + assert_eq!(before_total, after_total); + assert_eq!( + kernel.state.events.last().unwrap().effects, + vec![ResolvedOp::Transfer { + from: civic.farmer, + to: civic.treasury, + resource: civic.grain, + qty: Quantity(3), + }] + ); + assert_eq!(kernel.state.positions, positions); + assert_eq!(kernel.state.edges, edges); + assert_eq!(kernel.state.entities, entities); + } + + /// Representation is person-and-institution shaped, and that is the check + /// that stops the two-subject shape from collapsing back into one. + #[test] + fn office_admission_is_person_and_institution_shaped() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "Offices"); + let (_, civic, _) = civic_world(&mut kernel); + let refuse = |kernel: &mut WorldKernel, ops: Vec<ComponentOp>| { + let before = kernel.snapshot().unwrap(); + reject_owner(kernel, &before, operations(ops)) + }; + + // An institution cannot occupy its own office. + assert_eq!( + refuse( + &mut kernel, + vec![ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office(BAILIFF_OFFICE), + incumbent: Ref::Existing(civic.treasury), + }] + ), + vec![Mismatch::OfficeHolderNotPerson { operation: 0 }] + ); + // An office cannot be opened on a person. + assert_eq!( + refuse( + &mut kernel, + vec![ComponentOp::OpenOffice { + institution: Ref::Existing(civic.reeve), + office: office(WARDEN_OFFICE), + delegated: BTreeSet::from([authority_kind(LEVY_KIND)]), + }] + ), + vec![Mismatch::OfficeOnNonInstitution { operation: 0 }] + ); + // One person, at most one office per institution. + assert_eq!( + refuse( + &mut kernel, + vec![ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office(BAILIFF_OFFICE), + incumbent: Ref::Existing(civic.reeve), + }] + ), + vec![Mismatch::DuplicateIncumbency { operation: 0 }] + ); + } + + /// Disjointness in both directions: overlap inside one subject's effective + /// authority is refused, overlap between subjects is layered government. + #[test] + fn overlapping_jurisdiction_within_one_subject_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "Overlap"); + let (_, civic, _) = civic_world(&mut kernel); + let refuse = |kernel: &mut WorldKernel, ops: Vec<ComponentOp>| { + let before = kernel.snapshot().unwrap(); + reject_owner(kernel, &before, operations(ops)) + }; + let admit = |kernel: &mut WorldKernel, ops: Vec<ComponentOp>| { + let before = kernel.snapshot().unwrap(); + submit_owner(kernel, &before, operations(ops)) + }; + + // A direct grant under what the reeve's office already lends. + assert_eq!( + refuse( + &mut kernel, + vec![grant_to(civic.reeve, LEVY_KIND, over_place(civic.chamber))] + ), + vec![Mismatch::OverlappingJurisdiction { operation: 0 }] + ); + // Two direct grants of one kind, nested, in one patch. + assert_eq!( + refuse( + &mut kernel, + vec![ + grant_to(civic.farmer, LEVY_KIND, over_place(civic.hall)), + grant_to(civic.farmer, LEVY_KIND, over_place(civic.chamber)), + ] + ), + vec![Mismatch::OverlappingJurisdiction { operation: 1 }] + ); + // An incumbency that would lend the farmer ground it already holds. + admit( + &mut kernel, + vec![grant_to(civic.farmer, LEVY_KIND, over_place(civic.chamber))], + ); + assert_eq!( + refuse( + &mut kernel, + vec![ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office(WARDEN_OFFICE), + incumbent: Ref::Existing(civic.farmer), + }] + ), + vec![Mismatch::OverlappingJurisdiction { operation: 0 }] + ); + + // A different kind over the same ground commits, and so does the same + // kind held by a different subject: two holders authorized over one + // target is not a contradiction, because nothing arbitrates. + assert!(matches!( + admit( + &mut kernel, + vec![ + grant_to(civic.reeve, JUDGE_KIND, over_place(civic.chamber)), + grant_to(civic.outsider, LEVY_KIND, over_place(civic.chamber)), + ] + ), + SubmitReceipt::Applied(_) + )); + } + + /// Contract 6 on the civic surface: one patch, the complete sorted set, no + /// allocation, and repairing exactly those failures commits. + #[test] + fn civic_operations_are_rejected_with_the_complete_set() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "CivicSet"); + let (_, civic, _) = civic_world(&mut kernel); + let before = kernel.snapshot().unwrap(); + let broken = vec![ + ComponentOp::OpenOffice { + institution: Ref::Existing(civic.treasury), + office: office("steward"), + delegated: BTreeSet::new(), + }, + ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office("provost"), + incumbent: Ref::Existing(civic.farmer), + }, + ComponentOp::CloseForum { + grievance: grievance("eviction"), + }, + ComponentOp::OpenOffice { + institution: Ref::Existing(civic.treasury), + office: office("Chief Steward"), + delegated: BTreeSet::from([authority_kind(JUDGE_KIND)]), + }, + ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office(BAILIFF_OFFICE), + incumbent: Ref::Existing(civic.treasury), + }, + grant_to(civic.reeve, LEVY_KIND, over_place(civic.chamber)), + ]; + let mut expected = vec![ + Mismatch::EmptyDelegation { operation: 0 }, + Mismatch::UnknownOffice { operation: 1 }, + Mismatch::UnknownForum { operation: 2 }, + Mismatch::InvalidCivicName { + site: patch::Site::Operation(3), + }, + Mismatch::OfficeHolderNotPerson { operation: 4 }, + Mismatch::OverlappingJurisdiction { operation: 5 }, + ]; + expected.sort(); + assert_eq!( + reject_owner(&mut kernel, &before, operations(broken)), + expected + ); + assert_eq!(kernel.snapshot().unwrap(), before); + + let repaired = vec![ + ComponentOp::OpenOffice { + institution: Ref::Existing(civic.treasury), + office: office("steward"), + delegated: BTreeSet::from([authority_kind(JUDGE_KIND)]), + }, + ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office("steward"), + incumbent: Ref::Existing(civic.farmer), + }, + ComponentOp::OpenForum { + grievance: grievance("eviction"), + forum: Ref::Existing(civic.treasury), + standing: over_place(civic.hall), + }, + ]; + assert!(matches!( + submit_owner(&mut kernel, &before, operations(repaired)), + SubmitReceipt::Applied(_) + )); + } + + /// A civic operation that changes nothing is not a canonical change. + #[test] + fn an_idempotent_civic_operation_is_no_change() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = + crate::custody_tests::custody_kernel(directory.path(), "Idempotent"); + let (_, civic, _) = civic_world(&mut kernel); + for operation in [ + grant_to(civic.treasury, LEVY_KIND, over_place(civic.hall)), + ComponentOp::RevokeAuthority { + holder: Ref::Existing(civic.treasury), + grant: grant_of(JUDGE_KIND, over_place(civic.hall)), + }, + ComponentOp::VacateOffice { + institution: Ref::Existing(civic.treasury), + office: office(BAILIFF_OFFICE), + }, + ComponentOp::OpenForum { + grievance: grievance(SEIZURE_GRIEVANCE), + forum: Ref::Existing(civic.treasury), + standing: over_place(civic.chamber), + }, + ComponentOp::OpenOffice { + institution: Ref::Existing(civic.treasury), + office: office(WARDEN_OFFICE), + delegated: BTreeSet::from([authority_kind(LEVY_KIND)]), + }, + ] { + let before = kernel.snapshot().unwrap(); + assert_eq!( + reject_owner(&mut kernel, &before, operations(vec![operation])), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + } + } + + /// The digest reads what the actor is authorized over and nothing about the + /// world the actor reaches. + #[test] + fn scope_digest_reads_authority_and_delegation_but_not_occupancy() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "Digest"); + let (topology, civic, _) = civic_world(&mut kernel); + let scope = |subject_id| DecisionScope { subject_id }; + let digest_of = |kernel: &WorldKernel, subject_id| { + scope_digest(&kernel.state, scope(subject_id)).unwrap() + }; + let admit = |kernel: &mut WorldKernel, ops: Vec<ComponentOp>| { + let before = kernel.snapshot().unwrap(); + submit_owner(kernel, &before, operations(ops)); + }; + + // Moving an unrelated subject into and out of the jurisdiction, and + // opening a forum, leave every digest alone. + let reeve_before = digest_of(&kernel, civic.reeve); + let treasury_before = digest_of(&kernel, civic.treasury); + admit( + &mut kernel, + vec![ + ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Existing(topology.ramp), + }, + ComponentOp::OpenForum { + grievance: grievance("eviction"), + forum: Ref::Existing(civic.treasury), + standing: over_place(civic.hall), + }, + ], + ); + assert_eq!(digest_of(&kernel, civic.reeve), reeve_before); + assert_eq!(digest_of(&kernel, civic.treasury), treasury_before); + + // Installing an office the subject does not hold leaves it alone too. + admit( + &mut kernel, + vec![ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office(BAILIFF_OFFICE), + incumbent: Ref::Existing(civic.farmer), + }], + ); + assert_eq!(digest_of(&kernel, civic.reeve), reeve_before); + assert_eq!(digest_of(&kernel, civic.treasury), treasury_before); + + // Revoking the institution's grant for a lent kind moves the + // incumbent's digest, because the office copies it in. + admit( + &mut kernel, + vec![ComponentOp::RevokeAuthority { + holder: Ref::Existing(civic.treasury), + grant: grant_of(LEVY_KIND, over_place(civic.hall)), + }], + ); + assert_ne!(digest_of(&kernel, civic.reeve), reeve_before); + assert_ne!(digest_of(&kernel, civic.treasury), treasury_before); + + // Granting the actor's own, and narrowing a held office, move it too. + let reeve_before = digest_of(&kernel, civic.reeve); + admit( + &mut kernel, + vec![grant_to(civic.reeve, LEVY_KIND, over_place(civic.chamber))], + ); + assert_ne!(digest_of(&kernel, civic.reeve), reeve_before); + let reeve_before = digest_of(&kernel, civic.reeve); + admit( + &mut kernel, + vec![ComponentOp::OpenOffice { + institution: Ref::Existing(civic.treasury), + office: office(WARDEN_OFFICE), + delegated: BTreeSet::from([authority_kind(COMMAND_KIND)]), + }], + ); + assert_ne!(digest_of(&kernel, civic.reeve), reeve_before); + let reeve_before = digest_of(&kernel, civic.reeve); + admit( + &mut kernel, + vec![ComponentOp::VacateOffice { + institution: Ref::Existing(civic.treasury), + office: office(WARDEN_OFFICE), + }], + ); + assert_ne!(digest_of(&kernel, civic.reeve), reeve_before); + } + + /// The snapshot carries a subject's own civic state and no gazetteer: a + /// forum is visible only to its standing, and no subject sees another's + /// grants. + #[test] + fn a_forum_is_visible_only_to_its_standing() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "Redress"); + let (_, civic, active) = civic_world(&mut kernel); + let of = |subject_id: SubjectId| { + active + .subjects + .iter() + .find(|subject| subject.id == subject_id) + .expect("a declared subject") + }; + + // The farmer stands in the chamber, which is the forum's standing. + assert_eq!( + of(civic.farmer).redress, + vec![ForumSnapshot { + grievance: grievance(SEIZURE_GRIEVANCE), + forum: civic.treasury, + }] + ); + assert!(of(civic.outsider).redress.is_empty()); + + // Grants are the subject's own; offices held and offices granted are + // the two ends of one link and never merge. + assert!(of(civic.reeve).components.authority.is_empty()); + assert_eq!(of(civic.reeve).offices_held.len(), 1); + assert!(of(civic.reeve).offices_granted.is_empty()); + assert_eq!(of(civic.treasury).offices_granted.len(), 2); + assert!(of(civic.treasury).offices_held.is_empty()); + assert!(of(civic.farmer).components.authority.is_empty()); + assert_eq!( + of(civic.treasury).components.authority, + BTreeSet::from([ + AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: AuthorityTarget::PlaceSubtree(civic.hall), + }, + AuthorityGrant { + kind: authority_kind(COMMAND_KIND), + over: AuthorityTarget::PlaceSubtree(civic.hall), + }, + ]) + ); + } + + /// Soul falsification of the candidate authority shadow's reach: a grant + /// minted in the same patch resolves, but a *destination* declared in the + /// same patch does not, because the shadow is projected to canonical + /// referents before the covering predicate runs. A genesis patch therefore + /// cannot declare a restricted room and walk anyone into it in one batch. + #[test] + fn a_same_patch_destination_is_covered_by_no_grant() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "DraftDoor"); + let topology = admit_topology(&mut kernel); + let before = kernel.snapshot().unwrap(); + let patch = WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("keep"), + label: "The Inner Keep".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("keepgate"), + label: "The Keep Gate".into(), + from: Ref::Existing(topology.yard), + to: Ref::Draft(DraftHandle::new("keep")), + access: AccessKind::Restricted { + requires: authority_kind(ADMIT_KIND), + }, + cost: Cost(2), + }), + ], + operations: vec![ + ComponentOp::GrantAuthority { + holder: Ref::Existing(topology.walker), + grant: AuthorityGrantRef { + kind: authority_kind(ADMIT_KIND), + over: AuthorityTargetRef::PlaceSubtree(Ref::Draft(DraftHandle::new( + "keep", + ))), + }, + }, + ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Draft(DraftHandle::new("keepgate")), + }, + ], + evidence: Vec::new(), + }; + assert_eq!( + reject_owner( + &mut kernel, + &before, + CommandBody::AdmitPatch { + answers: None, + patch + } + ), + vec![Mismatch::RouteAccessRestricted { operation: 1 }], + "the key covers the door, but the door's far side is still a draft" + ); + } + + /// PA.f38: a retired institution lends nothing. `Retire` does not vacate + /// the office the reeve holds — the incumbency stays on the ledger — but + /// `delegated_authority` stops reading a dissolved institution's grants, + /// the one site that turns an office into effective authority. + #[test] + fn a_retired_institution_lends_no_authority_to_its_office_holder() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "RetiredLends"); + let (_, civic, before) = civic_world(&mut kernel); + let over_hall = AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: AuthorityTarget::PlaceSubtree(civic.hall), + }; + assert!( + subject_authority(&kernel.state, civic.reeve).contains(&over_hall), + "the reeve holds levy only through the warden office before retirement" + ); + + submit_owner( + &mut kernel, + &before, + operations(vec![ComponentOp::Retire { + subject: Ref::Existing(civic.treasury), + }]), + ); + + let warden = kernel + .state + .selection + .get(&civic.treasury) + .and_then(|offices| offices.get(&office(WARDEN_OFFICE))) + .expect("retire did not vacate the office"); + assert_eq!( + warden.incumbent, + Some(civic.reeve), + "the reeve still holds the office after the institution retires" + ); + assert!( + !subject_authority(&kernel.state, civic.reeve).contains(&over_hall), + "a retired institution still lent authority through its office" + ); + } +} + +#[cfg(test)] +mod custody_tests { + use super::tests::{ + OPENING_BALANCE, TITHE_RECEIPT, activate, admit_custody, admit_topology, auth_principal, + command, creation, custody_world, operations, opportunity_for, owner, reject_owner, + speak_entry, submit_owner, + }; + use super::*; + + pub(crate) fn custody_kernel(path: &Path, title: &str) -> WorldKernel { + WorldKernel::create( + path.join("world.cc"), + creation(CommandId::new(), title), + &auth_principal(owner()), + ) + .expect("a created world") + .0 + } + + fn holding(kernel: &WorldKernel, holder: SubjectId, resource: EntityId) -> u64 { + held(&kernel.state, holder, resource) + } + + /// A forged `PatchAdmitted` never passes the resolver, so `admit_resolved` + /// re-derives every custody precondition from the committed partitions and + /// commits nothing when one fails. + /// + /// Deviation from the spec's wording, decided here: `ResolvedOp::Transfer` + /// carries one `qty`, so "a transfer whose debit and credit differ" is + /// unrepresentable — which is the stronger outcome that shape was chosen + /// for. The reachable forgery is a transfer the holder cannot cover, and + /// the conservation equation itself is falsified directly beside it. + #[test] + fn a_non_conserving_transfer_effect_does_not_apply() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Forged"); + let (_, custody, _) = custody_world(&mut kernel); + let before = kernel.state.holdings.clone(); + + let mut candidate = kernel.state.clone(); + let forged = WorldEffect::PatchAdmitted { + resolved: ResolvedPatch { + lens_weights: None, + subjects: Vec::new(), + entities: Vec::new(), + routes: Vec::new(), + affordances: Vec::new(), + facts: Vec::new(), + channels: Vec::new(), + operations: vec![ResolvedOp::Transfer { + from: custody.holder, + to: custody.counterparty, + resource: custody.tithe, + qty: Quantity(OPENING_BALANCE + 1), + }], + evidence: Vec::new(), + scale_intent: None, + }, + answers: None, + }; + let error = apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Principal(owner()), + &forged, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + assert_eq!(candidate.holdings, before); + + // The conservation equation is the one owner, and it refuses a ledger + // that does not balance regardless of which operation produced it. + let unbalanced = BTreeMap::from([( + custody.tithe, + LedgerDelta { + before: 7, + after: 9, + admitted: 1, + ..LedgerDelta::default() + }, + )]); + assert_eq!(patch::check_ledger(&unbalanced), Some(custody.tithe)); + let balanced = BTreeMap::from([( + custody.tithe, + LedgerDelta { + before: 7, + after: 8, + admitted: 1, + ..LedgerDelta::default() + }, + )]); + assert_eq!(patch::check_ledger(&balanced), None); + } + + /// Creation of quantity is attributable: an `Admit` whose ref is not in the + /// patch's own evidence list mints nothing and allocates no ID. + #[test] + fn an_admit_without_evidence_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Unevidenced"); + let topology = admit_topology(&mut kernel); + let speak = speak_entry(&kernel); + let before = kernel.snapshot().unwrap(); + let commits = kernel.journal.commit_count(); + + let mismatches = reject_owner( + &mut kernel, + &before, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("tithe"), + label: "The Rhythm Tithe".into(), + kind: EntityKind::Resource, + container: None, + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("clerk"), + label: "The Ledger Clerk".into(), + kind: SubjectKind::Institution, + controller: NewController::OperationalAgent, + affordances: BTreeSet::from([speak.clone()]), + position: Some(Ref::Existing(topology.yard)), + import_key: None, + }), + ], + operations: vec![ComponentOp::Admit { + holder: Ref::Draft(DraftHandle::new("clerk")), + resource: Ref::Draft(DraftHandle::new("tithe")), + qty: Quantity(4), + evidence: EvidenceRef::new("receipt:never-listed"), + }], + evidence: Vec::new(), + }, + }, + ); + + assert_eq!( + mismatches, + vec![Mismatch::AdmitWithoutEvidence { operation: 0 }] + ); + assert!(kernel.state.holdings.is_empty()); + assert_eq!(kernel.journal.commit_count(), commits); + assert_eq!(kernel.snapshot().unwrap(), before); + } + + #[test] + fn a_transfer_moves_the_exact_quantity_and_nothing_else() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Transfer"); + let (_, custody, active) = custody_world(&mut kernel); + let entities = kernel.state.entities.clone(); + let edges = kernel.state.edges.clone(); + let positions = kernel.state.positions.clone(); + + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }]), + ); + + assert_eq!(holding(&kernel, custody.holder, custody.tithe), 4); + assert_eq!(holding(&kernel, custody.counterparty, custody.tithe), 3); + assert_eq!(resource_total(&kernel.state, custody.tithe), 7); + assert_eq!(kernel.state.entities, entities); + assert_eq!(kernel.state.edges, edges); + assert_eq!(kernel.state.positions, positions); + } + + /// Absence is zero at both levels, so emptying a holding removes the + /// resource key and emptying a holder removes the holder key. + #[test] + fn consume_reduces_the_holding_and_emptying_removes_the_key() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Consume"); + let (_, custody, active) = custody_world(&mut kernel); + + let after_three = submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Consume { + holder: Ref::Existing(custody.holder), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }]), + ); + assert!(matches!(after_three, SubmitReceipt::Applied(_))); + assert_eq!(holding(&kernel, custody.holder, custody.tithe), 4); + + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::Consume { + holder: Ref::Existing(custody.holder), + resource: Ref::Existing(custody.tithe), + qty: Quantity(4), + }]), + ); + assert!(!kernel.state.holdings.contains_key(&custody.holder)); + let subject = kernel + .snapshot() + .unwrap() + .subjects + .into_iter() + .find(|subject| subject.id == custody.holder) + .expect("the holder is in the snapshot"); + assert!(subject.components.holdings.is_empty()); + } + + #[test] + fn a_transform_conserves_one_for_one() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Transform"); + let (_, custody, active) = custody_world(&mut kernel); + + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Transform { + holder: Ref::Existing(custody.holder), + from_resource: Ref::Existing(custody.tithe), + into_resource: Ref::Existing(custody.ingot), + qty: Quantity(5), + }]), + ); + + assert_eq!(holding(&kernel, custody.holder, custody.tithe), 2); + assert_eq!(holding(&kernel, custody.holder, custody.ingot), 5); + assert_eq!(resource_total(&kernel.state, custody.tithe), 2); + assert_eq!(resource_total(&kernel.state, custody.ingot), 5); + } + + #[test] + fn spending_more_than_held_is_rejected_with_insufficient_custody() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Insufficient"); + let (_, custody, _) = custody_world(&mut kernel); + let too_much = Quantity(OPENING_BALANCE + 1); + let attempts = [ + ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: too_much, + }, + ComponentOp::Transform { + holder: Ref::Existing(custody.holder), + from_resource: Ref::Existing(custody.tithe), + into_resource: Ref::Existing(custody.ingot), + qty: too_much, + }, + ComponentOp::Consume { + holder: Ref::Existing(custody.holder), + resource: Ref::Existing(custody.tithe), + qty: too_much, + }, + ]; + + for attempt in attempts { + let snapshot = kernel.snapshot().unwrap(); + let commits = kernel.journal.commit_count(); + let mismatches = reject_owner(&mut kernel, &snapshot, operations(vec![attempt])); + assert_eq!( + mismatches, + vec![Mismatch::InsufficientCustody { operation: 0 }] + ); + assert_eq!(kernel.journal.commit_count(), commits); + assert_eq!(kernel.snapshot().unwrap(), snapshot); + } + } + + /// A holder with no entry holds zero: there is no second name for it and no + /// zero entry anywhere in the snapshot. + #[test] + fn an_absent_holding_is_zero() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Absent"); + let (_, custody, active) = custody_world(&mut kernel); + + let mismatches = reject_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Consume { + holder: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(1), + }]), + ); + assert_eq!( + mismatches, + vec![Mismatch::InsufficientCustody { operation: 0 }] + ); + let counterparty = kernel + .snapshot() + .unwrap() + .subjects + .into_iter() + .find(|subject| subject.id == custody.counterparty) + .expect("the counterparty is in the snapshot"); + assert!(counterparty.components.holdings.is_empty()); + } + + #[test] + fn a_zero_quantity_operation_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Zero"); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + + // `Admit` is Draft-only, because Active refuses a patch carrying + // evidence, so its zero case is proven before activation. + let draft = kernel.snapshot().unwrap(); + let mismatches = reject_owner( + &mut kernel, + &draft, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Admit { + holder: Ref::Existing(custody.holder), + resource: Ref::Existing(custody.tithe), + qty: Quantity(0), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }], + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], + }, + }, + ); + assert_eq!(mismatches, vec![Mismatch::ZeroQuantity { operation: 0 }]); + + let active = activate(&mut kernel); + for attempt in [ + ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(0), + }, + ComponentOp::Consume { + holder: Ref::Existing(custody.holder), + resource: Ref::Existing(custody.tithe), + qty: Quantity(0), + }, + ] { + let snapshot = kernel.snapshot().unwrap(); + let mismatches = reject_owner(&mut kernel, &snapshot, operations(vec![attempt])); + assert_eq!(mismatches, vec![Mismatch::ZeroQuantity { operation: 0 }]); + } + assert_eq!(kernel.snapshot().unwrap(), active); + } + + #[test] + fn dependency_bind_and_release_round_trip() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Dependency"); + let (_, custody, active) = custody_world(&mut kernel); + let before = kernel.state.dependencies.clone(); + + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Resource(Ref::Existing(custody.tithe)), + }]), + ); + assert_eq!( + kernel.state.dependencies.get(&custody.holder), + Some(&BTreeSet::from([DependencyTarget::Resource(custody.tithe)])) + ); + + let bound = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &bound, + operations(vec![ComponentOp::Release { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Resource(Ref::Existing(custody.tithe)), + }]), + ); + assert_eq!(kernel.state.dependencies, before); + assert!(!kernel.state.dependencies.contains_key(&custody.holder)); + } + + /// A bind that changes nothing is `NoOperationEffect`, the name pass 2 + /// already owns; a subject bound to itself is `SelfDependency`. + #[test] + fn a_duplicate_dependency_bind_is_rejected_as_no_effect() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Duplicate"); + let (_, custody, active) = custody_world(&mut kernel); + + let bind = ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Resource(Ref::Existing(custody.tithe)), + }; + submit_owner(&mut kernel, &active, operations(vec![bind.clone()])); + + let bound = kernel.snapshot().unwrap(); + assert_eq!( + reject_owner(&mut kernel, &bound, operations(vec![bind])), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + assert_eq!( + reject_owner( + &mut kernel, + &bound, + operations(vec![ComponentOp::Release { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Resource(Ref::Existing(custody.ingot)), + }]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + assert_eq!( + reject_owner( + &mut kernel, + &bound, + operations(vec![ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Subject(Ref::Existing(custody.holder)), + }]), + ), + vec![Mismatch::SelfDependency { operation: 0 }] + ); + } + + /// Pass 3 owns the representation of a dependency, not its consequence. A + /// dependency on a closed route commits and shows up in the subject's + /// components; nothing rejects it and nothing fires from it. + #[test] + fn a_dependency_on_a_closed_route_is_representable_and_visible() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Closed"); + let (topology, custody, active) = custody_world(&mut kernel); + assert!(!kernel.state.edges[&topology.shutter].is_open()); + + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Route(Ref::Existing(topology.shutter)), + }]), + ); + + let subject = kernel + .snapshot() + .unwrap() + .subjects + .into_iter() + .find(|subject| subject.id == custody.holder) + .expect("the holder is in the snapshot"); + assert_eq!( + subject.components.dependencies, + BTreeSet::from([DependencyTarget::Route(topology.shutter)]) + ); + } + + /// The digest reads the acting subject's own holdings and dependencies, and + /// only its own: a counterparty's churn does not move it. + #[test] + fn scope_digest_reads_holdings_and_dependencies() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "ScopeCustody"); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + activate(&mut kernel); + let scope = DecisionScope { + subject_id: custody.holder, + }; + let base = scope_digest(&kernel.state, scope).unwrap(); + + let mut spent = kernel.state.clone(); + set_held(&mut spent, custody.holder, custody.tithe, 1); + assert_ne!(scope_digest(&spent, scope).unwrap(), base); + + let mut gained = kernel.state.clone(); + set_held(&mut gained, custody.holder, custody.ingot, 1); + assert_ne!(scope_digest(&gained, scope).unwrap(), base); + + let mut bound = kernel.state.clone(); + bound + .dependencies + .entry(custody.holder) + .or_default() + .insert(DependencyTarget::Resource(custody.tithe)); + assert_ne!(scope_digest(&bound, scope).unwrap(), base); + + let mut elsewhere = kernel.state.clone(); + set_held(&mut elsewhere, custody.counterparty, custody.tithe, 9); + elsewhere + .dependencies + .entry(custody.counterparty) + .or_default() + .insert(DependencyTarget::Resource(custody.ingot)); + assert_eq!(scope_digest(&elsewhere, scope).unwrap(), base); + } + + /// A proposal bound while its subject held seven must not commit after + /// someone took six. Custody churn rejects more bound proposals than route + /// churn did; that is the binding working. + #[test] + fn a_spend_bound_to_a_stale_balance_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Stale"); + let (_, custody, active) = custody_world(&mut kernel); + let bound = opportunity_for(&active, custody.holder); + + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(6), + }]), + ); + + let moved = kernel.snapshot().unwrap(); + let commits = kernel.journal.commit_count(); + let error = kernel + .submit( + command( + &moved, + CommandId::new(), + CallerId::Controller(bound.controller_id), + CommandBody::ExerciseDecision { + opportunity: bound.clone(), + invocation: DecisionInvocation { + affordance: bound.affordance_ids[0], + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("The tithe is short.").unwrap()), + display: None, + }, + }, + ), + &AuthenticatedCaller::fixture(CallerId::Controller(bound.controller_id)), + ) + .unwrap_err(); + + assert!(matches!(error, KernelError::ScopeChanged { .. })); + assert_eq!(kernel.journal.commit_count(), commits); + assert_eq!(kernel.snapshot().unwrap(), moved); + } + + /// Soul, proof 4: the ledger equation stated as arithmetic over the + /// committed partitions, across one patch that exercises every conserving + /// operation at once. Per resource, `after == before + admitted + gained - + /// consumed - spent`, and no third resource moves. + #[test] + fn soul_a_mixed_patch_conserves_every_resource_it_touches() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "MixedLedger"); + let (_, custody, active) = custody_world(&mut kernel); + + // The opening balance was created by `Admit` alone: before is zero, + // admitted is the balance, and the total equals the sum of the two. + assert_eq!( + resource_total(&kernel.state, custody.tithe), + u128::from(OPENING_BALANCE) + ); + assert_eq!(resource_total(&kernel.state, custody.ingot), 0); + + let tithe_before = resource_total(&kernel.state, custody.tithe); + let ingot_before = resource_total(&kernel.state, custody.ingot); + + let receipt = submit_owner( + &mut kernel, + &active, + operations(vec![ + ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }, + ComponentOp::Transform { + holder: Ref::Existing(custody.holder), + from_resource: Ref::Existing(custody.tithe), + into_resource: Ref::Existing(custody.ingot), + qty: Quantity(2), + }, + ComponentOp::Consume { + holder: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(1), + }, + ]), + ); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + + // Transfer contributes to no term; transform contributes one spent and + // one gained; consume contributes one consumed. Nothing was admitted. + assert_eq!( + resource_total(&kernel.state, custody.tithe), + tithe_before - 1 - 2 + ); + assert_eq!( + resource_total(&kernel.state, custody.ingot), + ingot_before + 2 + ); + assert_eq!(holding(&kernel, custody.holder, custody.tithe), 2); + assert_eq!(holding(&kernel, custody.holder, custody.ingot), 2); + assert_eq!(holding(&kernel, custody.counterparty, custody.tithe), 2); + // Absence is zero: the counterparty never held an ingot, so there is no + // row for one rather than a row holding nothing. + assert!(!kernel.state.holdings[&custody.counterparty].contains_key(&custody.ingot)); + } + + /// Soul: is the apply-side `check_ledger` reachable? + /// + /// A forged `PatchAdmitted` can carry a *sequence* whose second operation + /// exceeds what the first left. It dies at `apply_operation`'s own + /// re-derived precondition, one operation early, so the ledger never speaks. + /// A sequence in which every operation applies cannot break the equation, + /// because every `ResolvedOp` arm debits and credits the same `qty` it + /// records: the apply-side call is unreachable from the current closed set. + #[test] + fn soul_a_forged_sequence_dies_at_the_per_operation_check_not_the_ledger() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "ForgedSequence"); + let (_, custody, _) = custody_world(&mut kernel); + let before = kernel.state.holdings.clone(); + + let forge = |operations: Vec<ResolvedOp>| WorldEffect::PatchAdmitted { + resolved: ResolvedPatch { + lens_weights: None, + subjects: Vec::new(), + entities: Vec::new(), + routes: Vec::new(), + affordances: Vec::new(), + facts: Vec::new(), + channels: Vec::new(), + operations, + evidence: Vec::new(), + scale_intent: None, + }, + answers: None, + }; + let transfer = |qty: u64| ResolvedOp::Transfer { + from: custody.holder, + to: custody.counterparty, + resource: custody.tithe, + qty: Quantity(qty), + }; + + // Two transfers of five out of a balance of seven: the first leaves two, + // the second cannot cover five. + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Principal(owner()), + &forge(vec![transfer(5), transfer(5)]), + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::Invariant(message) if message == "holder does not hold enough"), + "the per-operation precondition speaks first, not the ledger: {error:?}" + ); + // The candidate is a throwaway clone; the live state never moved. + assert_eq!(kernel.state.holdings, before); + + // Every operation applying means the equation balances, so the same + // forged lane commits a conserving sequence with no ledger complaint. + let mut conserving = kernel.state.clone(); + apply_effect( + &mut conserving, + CommandId::issue(), + &CallerId::Principal(owner()), + &forge(vec![ + transfer(5), + ResolvedOp::Transfer { + from: custody.counterparty, + to: custody.holder, + resource: custody.tithe, + qty: Quantity(5), + }, + ]), + ) + .expect("a conserving forged sequence applies"); + assert_eq!(conserving.holdings, before); + + // The degenerate shapes a forgery could otherwise use to mint or burn + // are refused by the arms themselves, not by the equation. + for degenerate in [ + ResolvedOp::Transfer { + from: custody.holder, + to: custody.holder, + resource: custody.tithe, + qty: Quantity(1), + }, + ResolvedOp::Transform { + holder: custody.holder, + from_resource: custody.tithe, + into_resource: custody.tithe, + qty: Quantity(1), + }, + ] { + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Principal(owner()), + &forge(vec![degenerate]), + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::Invariant(message) if message == "custody operation moves nothing"), + "unexpected refusal: {error:?}" + ); + } + + // An `Admit` in a forged effect still needs its receipt in the same + // patch, so the apply lane mints no unattributable quantity either. + let mut unevidenced = kernel.state.clone(); + let error = apply_effect( + &mut unevidenced, + CommandId::issue(), + &CallerId::Principal(owner()), + &forge(vec![ResolvedOp::Admit { + holder: custody.holder, + resource: custody.tithe, + qty: Quantity(4), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }]), + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::Invariant(message) if message == "admitted quantity cites no evidence in its patch"), + "unexpected refusal: {error:?}" + ); + assert_eq!(kernel.state.holdings, before); + } + + /// Soul: `QuantityOverflow` is reachable, and the arithmetic that reaches it + /// is `checked_add` rather than a silent clamp. Two admissions in one patch + /// whose sum exceeds `u64::MAX` mint nothing and allocate no ID. + #[test] + fn soul_a_holding_cannot_overflow_silently() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Overflow"); + let topology = admit_topology(&mut kernel); + let speak = speak_entry(&kernel); + let before = kernel.snapshot().unwrap(); + let commits = kernel.journal.commit_count(); + + let admit = |qty: u64| ComponentOp::Admit { + holder: Ref::Draft(DraftHandle::new("clerk")), + resource: Ref::Draft(DraftHandle::new("tithe")), + qty: Quantity(qty), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }; + let mismatches = reject_owner( + &mut kernel, + &before, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("tithe"), + label: "The Rhythm Tithe".into(), + kind: EntityKind::Resource, + container: None, + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("clerk"), + label: "The Ledger Clerk".into(), + kind: SubjectKind::Institution, + controller: NewController::OperationalAgent, + affordances: BTreeSet::from([speak.clone()]), + position: Some(Ref::Existing(topology.yard)), + import_key: None, + }), + ], + operations: vec![admit(u64::MAX), admit(1)], + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], + }, + }, + ); + + assert_eq!( + mismatches, + vec![Mismatch::QuantityOverflow { operation: 1 }], + "the overflow is the complete verdict: no clamp, no second name" + ); + assert!(kernel.state.holdings.is_empty()); + assert_eq!(kernel.journal.commit_count(), commits); + assert_eq!(kernel.snapshot().unwrap(), before); + } + + /// Soul, scope: a transfer changes the *receiver's* components too, so the + /// counterparty's in-flight proposal is refused with `ScopeChanged` while an + /// unrelated subject's bound proposal still commits at the later revision. + #[test] + fn soul_an_incoming_transfer_changes_only_the_counterpartys_scope() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "IncomingScope"); + let (topology, custody, active) = custody_world(&mut kernel); + let receiver = opportunity_for(&active, custody.counterparty); + let bystander = opportunity_for(&active, topology.walker); + + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }]), + ); + let moved = kernel.snapshot().unwrap(); + + let exercise = |opportunity: &DecisionOpportunity| CommandBody::ExerciseDecision { + opportunity: opportunity.clone(), + invocation: DecisionInvocation { + affordance: opportunity.affordance_ids[0], + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("Counted before the tithe arrived.").unwrap()), + display: None, + }, + }; + + let error = kernel + .submit( + command( + &moved, + CommandId::new(), + CallerId::Controller(receiver.controller_id), + exercise(&receiver), + ), + &AuthenticatedCaller::fixture(CallerId::Controller(receiver.controller_id)), + ) + .unwrap_err(); + assert!( + matches!(error, KernelError::ScopeChanged { .. }), + "the receiver's holdings moved under its bound proposal: {error:?}" + ); + + let receipt = kernel + .submit( + command( + &moved, + CommandId::new(), + CallerId::Controller(bystander.controller_id), + exercise(&bystander), + ), + &AuthenticatedCaller::fixture(CallerId::Controller(bystander.controller_id)), + ) + .expect("an unrelated subject's bound proposal is untouched by the transfer"); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + } +} + +/// Pass 6: `Knowledge`, `Channel`, `Fact` standing, and the non-leakage rule. +/// A subject perceives a speech act if and only if it holds `Knowledge` of that +/// act's fact — the knowledge partition is the sole owner of who-heard-what. +#[cfg(test)] +mod knowledge_tests { + use super::patch::{RefName, Site}; + use super::tests::{ + affordance_named, + FLOOD_EVIDENCE, FLOOD_STATEMENT, Speech, auth_principal, command, creation, operations, + opportunity_for, owner, reject_owner, speech_world, spoken, submit_owner, + }; + use super::*; + use std::path::Path; + + fn speech_kernel(path: &Path, title: &str) -> (WorldKernel, Speech, WorldSnapshot) { + let mut kernel = WorldKernel::create( + path.join("world.cc"), + creation(CommandId::new(), title), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (speech, active) = speech_world(&mut kernel); + (kernel, speech, active) + } + + fn utter( + kernel: &mut WorldKernel, + snapshot: &WorldSnapshot, + actor: SubjectId, + invocation: DecisionInvocation, + ) -> Result<SubmitReceipt, KernelError> { + let opportunity = opportunity_for(snapshot, actor); + let caller = CallerId::Controller(opportunity.controller_id); + kernel.submit( + command( + snapshot, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + } + + fn say(affordance: AffordanceId, bindings: Vec<RoleBinding>, text: &str) -> DecisionInvocation { + DecisionInvocation { + affordance, + bindings, + proposed: Vec::new(), + speech: Some(Statement::new(text).unwrap()), + display: None, + } + } + + fn binding(role: &str, target: Target) -> RoleBinding { + RoleBinding { + role: Role(role.into()), + target, + } + } + + fn rejected(result: Result<SubmitReceipt, KernelError>) -> Vec<ActionMismatch> { + match result { + Err(KernelError::ActionRejected(mismatches)) => mismatches, + other => panic!("expected a rejected invocation, got {other:?}"), + } + } + + fn knows(kernel: &WorldKernel, subject: SubjectId, fact: EntityId) -> Option<Knowledge> { + kernel + .state + .knowledge + .get(&subject) + .and_then(|held| held.get(&fact)) + .copied() + } + + fn acquire(subject: SubjectId, fact: EntityId, source: AuthoredSource) -> ComponentOp { + ComponentOp::AcquireKnowledge { + subject: Ref::Existing(subject), + fact: Ref::Existing(fact), + source, + confidence: Confidence::Certain, + } + } + + fn minted_claim(kernel: &WorldKernel) -> EntityId { + kernel + .state + .events + .last() + .expect("the committed event") + .speech + .expect("a speech act names its claim") + } + + /// Verification 5, first half: a patch adds knowledge only by citing an + /// accessible fact, and a rejected citation allocates nothing. + #[test] + fn knowledge_citing_an_inaccessible_fact_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Inaccessible"); + let before = kernel.state.clone(); + + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![acquire( + speech.listener, + EntityId::issue(), + AuthoredSource::Witnessed + )]), + ), + vec![Mismatch::UnknownCanonical { + site: Site::Operation(0), + expected: RefKind::Entity(EntityKind::Fact), + }] + ); + // A live referent of the wrong kind names the kind it actually is. + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![acquire( + speech.listener, + speech.hall, + AuthoredSource::Witnessed + )]), + ), + vec![Mismatch::WrongKind { + site: Site::Operation(0), + referent: RefName::Entity(Ref::Existing(speech.hall)), + expected: RefKind::Entity(EntityKind::Fact), + actual: RefKind::Entity(EntityKind::Place), + }] + ); + assert_eq!(kernel.state, before); + + submit_owner( + &mut kernel, + &active, + operations(vec![acquire( + speech.listener, + speech.flood, + AuthoredSource::Witnessed, + )]), + ); + assert_eq!( + knows(&kernel, speech.listener, speech.flood).map(|held| held.source), + Some(KnowledgeSource::Witnessed) + ); + } + + /// Standing is what a fact *is*, so both halves are checked at declaration: + /// canon needs its receipt in the same patch, a claim needs a live asserter. + #[test] + fn a_canonical_fact_needs_evidence_and_a_claim_needs_an_asserter() { + let directory = tempfile::tempdir().unwrap(); + let mut draft = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "Standing"), + &auth_principal(owner()), + ) + .expect("a draft world") + .0; + let start = draft.snapshot().unwrap(); + let declare = + |standing: FactStandingRef, evidence: Vec<EvidenceRef>| CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("rumour"), + label: "a rumour".into(), + statement: Statement::new("The reeve took two tithes.").unwrap(), + standing, + })], + operations: Vec::new(), + evidence, + }, + }; + + assert_eq!( + reject_owner( + &mut draft, + &start, + declare( + FactStandingRef::Canonical { + evidence: EvidenceRef::new("vault:absent"), + }, + Vec::new(), + ), + ), + vec![Mismatch::FactWithoutEvidence { + handle: DraftHandle::new("rumour"), + }] + ); + assert_eq!( + reject_owner( + &mut draft, + &start, + declare( + FactStandingRef::Claimed { + by: Ref::Draft(DraftHandle::new("nobody")), + }, + Vec::new(), + ), + ), + vec![Mismatch::UnresolvedDraft { + site: Site::Declaration(DraftHandle::new("rumour")), + referent: DraftHandle::new("nobody"), + expected: RefKind::Subject(None), + }] + ); + assert!(draft.state.facts.is_empty()); + + submit_owner( + &mut draft, + &start, + declare( + FactStandingRef::Canonical { + evidence: EvidenceRef::new("vault:rumour"), + }, + vec![EvidenceRef::new("vault:rumour")], + ), + ); + assert_eq!(draft.state.facts.len(), 1); + // The bijection holds in both directions. + let fact = *draft.state.facts.keys().next().unwrap(); + assert_eq!(draft.state.entities[&fact].kind, EntityKind::Fact); + } + + /// A receipt vouches for canon. It cannot vouch for an assertion the kernel + /// never evaluated. + #[test] + fn evidenced_knowledge_of_a_claim_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Evidenced"); + utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The gate was left open.", + ), + ) + .expect("the proclamation commits"); + let claim = minted_claim(&kernel); + let active = kernel.snapshot().unwrap(); + + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![acquire( + speech.stranger, + claim, + AuthoredSource::Evidenced + )]), + ), + vec![Mismatch::EvidencedKnowledgeOfClaim { operation: 0 }] + ); + submit_owner( + &mut kernel, + &active, + operations(vec![acquire( + speech.stranger, + speech.flood, + AuthoredSource::Evidenced, + )]), + ); + assert_eq!( + knows(&kernel, speech.stranger, speech.flood).map(|held| held.source), + Some(KnowledgeSource::Evidenced) + ); + assert_eq!( + kernel.state.facts[&speech.flood].standing, + FactStanding::Canonical { + evidence: EvidenceRef::new(FLOOD_EVIDENCE), + } + ); + } + + /// The fan-out is the audience, less the speaker: co-located speech fills + /// the exact room, and the utterance lands in `facts` and nowhere else. + #[test] + fn speak_fans_out_to_the_audience_and_not_beyond() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "FanOut"); + utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + "Mind the hinge.", + ), + ) + .expect("the whisper commits"); + + let event = kernel.state.events.last().expect("the committed event"); + let claim = event.speech.expect("a speech act names its claim"); + assert_eq!(spoken(&kernel.state, event), Some("Mind the hinge.")); + assert_eq!( + knows(&kernel, speech.listener, claim), + Some(Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Told { + by: speech.speaker, + via: None, + }, + acquired_at: active.revision + 1, + }) + ); + // The yard is inside the hall, but a voice fills a room and not the + // district containing it. The speaker's own claim is not implied. + for outside in [speech.bystander, speech.stranger, speech.speaker] { + assert_eq!(knows(&kernel, outside, claim), None); + } + assert_eq!( + kernel.state.facts[&claim].standing, + FactStanding::Claimed { by: speech.speaker } + ); + // The utterance has exactly one home: a label is a name, not a + // transcript. + assert_ne!(kernel.state.entities[&claim].label, "Mind the hinge."); + } + + /// Co-location is the exact place; a channel's `Reach::Place` is the + /// subtree, through the same containment walk a jurisdiction uses. + #[test] + fn co_location_reach_is_the_exact_place_and_a_channel_place_is_the_subtree() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Reach"); + utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The horn carries.", + ), + ) + .expect("the proclamation commits"); + let broadcast = minted_claim(&kernel); + assert!(knows(&kernel, speech.listener, broadcast).is_some()); + assert!(knows(&kernel, speech.bystander, broadcast).is_some()); + assert_eq!(knows(&kernel, speech.stranger, broadcast), None); + + // The same speaker's voice reaches only the hall. + let active = kernel.snapshot().unwrap(); + utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + "A voice does not.", + ), + ) + .expect("the whisper commits"); + let voiced = minted_claim(&kernel); + assert!(knows(&kernel, speech.listener, voiced).is_some()); + assert_eq!(knows(&kernel, speech.bystander, voiced), None); + + // Moving the bystander up the stair puts it in both audiences. + let active = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Relocate { + subject: Ref::Existing(speech.bystander), + via: Ref::Existing(speech.stair), + }]), + ); + let active = kernel.snapshot().unwrap(); + utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.bystander))], + "Now you hear it.", + ), + ) + .expect("the whisper commits"); + assert!(knows(&kernel, speech.bystander, minted_claim(&kernel)).is_some()); + } + + /// The delta of a telling is a property of the world, not a defect in the + /// proposal: speaking alone commits the claim and the event and lands + /// nothing. + #[test] + fn speaking_into_an_empty_room_commits_the_claim_and_lands_nothing() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "EmptyRoom"); + let knowledge_before = kernel.state.knowledge.clone(); + utter( + &mut kernel, + &active, + speech.bystander, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.bystander))], + "Nobody is here.", + ), + ) + .expect("speech into an empty room commits"); + + assert_eq!(kernel.state.knowledge, knowledge_before); + assert_eq!(kernel.state.events.len(), 1); + assert_eq!( + spoken(&kernel.state, kernel.state.events.last().unwrap()), + Some("Nobody is here.") + ); + assert_eq!( + kernel + .state + .facts + .values() + .filter(|record| matches!(record.standing, FactStanding::Claimed { .. })) + .count(), + 1 + ); + } + + + fn show( + affordance: AffordanceId, + bindings: Vec<RoleBinding>, + speech: Option<&str>, + display: &str, + ) -> DecisionInvocation { + DecisionInvocation { + affordance, + bindings, + proposed: Vec::new(), + speech: speech.map(|text| Statement::new(text).unwrap()), + display: Some(Statement::new(display).unwrap()), + } + } + + /// A visible act is the room's to see and nobody else's: everyone standing + /// in the actor's place holds it as `Seen { by }`; the actor, the yard + /// below, and the placeless hold nothing. The entry's own audience is not + /// consulted: a proclamation down the horn carries its words to the yard + /// and still folds its arms only before the hall. + #[test] + fn a_display_is_seen_by_the_room_and_by_no_one_else() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Display"); + utter( + &mut kernel, + &active, + speech.speaker, + show( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + Some("The horn carries."), + "I fold my arms.", + ), + ) + .expect("the proclamation with a display commits"); + + let event = kernel.state.events.last().expect("the committed event"); + let said = event.speech.expect("the utterance names its claim"); + let seen = event.display.expect("the display names its claim"); + assert_ne!(said, seen); + assert_eq!(kernel.state.facts[&seen].statement.as_str(), "I fold my arms."); + assert_eq!( + kernel.state.facts[&seen].standing, + FactStanding::Claimed { by: speech.speaker } + ); + assert!(knows(&kernel, speech.bystander, said).is_some()); + assert_eq!( + knows(&kernel, speech.listener, seen), + Some(Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Seen { by: speech.speaker }, + acquired_at: active.revision + 1, + }) + ); + for blind in [speech.bystander, speech.stranger, speech.speaker] { + assert_eq!(knows(&kernel, blind, seen), None); + } + // One act minted both claims, so the listener's snapshot stamps both + // rows with the one revision, and the operator's feed carries both. + let snapshot = kernel.snapshot().unwrap(); + let listener = snapshot + .subjects + .iter() + .find(|subject| subject.id == speech.listener) + .unwrap(); + let stamps: BTreeSet<Option<u64>> = listener + .knowledge + .iter() + .filter(|row| row.fact == said || row.fact == seen) + .map(|row| row.minted_at) + .collect(); + assert_eq!(stamps, BTreeSet::from([Some(event.revision)])); + let log = kernel.operator_log().unwrap(); + assert_eq!(log.last().unwrap().speech.as_ref().unwrap().as_str(), "The horn carries."); + assert_eq!(log.last().unwrap().display.as_ref().unwrap().as_str(), "I fold my arms."); + } + + /// A silent turn: the kernel `speak` entry invoked with no utterance and a + /// display is an address, not `SpeechRequired`. The act lands, no speech + /// claim is minted, and alone in the yard the same act commits its claim + /// and lands nothing, as speaking alone does. + #[test] + fn a_silent_display_addresses_the_room_through_the_speak_entry() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Silent"); + let speak = affordance_named(&active, "speak"); + utter( + &mut kernel, + &active, + speech.speaker, + show(speak, Vec::new(), None, "I nod toward the stair."), + ) + .expect("a silent act commits"); + let event = kernel.state.events.last().unwrap(); + assert!(event.speech.is_none()); + let seen = event.display.expect("the display names its claim"); + assert_eq!( + knows(&kernel, speech.listener, seen).map(|held| held.source), + Some(KnowledgeSource::Seen { by: speech.speaker }) + ); + assert_eq!(claimed(&kernel), 1); + + let active = kernel.snapshot().unwrap(); + let knowledge_before = kernel.state.knowledge.clone(); + utter( + &mut kernel, + &active, + speech.bystander, + show(speak, Vec::new(), None, "I sit on the step."), + ) + .expect("a display into an empty room commits"); + assert_eq!(kernel.state.knowledge, knowledge_before); + assert_eq!(kernel.state.events.len(), 2); + assert_eq!(claimed(&kernel), 2); + } + + /// The refusals, each at its own layer: a padded act is `EmptyDisplay` at + /// the check; a speech-carrying entry given neither words nor act is + /// `SpeechRequired`; the placeless stranger has no room to be seen in and + /// fails the entry's own `NoAudience`. None of them mints anything. + #[test] + fn a_display_is_refused_when_empty_placeless_or_when_nothing_is_addressed() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Refused"); + let speak = affordance_named(&active, "speak"); + let mut padded = show(speak, Vec::new(), None, "placeholder"); + padded.display = Some(serde_json::from_str::<Statement>("\" \"").unwrap()); + assert_eq!( + rejected(utter(&mut kernel, &active, speech.speaker, padded)), + vec![ActionMismatch::EmptyDisplay] + ); + let mute = DecisionInvocation { + affordance: speech.whisper, + bindings: vec![binding("target", Target::Subject(speech.listener))], + proposed: Vec::new(), + speech: None, + display: None, + }; + assert_eq!( + rejected(utter(&mut kernel, &active, speech.speaker, mute)), + vec![ActionMismatch::SpeechRequired] + ); + assert_eq!( + rejected(utter( + &mut kernel, + &active, + speech.stranger, + show(speak, Vec::new(), None, "I shrug."), + )), + vec![ActionMismatch::NoAudience { precondition: 0 }] + ); + assert!(kernel.state.events.is_empty()); + assert_eq!(claimed(&kernel), 0); + } + + /// The claims a display minted, its `Seen` rows, and its event replay from + /// the journal exactly, through the same path as speech. + #[test] + fn restart_replay_after_a_display_is_exact() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (speech, world_id, expected) = { + let mut kernel = WorldKernel::create( + &path, + creation(CommandId::new(), "ReplayDisplay"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (speech, active) = speech_world(&mut kernel); + let speak = affordance_named(&active, "speak"); + utter( + &mut kernel, + &active, + speech.speaker, + show(speak, Vec::new(), Some("One."), "I raise one finger."), + ) + .expect("the act commits"); + let active = kernel.snapshot().unwrap(); + utter( + &mut kernel, + &active, + speech.listener, + show(speak, Vec::new(), None, "I look away."), + ) + .expect("the silent act commits"); + (speech, kernel.state.world_id, kernel.state.clone()) + }; + let reopened = WorldKernel::open(&path, world_id).expect("the store replays"); + assert_eq!(reopened.state, expected); + assert!(reopened.state.knowledge[&speech.listener] + .values() + .any(|held| held.source == KnowledgeSource::Seen { by: speech.speaker })); + assert!(reopened.state.knowledge[&speech.speaker] + .values() + .any(|held| held.source == KnowledgeSource::Seen { by: speech.listener })); + } + + fn claimed(kernel: &WorldKernel) -> usize { + kernel + .state + .facts + .values() + .filter(|record| matches!(record.standing, FactStanding::Claimed { .. })) + .count() + } + + /// The horn belongs to the temple: its controller may speak on it whether + /// or not it stands inside its reach, and removing the controller flips the + /// same invocation to exactly one named failure. + #[test] + fn a_channel_controller_may_speak_outside_its_own_reach() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Controller"); + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::SetReach { + channel: Ref::Existing(speech.horn), + reach: ReachRef::Subjects(BTreeSet::from([Ref::Existing(speech.listener)])), + }]), + ); + let proclaim = || { + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The horn still carries.", + ) + }; + let active = kernel.snapshot().unwrap(); + utter(&mut kernel, &active, speech.speaker, proclaim()) + .expect("the controller may speak on its own channel"); + + let active = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::SetController { + channel: Ref::Existing(speech.horn), + controller: None, + }]), + ); + let active = kernel.snapshot().unwrap(); + assert_eq!( + rejected(utter(&mut kernel, &active, speech.speaker, proclaim())), + vec![ActionMismatch::NoAudience { precondition: 0 }] + ); + } + + /// Addressing does not narrow the audience, and a target outside it names + /// itself. A target that walked in mid-flight commits, and the whole + /// audience receives the telling, not only the addressed subject. + #[test] + fn an_addressed_subject_outside_the_audience_names_itself() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Addressing"); + let whisper = || { + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.bystander))], + "Come inside.", + ) + }; + assert_eq!( + rejected(utter(&mut kernel, &active, speech.speaker, whisper())), + vec![ActionMismatch::CannotReach { precondition: 0 }] + ); + + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Relocate { + subject: Ref::Existing(speech.bystander), + via: Ref::Existing(speech.stair), + }]), + ); + let active = kernel.snapshot().unwrap(); + utter(&mut kernel, &active, speech.speaker, whisper()) + .expect("the addressed subject is now in the room"); + let claim = minted_claim(&kernel); + assert!(knows(&kernel, speech.bystander, claim).is_some()); + assert!( + knows(&kernel, speech.listener, claim).is_some(), + "speaking to someone in a room is heard by the room" + ); + } + + /// `Knows` compares confidence with one `>=`, and `Forget` removes the key + /// rather than storing a zero. + #[test] + fn knows_fails_below_its_confidence_and_forget_removes() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Knows"); + let recant = || DecisionInvocation { + affordance: speech.recant, + bindings: vec![binding("fact", Target::Entity(speech.flood))], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + speech: None, + display: None, + }; + assert_eq!( + rejected(utter(&mut kernel, &active, speech.listener, recant())), + vec![ActionMismatch::FactUnknown { precondition: 0 }] + ); + + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::AcquireKnowledge { + subject: Ref::Existing(speech.listener), + fact: Ref::Existing(speech.flood), + source: AuthoredSource::Witnessed, + confidence: Confidence::Believed, + }]), + ); + let active = kernel.snapshot().unwrap(); + assert_eq!( + rejected(utter(&mut kernel, &active, speech.listener, recant())), + vec![ActionMismatch::FactUnknown { precondition: 0 }], + "Believed falls short of Certain" + ); + + submit_owner( + &mut kernel, + &active, + operations(vec![acquire( + speech.listener, + speech.flood, + AuthoredSource::Witnessed, + )]), + ); + let active = kernel.snapshot().unwrap(); + utter(&mut kernel, &active, speech.listener, recant()) + .expect("certainty admits the recant"); + // Absence is the one shape of knowing nothing: no empty inner map. + assert!(!kernel.state.knowledge.contains_key(&speech.listener)); + + let active = kernel.snapshot().unwrap(); + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Forget { + subject: Ref::Existing(speech.listener), + fact: Ref::Existing(speech.flood), + }]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + } + + /// A telling never overwrites and never downgrades: the knower owns its own + /// credence. + #[test] + fn a_telling_never_overwrites_a_holder() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "NoOverwrite"); + submit_owner( + &mut kernel, + &active, + operations(vec![acquire( + speech.listener, + speech.flood, + AuthoredSource::Witnessed, + )]), + ); + let before = knows(&kernel, speech.listener, speech.flood); + let active = kernel.snapshot().unwrap(); + + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Communicate { + speaker: Ref::Existing(speech.speaker), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Channel(Ref::Existing(speech.horn)), + }]), + ); + assert_eq!(knows(&kernel, speech.listener, speech.flood), before); + assert_eq!( + knows(&kernel, speech.bystander, speech.flood), + Some(Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Told { + by: speech.speaker, + via: Some(speech.horn), + }, + acquired_at: active.revision + 1, + }) + ); + } + + /// Ontology admission: communication reaches only subjects inside the + /// channel's reach, and a speaker outside it is not speaking. + #[test] + fn communicating_from_outside_the_audience_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "OutsideAudience"); + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Communicate { + speaker: Ref::Existing(speech.stranger), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Colocated, + }]), + ), + vec![Mismatch::SpeakerOutsideAudience { operation: 0 }] + ); + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Communicate { + speaker: Ref::Existing(speech.stranger), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Channel(Ref::Existing(speech.horn)), + }]), + ), + vec![Mismatch::SpeakerOutsideAudience { operation: 0 }] + ); + assert!(kernel.state.knowledge.is_empty()); + } + + /// The two allocation sites, asserted: only `derive_id` allocates, and the + /// action lane's one referent per invocation is reproduced by calling it + /// directly with the recorded world, command, handle, and discriminator. + #[test] + fn every_canonical_id_comes_from_one_of_two_sites() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Allocation"); + let world_id = kernel.state.world_id; + let command_id = CommandId::new(); + let opportunity = opportunity_for(&active, speech.speaker); + let caller = CallerId::Controller(opportunity.controller_id); + let entities_before = kernel.state.entities.len(); + kernel + .submit( + command( + &active, + command_id, + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation: say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + "Counted.", + ), + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .expect("the whisper commits"); + + let claim = minted_claim(&kernel); + assert_eq!( + claim, + EntityId(patch::derive_id( + patch::ENTITY_NAMESPACE, + world_id, + command_id, + &DraftHandle::new("ghostlight.speech"), + Some("0"), + )) + ); + // Exactly one referent, always a fact, always claimed by the actor. + assert_eq!(kernel.state.entities.len(), entities_before + 1); + assert_eq!(kernel.state.entities[&claim].kind, EntityKind::Fact); + assert_eq!( + kernel.state.facts[&claim].standing, + FactStanding::Claimed { by: speech.speaker } + ); + } + + /// Replay is exact because every allocation derives from committed inputs + /// and every fan-out is re-derived at apply from the audience plus live + /// state. + #[test] + fn restart_replay_after_speech_is_exact() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (speech, world_id, expected) = { + let mut kernel = WorldKernel::create( + &path, + creation(CommandId::new(), "ReplaySpeech"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (speech, active) = speech_world(&mut kernel); + utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "One.", + ), + ) + .expect("the first proclamation commits"); + let active = kernel.snapshot().unwrap(); + utter( + &mut kernel, + &active, + speech.listener, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.speaker))], + "Two.", + ), + ) + .expect("the whisper commits"); + let active = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Communicate { + speaker: Ref::Existing(speech.speaker), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Channel(Ref::Existing(speech.horn)), + }]), + ); + let world_id = kernel.state.world_id; + (speech, world_id, kernel.state.clone()) + }; + + let reopened = WorldKernel::open(&path, world_id).expect("the store replays"); + assert_eq!(reopened.state.facts, expected.facts); + assert_eq!(reopened.state.channels, expected.channels); + assert_eq!(reopened.state.knowledge, expected.knowledge); + assert_eq!(reopened.state.events, expected.events); + assert_eq!(reopened.state, expected); + assert!(!reopened.state.knowledge[&speech.bystander].is_empty()); + } + + /// A forged claim does not apply, and a forged recipient list is + /// unrepresentable: `ResolvedOp::Communicate` stores an audience, never + /// recipients. + #[test] + fn a_forged_claim_or_forged_recipient_does_not_apply() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Forgery"); + let command_id = CommandId::new(); + let opportunity = opportunity_for(&active, speech.speaker); + let caller = CallerId::Controller(opportunity.controller_id); + let invocation = say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "Honest.", + ); + let granted = require_granted(&kernel.state, &opportunity, invocation.affordance).unwrap(); + let honest = action::exercise( + &kernel.state, + command_id, + &opportunity, + &granted, + &invocation, + ) + .expect("the honest event derives"); + let fact = honest.speech.expect("the honest claim"); + + let mut forged_claim = honest.clone(); + forged_claim.speech = Some(speech.flood); + let mut forged_statement = honest.clone(); + forged_statement.effects[0] = ResolvedOp::AssertClaim { + fact, + statement: Statement::new("Forged.").unwrap(), + by: speech.speaker, + }; + let mut forged_asserter = honest.clone(); + forged_asserter.effects[0] = ResolvedOp::AssertClaim { + fact, + statement: Statement::new("Honest.").unwrap(), + by: speech.listener, + }; + for forged in [forged_claim, forged_statement, forged_asserter] { + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::DecisionExercised { + opportunity: opportunity.clone(), + invocation: invocation.clone(), + event: forged, + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + assert_eq!(candidate, kernel.state); + } + + // A recipient list cannot be forged because none is stored. + assert!(matches!( + honest.effects[1], + ResolvedOp::Communicate { + to: Audience::Channel(_), + .. + } + )); + let mut candidate = kernel.state.clone(); + apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::DecisionExercised { + opportunity, + invocation, + event: honest, + }, + ) + .expect("the honest event applies"); + assert!(candidate.knowledge.contains_key(&speech.listener)); + } + + /// The scope table: a telling rebinds its listener and leaves a bystander + /// alone, and a reach change moves only the controller's digest. + #[test] + fn a_telling_moves_only_the_listeners_scope() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "ScopeMove"); + let digest = |kernel: &WorldKernel, subject: SubjectId| { + scope_digest( + &kernel.state, + DecisionScope { + subject_id: subject, + }, + ) + .unwrap() + }; + let listener_before = digest(&kernel, speech.listener); + let bystander_before = digest(&kernel, speech.bystander); + + utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + "Only you.", + ), + ) + .expect("the whisper commits"); + assert_ne!(digest(&kernel, speech.listener), listener_before); + assert_eq!(digest(&kernel, speech.bystander), bystander_before); + + // Reach membership is admission-only: adding a hearer moves the + // controller's digest and nobody else's. + let active = kernel.snapshot().unwrap(); + let hearer_before = digest(&kernel, speech.listener); + let speaker_before = digest(&kernel, speech.speaker); + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::SetReach { + channel: Ref::Existing(speech.horn), + reach: ReachRef::Subjects(BTreeSet::from([Ref::Existing(speech.stranger)])), + }]), + ); + assert_eq!(digest(&kernel, speech.listener), hearer_before); + assert_ne!(digest(&kernel, speech.speaker), speaker_before); + } + + /// A speech-carrying entry names exactly one audience: none is unlowerable + /// and two is unchoosable. Each rejection allocates no `AffordanceId`. + #[test] + fn a_speech_carrying_entry_must_declare_exactly_one_audience() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "SpeechAudience"), + &auth_principal(owner()), + ) + .expect("a draft world") + .0; + let before = kernel.snapshot().unwrap(); + let catalog_before = kernel.state.affordance_catalog.len(); + let declare = |preconditions: Vec<Precondition>| CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("herald"), + kind: AffordanceKindName("herald".into()), + roles: Vec::new(), + preconditions, + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }; + assert_eq!( + reject_owner(&mut kernel, &before, declare(Vec::new())), + vec![Mismatch::SpeechWithoutAudience { + handle: DraftHandle::new("herald"), + }] + ); + assert_eq!( + reject_owner( + &mut kernel, + &before, + declare(vec![ + Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }, + Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }, + ]), + ), + vec![Mismatch::AmbiguousSpeechAudience { + handle: DraftHandle::new("herald"), + }] + ); + assert_eq!(kernel.state.affordance_catalog.len(), catalog_before); + } + + /// The kernel does not compare two statements: no dedup, no interning, no + /// contradiction check, no similarity. A claim byte-identical to a + /// canonical fact and one that plainly negates it commit identically. + #[test] + fn the_kernel_never_compares_two_statements() { + let directory = tempfile::tempdir().unwrap(); + let run = |name: &str, text: &str| { + let room = directory.path().join(name); + std::fs::create_dir_all(&room).unwrap(); + let (mut kernel, speech, active) = speech_kernel(&room, name); + let receipt = utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + text, + ), + ) + .expect("both statements commit identically"); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + let event = kernel.state.events.last().unwrap().clone(); + (kernel, speech, event) + }; + let (agreeing, agreeing_speech, agreeing_event) = run("agree", FLOOD_STATEMENT); + let (negating, _, negating_event) = run("negate", "The lower hinge is dry."); + + assert_eq!(agreeing_event.band, negating_event.band); + assert_eq!(agreeing_event.effects.len(), negating_event.effects.len()); + assert_eq!(agreeing.state.facts.len(), negating.state.facts.len()); + // Two facts with byte-identical statements are two facts: the claim is + // not the canonical fact it repeats, and neither run learned anything + // about the other's meaning. + let claim = agreeing_event.speech.unwrap(); + assert_ne!(claim, agreeing_speech.flood); + assert_eq!( + agreeing.state.facts[&claim].statement, + agreeing.state.facts[&agreeing_speech.flood].statement + ); + assert_ne!( + agreeing.state.facts[&claim].standing, + agreeing.state.facts[&agreeing_speech.flood].standing + ); + } +} + +/// Soul's pass-6 falsification set. Each test names the claim it attacks and, +/// where the landed behaviour differs from the specified one, pins the actual +/// behaviour so the difference is visible rather than assumed. +#[cfg(test)] +mod soul_knowledge_tests { + use super::tests::{ + FLOOD_STATEMENT, Speech, affordance_named, auth_principal, command, creation, operations, + opportunity_for, owner, speech_world, submit_owner, + }; + use super::*; + use std::path::Path; + + fn speech_kernel(path: &Path, title: &str) -> (WorldKernel, Speech, WorldSnapshot) { + let mut kernel = WorldKernel::create( + path.join("world.cc"), + creation(CommandId::new(), title), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (speech, active) = speech_world(&mut kernel); + (kernel, speech, active) + } + + fn say(affordance: AffordanceId, bindings: Vec<RoleBinding>, text: &str) -> DecisionInvocation { + DecisionInvocation { + affordance, + bindings, + proposed: Vec::new(), + speech: Some(Statement::new(text).unwrap()), + display: None, + } + } + + fn binding(role: &str, target: Target) -> RoleBinding { + RoleBinding { + role: Role(role.into()), + target, + } + } + + fn utter( + kernel: &mut WorldKernel, + snapshot: &WorldSnapshot, + actor: SubjectId, + invocation: DecisionInvocation, + ) -> Result<SubmitReceipt, KernelError> { + let opportunity = opportunity_for(snapshot, actor); + let caller = CallerId::Controller(opportunity.controller_id); + kernel.submit( + command( + snapshot, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + } + + fn knows(kernel: &WorldKernel, subject: SubjectId, fact: EntityId) -> Option<Knowledge> { + kernel + .state + .knowledge + .get(&subject) + .and_then(|held| held.get(&fact)) + .copied() + } + + fn digest_of(kernel: &WorldKernel, subject_id: SubjectId) -> ScopeDigest { + scope_digest(&kernel.state, DecisionScope { subject_id }).unwrap() + } + + fn minted_claim(kernel: &WorldKernel) -> EntityId { + kernel + .state + .events + .last() + .expect("the committed event") + .speech + .expect("a speech act names its claim") + } + + /// A channel's controller carries exactly one privilege: `can_broadcast` + /// lets it sound the horn from outside the declared reach. `audience` + /// itself never folds the controller in, so the controller is not a + /// recipient of a telling it did not stand inside, whether the telling is + /// its own or another subject's. + #[test] + fn soul_a_channel_controller_hears_what_it_is_out_of_reach_of() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "ControllerHears"); + // The horn now reaches exactly one subject. The speaker controls it and + // is not in that set. + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::SetReach { + channel: Ref::Existing(speech.horn), + reach: ReachRef::Subjects(BTreeSet::from([Ref::Existing(speech.listener)])), + }]), + ); + let active = kernel.snapshot().unwrap(); + assert_eq!( + kernel.state.channels[&speech.horn].reach, + Reach::Subjects(BTreeSet::from([speech.listener])) + ); + + // The controller may still speak from outside its own reach — the horn + // belongs to the temple — and the listener, who stands inside the + // reach, hears it. + utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The horn is mine to sound.", + ), + ) + .expect("the controller may speak on its own channel"); + let controllers_claim = minted_claim(&kernel); + assert_eq!( + knows(&kernel, speech.listener, controllers_claim), + Some(Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Told { + by: speech.speaker, + via: Some(speech.horn), + }, + acquired_at: active.revision + 1, + }) + ); + // The controller gains no knowledge of its own claim: it is outside + // the reach, and speaking privilege is not audience membership. + assert_eq!(knows(&kernel, speech.speaker, controllers_claim), None); + + // Now the listener speaks on the same channel. + let active = kernel.snapshot().unwrap(); + utter( + &mut kernel, + &active, + speech.listener, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The horn is mine tonight.", + ), + ) + .expect("a subject inside the reach may broadcast"); + let claim = minted_claim(&kernel); + + // The declared reach names the listener alone, and the listener spoke, + // so the declared fan-out is empty. The controller — outside the + // reach, and not the speaker this time either — learns nothing. + assert_eq!( + knows(&kernel, speech.speaker, claim), + None, + "the controller does not gain knowledge through fan-out" + ); + assert_eq!(knows(&kernel, speech.bystander, claim), None); + assert_eq!(knows(&kernel, speech.stranger, claim), None); + assert_eq!(knows(&kernel, speech.listener, claim), None); + } + + /// Every speech precondition fails at `exercise`, before the band draw and + /// before the speech lowering, so a refused utterance mints no claim and + /// leaves the whole committed state byte-identical. Nothing here reaches + /// replay to be caught later. + #[test] + fn soul_a_refused_utterance_dies_at_the_gate_and_allocates_nothing() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "GateNotReplay"); + let speak = affordance_named(&active, "speak"); + let before = kernel.state.clone(); + + let cases: Vec<(SubjectId, DecisionInvocation, Vec<ActionMismatch>)> = vec![ + // Unplaced: no co-location audience at all. + ( + speech.stranger, + say(speak, Vec::new(), "Anyone?"), + vec![ActionMismatch::NoAudience { precondition: 0 }], + ), + // Addressed at a subject one containment level down. + ( + speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.bystander))], + "Down there.", + ), + vec![ActionMismatch::CannotReach { precondition: 0 }], + ), + // `recant` requires `Knows { at_least: Certain }` of the bound fact. + // Its unproposed slot names itself beside the precondition; the + // point is that the complete set lands at the gate, in one pass. + ( + speech.speaker, + DecisionInvocation { + affordance: speech.recant, + bindings: vec![binding("fact", Target::Entity(speech.flood))], + proposed: Vec::new(), + speech: None, + display: None, + }, + vec![ + ActionMismatch::SlotNotProposed { slot: 0 }, + ActionMismatch::FactUnknown { precondition: 0 }, + ], + ), + ]; + + for (actor, invocation, expected) in cases { + let error = utter(&mut kernel, &active, actor, invocation).unwrap_err(); + let KernelError::ActionRejected(mismatches) = error else { + panic!("expected an action rejection, got {error:?}"); + }; + assert_eq!(mismatches, expected); + // No claim, no entity row, no event, no revision: the gate ran + // before anything was drawn or lowered. + assert_eq!(kernel.state, before); + } + } + + /// Fan-out is the sole way knowledge enters another subject from speech, and + /// it is not carried by the effect. A forged `DecisionExercised` that widens + /// the audience, appends a second telling, or tells a foreign fact is refused + /// by `apply_effect` itself, so replay is never the first reader to notice. + #[test] + fn soul_a_forged_wider_audience_does_not_apply() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, speech, active) = speech_kernel(directory.path(), "WiderAudience"); + let command_id = CommandId::new(); + let opportunity = opportunity_for(&active, speech.speaker); + let caller = CallerId::Controller(opportunity.controller_id); + let invocation = say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + "Only the hall.", + ); + let granted = require_granted(&kernel.state, &opportunity, invocation.affordance).unwrap(); + let honest = action::exercise( + &kernel.state, + command_id, + &opportunity, + &granted, + &invocation, + ) + .expect("the honest event derives"); + let fact = honest.speech.expect("the honest claim"); + assert_eq!( + honest.effects[1], + ResolvedOp::Communicate { + speaker: speech.speaker, + fact, + to: Audience::Colocated, + } + ); + + // Widened to the horn, which covers the yard through `covers_place`. + let mut widened = honest.clone(); + widened.effects[1] = ResolvedOp::Communicate { + speaker: speech.speaker, + fact, + to: Audience::Channel(speech.horn), + }; + // A second telling appended to the same event. + let mut doubled = honest.clone(); + doubled.effects.push(ResolvedOp::Communicate { + speaker: speech.speaker, + fact: speech.flood, + to: Audience::Colocated, + }); + // A telling of a fact this act did not mint. + let mut foreign = honest.clone(); + foreign.effects[1] = ResolvedOp::Communicate { + speaker: speech.speaker, + fact: speech.flood, + to: Audience::Colocated, + }; + + for forged in [widened, doubled, foreign] { + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::DecisionExercised { + opportunity: opportunity.clone(), + invocation: invocation.clone(), + event: forged, + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + assert_eq!(candidate, kernel.state); + } + } + + /// A speech act that lands nothing moves no digest at all, the speaker's own + /// included. `AssertClaim` writes `entities` and `facts`, and neither is a + /// scope component, so an in-flight proposal held by anyone in the world + /// survives an utterance nobody heard. + #[test] + fn soul_speech_that_lands_nothing_moves_no_digest_including_the_speakers() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "NoDigestMove"); + let speak = affordance_named(&active, "speak"); + let everyone = [ + speech.speaker, + speech.listener, + speech.bystander, + speech.stranger, + ]; + let before: Vec<ScopeDigest> = everyone + .iter() + .map(|subject| digest_of(&kernel, *subject)) + .collect(); + let facts_before = kernel.state.facts.len(); + + // The bystander stands alone in the yard. + utter( + &mut kernel, + &active, + speech.bystander, + say(speak, Vec::new(), "Nobody is here."), + ) + .expect("speaking into an empty room commits"); + + assert_eq!(kernel.state.facts.len(), facts_before + 1); + assert_eq!(kernel.state.events.len(), 1); + assert!(kernel.state.knowledge.is_empty()); + for (subject, digest) in everyone.iter().zip(before) { + assert_eq!( + digest_of(&kernel, *subject), + digest, + "an utterance nobody heard moved a scope digest" + ); + } + } + + /// The resolver does not model a `Communicate`'s fan-out, so a same-patch + /// telling followed by a `Forget` of what that telling would have landed is + /// refused at resolve although apply would accept it. The asymmetry is + /// fail-closed, and it does not refuse the order that must work: forgetting + /// first and being told again in the same patch commits, and the telling is + /// what the subject ends up holding. + #[test] + fn soul_a_same_patch_telling_then_forget_fails_closed_only() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "SamePatchOrder"); + let tell = ComponentOp::Communicate { + speaker: Ref::Existing(speech.speaker), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Colocated, + }; + let forget = ComponentOp::Forget { + subject: Ref::Existing(speech.listener), + fact: Ref::Existing(speech.flood), + }; + + let error = kernel + .submit( + command( + &active, + CommandId::new(), + CallerId::Principal(owner()), + operations(vec![tell.clone(), forget.clone()]), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch, got {error:?}"); + }; + assert_eq!( + mismatches, + vec![Mismatch::NoOperationEffect { operation: 1 }] + ); + + // The legitimate order. The listener holds the fact first, forgets it, + // and the telling in the same patch lands it again as a telling, which + // is what the committed state carries. + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::AcquireKnowledge { + subject: Ref::Existing(speech.listener), + fact: Ref::Existing(speech.flood), + source: AuthoredSource::Witnessed, + confidence: Confidence::Certain, + }]), + ); + let active = kernel.snapshot().unwrap(); + submit_owner(&mut kernel, &active, operations(vec![forget, tell])); + assert_eq!( + knows(&kernel, speech.listener, speech.flood), + Some(Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Told { + by: speech.speaker, + via: None, + }, + acquired_at: active.revision + 1, + }) + ); + } + + /// `verify_state_shape` checks the forward speech direction only: an event's + /// claim is asserted by the acting subject and named by no other event. The + /// reverse, that every claim is named by some event, is deliberately absent, + /// because a world may declare a claim in Draft with no event behind it. + /// That gap is not a hole: active admission refuses every declaration, so + /// `AssertClaim` is the only way a claim enters an active world and it is + /// synthesized with its event. + #[test] + fn soul_an_orphan_claim_is_a_draft_shape_and_unreachable_in_active() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "OrphanClaim"); + // The Draft-declared fact is an orphan by construction: no event names + // it. Reopening runs the shape verifier over the replayed state. + assert!(kernel.state.facts.contains_key(&speech.flood)); + assert!( + kernel + .state + .events + .iter() + .all(|event| event.speech.is_none()) + ); + let world_id = kernel.state.world_id; + + let before = kernel.state.clone(); + let error = kernel + .submit( + command( + &active, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("rumour"), + label: "a rumour".into(), + statement: Statement::new("The gate is unguarded.").unwrap(), + standing: FactStandingRef::Claimed { + by: Ref::Existing(speech.speaker), + }, + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ), + &auth_principal(owner()), + ) + .unwrap_err(); + assert!( + matches!(error, KernelError::AnswerRequired), + "an active world admitted an unanswered declaration: {error:?}" + ); + assert_eq!(kernel.state, before); + drop(kernel); + let replayed = WorldKernel::open(&path, world_id).expect("the orphan store is healthy"); + assert_eq!(replayed.state.facts, before.facts); + } + + /// Replay equality across every new arm, twice, with no RNG and no clock in + /// any of them: a speech act, a telling, an authored acquisition, a forget, + /// a reach change, and a controller change all reproduce byte-identically + /// from the journal, and reopening again reproduces the same state. + #[test] + fn soul_replay_is_exact_across_every_new_arm() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (world_id, expected) = { + let (mut kernel, speech, active) = speech_kernel(directory.path(), "ReplayArms"); + utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The hinge is flooding.", + ), + ) + .expect("the proclamation commits"); + let active = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &active, + operations(vec![ + ComponentOp::AcquireKnowledge { + subject: Ref::Existing(speech.stranger), + fact: Ref::Existing(speech.flood), + source: AuthoredSource::Evidenced, + confidence: Confidence::Certain, + }, + ComponentOp::Communicate { + speaker: Ref::Existing(speech.speaker), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Colocated, + }, + ComponentOp::SetController { + channel: Ref::Existing(speech.horn), + controller: Some(Ref::Existing(speech.listener)), + }, + ComponentOp::SetReach { + channel: Ref::Existing(speech.horn), + reach: ReachRef::Place(Ref::Existing(speech.yard)), + }, + ]), + ); + let active = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Forget { + subject: Ref::Existing(speech.stranger), + fact: Ref::Existing(speech.flood), + }]), + ); + assert!(!kernel.state.knowledge.is_empty()); + assert!(!kernel.state.facts.is_empty()); + (kernel.state.world_id, kernel.state.clone()) + }; + + for _ in 0..2 { + let replayed = WorldKernel::open(&path, world_id).expect("the store replays"); + assert_eq!(replayed.state.facts, expected.facts); + assert_eq!(replayed.state.channels, expected.channels); + assert_eq!(replayed.state.knowledge, expected.knowledge); + assert_eq!(replayed.state.entities, expected.entities); + assert_eq!(replayed.state.events, expected.events); + assert_eq!(replayed.state, expected); + } + } + + /// The statement's bytes are stored twice, and only one of the two copies + /// is a read surface. `facts[fact].statement` is the readable home: + /// `spoken()` and every projection consult it. The committed event's own + /// `AssertClaim` effect carries the same bytes as the replay witness — + /// required so `apply_effect` can re-derive the identical event on replay + /// without re-deriving the statement from elsewhere — but nothing reads + /// that copy back out. Those two are the whole of it, and neither reaches + /// a subject-facing surface. + #[test] + fn soul_the_utterance_is_stored_in_facts_and_in_the_committed_effect() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "OneHome"); + let speak = affordance_named(&active, "speak"); + let text = "A statement that appears nowhere else."; + utter( + &mut kernel, + &active, + speech.speaker, + say(speak, Vec::new(), text), + ) + .expect("the kernel speak commits"); + let claim = minted_claim(&kernel); + + assert_eq!(kernel.state.facts[&claim].statement.as_str(), text); + assert_eq!( + kernel.state.entities[&claim].label, CLAIM_LABEL, + "the label is a name, not a transcript" + ); + // The event no longer embeds the invocation, and its `speech` field is + // the fact id. The bytes still appear in the event, inside the committed + // `AssertClaim` effect. + let event = kernel.state.events.last().unwrap(); + assert_eq!(event.speech, Some(claim)); + assert_eq!( + event.effects[0], + ResolvedOp::AssertClaim { + fact: claim, + statement: Statement::new(text).unwrap(), + by: speech.speaker, + }, + "the event carries the statement as a replay witness, not a second read surface" + ); + // Those two are the whole of it: strip `facts` and `events` and the + // rest of the state is silent. + let mut stripped = kernel.state.clone(); + stripped.facts.clear(); + stripped.events.clear(); + let encoded = rmp_serde::to_vec_named(&stripped).unwrap(); + assert!( + !encoded + .windows(text.len()) + .any(|window| window == text.as_bytes()) + ); + // The statement declared in Draft is untouched by any of it. + assert_eq!( + kernel.state.facts[&speech.flood].statement.as_str(), + FLOOD_STATEMENT + ); + } + + /// `operator_log` is unscoped by construction: it renders every committed + /// act's utterance regardless of who holds knowledge of it. That is correct + /// for the human operator's story feed and is exactly why it must never + /// become reachable from a controller lane. `ControllerRunner` no longer + /// owns a `WorldMailbox`; it owns a `ControllerPort`, which forwards + /// exactly the five requests a controller lane makes and has no + /// `operator_log` method at all. The separation is a type boundary now: + /// `WorldMailbox::operator_log` stays `pub(crate)` for the operator/story + /// feed owner, but nothing inside `controllers.rs` can name it. + #[test] + fn soul_the_operator_log_is_unscoped_and_must_stay_owner_only() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "OperatorLog"); + let text = "Nobody in this room but me."; + utter( + &mut kernel, + &active, + speech.bystander, + say(affordance_named(&active, "speak"), Vec::new(), text), + ) + .expect("speaking alone in the yard commits"); + + // Nobody holds it. + assert!(kernel.state.knowledge.is_empty()); + // The operator reads it anyway, with the speaker resolved by label. + let log = kernel.operator_log().unwrap(); + assert_eq!( + log, + vec![OperatorEvent { + revision: kernel.state.revision, + speaker: speech.bystander, + speaker_label: "The Yard Bystander".into(), + speech: Some(Statement::new(text).unwrap()), + display: None, + verb: "speak".into(), + render_path: None, + roles: Vec::new(), + }] + ); + // And no subject snapshot carries it. + for subject in kernel.snapshot().unwrap().subjects { + assert!(subject.knowledge.is_empty()); + } + } +} + +/// One witnessed event over a place subtree: who it reaches, who it leaves +/// alone, where it is refused, and what it costs an in-flight binding. +#[cfg(test)] +mod witness_tests { + use super::patch::Site; + use super::tests::{ + activate, auth_principal, command, creation, operations, opportunity_for, owner, + reject_owner, submit_owner, + }; + use super::*; + + /// Nesting, because "under a place" is the whole question. A hemisphere + /// holds a region and a far coast; the region holds a village and one + /// unwalked hollow; subjects stand in the village, on the coast, and in the + /// hemisphere under neither. The hollow is empty so an elaborator has a + /// boundary to answer and a witness has a place that reaches nobody. + struct Nesting { + hemisphere: EntityId, + region: EntityId, + village: EntityId, + coast: EntityId, + hollow: EntityId, + villager: SubjectId, + neighbour: SubjectId, + coaster: SubjectId, + drifter: SubjectId, + asteroid: EntityId, + moon: EntityId, + ferry: EdgeId, + } + + fn place(handle: &str, label: &str, container: Option<&str>) -> Declaration { + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: EntityKind::Place, + container: container.map(|value| Ref::Draft(DraftHandle::new(value))), + }) + } + + fn stander(handle: &str, label: &str, place: &str, speak: &Ref<AffordanceId>) -> Declaration { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([speak.clone(), Ref::Draft(DraftHandle::new("beacon"))]), + position: Some(Ref::Draft(DraftHandle::new(place))), + import_key: None, + }) + } + + fn sky_fact(handle: &str, label: &str, statement: &str, evidence: &str) -> Declaration { + Declaration::Fact(FactDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + statement: Statement::new(statement).unwrap(), + standing: FactStandingRef::Canonical { + evidence: EvidenceRef::new(evidence), + }, + }) + } + + fn witness(fact: EntityId, place: EntityId, confidence: Confidence) -> ComponentOp { + ComponentOp::Witness { + fact: Ref::Existing(fact), + place: Ref::Existing(place), + confidence, + } + } + + fn nesting_kernel(path: &Path, title: &str) -> (WorldKernel, Nesting, WorldSnapshot) { + let mut kernel = WorldKernel::create( + path.join("world.cc"), + creation(CommandId::new(), title), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let before = kernel.snapshot().unwrap(); + let speak = super::tests::speak_entry(&kernel); + submit_owner( + &mut kernel, + &before, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![ + place("hemisphere", "The Lit Hemisphere", None), + place("region", "The Rhythm Region", Some("hemisphere")), + place("village", "The Anchor Village", Some("region")), + place("hollow", "The Unwalked Hollow", Some("region")), + place("coast", "The Far Coast", Some("hemisphere")), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("ferry"), + label: "The Coast Ferry".into(), + from: Ref::Draft(DraftHandle::new("coast")), + to: Ref::Draft(DraftHandle::new("village")), + access: AccessKind::Public, + cost: Cost(1), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("path"), + label: "The Hollow Path".into(), + from: Ref::Draft(DraftHandle::new("village")), + to: Ref::Draft(DraftHandle::new("hollow")), + access: AccessKind::Public, + cost: Cost(1), + }), + // A world-authored verb with no speaker in it: the + // proposer chooses which declared place the entry + // binds and nothing else. + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("beacon"), + kind: AffordanceKindName("beacon".into()), + roles: vec![ + RoleSpec { + role: Role("fact".into()), + kind: RefKind::Entity(EntityKind::Fact), + }, + RoleSpec { + role: Role("place".into()), + kind: RefKind::Entity(EntityKind::Place), + }, + ], + preconditions: Vec::new(), + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::Witness { + confidence: Confidence::Believed, + }, + roles: vec![Role("fact".into()), Role("place".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }), + stander("villager", "The Anchor Villager", "village", &speak), + stander("neighbour", "The Anchor Neighbour", "village", &speak), + stander("coaster", "The Coast Watcher", "coast", &speak), + stander("drifter", "The Open Drifter", "hemisphere", &speak), + sky_fact( + "asteroid", + "the asteroid over the region", + "An asteroid crossed the sky above the region.", + "vault:asteroid", + ), + sky_fact( + "moon", + "the second moon", + "A second moon rose over the hemisphere.", + "vault:moon", + ), + ], + operations: Vec::new(), + evidence: vec![ + EvidenceRef::new("vault:asteroid"), + EvidenceRef::new("vault:moon"), + ], + }, + }, + ); + let entity = |label: &str| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared entity") + .0 + }; + let subject = |label: &str| { + *kernel + .state + .subjects + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared subject") + .0 + }; + let nesting = Nesting { + hemisphere: entity("The Lit Hemisphere"), + region: entity("The Rhythm Region"), + village: entity("The Anchor Village"), + coast: entity("The Far Coast"), + hollow: entity("The Unwalked Hollow"), + villager: subject("The Anchor Villager"), + neighbour: subject("The Anchor Neighbour"), + coaster: subject("The Coast Watcher"), + drifter: subject("The Open Drifter"), + asteroid: entity("the asteroid over the region"), + moon: entity("the second moon"), + ferry: *kernel + .state + .edges + .iter() + .find(|(_, record)| record.label() == "The Coast Ferry") + .expect("a declared route") + .0, + }; + let active = activate(&mut kernel); + (kernel, nesting, active) + } + + fn knows(kernel: &WorldKernel, subject: SubjectId, fact: EntityId) -> Option<Knowledge> { + kernel + .state + .knowledge + .get(&subject) + .and_then(|held| held.get(&fact)) + .copied() + } + + fn seen(confidence: Confidence, acquired_at: u64) -> Option<Knowledge> { + Some(Knowledge { + confidence, + source: KnowledgeSource::Witnessed, + acquired_at, + }) + } + + /// The subtree is the whole reach: everyone under the named place, nobody + /// beside it, and a wider place reaches the wider set. + #[test] + fn a_witness_reaches_every_subject_under_the_place_and_no_other() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, active) = nesting_kernel(directory.path(), "Reach"); + submit_owner( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.region, + Confidence::Believed, + )]), + ); + assert_eq!( + knows(&kernel, world.villager, world.asteroid), + seen(Confidence::Believed, active.revision + 1) + ); + assert_eq!( + knows(&kernel, world.neighbour, world.asteroid), + seen(Confidence::Believed, active.revision + 1) + ); + assert_eq!(knows(&kernel, world.coaster, world.asteroid), None); + assert_eq!(knows(&kernel, world.drifter, world.asteroid), None); + + let after = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &after, + operations(vec![witness( + world.moon, + world.hemisphere, + Confidence::Certain, + )]), + ); + for subject in [ + world.villager, + world.neighbour, + world.coaster, + world.drifter, + ] { + assert_eq!( + knows(&kernel, subject, world.moon), + seen(Confidence::Certain, after.revision + 1) + ); + } + + // No witness names a teller, so nothing in the world was told. + assert!( + kernel + .state + .knowledge + .values() + .flat_map(|held| held.values()) + .all(|entry| !matches!(entry.source, KnowledgeSource::Told { .. })), + "a witness wrote a told row" + ); + } + + /// The knower owns its credence. A holder is dropped from the landing + /// whatever it holds and however it came by it, so a witness cannot reset a + /// mind by repeating itself. + #[test] + fn a_witness_never_overwrites_a_holder() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, world, _) = nesting_kernel(directory.path(), "Holder"); + // `Told` has exactly one writer, so the holder's row is planted at the + // layer that can hold one and the witness is applied beside it. + let held = Knowledge { + confidence: Confidence::Doubted, + source: KnowledgeSource::Told { + by: world.coaster, + via: None, + }, + acquired_at: 0, + }; + let mut state = kernel.state.clone(); + let state_revision = state.revision; + state + .knowledge + .entry(world.villager) + .or_default() + .insert(world.asteroid, held); + apply_operation( + &mut state, + &ResolvedOp::Witness { + fact: world.asteroid, + place: world.region, + confidence: Confidence::Certain, + }, + &[], + state_revision + 1, + ) + .expect("the witness lands"); + assert_eq!(state.knowledge[&world.villager][&world.asteroid], held); + assert_eq!( + state.knowledge[&world.neighbour][&world.asteroid], + Knowledge { + confidence: Confidence::Certain, + source: KnowledgeSource::Witnessed, + acquired_at: state_revision + 1, + } + ); + } + + /// A witnessed event is only its reception, so a landing that reaches + /// nobody is not an event the world recorded. Both layers refuse it, and + /// they refuse the same two cases: an empty subtree, and a subtree whose + /// every stander already holds the fact. + #[test] + fn a_witness_over_nobody_is_refused_at_resolve_and_at_apply() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, active) = nesting_kernel(directory.path(), "Nobody"); + let forged = |place: EntityId, state: &WorldState| { + let resolves_to = state.revision + 1; + let mut state = state.clone(); + apply_operation( + &mut state, + &ResolvedOp::Witness { + fact: world.asteroid, + place, + confidence: Confidence::Certain, + }, + &[], + resolves_to, + ) + .unwrap_err() + }; + + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.hollow, + Confidence::Certain + )]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + assert!(matches!( + forged(world.hollow, &kernel.state), + KernelError::Invariant(message) + if message == "a witness reaches nobody who does not already hold the fact" + )); + + // Every stander already holds it, which is the same refusal. + submit_owner( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.village, + Confidence::Certain, + )]), + ); + let after = kernel.snapshot().unwrap(); + assert_eq!( + reject_owner( + &mut kernel, + &after, + operations(vec![witness( + world.asteroid, + world.village, + Confidence::Certain + )]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + assert!(matches!( + forged(world.village, &kernel.state), + KernelError::Invariant(message) + if message == "a witness reaches nobody who does not already hold the fact" + )); + + // A forged effect naming a place that is not one, or no live fact, is + // refused by the arm's own kind check before any of that. + let mut state = kernel.state.clone(); + let resolves_to = state.revision + 1; + assert!(matches!( + apply_operation( + &mut state, + &ResolvedOp::Witness { + fact: world.asteroid, + place: world.asteroid, + confidence: Confidence::Certain, + }, + &[], + resolves_to, + ) + .unwrap_err(), + KernelError::Invariant(message) if message == "a witness names no live fact or place" + )); + } + + /// The candidate map models the fan-out, so a subject this patch moved into + /// the subtree is a recipient and a subject it moved out is not. The resolve + /// layer and the apply layer agree on both. + #[test] + fn a_mid_patch_relocation_into_the_subtree_counts() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, active) = nesting_kernel(directory.path(), "Relocation"); + // The village's own standers already hold it, so the relocated coaster + // is the only candidate recipient left. + submit_owner( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.village, + Confidence::Believed, + )]), + ); + let seeded = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &seeded, + operations(vec![ + ComponentOp::Relocate { + subject: Ref::Existing(world.coaster), + via: Ref::Existing(world.ferry), + }, + witness(world.asteroid, world.village, Confidence::Certain), + ]), + ); + assert_eq!( + kernel.state.positions[&world.coaster], + Position { + place: world.village + } + ); + assert_eq!( + knows(&kernel, world.coaster, world.asteroid), + seen(Confidence::Certain, seeded.revision + 1) + ); + + // The inverse: the coast's only stander leaves before the witness, so + // the coast reaches nobody. Both layers say so. + let moved = kernel.snapshot().unwrap(); + assert_eq!( + reject_owner( + &mut kernel, + &moved, + operations(vec![witness(world.moon, world.coast, Confidence::Certain)]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + let mut state = kernel.state.clone(); + let resolves_to = state.revision + 1; + assert!(matches!( + apply_operations( + &mut state, + &[ResolvedOp::Witness { + fact: world.moon, + place: world.coast, + confidence: Confidence::Certain, + }], + &[], + resolves_to, + ) + .unwrap_err(), + KernelError::Invariant(message) + if message == "a witness reaches nobody who does not already hold the fact" + )); + } + + /// The place is the whole ground, and it is not a weaker confinement than + /// the recipients: everyone the fan-out selects stands under it. An + /// elaborator witnesses inside its root, and nowhere outside or above it. + #[test] + fn an_elaborator_may_witness_inside_its_root_and_not_outside_or_above() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, _) = nesting_kernel(directory.path(), "Jurisdiction"); + let answer = derive_boundaries(&kernel.state) + .unwrap() + .into_iter() + .find(|boundary| { + matches!(boundary, CausalBoundary::UnelaboratedDestination { place, .. } + if *place == world.hollow) + }) + .expect("the hollow is an unelaborated destination"); + let submit = |kernel: &mut WorldKernel, place: EntityId| { + let snapshot = kernel.snapshot().unwrap(); + let caller = CallerId::System(SystemCapability::Elaborator { + jurisdiction: JurisdictionKey::PlaceSubtree(world.region), + }); + kernel.submit( + command( + &snapshot, + CommandId::new(), + caller.clone(), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answer.clone())), + patch: WorldPatch { + // The boundary the elaborator answers: the hollow + // grows a room. The witness rides beside it, and + // only the witness is confined by its place. + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("shed"), + label: "The Hollow Shed".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(world.hollow)), + })], + operations: vec![witness(world.asteroid, place, Confidence::Believed)], + evidence: Vec::new(), + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + }; + let outside = |result: Result<SubmitReceipt, KernelError>| match result { + Err(KernelError::PatchRejected(set)) => set, + other => panic!("expected a confined refusal, got {other:?}"), + }; + + assert_eq!( + outside(submit(&mut kernel, world.coast)), + vec![Mismatch::OutsideJurisdiction { + site: Site::Operation(0) + }] + ); + assert_eq!( + outside(submit(&mut kernel, world.hemisphere)), + vec![Mismatch::OutsideJurisdiction { + site: Site::Operation(0) + }] + ); + let before_admit = kernel.state.revision; + let admitted = submit(&mut kernel, world.village); + assert!( + matches!(admitted, Ok(SubmitReceipt::Applied(_))), + "{admitted:?}" + ); + assert_eq!( + knows(&kernel, world.villager, world.asteroid), + seen(Confidence::Believed, before_admit + 1) + ); + } + + /// A consumer names no ground, and a jurisdiction over placeless subjects + /// names no place. Both refuse every witness through the same closure, with + /// no rule in `confine_to_ground` naming the operation. + #[test] + fn a_consumer_cannot_witness() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, world, _) = nesting_kernel(directory.path(), "Consumer"); + let resolved = patch::resolve_patch( + &kernel.state, + CommandId::new(), + &WorldPatch { + declarations: Vec::new(), + operations: vec![witness(world.asteroid, world.village, Confidence::Certain)], + evidence: Vec::new(), + }, + None, + None, + ) + .expect("the witness resolves over committed state"); + for ground in [ + PatchGround::Consumer(ConsumerId::of_name("witness.consumer")), + PatchGround::Jurisdiction(JurisdictionKey::Uncovered), + ] { + assert_eq!( + confine_to_ground(&kernel.state, &resolved, ground), + Err(vec![Mismatch::OutsideJurisdiction { + site: Site::Operation(0) + }]), + "{ground:?} admitted a witness" + ); + } + } + + /// The digest reads the keys of a subject's own knowledge, so a witness + /// moves exactly the digests of the subjects that learned something. + #[test] + fn a_witness_moves_every_recipients_scope_digest_and_nobody_elses() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, active) = nesting_kernel(directory.path(), "Digest"); + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::AcquireKnowledge { + subject: Ref::Existing(world.neighbour), + fact: Ref::Existing(world.asteroid), + source: AuthoredSource::Witnessed, + confidence: Confidence::Doubted, + }]), + ); + let digest = |kernel: &WorldKernel, subject_id: SubjectId| { + scope_digest(&kernel.state, DecisionScope { subject_id }).unwrap() + }; + let learner = digest(&kernel, world.villager); + let holder = digest(&kernel, world.neighbour); + let outsider = digest(&kernel, world.coaster); + + let seeded = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &seeded, + operations(vec![witness( + world.asteroid, + world.region, + Confidence::Certain, + )]), + ); + assert_ne!(digest(&kernel, world.villager), learner); + assert_eq!(digest(&kernel, world.neighbour), holder); + assert_eq!(digest(&kernel, world.coaster), outsider); + } + + /// A witness is the loudest producer of a moved scope: every subject that + /// learned something loses its in-flight binding, and every subject that + /// already knew keeps it. What the learner sees carries no speaker. + #[test] + fn a_witness_between_a_bound_opportunity_and_its_exercise_is_a_scope_change() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, active) = nesting_kernel(directory.path(), "Interruption"); + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::AcquireKnowledge { + subject: Ref::Existing(world.neighbour), + fact: Ref::Existing(world.asteroid), + source: AuthoredSource::Witnessed, + confidence: Confidence::Doubted, + }]), + ); + let bound = kernel.snapshot().unwrap(); + let learner = opportunity_for(&bound, world.villager); + let holder = opportunity_for(&bound, world.neighbour); + submit_owner( + &mut kernel, + &bound, + operations(vec![witness( + world.asteroid, + world.region, + Confidence::Certain, + )]), + ); + + let exercise = |kernel: &mut WorldKernel, opportunity: &DecisionOpportunity| { + let snapshot = kernel.snapshot().unwrap(); + let speak = *opportunity + .affordance_ids + .iter() + .find(|id| { + snapshot + .affordances + .iter() + .any(|entry| entry.id == **id && entry.entry.carries_speech) + }) + .expect("the scope holds a speech-carrying entry"); + let caller = CallerId::Controller(opportunity.controller_id); + kernel.submit( + command( + &snapshot, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + invocation: DecisionInvocation { + affordance: speak, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("The sky moved.").unwrap()), + display: None, + }, + opportunity: opportunity.clone(), + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + }; + let error = exercise(&mut kernel, &learner).unwrap_err(); + let KernelError::ScopeChanged { + scope, + expected, + actual, + } = error + else { + panic!("expected a changed scope, got {error:?}"); + }; + assert_eq!(scope, learner.scope); + assert_eq!(expected, learner.scope_digest); + assert_ne!(expected, actual); + + // The subject that already held the fact learned nothing, so its + // binding survives the same witness. + let kept = exercise(&mut kernel, &holder); + assert!(matches!(kept, Ok(SubmitReceipt::Applied(_))), "{kept:?}"); + + // What the learner now holds names no speaker: it knows the thing, not + // the telling. + let entry = knows(&kernel, world.villager, world.asteroid).expect("the learner holds it"); + assert_eq!(entry.source, KnowledgeSource::Witnessed); + let snapshot = kernel.snapshot().unwrap(); + let held = snapshot + .subjects + .iter() + .find(|subject| subject.id == world.villager) + .expect("the learner is snapshotted") + .knowledge + .iter() + .find(|row| row.fact == world.asteroid) + .expect("the learner's snapshot carries the fact"); + assert_eq!(held.source, KnowledgeSource::Witnessed); + assert!( + held.minted_at.is_none(), + "a witnessed row named a speech act" + ); + } + + /// The slot names a fact and a place, never a subject, so an exercised + /// witness lands the subtree with no teller anywhere in it. A slot whose + /// place position binds a subject is refused before it is ever declared. + #[test] + fn a_witness_affordance_lowers_with_no_speaker() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, active) = nesting_kernel(directory.path(), "Affordance"); + let opportunity = opportunity_for(&active, world.villager); + let beacon = *opportunity + .affordance_ids + .iter() + .find(|id| { + active + .affordances + .iter() + .any(|entry| entry.id == **id && entry.entry.kind.0 == "beacon") + }) + .expect("the villager holds the beacon entry"); + let caller = CallerId::Controller(opportunity.controller_id); + kernel + .submit( + command( + &active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + invocation: DecisionInvocation { + affordance: beacon, + bindings: vec![ + RoleBinding { + role: Role("fact".into()), + target: Target::Entity(world.asteroid), + }, + RoleBinding { + role: Role("place".into()), + target: Target::Entity(world.region), + }, + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + speech: None, + display: None, + }, + opportunity: opportunity.clone(), + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .expect("the beacon lands"); + assert_eq!( + kernel + .state + .events + .last() + .expect("a committed event") + .effects, + vec![ResolvedOp::Witness { + fact: world.asteroid, + place: world.region, + confidence: Confidence::Believed, + }] + ); + assert_eq!( + knows(&kernel, world.villager, world.asteroid), + seen(Confidence::Believed, active.revision + 1) + ); + assert_eq!( + knows(&kernel, world.neighbour, world.asteroid), + seen(Confidence::Believed, active.revision + 1) + ); + assert_eq!(knows(&kernel, world.coaster, world.asteroid), None); + + // The second role is a place, and a subject cannot serve it, so a slot + // that named one is refused at affordance declaration. + let rules = ComponentOpKind::Witness { + confidence: Confidence::Believed, + } + .arity(); + assert_eq!(rules.len(), 2); + assert!(patch::role_kind_fits( + &rules[0], + RefKind::Entity(EntityKind::Fact) + )); + assert!(patch::role_kind_fits( + &rules[1], + RefKind::Entity(EntityKind::Place) + )); + assert!(!patch::role_kind_fits(&rules[1], RefKind::Subject(None))); + } + + /// A journal carrying a witness replays to digest equality, and the rows it + /// wrote pass the shape check with no clause of their own. + #[test] + fn a_world_with_a_witness_replays() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, active) = nesting_kernel(directory.path(), "Replay"); + submit_owner( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.region, + Confidence::Certain, + )]), + ); + assert!(journal::verify_state_shape(&kernel.state).is_ok()); + let world_id = kernel.state.world_id; + let committed = kernel.state.clone(); + drop(kernel); + let reopened = + WorldKernel::open(directory.path().join("world.cc"), world_id).expect("it replays"); + assert_eq!(reopened.state, committed); + assert_eq!( + knows(&reopened, world.villager, world.asteroid), + seen(Confidence::Certain, active.revision + 1) + ); + } + + /// PA.f49: `acquired_at` stamps the revision the write's own commit + /// resolves to on every path, genesis included. Genesis resolves to + /// revision 0 itself — `state.revision` never advances past 0 for the + /// creating commit — so a fact a genesis patch both declares and grants + /// knowledge of lands at `acquired_at: 0`, not one revision ahead of the + /// state it was written into. + #[test] + fn a_genesis_seeded_knowledge_row_is_acquired_at_revision_zero() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let mut creation = creation(CommandId::new(), "PAf49Genesis"); + creation.patch.declarations.push(Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("founding"), + label: "The Founding Ruling".into(), + statement: Statement::new("Stated by the table.").unwrap(), + standing: FactStandingRef::Claimed { + by: Ref::Draft(DraftHandle::new("human")), + }, + })); + creation.patch.operations.push(ComponentOp::AcquireKnowledge { + subject: Ref::Draft(DraftHandle::new("human")), + fact: Ref::Draft(DraftHandle::new("founding")), + source: AuthoredSource::Witnessed, + confidence: Confidence::Certain, + }); + let (kernel, _) = WorldKernel::create(&path, creation, &auth_principal(owner())).unwrap(); + assert_eq!(kernel.state.revision, 0); + let human = *kernel + .state + .subjects + .iter() + .find(|(_, subject)| subject.label == "The Human") + .expect("genesis admits the declared human") + .0; + let fact = *kernel + .state + .facts + .iter() + .find(|(_, record)| record.statement.as_str() == "Stated by the table.") + .expect("genesis admits the declared fact") + .0; + assert_eq!( + kernel.state.knowledge[&human][&fact].acquired_at, + 0, + "a genesis-seeded row landed one revision ahead of the state it was written into" + ); + assert!(journal::verify_state_shape(&kernel.state).is_ok()); + } + + /// PA.f49: every commit after genesis still stamps the revision it + /// resolves to, one past the state it was applied against. + #[test] + fn a_later_commits_knowledge_row_is_acquired_at_that_commits_revision() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, active) = nesting_kernel(directory.path(), "PAf49Later"); + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::AcquireKnowledge { + subject: Ref::Existing(world.villager), + fact: Ref::Existing(world.asteroid), + source: AuthoredSource::Witnessed, + confidence: Confidence::Certain, + }]), + ); + assert_eq!(kernel.state.revision, active.revision + 1); + assert_eq!( + kernel.state.knowledge[&world.villager][&world.asteroid].acquired_at, + active.revision + 1 + ); + } + + /// PA.f49: the shape check refuses a knowledge row forged ahead of the + /// world's own revision — the check `verify_state_shape` gained alongside + /// the genesis fix, so a corrupt or forged `acquired_at` cannot pass + /// replay silently. + #[test] + fn a_shape_check_refuses_a_knowledge_row_forged_ahead_of_the_world_revision() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, active) = nesting_kernel(directory.path(), "PAf49Shape"); + submit_owner( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.region, + Confidence::Certain, + )]), + ); + assert!(journal::verify_state_shape(&kernel.state).is_ok()); + let mut forged = kernel.state.clone(); + let entry = forged + .knowledge + .get_mut(&world.villager) + .and_then(|held| held.get_mut(&world.asteroid)) + .expect("the witness landed on the villager"); + entry.acquired_at = forged.revision + 1; + assert!(journal::verify_state_shape(&forged).is_err()); + } + + /// The two callers of the shared owners answer the same question. A + /// `Reach::Place` channel's fan-out and a witness over the same place select + /// the same subjects over the same state, so "under a place" and "already a + /// knower" cannot drift between a declared broadcast area and a witnessed + /// event. A grep proves there is one body; this proves the two lanes reach + /// it. + #[test] + fn soul_a_place_reach_fan_out_and_a_witness_select_the_same_subjects() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, world, _) = nesting_kernel(directory.path(), "One owner"); + let mut state = kernel.state.clone(); + // One holder, so the already-holds half of the selection is exercised + // and not merely the subtree half. + state.knowledge.entry(world.neighbour).or_default().insert( + world.asteroid, + Knowledge { + confidence: Confidence::Doubted, + source: KnowledgeSource::Witnessed, + acquired_at: 0, + }, + ); + for root in [world.hemisphere, world.region, world.village, world.coast] { + let horn = state + .entities + .keys() + .copied() + .find(|id| !state.channels.contains_key(id)) + .expect("an unused key for the horn"); + state.channels.insert( + horn, + patch::ChannelRecord { + reach: patch::Reach::Place(root), + controller: None, + }, + ); + for speaker in [world.coaster, world.drifter, world.villager] { + // `fan_out` is exactly the shared pair with the speaker taken + // out; the speaker clause is the only thing it owns itself. + let mut expected = under_place(&state, root); + expected.remove(&speaker); + assert_eq!( + fan_out( + &state, + speaker, + world.asteroid, + &patch::Audience::Channel(horn), + ), + unheld(&state, world.asteroid, expected), + "the two lanes disagreed about {root:?} for {speaker:?}" + ); + } + state.channels.remove(&horn); + } + } + + /// Presence in the subtree is read from `positions` alone. A place covers + /// itself, covers its children transitively, and covers nothing beside it; + /// a subject standing nowhere is under nothing, at every root including the + /// world's widest. + #[test] + fn soul_under_place_covers_itself_and_below_and_never_the_placeless() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, world, _) = nesting_kernel(directory.path(), "Nesting"); + let under = |root: EntityId| under_place(&kernel.state, root); + // The village holds its two standers and nobody else. + assert_eq!( + under(world.village), + BTreeSet::from([world.villager, world.neighbour]) + ); + // The region covers the village transitively and the drifter standing + // one level above it is not swept in. + assert_eq!( + under(world.region), + BTreeSet::from([world.villager, world.neighbour]) + ); + // The hemisphere covers everything below it and the drifter standing + // exactly at it, not merely below. + assert_eq!( + under(world.hemisphere), + BTreeSet::from([ + world.villager, + world.neighbour, + world.coaster, + world.drifter, + ]) + ); + assert_eq!(under(world.coast), BTreeSet::from([world.coaster])); + assert!(under(world.hollow).is_empty()); + + // A subject with no position is under nothing, at every root including + // the world's widest, and the widest witness in the world does not + // reach it. Presence is read from `positions` alone: there is no second + // notion of being somewhere for a placeless subject to fall back on. + let mut adrift = kernel.state.clone(); + let adrift_revision = adrift.revision; + adrift.positions.remove(&world.drifter); + for root in [ + world.hemisphere, + world.region, + world.village, + world.coast, + world.hollow, + ] { + assert!( + !under_place(&adrift, root).contains(&world.drifter), + "a placeless subject was under {root:?}" + ); + } + apply_operation( + &mut adrift, + &ResolvedOp::Witness { + fact: world.moon, + place: world.hemisphere, + confidence: Confidence::Certain, + }, + &[], + adrift_revision + 1, + ) + .expect("the hemisphere still reaches the standers"); + assert!( + !adrift + .knowledge + .get(&world.drifter) + .is_some_and(|held| held.contains_key(&world.moon)), + "a placeless subject witnessed the widest event in the world" + ); + for subject in [world.villager, world.neighbour, world.coaster] { + assert_eq!( + adrift.knowledge[&subject][&world.moon], + Knowledge { + confidence: Confidence::Certain, + source: KnowledgeSource::Witnessed, + acquired_at: adrift_revision + 1, + } + ); + } + } + + /// The candidate model and the apply arm are handed a patch built so they + /// could disagree: the only subject the witness can reach is one this same + /// patch declares and places, and every subject already standing there + /// already holds the fact. If the resolver did not see the draft stander it + /// would refuse a landing the apply pass performs; if the apply pass did + /// not see it, it would refuse a landing the resolver admitted. Both see + /// it. The inverse — a draft subject declared with no position — is refused + /// by both. + #[test] + fn soul_a_subject_declared_and_placed_in_one_patch_is_a_recipient_at_both_layers() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, active) = nesting_kernel(directory.path(), "Draft stander"); + submit_owner( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.village, + Confidence::Believed, + )]), + ); + // An active world admits declarations only through the elaborator lane, + // which is also the lane whose confinement the witness must satisfy. + let answer = derive_boundaries(&kernel.state) + .unwrap() + .into_iter() + .find(|boundary| { + matches!(boundary, CausalBoundary::UnelaboratedDestination { place, .. } + if *place == world.hollow) + }) + .expect("the hollow is an unelaborated destination"); + let beacon = *kernel + .state + .affordance_catalog + .iter() + .find(|(_, entry)| entry.kind.0 == "beacon") + .expect("the beacon entry is declared") + .0; + let arrival = + |kernel: &mut WorldKernel, handle: &str, label: &str, position: Option<EntityId>| { + let snapshot = kernel.snapshot().unwrap(); + let caller = CallerId::System(SystemCapability::Elaborator { + jurisdiction: JurisdictionKey::PlaceSubtree(world.region), + }); + kernel.submit( + command( + &snapshot, + CommandId::new(), + caller.clone(), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answer.clone())), + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("shed"), + label: format!("The Hollow Shed for {handle}"), + kind: EntityKind::Place, + container: Some(Ref::Existing(world.hollow)), + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + // Every non-mirror subject must hold one. + affordances: BTreeSet::from([Ref::Existing(beacon)]), + position: position.map(Ref::Existing), + import_key: None, + }), + ], + operations: vec![witness( + world.asteroid, + world.village, + Confidence::Certain, + )], + evidence: Vec::new(), + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + }; + + // Declared with no position: under nothing, so the witness still + // reaches nobody and the resolver says so. + match arrival(&mut kernel, "ghost", "The Unplaced Arrival", None) { + Err(KernelError::PatchRejected(set)) => assert_eq!( + set, + vec![Mismatch::NoOperationEffect { operation: 0 }], + "a placeless draft subject was counted as a recipient" + ), + other => panic!("expected a refusal, got {other:?}"), + } + + // Declared and placed under the witnessed place: the resolver's + // candidate map carries the draft position, and the apply pass derives + // the same subject from live state. + let before_arrival = kernel.state.revision; + let receipt = arrival( + &mut kernel, + "arrival", + "The Village Arrival", + Some(world.village), + ); + assert!( + matches!(receipt, Ok(SubmitReceipt::Applied(_))), + "{receipt:?}" + ); + let arrived = *kernel + .state + .subjects + .iter() + .find(|(_, record)| record.label == "The Village Arrival") + .expect("the arrival is declared") + .0; + assert_eq!( + knows(&kernel, arrived, world.asteroid), + seen(Confidence::Certain, before_arrival + 1) + ); + // The standers who already held it kept their own rows, from the + // earlier witness, and this landing did not touch them. + assert_eq!( + knows(&kernel, world.villager, world.asteroid), + seen(Confidence::Believed, active.revision + 1) + ); + assert_eq!( + knows(&kernel, world.neighbour, world.asteroid), + seen(Confidence::Believed, active.revision + 1) + ); + } + + /// The other way the two layers could disagree about who already holds the + /// fact: an earlier operation in the same patch takes it away. The + /// resolver's candidate map drops the row and the apply pass drops the + /// stored one, so a forget-then-witness lands rather than being refused as + /// reaching nobody. + #[test] + fn soul_a_forget_before_a_witness_agrees_at_both_layers() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, active) = nesting_kernel(directory.path(), "Forget first"); + submit_owner( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.village, + Confidence::Believed, + )]), + ); + // Everyone under the village holds it, so the witness alone is refused. + let seeded = kernel.snapshot().unwrap(); + assert_eq!( + reject_owner( + &mut kernel, + &seeded, + operations(vec![witness( + world.asteroid, + world.village, + Confidence::Certain + )]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + + let seeded = kernel.snapshot().unwrap(); + let receipt = submit_owner( + &mut kernel, + &seeded, + operations(vec![ + ComponentOp::Forget { + subject: Ref::Existing(world.villager), + fact: Ref::Existing(world.asteroid), + }, + witness(world.asteroid, world.village, Confidence::Certain), + ]), + ); + assert!(matches!(receipt, SubmitReceipt::Applied(_)), "{receipt:?}"); + assert_eq!( + knows(&kernel, world.villager, world.asteroid), + seen(Confidence::Certain, seeded.revision + 1), + "the forgotten subject was not re-reached" + ); + assert_eq!( + knows(&kernel, world.neighbour, world.asteroid), + seen(Confidence::Believed, active.revision + 1), + "a holder the patch did not touch was overwritten" + ); + } + + /// The brief is the world's authored premise: trimmed at ingress, carried + /// on the state and its snapshot, and identical after replay. + #[test] + fn the_world_brief_is_authored_once_trimmed_and_replayed() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let mut creation = creation(CommandId::new(), "Low Sere"); + creation.brief = " A dry basin town that owes its water to the gate above it. ".into(); + let (kernel, _) = WorldKernel::create(&path, creation, &auth_principal(owner())).unwrap(); + let created = kernel.snapshot().unwrap(); + assert_eq!( + created.brief, + "A dry basin town that owes its water to the gate above it." + ); + drop(kernel); + let reopened = WorldKernel::open(&path, created.world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), created); + } + + /// Persona material is set whole, refused when any text is non-canonical + /// or a read names a subject twice, refused when identical to what the + /// subject holds, and outside the scope digest: setting it moves no + /// opportunity's binding. + #[test] + fn soul_persona_material_is_set_whole_and_outside_the_scope_digest() { + use crate::patch::PersonaReadRef; + + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, active) = nesting_kernel(directory.path(), "Material"); + let text = |value: &str| Statement::new(value).unwrap(); + let material = |voice: Statement, reads: Vec<PersonaReadRef>| ComponentOp::SetPersonaMaterial { + subject: Ref::Existing(world.villager), + values: vec![text("Water is owed upward.")], + voice, + memories: vec![text("The gate froze the winter the ferry sank.")], + reads, + }; + let read = |subject: SubjectId| PersonaReadRef { + subject: Ref::Existing(subject), + statement: text("Counts every jar twice."), + }; + let digest_of = |snapshot: &WorldSnapshot| { + snapshot + .opportunities + .iter() + .find(|opportunity| opportunity.scope.subject_id == world.villager) + .map(|opportunity| opportunity.scope_digest.clone()) + }; + let before = digest_of(&active); + + // Padded text is refused at resolve, as is a subject read twice. + let padded: Statement = serde_json::from_value(serde_json::json!(" padded ")).unwrap(); + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![material(padded, vec![read(world.neighbour)])]), + ), + vec![Mismatch::NoncanonicalText { operation: 0 }] + ); + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![material( + text("Dry and exact."), + vec![read(world.neighbour), read(world.neighbour)], + )]), + ), + vec![Mismatch::NoncanonicalText { operation: 0 }] + ); + // A read of a subject the world does not hold is refused. + assert!( + !reject_owner( + &mut kernel, + &active, + operations(vec![material( + text("Dry and exact."), + vec![read(SubjectId::issue())], + )]), + ) + .is_empty() + ); + + let receipt = submit_owner( + &mut kernel, + &active, + operations(vec![material(text("Dry and exact."), vec![read(world.neighbour)])]), + ); + assert!(matches!(receipt, SubmitReceipt::Applied(_)), "{receipt:?}"); + let held = kernel.snapshot().unwrap(); + let villager = held + .subjects + .iter() + .find(|subject| subject.id == world.villager) + .unwrap(); + let carried = villager.material.as_ref().expect("material was set"); + assert_eq!(carried.voice.as_str(), "Dry and exact."); + assert_eq!( + carried.reads.get(&world.neighbour).map(Statement::as_str), + Some("Counts every jar twice.") + ); + assert_eq!(digest_of(&held), before, "material moved a scope digest"); + + // Identical material changes nothing; different material replaces all. + assert_eq!( + reject_owner( + &mut kernel, + &held, + operations(vec![material(text("Dry and exact."), vec![read(world.neighbour)])]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + let held = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &held, + operations(vec![material(text("Slow and courteous."), Vec::new())]), + ); + let replaced = kernel.snapshot().unwrap(); + let carried = replaced + .subjects + .iter() + .find(|subject| subject.id == world.villager) + .unwrap() + .material + .clone() + .unwrap(); + assert_eq!(carried.voice.as_str(), "Slow and courteous."); + assert!(carried.reads.is_empty(), "a whole-value set kept an old read"); + } + + /// What a witness hands the narrative lane's interruption renderer. The + /// renderer takes a subject's own `ScopeComponents` and its own knowledge + /// rows and nothing else, so both of its inputs are pinned here rather than + /// in the lane that owns the prose: exactly one component moved, `knows`, + /// which is the anonymous line and names no author; and the row the witness + /// wrote carries no `minted_at`, which is the sole gate on an `Overheard` + /// row, so no attributable line can be built from it. + #[test] + fn soul_a_witness_moves_only_knows_and_writes_no_spoken_row() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, active) = nesting_kernel(directory.path(), "Anonymous"); + let before = scope_components(&kernel.state, world.villager); + submit_owner( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.region, + Confidence::Certain, + )]), + ); + let after = scope_components(&kernel.state, world.villager); + assert_ne!(before.knows, after.knows); + assert_eq!( + after, + ScopeComponents { + knows: after.knows.clone(), + ..before + }, + "a witness moved a component other than what this person knows" + ); + + let snapshot = kernel.snapshot().unwrap(); + let held = snapshot + .subjects + .iter() + .find(|subject| subject.id == world.villager) + .expect("the learner is snapshotted"); + assert!( + held.knowledge + .iter() + .filter(|row| row.fact == world.asteroid) + .all(|row| row.minted_at.is_none() && row.source == KnowledgeSource::Witnessed), + "a witnessed row carried a speech act" + ); + } +} + +/// The clock, commitments, pressure, ordered attention, boundaries, and scale. +#[cfg(test)] +mod clock_tests { + use super::patch::{PreconditionRef, PressureSourceRef, WorldScaleIntentRef}; + use super::tests::{ + activate, affordance_named, authority_kind, auth_principal, command, creation, office, + operations, opportunity_for, owner, human_principal, reject_owner, speech_world, + submit_owner, + }; + use super::*; + use std::path::Path; + + /// The canonical IDs of the clock fixture: a hall containing a yard, a + /// dead end reached by exactly one route, three subjects, a resource, and + /// one commitment of each kind. + pub(crate) struct Clockwork { + yard: EntityId, + dead_end: EntityId, + gate: EdgeId, + reeve: SubjectId, + farmer: SubjectId, + treasury: SubjectId, + routine: CommitmentKey, + obligation: CommitmentKey, + goal: CommitmentKey, + deliver: AffordanceId, + threaten: AffordanceId, + } + + const ROUTINE_DUE: u64 = 60; + const LATE_DUE: u64 = 100; + + fn minutes(value: u32) -> TickMinutes { + TickMinutes::new(value).expect("a valid span") + } + + fn clock_kernel(path: &Path, title: &str) -> (WorldKernel, Clockwork, WorldSnapshot) { + let mut kernel = WorldKernel::create( + path.join("world.cc"), + creation(CommandId::new(), title), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (clockwork, active) = clock_world(&mut kernel); + (kernel, clockwork, active) + } + + fn clock_world(kernel: &mut WorldKernel) -> (Clockwork, WorldSnapshot) { + let before = kernel.snapshot().unwrap(); + let speak = super::tests::speak_entry(kernel); + let person = |handle: &str, label: &str, kind: SubjectKind, place: &str| { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([ + speak.clone(), + Ref::Draft(DraftHandle::new("deliver")), + Ref::Draft(DraftHandle::new("threaten")), + ]), + position: Some(Ref::Draft(DraftHandle::new(place))), + import_key: None, + }) + }; + let subject = |handle: &str| Ref::Draft(DraftHandle::new(handle)); + submit_owner( + kernel, + &before, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + evidence: vec![EvidenceRef::new("vault:harvest")], + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("hall"), + label: "The Long Hall".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("yard"), + label: "The Cavity Yard".into(), + kind: EntityKind::Place, + container: Some(Ref::Draft(DraftHandle::new("hall"))), + }), + // Nothing inside it, nobody in it, and one route out: + // the world has not grown into it yet. + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("dead-end"), + label: "The Unwalked Road".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("grain"), + label: "Winter Grain".into(), + kind: EntityKind::Resource, + container: None, + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("stair"), + label: "The Yard Stair".into(), + from: Ref::Draft(DraftHandle::new("yard")), + to: Ref::Draft(DraftHandle::new("hall")), + access: AccessKind::Public, + cost: Cost(1), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("back"), + label: "The Hall Steps".into(), + from: Ref::Draft(DraftHandle::new("hall")), + to: Ref::Draft(DraftHandle::new("yard")), + access: AccessKind::Public, + cost: Cost(1), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("gate"), + label: "The Field Gate".into(), + from: Ref::Draft(DraftHandle::new("hall")), + to: Ref::Draft(DraftHandle::new("dead-end")), + access: AccessKind::Public, + cost: Cost(1), + }), + // An affordance whose legitimacy is a promise rather + // than a jurisdiction, and one that presses directly. + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("deliver"), + kind: AffordanceKindName("deliver".into()), + roles: vec![RoleSpec { + role: Role("creditor".into()), + kind: RefKind::Subject(None), + }], + preconditions: vec![Precondition::Committed { + to: Role("creditor".into()), + kind: CommitmentKind::Obligation, + }], + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::CreateCommitment { + kind: CommitmentKind::Obligation, + horizon: minutes(1440), + period: None, + }, + roles: vec![Role("actor".into()), Role("creditor".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }), + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("threaten"), + kind: AffordanceKindName("threaten".into()), + roles: vec![RoleSpec { + role: Role("target".into()), + kind: RefKind::Subject(None), + }], + preconditions: Vec::new(), + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::AdvancePressure { + by: PressureMagnitude(3), + }, + roles: vec![Role("target".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }), + person("reeve", "The Yard Reeve", SubjectKind::Person, "yard"), + person("farmer", "The Yard Farmer", SubjectKind::Person, "yard"), + person( + "treasury", + "The Hall Treasury", + SubjectKind::Institution, + "hall", + ), + ], + operations: vec![ + ComponentOp::Admit { + holder: subject("farmer"), + resource: Ref::Draft(DraftHandle::new("grain")), + qty: Quantity(4), + evidence: EvidenceRef::new("vault:harvest"), + }, + // 0: the routine, whose check is where its subject stands. + ComponentOp::CreateCommitment { + subject: subject("farmer"), + counterparty: None, + kind: CommitmentKind::Routine, + due: FictionalMinutes(ROUTINE_DUE), + period: Some(minutes(10)), + checks: vec![PreconditionRef::Present { + at: Ref::Draft(DraftHandle::new("yard")), + }], + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }, + ComponentOp::CreateCommitment { + subject: subject("farmer"), + counterparty: Some(subject("treasury")), + kind: CommitmentKind::Obligation, + due: FictionalMinutes(LATE_DUE), + period: None, + checks: Vec::new(), + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }, + ComponentOp::CreateCommitment { + subject: subject("reeve"), + counterparty: None, + kind: CommitmentKind::Goal, + due: FictionalMinutes(LATE_DUE), + period: None, + checks: Vec::new(), + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }, + ComponentOp::Bind { + subject: subject("reeve"), + target: DependencyRef::Route(Ref::Draft(DraftHandle::new("gate"))), + }, + ], + }, + }, + ); + let active = activate(kernel); + let place = |label: &str| { + active + .places + .iter() + .find(|place| place.label == label) + .expect("the declared place") + .id + }; + let who = |label: &str| { + active + .subjects + .iter() + .find(|subject| subject.label == label) + .expect("the declared subject") + .id + }; + let reeve = who("The Yard Reeve"); + let farmer = who("The Yard Farmer"); + let key_of = |subject: SubjectId, kind: CommitmentKind| { + *kernel + .state + .commitments + .get(&subject) + .expect("the subject holds commitments") + .iter() + .find(|(_, commitment)| commitment.kind == kind) + .expect("the declared commitment") + .0 + }; + let gate = active + .routes + .iter() + .find(|route| route.label == "The Field Gate") + .expect("the declared route") + .id; + ( + Clockwork { + yard: place("The Cavity Yard"), + dead_end: place("The Unwalked Road"), + gate, + reeve, + farmer, + treasury: who("The Hall Treasury"), + routine: key_of(farmer, CommitmentKind::Routine), + obligation: key_of(farmer, CommitmentKind::Obligation), + goal: key_of(reeve, CommitmentKind::Goal), + deliver: affordance_named(&active, "deliver"), + threaten: affordance_named(&active, "threaten"), + }, + active, + ) + } + + fn clock_caller() -> CallerId { + CallerId::System(SystemCapability::Clock) + } + + fn tick(kernel: &mut WorldKernel, span: u32) -> Result<SubmitReceipt, KernelError> { + let snapshot = kernel.snapshot().unwrap(); + kernel.submit( + command( + &snapshot, + CommandId::new(), + clock_caller(), + CommandBody::AdvanceTime { + minutes: minutes(span), + }, + ), + &AuthenticatedCaller::fixture(clock_caller()), + ) + } + + fn exercise( + kernel: &mut WorldKernel, + actor: SubjectId, + affordance: AffordanceId, + bindings: Vec<RoleBinding>, + ) -> Result<SubmitReceipt, KernelError> { + let snapshot = kernel.snapshot().unwrap(); + let opportunity = opportunity_for(&snapshot, actor); + let caller = CallerId::Controller(opportunity.controller_id); + kernel.submit( + command( + &snapshot, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation: DecisionInvocation { + affordance, + bindings, + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + speech: None, + display: None, + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + } + + fn binding(role: &str, target: Target) -> RoleBinding { + RoleBinding { + role: Role(role.into()), + target, + } + } + + fn pressure(kernel: &WorldKernel, target: SubjectId, source: PressureSource) -> u32 { + kernel + .state + .pressures + .get(&target) + .and_then(|held| held.get(&source)) + .map_or(0, |magnitude| magnitude.0) + } + + fn due(kernel: &WorldKernel, subject: SubjectId, key: CommitmentKey) -> FictionalMinutes { + kernel + .state + .commitments + .get(&subject) + .and_then(|held| held.get(&key)) + .expect("the live commitment") + .due + } + + /// Verification 12, both halves: a defaulted commitment advances pressure on + /// its subject, and that subject still derives exactly one opportunity. + #[test] + fn a_defaulted_commitment_advances_pressure_and_the_subject_derives_an_opportunity() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Default"); + let sourced = PressureSource::Commitment { + subject: clockwork.farmer, + key: clockwork.obligation, + }; + + tick(&mut kernel, 120).expect("the tick commits"); + assert_eq!(pressure(&kernel, clockwork.farmer, sourced), 1); + assert_eq!( + kernel.state.pressures[&clockwork.farmer].len(), + 1, + "only the past-due obligation pressed the farmer" + ); + let snapshot = kernel.snapshot().unwrap(); + assert_eq!( + snapshot + .opportunities + .iter() + .filter(|opportunity| opportunity.scope.subject_id == clockwork.farmer) + .count(), + 1 + ); + + tick(&mut kernel, 1).expect("the second tick commits"); + assert_eq!(pressure(&kernel, clockwork.farmer, sourced), 2); + } + + /// Verification 19: a due routine fulfils with no inference and no pressure, + /// and a blocked one neither rolls nor presses. + #[test] + fn a_due_routine_auto_fulfils_and_a_blocked_one_does_not() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "Routine"); + let holdings = kernel.state.holdings.clone(); + let positions = kernel.state.positions.clone(); + let edges = kernel.state.edges.clone(); + + tick(&mut kernel, ROUTINE_DUE as u32).expect("the tick commits"); + assert_eq!( + due(&kernel, clockwork.farmer, clockwork.routine), + FictionalMinutes(ROUTINE_DUE + 10) + ); + assert!( + kernel.state.pressures.is_empty(), + "a routine raises nothing" + ); + assert_eq!(kernel.state.holdings, holdings); + assert_eq!(kernel.state.positions, positions); + assert_eq!(kernel.state.edges, edges); + + // Out of the yard: the check fails, so the routine neither rolls nor + // presses, and it retries on the next tick. + let route = |label: &str| { + active + .routes + .iter() + .find(|route| route.label == label) + .expect("the declared route") + .id + }; + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::Relocate { + subject: Ref::Existing(clockwork.farmer), + via: Ref::Existing(route("The Yard Stair")), + }]), + ); + tick(&mut kernel, 10).expect("the tick commits"); + assert_eq!( + due(&kernel, clockwork.farmer, clockwork.routine), + FictionalMinutes(ROUTINE_DUE + 10) + ); + assert!( + kernel.state.pressures.is_empty(), + "a blocked routine neither rolls nor presses" + ); + + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::Relocate { + subject: Ref::Existing(clockwork.farmer), + via: Ref::Existing(route("The Hall Steps")), + }]), + ); + tick(&mut kernel, 1).expect("the tick commits"); + assert_eq!( + due(&kernel, clockwork.farmer, clockwork.routine), + FictionalMinutes(ROUTINE_DUE + 20) + ); + } + + /// A tick with nothing due is still a commit: the clock moved, which is a + /// canonical change. + #[test] + fn a_tick_with_nothing_due_moves_only_the_clock() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, _, _) = clock_kernel(directory.path(), "Quiet"); + let before = kernel.state.clone(); + + tick(&mut kernel, 1).expect("the tick commits"); + assert_eq!(kernel.state.now, FictionalMinutes(1)); + assert_eq!(kernel.state.revision, before.revision + 1); + assert!(kernel.state.pressures.is_empty()); + assert_eq!(kernel.state.commitments, before.commitments); + assert_eq!(kernel.state.holdings, before.holdings); + assert_eq!(kernel.state.positions, before.positions); + assert_eq!(kernel.state.events, before.events); + + tick(&mut kernel, 2).expect("the tick commits"); + assert_eq!(kernel.state.now, FictionalMinutes(3)); + } + + /// A closed route in one place becomes political pressure in another without + /// anyone deciding that it should. The tick never reduces; only an operation + /// does. + #[test] + fn an_unavailable_dependency_presses_its_depender() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Dependency"); + let sourced = PressureSource::Dependency(DependencyTarget::Route(clockwork.gate)); + + tick(&mut kernel, 1).expect("the tick commits"); + assert_eq!(pressure(&kernel, clockwork.reeve, sourced), 0); + + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(clockwork.gate), + }]), + ); + tick(&mut kernel, 1).expect("the tick commits"); + assert_eq!(pressure(&kernel, clockwork.reeve, sourced), 1); + + // Repair stops the pressing but never unwrites what accrued. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::OpenRoute { + route: Ref::Existing(clockwork.gate), + }]), + ); + tick(&mut kernel, 1).expect("the tick commits"); + assert_eq!(pressure(&kernel, clockwork.reeve, sourced), 1); + + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::ResolvePressure { + source: PressureSourceRef::Dependency(DependencyRef::Route(Ref::Existing( + clockwork.gate, + ))), + target: Ref::Existing(clockwork.reeve), + }]), + ); + assert!( + !kernel.state.pressures.contains_key(&clockwork.reeve), + "an emptied target removes its key rather than storing an empty map" + ); + } + + /// The clock moves through exactly one command body. + #[test] + fn time_advances_only_through_advance_time() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "OnlyTick"); + tick(&mut kernel, 5).expect("the tick commits"); + let now = kernel.state.now; + + exercise( + &mut kernel, + clockwork.reeve, + clockwork.threaten, + vec![binding("target", Target::Subject(clockwork.farmer))], + ) + .expect("the threat commits"); + assert_eq!(kernel.state.now, now); + + let snapshot = kernel.snapshot().unwrap(); + let opportunity = opportunity_for(&snapshot, clockwork.farmer); + let caller = CallerId::Controller(opportunity.controller_id); + kernel + .submit( + command( + &snapshot, + CommandId::new(), + caller.clone(), + CommandBody::DeclineDecision { opportunity }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .expect("the decline commits"); + assert_eq!(kernel.state.now, now); + + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(clockwork.gate), + }]), + ); + assert_eq!(kernel.state.now, now); + } + + /// The clock capability is admitted for one body and nothing else. + #[test] + fn the_clock_capability_can_do_nothing_else() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Capability"); + let before = kernel.state.clone(); + let snapshot = kernel.snapshot().unwrap(); + let opportunity = opportunity_for(&snapshot, clockwork.reeve); + + for body in [ + CommandBody::ApproveDraft, + CommandBody::ActivateWorld, + CommandBody::DeclineDecision { + opportunity: opportunity.clone(), + }, + CommandBody::ExerciseDecision { + opportunity, + invocation: DecisionInvocation { + affordance: clockwork.threaten, + bindings: vec![binding("target", Target::Subject(clockwork.farmer))], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + speech: None, + display: None, + }, + }, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(clockwork.gate), + }]), + ] { + let error = kernel + .submit( + command(&snapshot, CommandId::new(), clock_caller(), body), + &AuthenticatedCaller::fixture(clock_caller()), + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + } + assert_eq!(kernel.state, before); + tick(&mut kernel, 1).expect("the same caller may tick"); + } + + /// Who may tick, when, and how far. + #[test] + fn advance_time_negatives() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "Negatives"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + + // There is no time in Draft. + let draft = kernel.snapshot().unwrap(); + let error = kernel + .submit( + command( + &draft, + CommandId::new(), + clock_caller(), + CommandBody::AdvanceTime { + minutes: minutes(1), + }, + ), + &AuthenticatedCaller::fixture(clock_caller()), + ) + .unwrap_err(); + assert!(matches!( + error, + KernelError::WrongPhase { + expected: WorldPhase::Active, + actual: WorldPhase::Draft, + } + )); + + let active = activate(&mut kernel); + // A span is constructor-checked, so a malformed one never reaches a + // command at all. + assert!(TickMinutes::new(0).is_none()); + assert!(TickMinutes::new(super::patch::MAX_ROUTE_COST + 1).is_none()); + + for caller in [ + CallerId::Principal(human_principal()), + CallerId::Controller(active.opportunities[0].controller_id), + ] { + let error = kernel + .submit( + command( + &active, + CommandId::new(), + caller.clone(), + CommandBody::AdvanceTime { + minutes: minutes(1), + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + } + + // The owner may tick from an interface. + submit_owner( + &mut kernel, + &active, + CommandBody::AdvanceTime { + minutes: minutes(7), + }, + ); + assert_eq!(kernel.state.now, FictionalMinutes(7)); + + // And a span that would overflow the clock is refused rather than + // wrapping. + kernel.state.now = FictionalMinutes(u64::MAX); + let snapshot = kernel.snapshot().unwrap(); + let error = kernel + .submit( + command( + &snapshot, + CommandId::new(), + clock_caller(), + CommandBody::AdvanceTime { + minutes: minutes(1), + }, + ), + &AuthenticatedCaller::fixture(clock_caller()), + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Serialization(_)), "{error:?}"); + } + + /// The whole motion is re-derived at apply, so a forged fulfilment, target, + /// magnitude, or clock reading is one comparison. + #[test] + fn a_forged_motion_does_not_apply() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Forged"); + let to = FictionalMinutes(120); + let honest = clock::derive_motion(&kernel.state, to); + assert!(!honest.fulfilled.is_empty() || !honest.pressed.is_empty()); + + let forgeries = [ + // A forged clock reading. + WorldEffect::TimeAdvanced { + minutes: minutes(120), + to: FictionalMinutes(121), + motion: honest.clone(), + }, + // A fulfilment nothing derived. + WorldEffect::TimeAdvanced { + minutes: minutes(120), + to, + motion: Motion { + fulfilled: vec![clock::RoutineFulfilled { + subject: clockwork.farmer, + key: clockwork.routine, + next_due: FictionalMinutes(9_999), + }], + pressed: honest.pressed.clone(), + }, + }, + // A forged magnitude. + WorldEffect::TimeAdvanced { + minutes: minutes(120), + to, + motion: Motion { + fulfilled: honest.fulfilled.clone(), + pressed: honest + .pressed + .iter() + .map(|written| clock::PressureWritten { + magnitude: PressureMagnitude(written.magnitude.0 + 9), + ..written.clone() + }) + .collect(), + }, + }, + // A pressure row for an untouched subject. + WorldEffect::TimeAdvanced { + minutes: minutes(120), + to, + motion: Motion { + fulfilled: honest.fulfilled.clone(), + pressed: honest + .pressed + .iter() + .cloned() + .chain(std::iter::once(clock::PressureWritten { + target: clockwork.treasury, + source: PressureSource::Subject(clockwork.reeve), + magnitude: PressureMagnitude(5), + })) + .collect(), + }, + }, + ]; + for forged in forgeries { + let mut candidate = kernel.state.clone(); + let error = apply_effect(&mut candidate, CommandId::issue(), &clock_caller(), &forged) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + assert_eq!(candidate, kernel.state); + } + + // The honest one applies. + let mut candidate = kernel.state.clone(); + apply_effect( + &mut candidate, + CommandId::issue(), + &clock_caller(), + &WorldEffect::TimeAdvanced { + minutes: minutes(120), + to, + motion: honest, + }, + ) + .expect("the honest motion applies"); + assert_eq!(candidate.now, to); + } + + /// Replay across a tick is exact, and every envelope is idempotent. + #[test] + fn restart_replay_across_a_tick_is_exact() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Replay"); + let world_id = kernel.state.world_id; + + exercise( + &mut kernel, + clockwork.reeve, + clockwork.threaten, + vec![binding("target", Target::Subject(clockwork.farmer))], + ) + .expect("the threat commits"); + tick(&mut kernel, 60).expect("the routine tick commits"); + tick(&mut kernel, 60).expect("the obligation tick commits"); + let snapshot = kernel.snapshot().unwrap(); + let repeat = command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.obligation, + }]), + ); + kernel + .submit(repeat.clone(), &auth_principal(owner())) + .expect("the discharge commits"); + // Discharge removes every pressure row it sourced. + assert_eq!( + pressure( + &kernel, + clockwork.farmer, + PressureSource::Commitment { + subject: clockwork.farmer, + key: clockwork.obligation, + } + ), + 0 + ); + + let before = kernel.state.clone(); + let before_snapshot = kernel.snapshot().unwrap(); + drop(kernel); + let mut replayed = WorldKernel::open(&path, world_id).expect("the store replays"); + assert_eq!(replayed.state, before); + assert_eq!(replayed.snapshot().unwrap(), before_snapshot); + assert!(matches!( + replayed.submit(repeat, &auth_principal(owner())), + Ok(SubmitReceipt::AlreadyApplied(_)) + )); + } + + /// The order is total, deterministic, and never a filter. + #[test] + fn the_attention_order_is_total_and_deterministic() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, clockwork, active) = clock_kernel(directory.path(), "Order"); + let derived = derive_opportunities(&kernel.state).unwrap(); + + let with = |pressures: BTreeMap<SubjectId, u32>, + stamps: BTreeMap<SubjectId, u64>| + -> Vec<SubjectId> { + let mut state = kernel.state.clone(); + state.now = FictionalMinutes(1_000); + state.pressures = pressures + .into_iter() + .map(|(subject, magnitude)| { + ( + subject, + BTreeMap::from([( + PressureSource::Subject(subject), + PressureMagnitude(magnitude), + )]), + ) + }) + .collect(); + state.last_opportunity_at = stamps + .into_iter() + .map(|(subject, stamp)| (subject, FictionalMinutes(stamp))) + .collect(); + order_opportunities(&state, derived.clone()) + .into_iter() + .map(|opportunity| opportunity.scope.subject_id) + .collect() + }; + + // Pressure dominates. + let ordered = with( + BTreeMap::from([(clockwork.farmer, 5), (clockwork.reeve, 3)]), + BTreeMap::new(), + ); + assert_eq!(ordered[0], clockwork.farmer); + assert_eq!(ordered[1], clockwork.reeve); + + // Equal pressure orders by debt, and a subject never attended outranks + // every subject that has. + let stamped: BTreeMap<SubjectId, u64> = active + .subjects + .iter() + .map(|subject| (subject.id, 900)) + .collect(); + let mut earlier = stamped.clone(); + earlier.insert(clockwork.treasury, 100); + let ordered = with(BTreeMap::new(), earlier); + assert_eq!(ordered[0], clockwork.treasury); + + // Never a filter: the same length and the same set, whatever the terms. + for pressures in [ + BTreeMap::new(), + BTreeMap::from([(clockwork.reeve, 1)]), + BTreeMap::from([(clockwork.farmer, 9), (clockwork.treasury, 9)]), + ] { + let ordered = with(pressures, stamped.clone()); + assert_eq!(ordered.len(), derived.len()); + assert_eq!( + ordered.iter().copied().collect::<BTreeSet<_>>(), + derived + .iter() + .map(|opportunity| opportunity.scope.subject_id) + .collect::<BTreeSet<_>>() + ); + } + } + + /// The debt term rotates: with no pressure anywhere, every subject reaches + /// the head within one pass, and standing pressure holds the head until it + /// is resolved. + #[test] + fn every_subject_reaches_the_head_within_bounded_ticks() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, clockwork, _) = clock_kernel(directory.path(), "Rotation"); + let derived = derive_opportunities(&kernel.state).unwrap(); + let count = derived.len(); + + let mut state = kernel.state.clone(); + let mut seen = BTreeSet::new(); + for step in 0..count { + state.now = FictionalMinutes(u64::try_from(step).unwrap() + 1); + let head = order_opportunities(&state, derived.clone())[0] + .scope + .subject_id; + seen.insert(head); + state.last_opportunity_at.insert(head, state.now); + } + assert_eq!(seen.len(), count, "every subject reached the head"); + + // Standing pressure holds the head; the others still rotate among + // themselves once it is resolved. + state.pressures.insert( + clockwork.farmer, + BTreeMap::from([( + PressureSource::Subject(clockwork.reeve), + PressureMagnitude(4), + )]), + ); + for step in 0..count { + state.now = FictionalMinutes(1_000 + u64::try_from(step).unwrap()); + let head = order_opportunities(&state, derived.clone())[0] + .scope + .subject_id; + assert_eq!(head, clockwork.farmer); + state.last_opportunity_at.insert(head, state.now); + } + state.pressures.remove(&clockwork.farmer); + assert_ne!( + order_opportunities(&state, derived.clone())[0] + .scope + .subject_id, + clockwork.farmer + ); + } + + /// Verification 14, first half: a dead end is derived, answered once, and + /// then no longer derived. Nothing clears one but the predicate failing. + #[test] + fn an_unelaborated_destination_is_derived_and_answered_exactly_once() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "DeadEnd"); + let boundaries = derive_boundaries(&kernel.state).unwrap(); + let destinations: Vec<_> = boundaries + .iter() + .filter(|boundary| matches!(boundary, CausalBoundary::UnelaboratedDestination { .. })) + .collect(); + assert_eq!(destinations.len(), 1); + let answered = destinations[0].clone(); + assert!(matches!( + answered, + CausalBoundary::UnelaboratedDestination { route, place, .. } + if route == clockwork.gate && place == clockwork.dead_end + )); + + let snapshot = kernel.snapshot().unwrap(); + assert!(snapshot.boundaries.contains(&answered)); + submit_owner( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch: WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("shed"), + label: "The Roadside Shed".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(clockwork.dead_end)), + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + assert!( + !derive_boundaries(&kernel.state) + .unwrap() + .contains(&answered) + ); + + // Answering it again names a boundary the kernel no longer derives. + let snapshot = kernel.snapshot().unwrap(); + let error = kernel + .submit( + command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("byre"), + label: "The Roadside Byre".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(clockwork.dead_end)), + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ), + &auth_principal(owner()), + ) + .unwrap_err(); + assert!(matches!(error, KernelError::AnswerNotDerived), "{error:?}"); + } + + /// A promise the counterparty can neither command nor litigate is a missing + /// structure, and either repair clears it. A goal never derives one. + #[test] + fn a_commitment_with_no_authority_or_redress_derives_missing_structure() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Structure"); + let missing = CausalBoundary::MissingStructure { + subject: clockwork.farmer, + key: clockwork.obligation, + scope: BoundaryDigest(String::new()), + }; + let derives = |kernel: &WorldKernel| { + derive_boundaries(&kernel.state) + .unwrap() + .into_iter() + .any(|boundary| match (&boundary, &missing) { + ( + CausalBoundary::MissingStructure { subject, key, .. }, + CausalBoundary::MissingStructure { + subject: expected_subject, + key: expected_key, + .. + }, + ) => subject == expected_subject && key == expected_key, + _ => false, + }) + }; + assert!(derives(&kernel)); + // A goal is a promise to oneself and needs no forum. + assert!(!derive_boundaries(&kernel.state).unwrap().iter().any( + |boundary| matches!(boundary, CausalBoundary::MissingStructure { key, .. } if *key == clockwork.goal) + )); + + // Jurisdiction over the promisor's ground clears it. + let snapshot = kernel.snapshot().unwrap(); + let grant = ComponentOp::GrantAuthority { + holder: Ref::Existing(clockwork.treasury), + grant: AuthorityGrantRef { + kind: AuthorityKindName("command".into()), + over: AuthorityTargetRef::PlaceSubtree(Ref::Existing(clockwork.yard)), + }, + }; + submit_owner(&mut kernel, &snapshot, operations(vec![grant.clone()])); + assert!(!derives(&kernel)); + + // Revoke it, and a forum whose standing covers the counterparty clears + // it the other way. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::RevokeAuthority { + holder: Ref::Existing(clockwork.treasury), + grant: AuthorityGrantRef { + kind: AuthorityKindName("command".into()), + over: AuthorityTargetRef::PlaceSubtree(Ref::Existing(clockwork.yard)), + }, + }]), + ); + assert!(derives(&kernel)); + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::OpenForum { + grievance: GrievanceKindName("debt".into()), + forum: Ref::Existing(clockwork.reeve), + standing: AuthorityTargetRef::Subject(Ref::Existing(clockwork.treasury)), + }]), + ); + assert!(!derives(&kernel)); + } + + /// Verification 14, second half: an answer must be derived, and the commit + /// must satisfy what it answered. + #[test] + fn an_answer_must_be_derived_and_must_be_satisfied() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Answers"); + let before = kernel.state.clone(); + let declaring = |answers: Option<PatchAnswer>, handle: &str| CommandBody::AdmitPatch { + answers, + patch: WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: "A Later Room".into(), + kind: EntityKind::Place, + container: None, + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }; + let refuse = |kernel: &mut WorldKernel, body: CommandBody| { + let snapshot = kernel.snapshot().unwrap(); + kernel + .submit( + command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + body, + ), + &auth_principal(owner()), + ) + .unwrap_err() + }; + + // Declaring in Active without answering. + assert!(matches!( + refuse(&mut kernel, declaring(None, "unanswered")), + KernelError::AnswerRequired + )); + // The two declared-but-never-derived variants. + for boundary in [ + CausalBoundary::PolityInCausalRange { + subject: clockwork.reeve, + scope: BoundaryDigest(String::new()), + }, + CausalBoundary::IndividuationRequired { + population: clockwork.reeve, + scope: BoundaryDigest(String::new()), + }, + ] { + assert!(matches!( + refuse( + &mut kernel, + declaring(Some(PatchAnswer::Boundary(boundary)), "underived") + ), + KernelError::AnswerNotDerived + )); + } + // A jurisdiction with no deficit. + assert!(matches!( + refuse( + &mut kernel, + declaring( + Some(PatchAnswer::Deficit(JurisdictionKey::Uncovered)), + "no-deficit" + ) + ), + KernelError::AnswerNotDerived + )); + // A derived boundary answered by a patch that leaves the predicate + // holding. + let destination = derive_boundaries(&kernel.state) + .unwrap() + .into_iter() + .find(|boundary| matches!(boundary, CausalBoundary::UnelaboratedDestination { .. })) + .expect("the dead end"); + assert!(matches!( + refuse( + &mut kernel, + declaring(Some(PatchAnswer::Boundary(destination)), "elsewhere") + ), + KernelError::AnswerNotSatisfied + )); + assert_eq!(kernel.state, before); + + // Draft answers nothing. + let directory = tempfile::tempdir().unwrap(); + let mut draft_kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "Draft"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + assert!(matches!( + refuse( + &mut draft_kernel, + declaring( + Some(PatchAnswer::Deficit(JurisdictionKey::Uncovered)), + "in-draft" + ) + ), + KernelError::AnswerNotDerived + )); + } + + fn creation_with_intent( + id: CommandId, + title: &str, + intent: WorldScaleIntentRef, + ) -> CreateWorld { + let mut creation = creation(id, title); + creation.scale_intent = intent; + creation + } + + fn intent(root: &str, persons: u32, permille: u32) -> WorldScaleIntentRef { + WorldScaleIntentRef { + targets: BTreeMap::from([(SubjectKind::Person, persons)]), + jurisdictions: BTreeMap::from([(DraftHandle::new(root), permille)]), + } + } + + /// Verification 22, first half: only a qualified subject reduces the + /// deficit, and `Goal` carries the whole discrimination. + #[test] + fn a_subject_counts_toward_the_deficit_only_when_qualified() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation_with_intent( + CommandId::new(), + "Scale", + intent(super::tests::COMMONS, 3, 1000), + ), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let commons = kernel + .state + .scale_intent + .jurisdictions + .keys() + .copied() + .next() + .expect("the declared root"); + let active = activate(&mut kernel); + let counted = active + .subjects + .iter() + .find(|subject| subject.kind == SubjectKind::Person) + .expect("the fixture world has a person") + .id; + + let deficit = |kernel: &WorldKernel, jurisdiction: JurisdictionKey| { + derive_scale_deficit(&kernel.state) + .unwrap() + .into_iter() + .find(|row| row.jurisdiction == jurisdiction && row.kind == SubjectKind::Person) + }; + let row = deficit(&kernel, JurisdictionKey::PlaceSubtree(commons)) + .expect("a target of three persons"); + assert_eq!((row.target, row.qualified, row.deficit), (3, 0, 3)); + + // A controller and a grant are not enough; a `Goal` is what counts. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CreateCommitment { + subject: Ref::Existing(counted), + counterparty: None, + kind: CommitmentKind::Goal, + due: FictionalMinutes(500), + period: None, + checks: Vec::new(), + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }]), + ); + let goal = *kernel.state.commitments[&counted] + .keys() + .next() + .expect("the goal"); + let row = deficit(&kernel, JurisdictionKey::PlaceSubtree(commons)).unwrap(); + assert_eq!((row.target, row.qualified, row.deficit), (3, 1, 2)); + + // Discharging it raises the deficit again. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(counted), + key: goal, + }]), + ); + let row = deficit(&kernel, JurisdictionKey::PlaceSubtree(commons)).unwrap(); + assert_eq!((row.target, row.qualified, row.deficit), (3, 0, 3)); + } + + /// A qualifying subject standing somewhere no declared root covers still + /// counts, in the `Uncovered` row, rather than vanishing from the deficit + /// entirely: the count is total over every qualifying subject. + #[test] + fn a_subject_placed_outside_every_root_counts_as_uncovered() { + let directory = tempfile::tempdir().unwrap(); + let mut creation = creation_with_intent( + CommandId::new(), + "Uncovered", + intent(super::tests::COMMONS, 3, 1000), + ); + creation + .patch + .declarations + .push(Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("elsewhere"), + label: "The Elsewhere".into(), + kind: EntityKind::Place, + container: None, + })); + creation + .patch + .declarations + .push(Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("bridge"), + label: "The Elsewhere Bridge".into(), + from: Ref::Draft(DraftHandle::new(super::tests::COMMONS)), + to: Ref::Draft(DraftHandle::new("elsewhere")), + access: AccessKind::Public, + cost: Cost(1), + })); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation, + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let active = activate(&mut kernel); + let subject_count = kernel.state.subjects.len() as u32; + assert_eq!(subject_count, 3, "the base fixture declares three subjects"); + + // Every subject qualifies, so the deficit's row counts must sum to + // the whole subject count. + let goal = |subject: SubjectId| ComponentOp::CreateCommitment { + subject: Ref::Existing(subject), + counterparty: None, + kind: CommitmentKind::Goal, + due: FictionalMinutes(500), + period: None, + checks: Vec::new(), + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }; + let subject_ids: Vec<SubjectId> = + active.subjects.iter().map(|subject| subject.id).collect(); + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(subject_ids.iter().copied().map(goal).collect()), + ); + + let moved = active + .subjects + .iter() + .find(|subject| subject.kind == SubjectKind::Person) + .expect("the fixture world has a person") + .id; + let bridge = active + .routes + .iter() + .find(|route| route.label == "The Elsewhere Bridge") + .expect("the declared route") + .id; + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::Relocate { + subject: Ref::Existing(moved), + via: Ref::Existing(bridge), + }]), + ); + + let rows = derive_scale_deficit(&kernel.state).unwrap(); + let uncovered = rows + .iter() + .find(|row| { + row.jurisdiction == JurisdictionKey::Uncovered && row.kind == SubjectKind::Person + }) + .expect("the relocated subject counts as uncovered"); + assert_eq!(uncovered.qualified, 1); + + let counted_total: u32 = rows.iter().map(|row| row.qualified).sum(); + assert_eq!( + counted_total, subject_count, + "the deficit is total over every qualifying subject" + ); + } + + /// Weights distribute the target and never raise it, and a root must be a + /// declared place. + #[test] + fn scale_weights_distribute_and_never_raise() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let over_whole = WorldScaleIntentRef { + targets: BTreeMap::from([(SubjectKind::Person, 10)]), + jurisdictions: BTreeMap::from([ + (DraftHandle::new(super::tests::COMMONS), 700), + (DraftHandle::new("human"), 400), + ]), + }; + let Err(error) = WorldKernel::create( + &path, + creation_with_intent(CommandId::new(), "TooMuch", over_whole), + &auth_principal(owner()), + ) else { + panic!("a genesis intent over the whole was admitted"); + }; + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected genesis patch"); + }; + assert!(mismatches.contains(&Mismatch::ScaleWeightsExceedWhole)); + // `human` is a subject handle, not a place. + assert!(mismatches.contains(&Mismatch::UnknownJurisdictionRoot { + handle: DraftHandle::new("human"), + })); + + // Half the whole distributes half the target, rounded down. + let mut kernel = WorldKernel::create( + &path, + creation_with_intent( + CommandId::new(), + "Half", + intent(super::tests::COMMONS, 5, 500), + ), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + activate(&mut kernel); + let rows = derive_scale_deficit(&kernel.state).unwrap(); + let commons_target: u32 = rows + .iter() + .filter(|row| matches!(row.jurisdiction, JurisdictionKey::PlaceSubtree(_))) + .map(|row| row.target) + .sum(); + assert_eq!(commons_target, 2); + assert!(commons_target <= 5); + } + + /// A rejected patch mutates nothing, so the deficit it would have reduced + /// stays visible. + #[test] + fn a_rejected_patch_leaves_the_deficit_unchanged_and_visible() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation_with_intent( + CommandId::new(), + "Rejected", + intent(super::tests::COMMONS, 3, 1000), + ), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let active = activate(&mut kernel); + let before = derive_scale_deficit(&kernel.state).unwrap(); + let subjects: Vec<SubjectId> = active + .subjects + .iter() + .filter(|subject| subject.kind == SubjectKind::Person) + .map(|subject| subject.id) + .collect(); + let goal = |subject: SubjectId, due: u64| ComponentOp::CreateCommitment { + subject: Ref::Existing(subject), + counterparty: None, + kind: CommitmentKind::Goal, + due: FictionalMinutes(due), + period: None, + checks: Vec::new(), + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }; + + // One of the two goals is born past due. + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![goal(subjects[0], 500), goal(subjects[1], 0)]), + ), + vec![Mismatch::CommitmentDueInThePast { operation: 1 }] + ); + assert_eq!(derive_scale_deficit(&kernel.state).unwrap(), before); + + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![goal(subjects[0], 500), goal(subjects[1], 600)]), + ); + let after = derive_scale_deficit(&kernel.state).unwrap(); + let total = |rows: &[ScaleDeficitRow]| -> u32 { rows.iter().map(|row| row.deficit).sum() }; + assert_eq!(total(&after) + 2, total(&before)); + } + + /// Every commitment shape check, in one complete sorted set. + #[test] + fn commitment_declaration_negatives() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "Shapes"); + let before = kernel.state.clone(); + let create = |kind: CommitmentKind, + counterparty: Option<SubjectId>, + due: u64, + period: Option<TickMinutes>, + checks: Vec<PreconditionRef>| { + ComponentOp::CreateCommitment { + subject: Ref::Existing(clockwork.farmer), + counterparty: counterparty.map(Ref::Existing), + kind, + due: FictionalMinutes(due), + period, + checks, + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + } + }; + + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![ + // 0: a routine with no period. + create(CommitmentKind::Routine, None, 500, None, Vec::new()), + // 1: a goal with a period. + create( + CommitmentKind::Goal, + None, + 500, + Some(minutes(10)), + Vec::new() + ), + // 2: checks on a non-routine. + create( + CommitmentKind::Obligation, + Some(clockwork.treasury), + 500, + None, + vec![PreconditionRef::Present { + at: Ref::Existing(clockwork.yard), + }], + ), + // 3: born past due. + create( + CommitmentKind::Obligation, + Some(clockwork.treasury), + 0, + None, + Vec::new() + ), + // 4: a promise to oneself with a counterparty. + create( + CommitmentKind::Obligation, + Some(clockwork.farmer), + 500, + None, + Vec::new() + ), + // 5: a goal with a counterparty. + create( + CommitmentKind::Goal, + Some(clockwork.treasury), + 500, + None, + Vec::new() + ), + // 6: a discharge of a key nobody holds. + ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: CommitmentKey { + command: CommandId::new(), + index: 0, + }, + }, + ]), + ), + { + let mut expected = vec![ + Mismatch::CommitmentPeriodMismatch { operation: 0 }, + Mismatch::CommitmentPeriodMismatch { operation: 1 }, + Mismatch::ChecksOnNonRoutine { operation: 2 }, + Mismatch::CommitmentDueInThePast { operation: 3 }, + Mismatch::SelfCommitment { operation: 4 }, + Mismatch::GoalWithCounterparty { operation: 5 }, + Mismatch::UnknownCommitment { operation: 6 }, + ]; + expected.sort(); + expected + } + ); + assert_eq!(kernel.state, before); + + // Repairing exactly those commits. + submit_owner( + &mut kernel, + &active, + operations(vec![ + create( + CommitmentKind::Routine, + None, + 500, + Some(minutes(10)), + Vec::new(), + ), + create(CommitmentKind::Goal, None, 500, None, Vec::new()), + create( + CommitmentKind::Obligation, + Some(clockwork.treasury), + 500, + None, + Vec::new(), + ), + ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.routine, + }, + ]), + ); + assert!( + !kernel.state.commitments[&clockwork.farmer].contains_key(&clockwork.routine), + "the discharge removed the routine" + ); + } + + /// `Committed` reads the actor's own commitments, and a discharge mid-flight + /// rejects the promisor's bound proposal while the counterparty's own + /// invocation fails at admission. + #[test] + fn committed_reads_the_actors_own_commitments() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Committed"); + + // The reeve promised the treasury nothing. + let error = exercise( + &mut kernel, + clockwork.reeve, + clockwork.deliver, + vec![binding("creditor", Target::Subject(clockwork.treasury))], + ) + .unwrap_err(); + assert!(matches!( + error, + KernelError::ActionRejected(ref mismatches) + if *mismatches == vec![ActionMismatch::NotCommitted { precondition: 0 }] + )); + + // The farmer did, so the entry commits and mints a second obligation + // whose due date the kernel computed. + let before = kernel.state.commitments[&clockwork.farmer].len(); + exercise( + &mut kernel, + clockwork.farmer, + clockwork.deliver, + vec![binding("creditor", Target::Subject(clockwork.treasury))], + ) + .expect("the delivery commits"); + assert_eq!( + kernel.state.commitments[&clockwork.farmer].len(), + before + 1 + ); + + // A proposal bound before a discharge is rejected as a scope change for + // the promisor: `Committed` reads commitments, so the digest binds them. + let snapshot = kernel.snapshot().unwrap(); + let stale = opportunity_for(&snapshot, clockwork.farmer); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.obligation, + }]), + ); + let caller = CallerId::Controller(stale.controller_id); + let after = kernel.snapshot().unwrap(); + let error = kernel + .submit( + command( + &after, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity: stale, + invocation: DecisionInvocation { + affordance: clockwork.deliver, + bindings: vec![binding( + "creditor", + Target::Subject(clockwork.treasury), + )], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + speech: None, + display: None, + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap_err(); + assert!( + matches!(error, KernelError::ScopeChanged { .. }), + "{error:?}" + ); + } + + /// A tick that only advances pressure moves nobody's scope digest; a tick + /// that fulfils a routine moves exactly that subject's. + #[test] + fn a_pressure_tick_moves_no_scope_digest_and_a_routine_tick_moves_one() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Digests"); + let digests = |kernel: &WorldKernel| -> BTreeMap<SubjectId, ScopeDigest> { + derive_opportunities(&kernel.state) + .unwrap() + .into_iter() + .map(|opportunity| (opportunity.scope.subject_id, opportunity.scope_digest)) + .collect() + }; + + // Past the obligation and the goal, but the routine is blocked out of + // the yard first so only pressure moves. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.routine, + }]), + ); + let before = digests(&kernel); + tick(&mut kernel, 200).expect("the tick commits"); + assert!(!kernel.state.pressures.is_empty(), "the tick pressed"); + assert_eq!(digests(&kernel), before, "pressure binds no proposal"); + + // A routine fulfilment moves exactly its own subject's digest. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CreateCommitment { + subject: Ref::Existing(clockwork.reeve), + counterparty: None, + kind: CommitmentKind::Routine, + due: FictionalMinutes(500), + period: Some(minutes(60)), + checks: Vec::new(), + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }]), + ); + let before = digests(&kernel); + tick(&mut kernel, 400).expect("the tick commits"); + let after = digests(&kernel); + for (subject, digest) in &before { + if *subject == clockwork.reeve { + assert_ne!(after[subject], *digest, "the fulfilling subject rebinds"); + } else { + assert_eq!(after[subject], *digest, "everyone else still commits"); + } + } + } + + /// Soul falsification: the attention order is total on `SubjectId` when + /// pressure and debt tie, and it is the same order for every input + /// permutation. `sort_by_key` is stable, so an order that leaned on its + /// input's order would pass a single-vector test and drift with map + /// iteration. + #[test] + fn soul_the_attention_order_is_id_total_under_every_input_permutation() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, clockwork, _) = clock_kernel(directory.path(), "Ties"); + let mut state = kernel.state.clone(); + state.now = FictionalMinutes(5_000); + // Equal pressure and an equal stamp on every subject: only the id can + // decide. + for subject_id in state.subjects.keys().copied().collect::<Vec<_>>() { + state.pressures.insert( + subject_id, + BTreeMap::from([( + PressureSource::Subject(clockwork.reeve), + PressureMagnitude(7), + )]), + ); + state + .last_opportunity_at + .insert(subject_id, FictionalMinutes(400)); + } + let derived = derive_opportunities(&state).unwrap(); + assert!( + derived.len() >= 3, + "the fixture ties at least three subjects" + ); + let expected: Vec<SubjectId> = order_opportunities(&state, derived.clone()) + .into_iter() + .map(|opportunity| opportunity.scope.subject_id) + .collect(); + let mut ascending = expected.clone(); + ascending.sort_unstable(); + assert_eq!(expected, ascending, "an equal-key tie is broken by id"); + + // Every rotation and the full reversal produce the same order. + for shift in 0..derived.len() { + let mut permuted = derived.clone(); + permuted.rotate_left(shift); + let mut reversed = permuted.clone(); + reversed.reverse(); + for candidate in [permuted, reversed] { + let ordered: Vec<SubjectId> = order_opportunities(&state, candidate) + .into_iter() + .map(|opportunity| opportunity.scope.subject_id) + .collect(); + assert_eq!(ordered, expected, "the order read its input's order"); + } + } + } + + /// Soul falsification of the admission ruling: in Active a patch that only + /// changes components answers nothing, a patch that declares or admits + /// evidence must answer, and the answer gate closes before the resolver + /// ever runs. + #[test] + fn soul_an_active_patch_answers_only_when_it_elaborates() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Elaborate"); + + // Component-only, no answer: admitted. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::AdvancePressure { + source: PressureSourceRef::Subject(Ref::Existing(clockwork.reeve)), + target: Ref::Existing(clockwork.farmer), + by: PressureMagnitude(2), + }]), + ); + assert_eq!( + pressure( + &kernel, + clockwork.farmer, + PressureSource::Subject(clockwork.reeve) + ), + 2 + ); + + let refuse = |kernel: &mut WorldKernel, body: CommandBody| { + let snapshot = kernel.snapshot().unwrap(); + kernel + .submit( + command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + body, + ), + &auth_principal(owner()), + ) + .unwrap_err() + }; + + // Evidence alone is elaboration too, so it answers. + let evidence_only = CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: Vec::new(), + evidence: vec![EvidenceRef::new("soul://evidence-only")], + }, + }; + assert!(matches!( + refuse(&mut kernel, evidence_only), + KernelError::AnswerRequired + )); + + // The gate is ahead of the resolver: a declaring patch that is also + // structurally broken is refused for the missing answer, not for the + // mismatch it would otherwise return. + let broken = CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("orphan"), + label: "An Orphan Room".into(), + kind: EntityKind::Place, + container: Some(Ref::Draft(DraftHandle::new("nowhere"))), + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }; + assert!( + matches!(refuse(&mut kernel, broken), KernelError::AnswerRequired), + "the resolver ran before the answer gate" + ); + + // A derived answer that the patch satisfies commits, and the boundary + // is gone afterwards. + let answered = derive_boundaries(&kernel.state) + .unwrap() + .into_iter() + .find(|boundary| matches!(boundary, CausalBoundary::UnelaboratedDestination { .. })) + .expect("the dead end"); + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch: WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("cairn"), + label: "A Roadside Cairn".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(clockwork.dead_end)), + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + assert!( + !derive_boundaries(&kernel.state) + .unwrap() + .contains(&answered), + "the answered boundary is still derived" + ); + } + + /// Soul falsification: pressure magnitude cannot overflow or go negative, + /// and zero is spelled by absence at both ends. + #[test] + fn soul_pressure_saturates_and_never_underflows() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Saturate"); + let sourced = PressureSource::Commitment { + subject: clockwork.farmer, + key: clockwork.obligation, + }; + + // A tick over a magnitude already at the ceiling saturates rather than + // wrapping. + let mut brimming = kernel.state.clone(); + brimming.pressures.insert( + clockwork.farmer, + BTreeMap::from([(sourced, PressureMagnitude(u32::MAX))]), + ); + let motion = clock::derive_motion(&brimming, FictionalMinutes(LATE_DUE)); + let written = motion + .pressed + .iter() + .find(|written| written.source == sourced) + .expect("the past-due obligation pressed"); + assert_eq!(written.magnitude, PressureMagnitude(u32::MAX)); + + // Reducing by more than the row holds removes it instead of wrapping. + tick(&mut kernel, u32::try_from(LATE_DUE).unwrap()).expect("the tick commits"); + assert_eq!(pressure(&kernel, clockwork.farmer, sourced), 1); + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::ReducePressure { + source: PressureSourceRef::Commitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.obligation, + }, + target: Ref::Existing(clockwork.farmer), + by: PressureMagnitude(9), + }]), + ); + assert_eq!(pressure(&kernel, clockwork.farmer, sourced), 0); + assert!( + !kernel.state.pressures.contains_key(&clockwork.farmer), + "an emptied target keeps no empty inner map" + ); + + // `pressure_total` and `attention_debt` are derived, never stored. + assert_eq!(pressure_total(&kernel.state, clockwork.farmer), 0); + assert_eq!( + attention_debt(&kernel.state, clockwork.treasury), + u64::MAX, + "a subject never attended carries the whole debt" + ); + + // Resolving an absent row changes nothing and is refused. + let snapshot = kernel.snapshot().unwrap(); + let mismatches = reject_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::ResolvePressure { + source: PressureSourceRef::Commitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.obligation, + }, + target: Ref::Existing(clockwork.farmer), + }]), + ); + assert_eq!( + mismatches, + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + } + + /// Soul falsification: `now` is in no scope preimage. A tick with nothing + /// due moves the clock and not one subject's digest. + #[test] + fn soul_a_clock_only_tick_moves_no_scope_digest() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, _, _) = clock_kernel(directory.path(), "ClockOnly"); + let digests = |kernel: &WorldKernel| -> BTreeMap<SubjectId, ScopeDigest> { + derive_opportunities(&kernel.state) + .unwrap() + .into_iter() + .map(|opportunity| (opportunity.scope.subject_id, opportunity.scope_digest)) + .collect() + }; + let before = digests(&kernel); + let before_now = kernel.state.now; + + // Short of every due date in the fixture. + tick(&mut kernel, 10).expect("the tick commits"); + assert_eq!(kernel.state.now, FictionalMinutes(before_now.0 + 10)); + assert!(kernel.state.pressures.is_empty()); + assert_eq!(digests(&kernel), before, "the clock entered a scope digest"); + } + + /// Soul falsification: the authored scale target is written once by genesis + /// and by no Active lane. `AdmitPatch` resolves with no intent at all, so + /// there is no shape for an Active rewrite to take. + #[test] + fn soul_the_scale_intent_is_written_once_by_genesis() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation_with_intent( + CommandId::new(), + "WriteOnce", + intent(super::tests::COMMONS, 3, 1000), + ), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let active = activate(&mut kernel); + let authored = kernel.state.scale_intent.clone(); + assert!(!authored.jurisdictions.is_empty()); + + let subject = active + .subjects + .iter() + .find(|subject| subject.kind == SubjectKind::Person) + .expect("a person") + .id; + let body = operations(vec![ComponentOp::CreateCommitment { + subject: Ref::Existing(subject), + counterparty: None, + kind: CommitmentKind::Goal, + due: FictionalMinutes(500), + period: None, + checks: Vec::new(), + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }]); + // The Active resolver is handed no intent, so the resolved patch cannot + // carry one. + let CommandBody::AdmitPatch { patch, .. } = &body else { + panic!("the operations helper builds an admitted patch"); + }; + let resolved = + patch::resolve_patch(&kernel.state, CommandId::new(), patch, None, None).expect("resolves"); + assert!( + resolved.scale_intent.is_none(), + "an Active patch resolved a scale intent" + ); + + submit_owner(&mut kernel, &active, body); + assert_eq!(kernel.state.scale_intent, authored); + } + + // ---- lens weights: world data, genesis, and the owner command -------- + + fn every_lens_at_zero() -> LensWeights { + LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 0)).collect()) + } + + #[test] + fn genesis_writes_the_lens_weights_it_was_given() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let given = LensWeights::new(BTreeMap::from([(Lens::Patina, 2), (Lens::Numen, 1)])); + let mut input = creation(CommandId::new(), "Flavored"); + input.lens_weights = given.clone(); + let (kernel, _) = WorldKernel::create(&path, input, &auth_principal(owner())).unwrap(); + let created = kernel.snapshot().unwrap(); + assert_eq!(created.lens_weights, given); + assert_eq!(kernel.state.lens_weights, given); + + let world_id = created.world_id; + drop(kernel); + let replayed = WorldKernel::open(&path, world_id).unwrap(); + assert_eq!(replayed.snapshot().unwrap(), created); + assert_eq!(replayed.state.state_digest, created.state_digest); + } + + #[test] + fn a_genesis_lens_set_that_never_draws_is_refused() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let mut input = creation(CommandId::new(), "Flavorless"); + input.lens_weights = every_lens_at_zero(); + let Err(error) = WorldKernel::create(&path, input, &auth_principal(owner())) else { + panic!("a genesis lens set that never draws was admitted"); + }; + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected genesis patch, got {error:?}"); + }; + assert_eq!(mismatches, vec![Mismatch::LensWeightsNeverDraw]); + assert!(!path.exists(), "a refused genesis wrote a world file"); + + // The same creation with one real weight among the zeros is admitted. + let mut input = creation(CommandId::new(), "Flavorless"); + let mut weights = BTreeMap::from_iter(every_lens_at_zero().iter()); + weights.insert(Lens::Veil, 1); + input.lens_weights = LensWeights::new(weights); + WorldKernel::create(&path, input, &auth_principal(owner())).expect("one nonzero weight"); + } + + // ---- PA.f26: the genesis lane obeys `require_ruler` too ------------ + + /// PA.f26: `prepare_creation` and `WorldState::genesis` both call + /// `require_ruler` exactly where every other admission lane does. A + /// creation patch that carries a `Ruled` fact is refused before a world + /// is ever written. + #[test] + fn a_genesis_patch_carrying_a_ruled_fact_is_refused() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let mut input = creation(CommandId::new(), "RuledGenesis"); + input + .patch + .declarations + .push(Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("rule"), + label: "The Ruling".into(), + statement: Statement::new("Stated by the table.").unwrap(), + standing: FactStandingRef::Ruled, + })); + let Err(error) = WorldKernel::create(&path, input, &auth_principal(owner())) else { + panic!("a genesis patch carrying a Ruled fact was admitted"); + }; + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RuledWithoutAuthority { + site: patch::Site::Declaration(DraftHandle::new("rule")), + })), + "{error:?}" + ); + assert!(!path.exists(), "a refused genesis wrote a world file"); + } + + /// PA.f26, the `Mint` half: a creation patch that carries a `Mint` is + /// refused the same way. + #[test] + fn a_genesis_patch_carrying_a_mint_is_refused() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let mut input = creation(CommandId::new(), "MintGenesis"); + input + .patch + .declarations + .push(super::tests::resource("loot", "Roadside Loot")); + input.patch.operations.push(ComponentOp::Mint { + holder: Ref::Draft(DraftHandle::new("human")), + resource: Ref::Draft(DraftHandle::new("loot")), + qty: Quantity(4), + }); + let Err(error) = WorldKernel::create(&path, input, &auth_principal(owner())) else { + panic!("a genesis patch carrying a Mint was admitted"); + }; + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RuledWithoutAuthority { + site: patch::Site::Operation(0), + })), + "{error:?}" + ); + assert!(!path.exists(), "a refused genesis wrote a world file"); + } + + /// PA.f26: `WorldState::genesis` re-decides `require_ruler` on its own + /// terms, independent of `prepare_creation` — that is what protects + /// journal replay of a stored genesis commit, not only a freshly + /// admitted one. Called directly, bypassing `prepare_creation` entirely, + /// so this cannot be satisfied by `prepare_creation`'s own check. + #[test] + fn genesis_itself_refuses_a_ruled_fact_and_a_mint() { + let world_id = WorldId::issue(); + let mut input = creation(CommandId::new(), "GenesisRuleDirect"); + input + .patch + .declarations + .push(Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("rule"), + label: "The Ruling".into(), + statement: Statement::new("Stated by the table.").unwrap(), + standing: FactStandingRef::Ruled, + })); + let title = normalize_title(&input.title).unwrap(); + let resolved = patch::resolve_patch( + &WorldState::empty(world_id, input.owner.clone(), title.clone(), None), + input.id, + &input.patch, + Some(&input.scale_intent), + Some(&input.lens_weights), + ) + .expect("the resolver is actor-blind and accepts a Ruled fact"); + let effect = WorldEffect::WorldCreated { + owner: input.owner.clone(), + title, + brief: input.brief.clone(), + resolved, + }; + let error = WorldState::genesis(world_id, &input, &effect).unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + + let world_id = WorldId::issue(); + let mut input = creation(CommandId::new(), "GenesisMintDirect"); + input + .patch + .declarations + .push(super::tests::resource("loot", "Roadside Loot")); + input.patch.operations.push(ComponentOp::Mint { + holder: Ref::Draft(DraftHandle::new("human")), + resource: Ref::Draft(DraftHandle::new("loot")), + qty: Quantity(4), + }); + let title = normalize_title(&input.title).unwrap(); + let resolved = patch::resolve_patch( + &WorldState::empty(world_id, input.owner.clone(), title.clone(), None), + input.id, + &input.patch, + Some(&input.scale_intent), + Some(&input.lens_weights), + ) + .expect("the resolver is actor-blind and accepts a Mint"); + let effect = WorldEffect::WorldCreated { + owner: input.owner.clone(), + title, + brief: input.brief.clone(), + resolved, + }; + let error = WorldState::genesis(world_id, &input, &effect).unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + } + + /// Soul falsification, the lens twin of the scale intent's write-once + /// test: an Active patch resolves no weights; only the owner's + /// `SetLensWeights` replaces them, in Draft and in Active; every other + /// caller is `Unauthorized`; a set that never draws is refused; and + /// `apply_effect` re-decides the owner against a hand-built effect. + #[test] + fn soul_the_lens_weights_are_replaced_only_by_the_owner_command() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, _) = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "Owner Flavor"), + &auth_principal(owner()), + ) + .unwrap(); + let draft_weights = LensWeights::new(BTreeMap::from([ + (Lens::Patina, 0), + (Lens::Charter, 3), + (Lens::Ledger, 1), + ])); + let draft = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &draft, + CommandBody::SetLensWeights { + weights: draft_weights.clone(), + }, + ); + assert_eq!(kernel.state.revision, draft.revision + 1); + assert_eq!(kernel.state.lens_weights, draft_weights); + + let active = activate(&mut kernel); + let active_weights = LensWeights::new(BTreeMap::from([ + (Lens::Hearth, 5), + (Lens::Tangle, 0), + (Lens::Ember, 2), + ])); + submit_owner( + &mut kernel, + &active, + CommandBody::SetLensWeights { + weights: active_weights.clone(), + }, + ); + assert_eq!(kernel.state.revision, active.revision + 1); + assert_eq!(kernel.state.lens_weights, active_weights); + + // An Active patch is handed no weights, so it cannot resolve any. + let resolved = patch::resolve_patch( + &kernel.state, + CommandId::new(), + &operations_patch(&kernel), + None, + None, + ) + .expect("resolves"); + assert!(resolved.lens_weights.is_none(), "an Active patch resolved lens weights"); + let after_patch = kernel.snapshot().unwrap(); + let patch = operations_patch(&kernel); + submit_owner( + &mut kernel, + &after_patch, + CommandBody::AdmitPatch { + answers: None, + patch, + }, + ); + assert_eq!(kernel.state.lens_weights, active_weights); + + // Every caller but the owner, with real weights. + let proposed = super::tests::stock_weights(); + let before = kernel.state.clone(); + for caller in [ + CallerId::Principal(human_principal()), + CallerId::Principal(PrincipalId::new("stranger@example.test")), + elaborator(JurisdictionKey::Uncovered), + CallerId::System(SystemCapability::Clock), + CallerId::System(SystemCapability::Consumer { + consumer: ConsumerId::of_name("lens-consumer"), + }), + ] { + let result = submit_as( + &mut kernel, + caller.clone(), + CommandBody::SetLensWeights { + weights: proposed.clone(), + }, + ); + assert!( + matches!(result, Err(KernelError::Unauthorized)), + "{caller:?} replaced the lens weights: {result:?}" + ); + } + assert_eq!(kernel.state, before); + + // The owner, with every lens named at zero. + let result = submit_as( + &mut kernel, + CallerId::Principal(owner()), + CommandBody::SetLensWeights { + weights: every_lens_at_zero(), + }, + ); + let Err(KernelError::PatchRejected(mismatches)) = result else { + panic!("a lens set that never draws was admitted: {result:?}"); + }; + assert_eq!(mismatches, vec![Mismatch::LensWeightsNeverDraw]); + assert_eq!(kernel.state, before); + + // The owner, with valid weights, against the revision before the + // last commit. + let stale = command( + &draft, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::SetLensWeights { + weights: proposed.clone(), + }, + ); + assert!(matches!( + kernel.submit(stale, &auth_principal(owner())), + Err(KernelError::RevisionMismatch { .. }) + )); + assert_eq!(kernel.state, before); + + // `apply_effect` re-decides: a hand-built effect under a non-owner or + // a system caller never applies, and neither does one that never draws. + for (caller, weights) in [ + (CallerId::Principal(human_principal()), proposed.clone()), + (CallerId::System(SystemCapability::Clock), proposed.clone()), + (CallerId::Principal(owner()), every_lens_at_zero()), + ] { + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + CommandId::new(), + &caller, + &WorldEffect::LensWeightsReplaced { weights }, + ) + .unwrap_err(); + assert!( + matches!( + error, + KernelError::Invariant(_) | KernelError::Unauthorized + ), + "{caller:?}: {error:?}" + ); + assert_eq!(candidate, kernel.state); + } + // The honest effect applies through the same arm. + let mut candidate = kernel.state.clone(); + apply_effect( + &mut candidate, + CommandId::new(), + &CallerId::Principal(owner()), + &WorldEffect::LensWeightsReplaced { + weights: proposed.clone(), + }, + ) + .expect("the owner's effect applies"); + assert_eq!(candidate.lens_weights, proposed); + + // Identical weights from the owner change nothing canonical: refused + // as `NoCanonicalChange`, and nothing commits. + let result = submit_as( + &mut kernel, + CallerId::Principal(owner()), + CommandBody::SetLensWeights { + weights: active_weights.clone(), + }, + ); + let Err(KernelError::PatchRejected(mismatches)) = result else { + panic!("identical lens weights were admitted: {result:?}"); + }; + assert_eq!(mismatches, vec![Mismatch::NoCanonicalChange]); + assert_eq!(kernel.state, before); + + // The order is admission, then effect. Identical weights from a + // non-owner are `Unauthorized`; and against a state whose own set + // never draws (no store holds one, so the state is built by hand), an + // identical all-zero set is `LensWeightsNeverDraw`, not a no-op. + let result = submit_as( + &mut kernel, + CallerId::Principal(human_principal()), + CommandBody::SetLensWeights { + weights: active_weights.clone(), + }, + ); + assert!( + matches!(result, Err(KernelError::Unauthorized)), + "a non-owner's identical set: {result:?}" + ); + assert_eq!(kernel.state, before); + let mut never = kernel.state.clone(); + never.lens_weights = every_lens_at_zero(); + let current = kernel.snapshot().unwrap(); + let identical_zero = command( + ¤t, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::SetLensWeights { + weights: every_lens_at_zero(), + }, + ); + let result = reduce(&never, &identical_zero); + let Err(KernelError::PatchRejected(mismatches)) = result else { + panic!("an identical set that never draws: {result:?}"); + }; + assert_eq!(mismatches, vec![Mismatch::LensWeightsNeverDraw]); + + // Replay across that history is unchanged: the refused attempts wrote + // nothing, and the store reopens to the same head. + let (path, world_id) = (directory.path().join("world.cc"), kernel.state.world_id); + drop(kernel); + let reopened = WorldKernel::open(path, world_id).expect("the history reopens"); + assert_eq!(reopened.state, before); + } + + /// An owner commit that adds a commitment to the first person: a real + /// Active patch with no answer, and nothing to do with lenses. + fn operations_patch(kernel: &WorldKernel) -> WorldPatch { + let subject = kernel + .state + .subjects + .iter() + .find(|(_, state)| state.kind == SubjectKind::Person) + .map(|(id, _)| *id) + .expect("a person"); + let CommandBody::AdmitPatch { patch, .. } = operations(vec![ComponentOp::CreateCommitment { + subject: Ref::Existing(subject), + counterparty: None, + kind: CommitmentKind::Goal, + due: FictionalMinutes(kernel.state.now.0 + 500), + period: None, + checks: Vec::new(), + statement: Statement::new("A promise kept with no flavor at all.").unwrap(), + }]) else { + panic!("the operations helper builds an admitted patch"); + }; + patch + } + + #[test] + fn lens_weights_enter_the_state_digest_and_no_scope_digest() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, _) = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "Digest Flavor"), + &auth_principal(owner()), + ) + .unwrap(); + let active = activate(&mut kernel); + + let mut other = kernel.state.clone(); + other.lens_weights = + LensWeights::new(BTreeMap::from([(Lens::Patina, 1), (Lens::Veil, 7)])); + assert_ne!( + state_digest(&other).unwrap(), + state_digest(&kernel.state).unwrap(), + "lens weights did not enter the state digest" + ); + + let digests = |kernel: &WorldKernel| -> BTreeMap<SubjectId, ScopeDigest> { + derive_opportunities(&kernel.state) + .unwrap() + .into_iter() + .map(|opportunity| (opportunity.scope.subject_id, opportunity.scope_digest)) + .collect() + }; + let before = digests(&kernel); + assert!(!before.is_empty(), "the active fixture derives opportunities"); + submit_owner( + &mut kernel, + &active, + CommandBody::SetLensWeights { + weights: other.lens_weights.clone(), + }, + ); + assert_ne!(kernel.state.state_digest, active.state_digest); + assert_eq!(digests(&kernel), before, "lens weights entered a scope digest"); + } + + /// Soul falsification: a discharge names one subject's own live key. + #[test] + fn soul_discharging_a_foreign_or_already_discharged_commitment_is_refused() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Discharge"); + + // The farmer's obligation, claimed by the reeve. + let snapshot = kernel.snapshot().unwrap(); + assert_eq!( + reject_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.reeve), + key: clockwork.obligation, + }]), + ), + vec![Mismatch::UnknownCommitment { operation: 0 }] + ); + + // Discharged once, and then not again. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.obligation, + }]), + ); + let snapshot = kernel.snapshot().unwrap(); + assert_eq!( + reject_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.obligation, + }]), + ), + vec![Mismatch::UnknownCommitment { operation: 0 }] + ); + } + + /// Soul falsification: a routine re-arms by exactly one period per command, + /// whatever the span, and a non-routine cannot carry checks. + #[test] + fn soul_a_routine_re_arms_exactly_one_period_per_command() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Rearm"); + let period = u64::from( + kernel.state.commitments[&clockwork.farmer][&clockwork.routine] + .period + .expect("a routine carries a period") + .minutes(), + ); + let start = due(&kernel, clockwork.farmer, clockwork.routine); + + // One roll per command, even for a span that clears many periods. + tick(&mut kernel, u32::try_from(period * 10).unwrap()).expect("the long tick commits"); + assert_eq!( + due(&kernel, clockwork.farmer, clockwork.routine), + FictionalMinutes(start.0 + period) + ); + tick(&mut kernel, 1).expect("the short tick commits"); + assert_eq!( + due(&kernel, clockwork.farmer, clockwork.routine), + FictionalMinutes(start.0 + 2 * period) + ); + + // Checks belong to routines alone. + let snapshot = kernel.snapshot().unwrap(); + assert_eq!( + reject_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CreateCommitment { + subject: Ref::Existing(clockwork.reeve), + counterparty: None, + kind: CommitmentKind::Goal, + due: FictionalMinutes(100_000), + period: None, + checks: vec![PreconditionRef::Present { + at: Ref::Existing(clockwork.yard), + }], + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }]), + ), + vec![Mismatch::ChecksOnNonRoutine { operation: 0 }] + ); + } + + /// Soul falsification: `derive_motion` is a function of state and span + /// alone, and the committed effect is exactly what `reduce` re-derives for + /// a tick that fulfils a routine, presses past-due promises, and presses a + /// failing dependency at once. + #[test] + fn soul_derive_motion_is_pure_and_the_tick_replays_exactly() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Pure"); + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(clockwork.gate), + }]), + ); + + // The same state and the same span, twenty times: one answer. + let span = u32::try_from(LATE_DUE + 10).unwrap(); + let to = FictionalMinutes(LATE_DUE + 10); + let first = clock::derive_motion(&kernel.state, to); + assert!(!first.fulfilled.is_empty(), "the routine is due"); + assert!( + first.pressed.len() >= 2, + "past-due promises and the closed route all press" + ); + for _ in 0..20 { + assert_eq!(clock::derive_motion(&kernel.state, to), first); + } + + // And the commit carries exactly that motion. + let snapshot = kernel.snapshot().unwrap(); + let ticking = command( + &snapshot, + CommandId::new(), + clock_caller(), + CommandBody::AdvanceTime { + minutes: minutes(span), + }, + ); + let expected = reduce(&kernel.state, &ticking).expect("the tick reduces"); + assert_eq!( + expected, + WorldEffect::TimeAdvanced { + minutes: minutes(span), + to, + motion: first, + } + ); + // Applying the re-derived effect to a copy reproduces the committed + // state exactly, which is the replay identity the journal relies on. + let mut replayed = kernel.state.clone(); + apply_effect(&mut replayed, ticking.id, &clock_caller(), &expected) + .expect("the re-derived effect applies"); + kernel + .submit(ticking, &AuthenticatedCaller::fixture(clock_caller())) + .expect("the tick commits"); + assert_eq!(replayed.now, kernel.state.now); + assert_eq!(replayed.commitments, kernel.state.commitments); + assert_eq!(replayed.pressures, kernel.state.pressures); + } + + /// Soul falsification: a `BoundaryDigest` binds the structure that derives + /// it, and nothing else. The clock is not in the preimage, so a tick leaves + /// it where it is; closing the one route out of the dead end leaves the + /// predicate holding and must still move the digest. + #[test] + fn soul_a_boundary_digest_binds_its_structure_and_not_the_clock() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Digest"); + let destination = |kernel: &WorldKernel| { + derive_boundaries(&kernel.state) + .unwrap() + .into_iter() + .find_map(|boundary| match boundary { + CausalBoundary::UnelaboratedDestination { place, scope, .. } + if place == clockwork.dead_end => + { + Some(scope) + } + _ => None, + }) + .expect("the dead end") + }; + let before = destination(&kernel); + + // The clock moves; the digest does not. + tick(&mut kernel, 10).expect("the tick commits"); + assert_eq!(destination(&kernel), before, "the clock entered a preimage"); + + // The route's own record moves; the digest must follow. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(clockwork.gate), + }]), + ); + assert_ne!( + destination(&kernel), + before, + "the digest ignored the route it names" + ); + } + + // ---- the elaborator capability ------------------------------------- + + fn elaborator(jurisdiction: JurisdictionKey) -> CallerId { + CallerId::System(SystemCapability::Elaborator { jurisdiction }) + } + + fn submit_as( + kernel: &mut WorldKernel, + caller: CallerId, + body: CommandBody, + ) -> Result<SubmitReceipt, KernelError> { + let snapshot = kernel.snapshot().unwrap(); + kernel.submit( + command(&snapshot, CommandId::new(), caller.clone(), body), + &AuthenticatedCaller::fixture(caller), + ) + } + + fn dead_end_boundary(kernel: &WorldKernel) -> CausalBoundary { + derive_boundaries(&kernel.state) + .unwrap() + .into_iter() + .find(|boundary| matches!(boundary, CausalBoundary::UnelaboratedDestination { .. })) + .expect("the fixture derives one dead end") + } + + fn shed_under(container: EntityId, handle: &str) -> WorldPatch { + WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: format!("The {handle}"), + kind: EntityKind::Place, + container: Some(Ref::Existing(container)), + })], + operations: Vec::new(), + evidence: Vec::new(), + } + } + + /// Verification 14: the mailbox port cannot express an unanswered + /// elaborator patch, so this is reachable only through the journal lane — + /// and it is refused there. + #[test] + fn elaborator_patch_without_answer_is_answer_required() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Unanswered"); + let revision = kernel.state.revision; + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: None, + patch: shed_under(clockwork.dead_end, "shed"), + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::AnswerRequired), "{error:?}"); + assert_eq!(kernel.state.revision, revision); + } + + /// Verification 14: a jurisdiction whose every row is zero has nothing to + /// answer, so the answer is not derived. + #[test] + fn patch_answering_a_zero_deficit_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "ZeroDeficit"); + let jurisdiction = JurisdictionKey::PlaceSubtree(clockwork.dead_end); + assert!( + derive_scale_deficit(&kernel.state) + .unwrap() + .iter() + .all(|row| row.deficit == 0) + ); + let error = submit_as( + &mut kernel, + elaborator(jurisdiction), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Deficit(jurisdiction)), + patch: shed_under(clockwork.dead_end, "shed"), + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::AnswerNotDerived), "{error:?}"); + } + + /// The one admission rule at the top of `reduce` refuses four bodies before + /// any of them is read, and the clock's capability is refused the fifth. + #[test] + fn a_system_capability_is_admitted_for_exactly_one_body() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "Capability"); + let held = elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)); + let opportunity = opportunity_for(&active, clockwork.reeve); + let answered = dead_end_boundary(&kernel); + let forbidden = [ + CommandBody::ApproveDraft, + CommandBody::ActivateWorld, + CommandBody::DeclineDecision { + opportunity: opportunity.clone(), + }, + CommandBody::AdvanceTime { + minutes: minutes(60), + }, + ]; + for body in forbidden { + let error = submit_as(&mut kernel, held.clone(), body).unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + } + // The mirror: the clock may not author. + let error = submit_as( + &mut kernel, + clock_caller(), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: shed_under(clockwork.dead_end, "shed"), + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + assert_eq!(kernel.state.revision, active.revision); + } + + /// Seed admission is the owner's lane: an elaborator in Draft has no + /// derived boundary to answer and nothing to be authorized for. + #[test] + fn elaborator_in_draft_is_unauthorized() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "DraftLane"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let commons = kernel.snapshot().unwrap().places[0].id; + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(commons)), + CommandBody::AdmitPatch { + answers: None, + patch: shed_under(commons, "shed"), + }, + ) + .unwrap_err(); + // Draft answers nothing, so the answer gate passes and authority + // refuses: an elaborator with no answer holds nothing. + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + } + + /// Boundaries are covered transitively, so a parent jurisdiction's + /// elaborator may answer a boundary in a nested child — and a sibling root + /// may not answer it at all. + #[test] + fn boundary_jurisdiction_is_transitive_and_exclusive() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Transitive"); + let answered = dead_end_boundary(&kernel); + let hall = kernel.state.entities[&clockwork.yard] + .container + .expect("the yard sits in the hall"); + + // The hall's elaborator does not cover the unwalked road. + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(hall)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch: shed_under(clockwork.dead_end, "shed"), + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + + // One unconfined owner patch answers that boundary and opens a second + // one strictly inside the hall, so the two coverings can be told apart + // on one world. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("shed"), + label: "The Roadside Shed".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(clockwork.dead_end)), + }), + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("cellar"), + label: "The Yard Cellar".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(clockwork.yard)), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("hatch"), + label: "The Cellar Hatch".into(), + from: Ref::Existing(clockwork.yard), + to: Ref::Draft(DraftHandle::new("cellar")), + access: AccessKind::Public, + cost: Cost(1), + }), + ], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + assert!( + !derive_boundaries(&kernel.state) + .unwrap() + .contains(&answered) + ); + + let cellar = kernel + .state + .entities + .iter() + .find(|(_, entity)| entity.label == "The Yard Cellar") + .map(|(id, _)| *id) + .expect("the declared cellar"); + let nested = dead_end_boundary(&kernel); + assert!(matches!( + nested, + CausalBoundary::UnelaboratedDestination { place, .. } if place == cellar + )); + + // The road's root does not reach into the hall. + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(nested.clone())), + patch: shed_under(cellar, "crock"), + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + + // The hall's does, transitively, through the same containment walk the + // civic lane uses. + submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(hall)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(nested.clone())), + patch: shed_under(cellar, "crock"), + }, + ) + .expect("the parent root covers a nested boundary"); + assert!(!derive_boundaries(&kernel.state).unwrap().contains(&nested)); + } + + /// A deficit is covered by exact key equality. A parent answering a child's + /// row would reduce two targets with one subject, because a subject under + /// nested roots counts toward both. + #[test] + fn parent_jurisdiction_cannot_answer_a_child_deficit_row() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation_with_intent( + CommandId::new(), + "Rows", + intent(super::tests::COMMONS, 3, 1000), + ), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let commons = *kernel + .state + .scale_intent + .jurisdictions + .keys() + .next() + .expect("the declared root"); + let active = activate(&mut kernel); + let inner = active.places[0].id; + let row = JurisdictionKey::PlaceSubtree(commons); + assert!( + derive_scale_deficit(&kernel.state) + .unwrap() + .iter() + .any(|candidate| candidate.jurisdiction == row && candidate.deficit > 0) + ); + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::Uncovered), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Deficit(row)), + patch: shed_under(inner, "shed"), + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + } + + /// Confinement: a valid answer does not license a write outside the + /// jurisdiction, and a place with no container is a new root, which is the + /// owner's act. + #[test] + fn an_elaborator_cannot_write_outside_its_jurisdiction() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Confined"); + let answered = dead_end_boundary(&kernel); + let held = elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)); + + let foreign = submit_as( + &mut kernel, + held.clone(), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch: shed_under(clockwork.yard, "yardshed"), + }, + ) + .unwrap_err(); + assert!( + matches!(&foreign, KernelError::PatchRejected(set) + if set == &vec![Mismatch::OutsideJurisdiction { + site: Site::Declaration(DraftHandle::new("yardshed")), + }]), + "{foreign:?}" + ); + + let rootless = submit_as( + &mut kernel, + held, + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch: WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("newroot"), + label: "A New Country".into(), + kind: EntityKind::Place, + container: None, + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ) + .unwrap_err(); + assert!( + matches!(&rootless, KernelError::PatchRejected(set) + if set == &vec![Mismatch::OutsideJurisdiction { + site: Site::Declaration(DraftHandle::new("newroot")), + }]), + "{rootless:?}" + ); + + // The owner is unconfined, and the identical rootless patch commits — + // once it answers something the kernel derives. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("newroot"), + label: "A New Country".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(clockwork.dead_end)), + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + } + + /// Verification 17: seed admission and boundary elaboration reach one + /// reducer. The same structural defect returns the same complete set on + /// both lanes. + #[test] + fn seed_admission_and_boundary_elaboration_reach_one_reducer() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "OneReducer"); + let answered = dead_end_boundary(&kernel); + let dangling = |handle: &str| WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: "The Nowhere Shed".into(), + kind: EntityKind::Place, + container: Some(Ref::Draft(DraftHandle::new("nothing"))), + })], + operations: Vec::new(), + evidence: Vec::new(), + }; + let snapshot = kernel.snapshot().unwrap(); + let owner_error = kernel + .submit( + command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch: dangling("shed"), + }, + ), + &auth_principal(owner()), + ) + .unwrap_err(); + let elaborator_error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch: dangling("shed"), + }, + ) + .unwrap_err(); + let set_of = |error: &KernelError| match error { + KernelError::PatchRejected(set) => set.clone(), + other => panic!("{other:?}"), + }; + assert_eq!(set_of(&owner_error), set_of(&elaborator_error)); + + // And both lanes commit the sound patch through the one writer. + submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: shed_under(clockwork.dead_end, "shed"), + }, + ) + .expect("the elaborated patch commits"); + } + + /// `reduce` decides and `apply_effect` re-decides: a hand-built effect with + /// a jurisdiction that does not cover its answer never applies. + #[test] + fn apply_effect_re_decides_elaborator_authority() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, clockwork, _) = clock_kernel(directory.path(), "Redecide"); + let answered = dead_end_boundary(&kernel); + let hall = kernel.state.entities[&clockwork.yard].container.unwrap(); + let command_id = CommandId::issue(); + let resolved = patch::resolve_patch( + &kernel.state, + command_id, + &shed_under(clockwork.dead_end, "shed"), + None, + None, + ) + .expect("the patch resolves"); + let effect = WorldEffect::PatchAdmitted { + answers: Some(PatchAnswer::Boundary(answered)), + resolved, + }; + + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + command_id, + &elaborator(JurisdictionKey::PlaceSubtree(hall)), + &effect, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + assert_eq!(candidate, kernel.state); + + // The honest jurisdiction applies through the same arm. + let mut candidate = kernel.state.clone(); + apply_effect( + &mut candidate, + command_id, + &elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + &effect, + ) + .expect("the covering jurisdiction applies"); + assert_ne!(candidate, kernel.state); + } + + /// The mismatch vocabulary is kernel-internal plus controller telemetry. It + /// never enters a commit, and `verify_state_shape` never grows a clause for + /// it because no partition holds one. + #[test] + fn mismatch_never_appears_in_a_world_commit() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Separation"); + let answered = dead_end_boundary(&kernel); + submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: shed_under(clockwork.dead_end, "shed"), + }, + ) + .expect("the elaboration commits"); + + let bytes = rmp_serde::to_vec_named(&kernel.state).expect("state encodes"); + let text = String::from_utf8_lossy(&bytes); + for tag in [ + "outside_jurisdiction", + "unresolved_draft", + "no_canonical_change", + "mismatch", + ] { + assert!(!text.contains(tag), "{tag} reached world state"); + } + } + + // ---- Soul: the confinement predicate past its declaration lane ------ + + /// Confinement is claimed for every referent a jurisdictional author + /// writes, not only for declarations. An operation naming a route with one + /// endpoint outside the jurisdiction is outside, and the site it reports is + /// the operation's. + #[test] + fn soul_an_operation_naming_a_half_outside_route_is_outside_the_jurisdiction() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "OperationLane"); + let answered = dead_end_boundary(&kernel); + let revision = kernel.state.revision; + // The Field Gate runs hall -> dead end. The dead end's elaborator holds + // one of its two ends and therefore holds neither. + let mut patch = shed_under(clockwork.dead_end, "shed"); + patch.operations = vec![ComponentOp::AlterCost { + route: Ref::Existing(clockwork.gate), + cost: Cost(2), + }]; + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set == &vec![Mismatch::OutsideJurisdiction { site: Site::Operation(0) }]), + "{error:?}" + ); + assert_eq!(kernel.state.revision, revision); + + // The owner is unconfined and the identical patch commits. + let snapshot = kernel.snapshot().unwrap(); + let mut owner_patch = shed_under(clockwork.dead_end, "shed"); + owner_patch.operations = vec![ComponentOp::AlterCost { + route: Ref::Existing(clockwork.gate), + cost: Cost(2), + }]; + submit_owner( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: owner_patch, + }, + ); + } + + /// The fifth body the capability rule refuses. `ExerciseDecision` is the + /// one the existing negative omits, and it is the one a subject's lane uses. + #[test] + fn soul_an_elaborator_cannot_exercise_a_decision() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "NoExercise"); + let revision = kernel.state.revision; + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::ExerciseDecision { + opportunity: opportunity_for(&active, clockwork.reeve), + invocation: DecisionInvocation { + affordance: clockwork.deliver, + bindings: Vec::new(), + proposed: Vec::new(), + speech: None, + display: None, + }, + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + assert_eq!(kernel.state.revision, revision); + } + + /// Two boundaries under two disjoint roots, opened by one owner patch. + /// Answering one leaves the other derived with its digest unmoved, so the + /// second elaborator commits afterwards at a later revision. Answering the + /// first a second time is not derived. + #[test] + fn soul_disjoint_boundaries_commit_independently_and_a_spent_answer_is_not_derived() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Disjoint"); + let road = dead_end_boundary(&kernel); + let hall = kernel.state.entities[&clockwork.yard] + .container + .expect("the yard sits in the hall"); + + // One unconfined patch answers the road and opens one dead end under + // each root: a cellar under the yard, an annex off the road. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(road)), + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("cellar"), + label: "The Yard Cellar".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(clockwork.yard)), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("hatch"), + label: "The Cellar Hatch".into(), + from: Ref::Existing(clockwork.yard), + to: Ref::Draft(DraftHandle::new("cellar")), + access: AccessKind::Public, + cost: Cost(1), + }), + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("annex"), + label: "The Road Annex".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(clockwork.dead_end)), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("spur"), + label: "The Road Spur".into(), + from: Ref::Existing(clockwork.dead_end), + to: Ref::Draft(DraftHandle::new("annex")), + access: AccessKind::Public, + cost: Cost(1), + }), + ], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + + let place_named = |kernel: &WorldKernel, label: &str| { + kernel + .state + .entities + .iter() + .find(|(_, entity)| entity.label == label) + .map(|(id, _)| *id) + .expect("the declared place") + }; + let cellar = place_named(&kernel, "The Yard Cellar"); + let annex = place_named(&kernel, "The Road Annex"); + let boundary_at = |kernel: &WorldKernel, place: EntityId| { + derive_boundaries(&kernel.state) + .unwrap() + .into_iter() + .find(|boundary| { + matches!(boundary, CausalBoundary::UnelaboratedDestination { place: at, .. } if *at == place) + }) + .unwrap_or_else(|| panic!("no boundary at {place:?}")) + }; + // Both are derived at the same revision, and both are read before + // either is answered. + let cellar_answer = boundary_at(&kernel, cellar); + let annex_answer = boundary_at(&kernel, annex); + + submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(hall)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(cellar_answer.clone())), + patch: shed_under(cellar, "crock"), + }, + ) + .expect("the hall's elaborator answers the cellar"); + let after_first = kernel.state.revision; + + // The other root's answer is untouched by that commit: same value, + // same digest, still derived. + assert!( + derive_boundaries(&kernel.state) + .unwrap() + .contains(&annex_answer) + ); + submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(annex_answer)), + patch: shed_under(annex, "barrow"), + }, + ) + .expect("the road's elaborator answers the annex"); + assert!(kernel.state.revision > after_first); + + // The spent answer is a value nothing derives any more. + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(hall)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(cellar_answer)), + patch: shed_under(cellar, "second_crock"), + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::AnswerNotDerived), "{error:?}"); + } + + /// The third structural bound, reached through the elaborator lane: the + /// answer must be derived, every write must be inside the jurisdiction, and + /// the answer must stop being derived after the write. + #[test] + fn soul_an_elaborator_patch_that_does_not_satisfy_its_answer_is_refused() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Unsatisfied"); + let road = dead_end_boundary(&kernel); + let hall = kernel.state.entities[&clockwork.yard] + .container + .expect("the yard sits in the hall"); + + // One owner patch answers the road and opens a cellar dead end inside + // the hall, so the hall's elaborator has an answer it covers and a + // legal write that does not satisfy it. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(road)), + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("shed"), + label: "The Roadside Shed".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(clockwork.dead_end)), + }), + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("cellar"), + label: "The Yard Cellar".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(clockwork.yard)), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("hatch"), + label: "The Cellar Hatch".into(), + from: Ref::Existing(clockwork.yard), + to: Ref::Draft(DraftHandle::new("cellar")), + access: AccessKind::Public, + cost: Cost(1), + }), + ], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + let cellar = kernel + .state + .entities + .iter() + .find(|(_, entity)| entity.label == "The Yard Cellar") + .map(|(id, _)| *id) + .expect("the declared cellar"); + let cellar_answer = derive_boundaries(&kernel.state) + .unwrap() + .into_iter() + .find(|boundary| { + matches!(boundary, CausalBoundary::UnelaboratedDestination { place, .. } if *place == cellar) + }) + .expect("the cellar is a dead end"); + let revision = kernel.state.revision; + + // Inside the hall, so confinement passes; nowhere near the cellar, so + // the answered boundary is still derived after the write. + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(hall)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(cellar_answer.clone())), + patch: shed_under(clockwork.yard, "yardshed"), + }, + ) + .unwrap_err(); + assert!( + matches!(error, KernelError::AnswerNotSatisfied), + "{error:?}" + ); + assert_eq!(kernel.state.revision, revision); + assert!( + derive_boundaries(&kernel.state) + .unwrap() + .contains(&cellar_answer), + "a refused patch left the boundary derived" + ); + + // The same author satisfying the same answer commits. + submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(hall)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(cellar_answer.clone())), + patch: shed_under(cellar, "crock"), + }, + ) + .expect("the satisfying patch commits"); + assert!( + !derive_boundaries(&kernel.state) + .unwrap() + .contains(&cellar_answer) + ); + } + + /// Pass 6's rule survives the ungating of `EvidenceRef::new`: a canonical + /// fact still needs its receipt listed on the patch that declares it, and an + /// elaborator gets the same refusal the owner does. + #[test] + fn soul_an_elaborator_cannot_mint_a_canonical_fact_without_a_listed_receipt() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Provenance"); + let answered = dead_end_boundary(&kernel); + let revision = kernel.state.revision; + let mut patch = shed_under(clockwork.dead_end, "shed"); + patch.declarations.push(Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("flood"), + label: "The Flooded Hinge".into(), + statement: Statement::new("The lower hinge flooded.").expect("a canonical statement"), + standing: FactStandingRef::Canonical { + evidence: EvidenceRef::new("vault:forged"), + }, + })); + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::FactWithoutEvidence { + handle: DraftHandle::new("flood"), + })), + "{error:?}" + ); + assert_eq!(kernel.state.revision, revision); + } + + // ---- Cut 3: the play authority, `Ruled` facts and `Mint` ----------- + + fn play_caller() -> CallerId { + CallerId::System(SystemCapability::Play) + } + + fn ruled_fact_patch(handle: &str) -> WorldPatch { + WorldPatch { + declarations: vec![Declaration::Fact(FactDeclaration { + handle: DraftHandle::new(handle), + label: "The Ruling".into(), + statement: Statement::new("Stated by the table.").unwrap(), + standing: FactStandingRef::Ruled, + })], + operations: Vec::new(), + evidence: Vec::new(), + } + } + + fn resource_named(kernel: &WorldKernel, label: &str) -> EntityId { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .map(|(id, _)| id) + .expect("the declared resource") + } + + /// Invariant 5, first half, and P3.1: the play authority declares in + /// Active with no answer. + #[test] + fn the_play_authority_declares_in_active_without_an_answer() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PlayDeclares"); + let receipt = submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch: shed_under(clockwork.dead_end, "play-shed"), + }, + ) + .expect("the play authority declares unanswered in Active"); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + } + + /// Invariant 5, second half: the elaborator gate is unchanged. + #[test] + fn an_elaborator_declaration_in_active_without_an_answer_is_still_refused() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "ElaboratorUnanswered"); + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: None, + patch: shed_under(clockwork.dead_end, "shed"), + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::AnswerRequired), "{error:?}"); + } + + /// Invariant 5, second half: the owner's own gate is unchanged too. Only + /// `Play` is exempted from `AnswerRequired`. + #[test] + fn the_owner_still_cannot_declare_unanswered_in_active() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "OwnerUnanswered"); + let snapshot = kernel.snapshot().unwrap(); + let error = kernel + .submit( + command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: None, + patch: shed_under(clockwork.dead_end, "shed"), + }, + ), + &auth_principal(owner()), + ) + .unwrap_err(); + assert!(matches!(error, KernelError::AnswerRequired), "{error:?}"); + } + + /// Invariant 5: the play authority reaches the whole world, unconfined to + /// a ground. Writing under a place no jurisdiction covers, with no + /// answer, is exactly what an elaborator or the owner cannot do. + #[test] + fn the_play_authority_is_unconfined() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PlayUnconfined"); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch: shed_under(clockwork.dead_end, "unconfined-shed"), + }, + ) + .expect("the play authority is confined to no ground"); + } + + /// P3.6: the play authority cannot act in Draft. + #[test] + fn the_play_authority_is_refused_in_draft() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "PlayDraft"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let commons = kernel.snapshot().unwrap().places[0].id; + let error = submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch: shed_under(commons, "shed"), + }, + ) + .unwrap_err(); + assert!( + matches!( + error, + KernelError::WrongPhase { + expected: WorldPhase::Active, + actual: WorldPhase::Draft, + } + ), + "{error:?}" + ); + } + + /// Invariant 5: the play authority advances time, the clock's precedent. + #[test] + fn the_play_authority_advances_time() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, _clockwork, active) = clock_kernel(directory.path(), "PlayClock"); + let receipt = submit_as( + &mut kernel, + play_caller(), + CommandBody::AdvanceTime { + minutes: minutes(30), + }, + ) + .expect("the play authority advances time"); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(kernel.state.now > active.now); + } + + /// P3.6: the play authority may not approve, activate, exercise, or + /// decline. `require_system_capability`, at the top of `reduce`, refuses + /// all four before any body-specific arm is read. + #[test] + fn the_play_authority_cannot_approve_activate_exercise_or_decline() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "PlayForbidden"); + let opportunity = opportunity_for(&active, clockwork.reeve); + let forbidden = [ + CommandBody::ApproveDraft, + CommandBody::ActivateWorld, + CommandBody::ExerciseDecision { + opportunity: opportunity.clone(), + invocation: DecisionInvocation { + affordance: clockwork.deliver, + bindings: Vec::new(), + proposed: Vec::new(), + speech: None, + display: None, + }, + }, + CommandBody::DeclineDecision { + opportunity: opportunity.clone(), + }, + ]; + for body in &forbidden { + let error = submit_as(&mut kernel, play_caller(), body.clone()).unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + } + // The end-to-end check above cannot tell "refused before any + // body-specific arm is read" apart from a downstream refusal that + // would fail Play just as closed (`require_owner`, for one, refuses + // every non-owner caller regardless of what admitted it). Pin + // `require_system_capability` directly, so widening its table for + // `Play` is caught even though every arm behind it still happens to + // refuse `Play` on its own. + for body in &forbidden { + assert!( + matches!( + require_system_capability(&play_caller(), body), + Err(KernelError::Unauthorized) + ), + "require_system_capability admitted {body:?} for the play authority" + ); + } + } + + /// P3.4: a ruled fact is world truth to every subject that knows it. + #[test] + fn the_play_authority_rules_a_fact_and_a_witness_knows_it_as_canon() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PlayRules"); + let mut patch = ruled_fact_patch("verdict"); + patch.operations.push(ComponentOp::AcquireKnowledge { + subject: Ref::Existing(clockwork.reeve), + fact: Ref::Draft(DraftHandle::new("verdict")), + source: AuthoredSource::Witnessed, + confidence: Confidence::Certain, + }); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch, + }, + ) + .expect("the play authority rules a fact and grants it as knowledge"); + + let fact = *kernel + .state + .facts + .iter() + .find(|(_, record)| record.statement.as_str() == "Stated by the table.") + .map(|(id, _)| id) + .expect("the ruled fact"); + assert_eq!(kernel.state.facts[&fact].standing, FactStanding::Ruled); + + let snapshot = kernel.snapshot().unwrap(); + let subject = snapshot + .subjects + .iter() + .find(|subject| subject.id == clockwork.reeve) + .expect("the reeve's snapshot"); + let known = subject + .knowledge + .iter() + .find(|held| held.fact == fact) + .expect("the reeve knows the ruled fact"); + assert_eq!(known.standing, FactStandingView::Canonical); + } + + /// P3.5: minted quantity balances the ledger, and replay reproduces it. + #[test] + fn the_play_authority_mints_and_the_ledger_balances() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (world_id, reeve, grain) = { + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PlayMints"); + let grain = resource_named(&kernel, "Winter Grain"); + let before = held(&kernel.state, clockwork.reeve, grain); + assert_eq!(before, 0); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Mint { + holder: Ref::Existing(clockwork.reeve), + resource: Ref::Existing(grain), + qty: Quantity(7), + }], + evidence: Vec::new(), + }, + }, + ) + .expect("the play authority mints"); + let after = held(&kernel.state, clockwork.reeve, grain); + assert_eq!(before + 7, after); + (kernel.state.world_id, clockwork.reeve, grain) + }; + let replayed = WorldKernel::open(&path, world_id).expect("the minted store replays"); + assert_eq!(held(&replayed.state, reeve, grain), 7); + } + + /// The evidenced-knowledge clause is unchanged: a receipt cannot vouch for + /// an assertion the kernel never evaluated, and a `Ruled` fact is exactly + /// such an assertion. + #[test] + fn a_ruled_fact_cannot_be_known_evidenced() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PlayEvidenced"); + let mut patch = ruled_fact_patch("verdict"); + patch.operations.push(ComponentOp::AcquireKnowledge { + subject: Ref::Existing(clockwork.reeve), + fact: Ref::Draft(DraftHandle::new("verdict")), + source: AuthoredSource::Evidenced, + confidence: Confidence::Certain, + }); + let error = submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::EvidencedKnowledgeOfClaim { operation: 0 })), + "{error:?}" + ); + } + + /// The evidence gate on `Canonical` facts and `Admit` is byte-for-byte the + /// same predicate at the same sites for every author, `Play` included + /// (P3.3). `Play` carries no receipts, so its `Admit` is refused like + /// anyone's without one. + #[test] + fn the_evidence_gate_is_unchanged_for_every_author() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PlayEvidenceGate"); + let grain = resource_named(&kernel, "Winter Grain"); + + // Without a receipt: `Play`'s `Admit` is refused exactly as anyone's. + let error = submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Admit { + holder: Ref::Existing(clockwork.reeve), + resource: Ref::Existing(grain), + qty: Quantity(1), + evidence: EvidenceRef::new("vault:uncited"), + }], + evidence: Vec::new(), + }, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::AdmitWithoutEvidence { operation: 0 })), + "{error:?}" + ); + + // With the receipt cited in the same patch, `Play`'s `Admit` is + // admitted like anyone unconfined's. + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Admit { + holder: Ref::Existing(clockwork.reeve), + resource: Ref::Existing(grain), + qty: Quantity(1), + evidence: EvidenceRef::new("vault:cited"), + }], + evidence: vec![EvidenceRef::new("vault:cited")], + }, + }, + ) + .expect("an evidenced admit is admitted for the play authority too"); + + // PA.f29a: the owner in Draft — the seed's caller. + { + let seed_directory = tempfile::tempdir().unwrap(); + let (mut seed_kernel, _) = WorldKernel::create( + seed_directory.path().join("world.cc"), + creation(CommandId::new(), "OwnerDraftEvidence"), + &auth_principal(owner()), + ) + .expect("a created world"); + let fact = |evidence: &str| { + Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("draft-fact"), + label: "The Draft Count".into(), + statement: Statement::new("The draft is counted.").unwrap(), + standing: FactStandingRef::Canonical { + evidence: EvidenceRef::new(evidence), + }, + }) + }; + let snapshot = seed_kernel.snapshot().unwrap(); + let uncited = seed_kernel + .submit( + command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![fact("vault:draft-uncited")], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ), + &auth_principal(owner()), + ) + .unwrap_err(); + assert!( + matches!(&uncited, KernelError::PatchRejected(set) + if set.contains(&Mismatch::FactWithoutEvidence { + handle: DraftHandle::new("draft-fact"), + })), + "{uncited:?}" + ); + let snapshot = seed_kernel.snapshot().unwrap(); + seed_kernel + .submit( + command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![fact("vault:draft-cited")], + operations: Vec::new(), + evidence: vec![EvidenceRef::new("vault:draft-cited")], + }, + }, + ), + &auth_principal(owner()), + ) + .expect("a cited canonical fact is admitted for the owner in Draft"); + } + + // PA.f29a: the owner in Active, with a real answer. Its own + // `clock_kernel`, so the boundary this answers is not the one the + // Play blocks above already left cleared. The cited patch also + // seats a fresh occupant at the dead end: what actually clears an + // `UnelaboratedDestination` boundary ("a commit clears exactly the + // boundary it answers"), so the citation succeeding is not + // masked by an `AnswerNotSatisfied` refusal. + { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "OwnerActiveEvidence"); + let answered = dead_end_boundary(&kernel); + let speak = super::tests::speak_entry(&kernel); + let fact = |evidence: &str| { + Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("active-fact"), + label: "The Active Count".into(), + statement: Statement::new("The active count stands.").unwrap(), + standing: FactStandingRef::Canonical { + evidence: EvidenceRef::new(evidence), + }, + }) + }; + let error = submit_as( + &mut kernel, + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch: WorldPatch { + declarations: vec![fact("vault:active-uncited")], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::FactWithoutEvidence { + handle: DraftHandle::new("active-fact"), + })), + "{error:?}" + ); + submit_as( + &mut kernel, + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: WorldPatch { + declarations: vec![ + fact("vault:active-cited"), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("wanderer"), + label: "The Owner's Wanderer".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([speak]), + position: Some(Ref::Existing(clockwork.dead_end)), + import_key: None, + }), + ], + operations: Vec::new(), + evidence: vec![EvidenceRef::new("vault:active-cited")], + }, + }, + ) + .expect("a cited canonical fact is admitted for the owner in Active"); + } + + // PA.f29a: an answered elaborator. Its own `clock_kernel` for the + // same reason. The occupant the cited patch seats at the dead end + // is inside the elaborator's own `PlaceSubtree` jurisdiction, so + // `confine_to_ground` admits it the same as the fact. + { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = + clock_kernel(directory.path(), "ElaboratorEvidence"); + let answered = dead_end_boundary(&kernel); + let speak = super::tests::speak_entry(&kernel); + let caller = elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)); + let fact = |evidence: &str| { + Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("elaborator-fact"), + label: "The Elaborator Count".into(), + statement: Statement::new("The elaborator count stands.").unwrap(), + standing: FactStandingRef::Canonical { + evidence: EvidenceRef::new(evidence), + }, + }) + }; + let error = submit_as( + &mut kernel, + caller.clone(), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch: WorldPatch { + declarations: vec![fact("vault:elaborator-uncited")], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::FactWithoutEvidence { + handle: DraftHandle::new("elaborator-fact"), + })), + "{error:?}" + ); + submit_as( + &mut kernel, + caller, + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: WorldPatch { + declarations: vec![ + fact("vault:elaborator-cited"), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("wanderer"), + label: "The Elaborator's Wanderer".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([speak]), + position: Some(Ref::Existing(clockwork.dead_end)), + import_key: None, + }), + ], + operations: Vec::new(), + evidence: vec![EvidenceRef::new("vault:elaborator-cited")], + }, + }, + ) + .expect("a cited canonical fact is admitted for an answered elaborator"); + } + + // PA.f29a: a consumer, on its own mirror. A consumer cannot canonize + // (confine_to_ground refuses `Canonical` for consumer ground + // outright), so this exercises the same gate through `Admit` + // instead. In Draft, where `require_answer` asks nothing of anyone, + // so this is the evidence gate alone and not entangled with a + // consumer's inability to ever clear a place-shaped boundary (a + // consumer touches no place at all). + { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "ConsumerMirrorEvidence"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let commons = *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "The Commons") + .expect("the declared commons") + .0; + let grain = { + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("grain"), + label: "Consumer Grain".into(), + kind: EntityKind::Resource, + container: None, + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "Consumer Grain") + .expect("the declared resource") + .0 + }; + let consumer_id = ConsumerId::of_name("clock-mirror-consumer"); + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("mirror"), + label: "The Clockwork Mirror".into(), + kind: SubjectKind::Institution, + controller: NewController::External { + consumer: consumer_id, + }, + affordances: BTreeSet::new(), + position: Some(Ref::Existing(commons)), + import_key: None, + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + let mirror = *kernel + .state + .subjects + .iter() + .find(|(_, subject)| subject.label == "The Clockwork Mirror") + .expect("the declared mirror") + .0; + let consumer_caller = CallerId::System(SystemCapability::Consumer { + consumer: consumer_id, + }); + + let error = submit_as( + &mut kernel, + consumer_caller.clone(), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Admit { + holder: Ref::Existing(mirror), + resource: Ref::Existing(grain), + qty: Quantity(1), + evidence: EvidenceRef::new("vault:mirror-uncited"), + }], + evidence: Vec::new(), + }, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::AdmitWithoutEvidence { operation: 0 })), + "{error:?}" + ); + + submit_as( + &mut kernel, + consumer_caller, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Admit { + holder: Ref::Existing(mirror), + resource: Ref::Existing(grain), + qty: Quantity(1), + evidence: EvidenceRef::new("vault:mirror-cited"), + }], + evidence: vec![EvidenceRef::new("vault:mirror-cited")], + }, + }, + ) + .expect("a cited admit is admitted for a consumer on its own mirror"); + } + } + + /// `reduce` decides and `apply_effect` re-decides: a forged + /// `PatchAdmitted` under an elaborator caller, carrying a `Mint` the + /// resolver would accept (the resolver is actor-blind) and that fully + /// satisfies confinement (the minted subject is declared inside the + /// elaborator's own jurisdiction), is still refused at apply. `Mint` + /// carries no confinement veto of its own — unlike a `Ruled` fact, + /// `confine_to_ground` has no redundant clause for it — so only + /// `require_ruler`'s re-decision can be refusing this. Follows + /// `apply_effect_re_decides_elaborator_authority`. + #[test] + fn apply_effect_re_decides_the_ruler() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, clockwork, _) = clock_kernel(directory.path(), "RedecideRulerMint"); + let answered = dead_end_boundary(&kernel); + let speak = super::tests::speak_entry(&kernel); + let command_id = CommandId::issue(); + let patch = WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("loot"), + label: "Roadside Loot".into(), + kind: EntityKind::Resource, + container: None, + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("finder"), + label: "The Roadside Finder".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([speak]), + position: Some(Ref::Existing(clockwork.dead_end)), + import_key: None, + }), + ], + operations: vec![ComponentOp::Mint { + holder: Ref::Draft(DraftHandle::new("finder")), + resource: Ref::Draft(DraftHandle::new("loot")), + qty: Quantity(4), + }], + evidence: Vec::new(), + }; + let resolved = patch::resolve_patch(&kernel.state, command_id, &patch, None, None) + .expect("the patch resolves; the resolver is actor-blind"); + let effect = WorldEffect::PatchAdmitted { + answers: Some(PatchAnswer::Boundary(answered)), + resolved, + }; + + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + command_id, + &elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + &effect, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + assert_eq!(candidate, kernel.state); + + let mut candidate = kernel.state.clone(); + apply_effect(&mut candidate, command_id, &play_caller(), &effect) + .expect("the play authority applies through the same arm"); + assert_ne!(candidate, kernel.state); + } + + /// PA.f27a: the owner is a `CallerId::Principal` like any other, and + /// `apply_effect`'s re-decision of `require_ruler` carries no exemption + /// for that variant. A forged `PatchAdmitted` under the owner, carrying + /// a `Ruled` fact the resolver accepts (actor-blind) and that fully + /// satisfies confinement (the owner is unconfined), is still refused at + /// apply. Follows `apply_effect_re_decides_the_ruler`. + #[test] + fn apply_effect_re_decides_the_ruler_for_the_owner_too() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, _, _) = clock_kernel(directory.path(), "RedecideRulerOwner"); + let answered = dead_end_boundary(&kernel); + let command_id = CommandId::issue(); + let patch = ruled_fact_patch("rule"); + let resolved = patch::resolve_patch(&kernel.state, command_id, &patch, None, None) + .expect("the patch resolves; the resolver is actor-blind"); + let effect = WorldEffect::PatchAdmitted { + answers: Some(PatchAnswer::Boundary(answered)), + resolved, + }; + + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + command_id, + &CallerId::Principal(owner()), + &effect, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + assert_eq!(candidate, kernel.state); + } + + /// PA.f27b: `require_ruler` walks every operation, not only the first. + /// A harmless `Relocate` at index 0 followed by a `Mint` at index 1, + /// from a non-`Play` author, is refused at index 1. Kills a scan + /// narrowed to `.take(1)`. + #[test] + fn require_ruler_catches_a_mint_past_the_first_operation() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RulerScansEveryOp"); + let grain = resource_named(&kernel, "Winter Grain"); + let stair = *kernel + .state + .edges + .iter() + .find(|(_, record)| record.label() == "The Yard Stair") + .expect("the declared route") + .0; + let snapshot = kernel.snapshot().unwrap(); + let Err(error) = kernel.submit( + command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + operations(vec![ + ComponentOp::Relocate { + subject: Ref::Existing(clockwork.reeve), + via: Ref::Existing(stair), + }, + ComponentOp::Mint { + holder: Ref::Existing(clockwork.reeve), + resource: Ref::Existing(grain), + qty: Quantity(4), + }, + ]), + ), + &auth_principal(owner()), + ) else { + panic!("a non-Play Mint past the first operation was admitted"); + }; + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RuledWithoutAuthority { + site: patch::Site::Operation(1), + })), + "{error:?}" + ); + } + + /// PA.f27c: `require_ruler` reports every `Ruled` declaration, not only + /// the first. Two `Ruled` facts from a non-`Play` author are both + /// reported. Kills a check narrowed to the first ruled fact. + #[test] + fn require_ruler_reports_every_ruled_fact() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "RulerScansEveryFact"), + &auth_principal(owner()), + ) + .expect("a created world"); + let snapshot = kernel.snapshot().unwrap(); + let mut patch = ruled_fact_patch("first-rule"); + patch.declarations.push(Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("second-rule"), + label: "The Second Ruling".into(), + statement: Statement::new("Stated by the table, again.").unwrap(), + standing: FactStandingRef::Ruled, + })); + let Err(error) = kernel.submit( + command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: None, + patch, + }, + ), + &auth_principal(owner()), + ) else { + panic!("two non-Play Ruled facts were admitted"); + }; + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RuledWithoutAuthority { + site: patch::Site::Declaration(DraftHandle::new("first-rule")), + }) && set.contains(&Mismatch::RuledWithoutAuthority { + site: patch::Site::Declaration(DraftHandle::new("second-rule")), + })), + "{error:?}" + ); + } + + /// P3.5, replay half, folded with a ruled fact: reopening the journal + /// reproduces both across the digest. + #[test] + fn a_journal_holding_a_ruled_fact_and_a_mint_replays() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (world_id, expected) = { + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PlayReplay"); + let grain = resource_named(&kernel, "Winter Grain"); + let mut patch = ruled_fact_patch("verdict"); + patch.operations.push(ComponentOp::Mint { + holder: Ref::Existing(clockwork.farmer), + resource: Ref::Existing(grain), + qty: Quantity(2), + }); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch, + }, + ) + .expect("the play authority rules and mints in one patch"); + (kernel.state.world_id, kernel.snapshot().unwrap()) + }; + let replayed = WorldKernel::open(&path, world_id).expect("the store replays"); + assert_eq!(replayed.snapshot().unwrap(), expected); + drop(replayed); + let replayed_again = + WorldKernel::open(&path, world_id).expect("the store replays a second time"); + assert_eq!(replayed_again.snapshot().unwrap(), expected); + } + + // ---- Cut 4: retirement ------------------------------------------- + + fn retire_patch(subject: SubjectId) -> WorldPatch { + WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Retire { + subject: Ref::Existing(subject), + }], + evidence: Vec::new(), + } + } + + /// The owner retires a subject in Active. `retire_patch` declares + /// nothing and cites no evidence, so `require_answer`'s `declares` gate + /// never opens for it and no answer is needed, exactly as an owner's + /// ordinary bare operation needs none. + fn owner_retires(kernel: &mut WorldKernel, subject: SubjectId) -> Result<SubmitReceipt, KernelError> { + submit_as( + kernel, + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: None, + patch: retire_patch(subject), + }, + ) + } + + /// Declares a mirror bound to a consumer this test invents, at the yard, + /// via the owner in Active. Shared by the retirement and grant tests that + /// need a subject `mode()` already excludes. + fn declare_mirror(kernel: &mut WorldKernel, clockwork: &Clockwork, name: &str) -> SubjectId { + let answered = dead_end_boundary(kernel); + submit_as( + kernel, + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: WorldPatch { + declarations: vec![Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("mirror"), + label: "The Bound Hold".into(), + kind: SubjectKind::Institution, + controller: NewController::External { + consumer: ConsumerId::of_name(name), + }, + affordances: BTreeSet::new(), + // At the dead end, so this declaration also clears + // the boundary its own answer claims: an occupied + // place is no longer unelaborated. + position: Some(Ref::Existing(clockwork.dead_end)), + import_key: None, + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ) + .expect("the owner declares a mirror in Active"); + kernel + .snapshot() + .unwrap() + .subjects + .iter() + .find(|subject| subject.label == "The Bound Hold") + .expect("the declared mirror") + .id + } + + /// P4.1, replay half: reopening the journal reproduces a retirement — + /// no opportunity and `retired` both survive the round trip. + #[test] + fn a_retired_subject_holds_no_opportunity_across_a_replay() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (world_id, reeve) = { + let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "RetireReplay"); + assert!( + active + .opportunities + .iter() + .any(|opportunity| opportunity.scope.subject_id == clockwork.reeve), + "the reeve holds an opportunity before retirement" + ); + owner_retires(&mut kernel, clockwork.reeve).expect("the owner retires the reeve"); + (kernel.state.world_id, clockwork.reeve) + }; + let replayed = WorldKernel::open(&path, world_id).expect("the store replays"); + let snapshot = replayed.snapshot().unwrap(); + assert!( + !snapshot + .opportunities + .iter() + .any(|opportunity| opportunity.scope.subject_id == reeve), + "a replayed retired subject holds no opportunity" + ); + let subject = snapshot + .subjects + .iter() + .find(|subject| subject.id == reeve) + .expect("the retired subject's own row"); + assert!(subject.retired); + } + + /// P4.1: a retired subject's last opportunity is stale, not honoured. + #[test] + fn a_retired_subject_cannot_act() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "RetireCannotAct"); + let opportunity = opportunity_for(&active, clockwork.reeve); + owner_retires(&mut kernel, clockwork.reeve).expect("the owner retires the reeve"); + let error = submit_as( + &mut kernel, + CallerId::Controller(opportunity.controller_id), + CommandBody::DeclineDecision { opportunity }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::OpportunityMismatch), "{error:?}"); + } + + /// P4.1: no position, so a witness at the retired subject's former place + /// never reaches it, while a still-present subject at the same place + /// does. + #[test] + fn a_retired_subject_hears_nothing() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RetireHearsNothing"); + owner_retires(&mut kernel, clockwork.reeve).expect("the owner retires the reeve"); + let mut patch = ruled_fact_patch("news"); + patch.operations.push(ComponentOp::Witness { + fact: Ref::Draft(DraftHandle::new("news")), + place: Ref::Existing(clockwork.yard), + confidence: Confidence::Certain, + }); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch, + }, + ) + .expect("the play authority witnesses at the yard"); + let snapshot = kernel.snapshot().unwrap(); + let reeve = snapshot + .subjects + .iter() + .find(|subject| subject.id == clockwork.reeve) + .expect("the retired reeve's own row"); + assert!(reeve.knowledge.is_empty(), "{:?}", reeve.knowledge); + let farmer = snapshot + .subjects + .iter() + .find(|subject| subject.id == clockwork.farmer) + .expect("the farmer's own row"); + assert!(!farmer.knowledge.is_empty(), "the farmer still hears it"); + } + + /// P4.2: events, knowledge, holdings, and commitments all survive + /// retirement untouched. + #[test] + fn a_retired_subject_keeps_its_history() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RetireKeepsHistory"); + let before_holdings = kernel.state.holdings.get(&clockwork.farmer).cloned(); + let before_commitments = kernel.state.commitments.get(&clockwork.farmer).cloned(); + assert!(before_holdings.is_some()); + assert!(before_commitments.is_some()); + owner_retires(&mut kernel, clockwork.farmer).expect("the owner retires the farmer"); + assert_eq!( + kernel.state.holdings.get(&clockwork.farmer).cloned(), + before_holdings + ); + assert_eq!( + kernel.state.commitments.get(&clockwork.farmer).cloned(), + before_commitments + ); + assert!(kernel.state.subjects.contains_key(&clockwork.farmer)); + } + + /// P4.1: retiring twice is `NoOperationEffect`, not a second retirement. + #[test] + fn retiring_twice_is_no_effect() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RetireTwice"); + owner_retires(&mut kernel, clockwork.reeve).expect("the first retirement commits"); + let error = owner_retires(&mut kernel, clockwork.reeve).unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::NoOperationEffect { operation: 0 })), + "{error:?}" + ); + } + + /// P4.3: a mirror is owned by another world; this one cannot retire it. + #[test] + fn a_mirror_cannot_be_retired() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RetireMirror"); + let mirror = declare_mirror(&mut kernel, &clockwork, "cut4-retire-mirror"); + let error = owner_retires(&mut kernel, mirror).unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RetiresAMirror { operation: 0 })), + "{error:?}" + ); + } + + /// P4.3: `confine_to_ground` refuses a `Retire` for a confined author + /// unconditionally, even for a subject this same patch declares and + /// places inside the elaborator's own jurisdiction. + #[test] + fn an_elaborator_cannot_retire_inside_its_jurisdiction() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RetireElaborator"); + let speak = super::tests::speak_entry(&kernel); + let answered = dead_end_boundary(&kernel); + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: WorldPatch { + declarations: vec![Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("stray"), + label: "The Roadside Stray".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([speak]), + position: Some(Ref::Existing(clockwork.dead_end)), + import_key: None, + })], + operations: vec![ComponentOp::Retire { + subject: Ref::Draft(DraftHandle::new("stray")), + }], + evidence: Vec::new(), + }, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::OutsideJurisdiction { + site: Site::Operation(0) + })), + "{error:?}" + ); + } + + /// P4.3: the owner and the play authority are the two callers a + /// `Retire` admits. + #[test] + fn the_owner_and_the_play_authority_may_retire() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RetireOwnerAndPlay"); + owner_retires(&mut kernel, clockwork.reeve).expect("the owner retires the reeve"); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch: retire_patch(clockwork.farmer), + }, + ) + .expect("the play authority retires the farmer"); + let snapshot = kernel.snapshot().unwrap(); + assert!( + snapshot + .subjects + .iter() + .find(|subject| subject.id == clockwork.reeve) + .unwrap() + .retired + ); + assert!( + snapshot + .subjects + .iter() + .find(|subject| subject.id == clockwork.farmer) + .unwrap() + .retired + ); + } + + // ---- Cut 5: granting and revoking affordances --------------------- + + fn wave_affordance() -> Declaration { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("wave"), + kind: AffordanceKindName("wave".into()), + roles: vec![RoleSpec { + role: Role("target".into()), + kind: RefKind::Subject(None), + }], + preconditions: Vec::new(), + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::AdvancePressure { + by: PressureMagnitude(1), + }, + roles: vec![Role("target".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }) + } + + /// P5.1: the seed lane is the owner in Draft, and it grants the player a + /// verb the same way any owner-authored `GrantAffordance` does. + #[test] + fn the_seed_grants_the_player_a_verb_in_draft() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "SeedGrantsDraft"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let before = kernel.snapshot().unwrap(); + let commons = before.places[0].id; + let speak = super::tests::speak_entry(&kernel); + submit_owner( + &mut kernel, + &before, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![ + wave_affordance(), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("player"), + label: "The Player".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([speak]), + position: Some(Ref::Existing(commons)), + import_key: None, + }), + ], + operations: vec![ComponentOp::GrantAffordance { + subject: Ref::Draft(DraftHandle::new("player")), + affordance: Ref::Draft(DraftHandle::new("wave")), + }], + evidence: Vec::new(), + }, + }, + ); + let snapshot = kernel.snapshot().unwrap(); + let player = snapshot + .subjects + .iter() + .find(|subject| subject.label == "The Player") + .expect("the declared player"); + assert_eq!(player.affordances.len(), 2); + } + + /// P5.1, and the scope digest half of Q10's design: a grant and a revoke + /// in Active both move the scope digest, so a stale opportunity is + /// `ScopeChanged` rather than silently honoured. + #[test] + fn the_play_authority_grants_and_revokes_in_active() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, active) = + clock_kernel(directory.path(), "PlayGrantRevoke"); + let stale = opportunity_for(&active, clockwork.reeve); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![wave_affordance()], + operations: vec![ComponentOp::GrantAffordance { + subject: Ref::Existing(clockwork.reeve), + affordance: Ref::Draft(DraftHandle::new("wave")), + }], + evidence: Vec::new(), + }, + }, + ) + .expect("the play authority grants a new verb"); + let after_grant = kernel.snapshot().unwrap(); + assert_eq!( + after_grant + .subjects + .iter() + .find(|subject| subject.id == clockwork.reeve) + .unwrap() + .affordances + .len(), + 4 + ); + let error = submit_as( + &mut kernel, + CallerId::Controller(stale.controller_id), + CommandBody::DeclineDecision { + opportunity: stale.clone(), + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::ScopeChanged { .. }), "{error:?}"); + + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::RevokeAffordance { + subject: Ref::Existing(clockwork.reeve), + affordance: Ref::Existing(clockwork.threaten), + }], + evidence: Vec::new(), + }, + }, + ) + .expect("the play authority revokes a held verb"); + let after_revoke = kernel.snapshot().unwrap(); + let reeve = after_revoke + .subjects + .iter() + .find(|subject| subject.id == clockwork.reeve) + .unwrap(); + assert_eq!(reeve.affordances.len(), 3); + assert!(!reeve.affordances.contains(&clockwork.threaten)); + } + + /// P5.2: `derive_opportunities` requires at least one grant; a revoke + /// that would leave the reeve mute is refused before it ever reaches + /// that invariant. + #[test] + fn a_revoke_cannot_leave_a_subject_mute() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RevokeMute"); + let speak = super::tests::speak_entry(&kernel); + for affordance in [clockwork.deliver, clockwork.threaten] { + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::RevokeAffordance { + subject: Ref::Existing(clockwork.reeve), + affordance: Ref::Existing(affordance), + }], + evidence: Vec::new(), + }, + }, + ) + .expect("the play authority revokes down toward one verb"); + } + let Ref::Existing(speak_id) = speak else { + panic!("speak is a standing affordance"); + }; + let error = submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::RevokeAffordance { + subject: Ref::Existing(clockwork.reeve), + affordance: Ref::Existing(speak_id), + }], + evidence: Vec::new(), + }, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::WouldLeaveSubjectMute { operation: 0 })), + "{error:?}" + ); + } + + /// PA.f30b: the last-verb refusal for `RevokeAffordance` (P5.2) holds for + /// a `Human`-controlled subject exactly as it does for any other + /// controller kind. Kills an exemption that only checks non-`Human` + /// subjects. + #[test] + fn a_revoke_cannot_leave_a_human_subject_mute() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, _, active) = clock_kernel(directory.path(), "RevokeHumanMute"); + let human = active + .subjects + .iter() + .find(|subject| subject.controller_mode == Some(ControllerMode::Human)) + .expect("the fixture world declares a human-controlled subject"); + let speak_affordance = *human + .affordances + .iter() + .next() + .expect("the human subject holds at least the kernel speak grant"); + let error = submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::RevokeAffordance { + subject: Ref::Existing(human.id), + affordance: Ref::Existing(speak_affordance), + }], + evidence: Vec::new(), + }, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::WouldLeaveSubjectMute { operation: 0 })), + "{error:?}" + ); + } + + /// PA.f30c: `ControllerAssignment::Retired.expected_caller()` is `None` + /// — a direct unit pin so an accidental `Some` for `Retired` is caught + /// here rather than only transitively through a submission test. + #[test] + fn retired_expects_no_caller() { + assert_eq!(ControllerAssignment::Retired.expected_caller(), None); + } + + /// P5.1: `confine_to_ground` refuses `GrantAffordance` for a confined + /// author unconditionally, even for a subject this same patch declares + /// and places inside the elaborator's own jurisdiction. + #[test] + fn an_elaborator_cannot_grant() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "GrantElaborator"); + let speak = super::tests::speak_entry(&kernel); + let answered = dead_end_boundary(&kernel); + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: WorldPatch { + declarations: vec![Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("stray"), + label: "The Roadside Stray".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([speak]), + position: Some(Ref::Existing(clockwork.dead_end)), + import_key: None, + })], + operations: vec![ComponentOp::GrantAffordance { + subject: Ref::Draft(DraftHandle::new("stray")), + affordance: Ref::Existing(clockwork.threaten), + }], + evidence: Vec::new(), + }, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::OutsideJurisdiction { + site: Site::Operation(0) + })), + "{error:?}" + ); + } + + // ---- Retirement fix batch (PA.f31-PA.f35) ------------------------------ + + fn human_subject(snapshot: &WorldSnapshot) -> SubjectId { + snapshot + .subjects + .iter() + .find(|subject| subject.controller_mode == Some(ControllerMode::Human)) + .expect("the genesis human") + .id + } + + /// PA.f31: `verify_state_shape` no longer judges a `DecisionEvent` against + /// the subject's *present* controller identity. Retiring a subject that + /// has acted commits, and the history survives a full reopen-and-replay + /// (`recover` -> `verify_history` -> `verify_state_shape` for every + /// commit, per the caller census in the report). + #[test] + fn retiring_a_subject_that_acted_survives_reopen_and_replay() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let world_id = { + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf31RetireActed"); + exercise( + &mut kernel, + clockwork.reeve, + clockwork.threaten, + vec![binding("target", Target::Subject(clockwork.farmer))], + ) + .expect("the threat commits"); + owner_retires(&mut kernel, clockwork.reeve) + .expect("a subject with history can be retired"); + kernel.state.world_id + }; + let reopened = WorldKernel::open(&path, world_id).expect("the store replays"); + let retired = reopened + .snapshot() + .unwrap() + .subjects + .iter() + .find(|subject| subject.label == "The Yard Reeve") + .expect("the reeve survives replay") + .retired; + assert!(retired); + } + + /// PA.f31: revoking a verb a subject has already used commits, and the + /// event that used it survives reopen-and-replay for the same reason: the + /// grant a `DecisionEvent` rode is judged once, at commit, not re-judged + /// against the present-day grant set. + #[test] + fn revoking_a_used_verb_survives_reopen_and_replay() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let world_id = { + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf31RevokeUsed"); + exercise( + &mut kernel, + clockwork.reeve, + clockwork.threaten, + vec![binding("target", Target::Subject(clockwork.farmer))], + ) + .expect("the threat commits"); + let before = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &before, + operations(vec![ComponentOp::RevokeAffordance { + subject: Ref::Existing(clockwork.reeve), + affordance: Ref::Existing(clockwork.threaten), + }]), + ); + kernel.state.world_id + }; + let reopened = WorldKernel::open(&path, world_id).expect("the store replays"); + assert_eq!(reopened.state.events.len(), 1); + } + + /// PA.f32(a): the resolver refuses `Retire` for a `Human`-controlled + /// subject while the world is Draft, before the owner can retire the + /// human, approve alone, and activate without the human's approval. + #[test] + fn retiring_the_human_in_draft_is_refused() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "PAf32DraftRefusal"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let human = human_subject(&kernel.snapshot().unwrap()); + let error = owner_retires(&mut kernel, human).unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RetiresAnApprover { operation: 0 })), + "{error:?}" + ); + } + + /// PA.f32(b, c): once the world is Active, the human's Draft approval is + /// frozen history, so the owner may retire the human — the player's + /// subject may die — and the retire survives reopen-and-replay because + /// the journal's approval-shape check no longer re-reads the present-day + /// controller roster in Active. + #[test] + fn retiring_the_human_in_active_survives_reopen_and_replay() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (world_id, human) = { + let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "PAf32ActiveRetire"); + let _ = &clockwork; + let human = human_subject(&active); + owner_retires(&mut kernel, human).expect("the owner retires the human subject"); + (kernel.state.world_id, human) + }; + let reopened = WorldKernel::open(&path, world_id).expect("the store replays"); + let retired = reopened + .snapshot() + .unwrap() + .subjects + .iter() + .find(|subject| subject.id == human) + .expect("the human survives replay") + .retired; + assert!(retired); + } + + /// PA.f33: audience derivation (`audience()`) is the one owner of who a + /// channel reaches, so a channel may still *declare* a retired member, + /// but that member is filtered out at the one read site — it gains no + /// knowledge from a telling into that channel. + #[test] + fn channel_audience_excludes_a_retired_member() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf33Audience"); + owner_retires(&mut kernel, clockwork.reeve).expect("retire"); + let mut patch = ruled_fact_patch("news"); + patch.declarations.push(Declaration::Channel(ChannelDeclaration { + handle: DraftHandle::new("wire"), + label: "The Wire".into(), + reach: ReachRef::Subjects(BTreeSet::from([ + Ref::Existing(clockwork.reeve), + Ref::Existing(clockwork.farmer), + ])), + controller: None, + })); + patch.operations.push(ComponentOp::Communicate { + speaker: Ref::Existing(clockwork.farmer), + fact: Ref::Draft(DraftHandle::new("news")), + to: AudienceRef::Channel(Ref::Draft(DraftHandle::new("wire"))), + }); + submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { answers: None, patch }) + .expect("admitted"); + let reeve_knows = kernel + .state + .knowledge + .get(&clockwork.reeve) + .map(BTreeMap::len) + .unwrap_or(0); + assert_eq!(reeve_knows, 0, "a retired subject was an audience"); + } + + /// PA.f33: `Communicate` resolves and refuses a retired speaker with + /// `RetiredSubjectActed`, whether or not it is also that channel's + /// controller. + #[test] + fn a_retired_subject_cannot_speak_through_a_channel() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf33RetiredSpeaks"); + let mut declare = ruled_fact_patch("wire-decl"); + declare.declarations.push(Declaration::Channel(ChannelDeclaration { + handle: DraftHandle::new("wire"), + label: "The Wire".into(), + reach: ReachRef::Subjects(BTreeSet::from([ + Ref::Existing(clockwork.reeve), + Ref::Existing(clockwork.farmer), + ])), + controller: None, + })); + submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { answers: None, patch: declare }) + .expect("declare"); + owner_retires(&mut kernel, clockwork.reeve).expect("retire"); + let wire = *kernel.state.channels.keys().next().unwrap(); + let mut patch = ruled_fact_patch("news"); + patch.operations.push(ComponentOp::Communicate { + speaker: Ref::Existing(clockwork.reeve), + fact: Ref::Draft(DraftHandle::new("news")), + to: AudienceRef::Channel(Ref::Existing(wire)), + }); + let error = submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { answers: None, patch }) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RetiredSubjectActed { operation: 0 })), + "{error:?}" + ); + } + + /// PA.f33: `CanReach` is `audience().contains(target)`, so a retired + /// target fails the same precondition every other reach check now + /// respects — one statement of reach, one fix. + #[test] + fn a_retired_subject_is_unreachable_through_can_reach() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "PAf33CanReach"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (speech, _) = speech_world(&mut kernel); + owner_retires(&mut kernel, speech.listener).expect("the owner retires the listener"); + let snapshot = kernel.snapshot().unwrap(); + let opportunity = opportunity_for(&snapshot, speech.speaker); + let invocation = DecisionInvocation { + affordance: speech.whisper, + bindings: vec![binding("target", Target::Subject(speech.listener))], + proposed: Vec::new(), + speech: Some(Statement::new("Are you still there?").unwrap()), + display: None, + }; + let error = submit_as( + &mut kernel, + CallerId::Controller(opportunity.controller_id), + CommandBody::ExerciseDecision { invocation, opportunity }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::ActionRejected(set) + if set.contains(&ActionMismatch::CannotReach { precondition: 0 })), + "{error:?}" + ); + } + + /// PA.f34: `AcquireKnowledge` refuses a retired subject. + #[test] + fn a_retired_subject_cannot_acquire_knowledge() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf34Acquire"); + owner_retires(&mut kernel, clockwork.reeve).expect("retire"); + let mut patch = ruled_fact_patch("news"); + patch.operations.push(ComponentOp::AcquireKnowledge { + subject: Ref::Existing(clockwork.reeve), + fact: Ref::Draft(DraftHandle::new("news")), + source: AuthoredSource::Witnessed, + confidence: Confidence::Certain, + }); + let error = submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { answers: None, patch }) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RetiredSubjectActed { operation: 0 })), + "{error:?}" + ); + } + + /// PA.f34: `Forget` refuses a retired subject. + #[test] + fn a_retired_subject_cannot_forget() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf34Forget"); + let mut declare = ruled_fact_patch("news"); + declare.operations.push(ComponentOp::AcquireKnowledge { + subject: Ref::Existing(clockwork.reeve), + fact: Ref::Draft(DraftHandle::new("news")), + source: AuthoredSource::Witnessed, + confidence: Confidence::Certain, + }); + submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { answers: None, patch: declare }) + .expect("the reeve learns the fact"); + let fact = *kernel.state.knowledge[&clockwork.reeve].keys().next().unwrap(); + owner_retires(&mut kernel, clockwork.reeve).expect("retire"); + let before = kernel.snapshot().unwrap(); + let error = reject_owner( + &mut kernel, + &before, + operations(vec![ComponentOp::Forget { + subject: Ref::Existing(clockwork.reeve), + fact: Ref::Existing(fact), + }]), + ); + assert_eq!(error, vec![Mismatch::RetiredSubjectActed { operation: 0 }]); + } + + /// PA.f34: `InstallIncumbent` refuses a retired subject as incumbent. + #[test] + fn a_retired_subject_cannot_take_office() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf34Office"); + owner_retires(&mut kernel, clockwork.farmer).expect("retire"); + let before = kernel.snapshot().unwrap(); + let error = reject_owner( + &mut kernel, + &before, + operations(vec![ + ComponentOp::OpenOffice { + institution: Ref::Existing(clockwork.treasury), + office: office("warden"), + delegated: BTreeSet::from([authority_kind("levy")]), + }, + ComponentOp::InstallIncumbent { + institution: Ref::Existing(clockwork.treasury), + office: office("warden"), + incumbent: Ref::Existing(clockwork.farmer), + }, + ]), + ); + assert_eq!(error, vec![Mismatch::RetiredSubjectActed { operation: 1 }]); + } + + /// PA.f34: a retired subject's holdings remain transferable — a body may + /// still be looted after it stops acting. + #[test] + fn holdings_are_still_transferable_from_a_retired_holder() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf34Loot"); + owner_retires(&mut kernel, clockwork.farmer).expect("retire"); + let before = kernel.snapshot().unwrap(); + let grain = *kernel + .state + .holdings + .get(&clockwork.farmer) + .expect("the retired farmer still holds grain") + .keys() + .next() + .expect("at least one resource"); + submit_owner( + &mut kernel, + &before, + operations(vec![ComponentOp::Transfer { + from: Ref::Existing(clockwork.farmer), + to: Ref::Existing(clockwork.reeve), + resource: Ref::Existing(grain), + qty: Quantity(2), + }]), + ); + assert_eq!( + kernel.state.holdings[&clockwork.reeve][&grain], + Quantity(2) + ); + } + + /// PA.f35, MuA: the resolver's `Retire` arm removes the subject's + /// Position (`positions.remove`) in the same candidate pass a later + /// `Relocate` in the same patch reads, so retire-then-relocate in one + /// patch is rejected as `UnplacedSubject` rather than silently placing a + /// retired subject. + #[test] + fn retiring_then_relocating_in_one_patch_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf35RetireRelocate"); + let stair = *kernel + .state + .edges + .iter() + .find(|(_, edge)| edge.endpoints().0 == clockwork.yard) + .unwrap() + .0; + let before = kernel.snapshot().unwrap(); + let error = reject_owner( + &mut kernel, + &before, + operations(vec![ + ComponentOp::Retire { subject: Ref::Existing(clockwork.reeve) }, + ComponentOp::Relocate { + subject: Ref::Existing(clockwork.reeve), + via: Ref::Existing(stair), + }, + ]), + ); + assert_eq!(error, vec![Mismatch::UnplacedSubject { operation: 1 }]); + } + + /// PA.f35, MuB: `RevokeAffordance` is confined exactly as every other + /// structural operation, so an elaborator cannot use it to touch a + /// subject's grants outside its jurisdiction. + #[test] + fn an_elaborator_cannot_revoke() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf35ElabRevoke"); + let answered = dead_end_boundary(&kernel); + let speak = super::tests::speak_entry(&kernel); + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: WorldPatch { + declarations: vec![Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("stray"), + label: "The Roadside Stray".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([ + speak.clone(), + Ref::Existing(clockwork.threaten), + ]), + position: Some(Ref::Existing(clockwork.dead_end)), + import_key: None, + })], + operations: vec![ComponentOp::RevokeAffordance { + subject: Ref::Draft(DraftHandle::new("stray")), + affordance: Ref::Existing(clockwork.threaten), + }], + evidence: Vec::new(), + }, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::OutsideJurisdiction { site: Site::Operation(0) })), + "{error:?}" + ); + } + + /// PA.f35, MuC: `retired` on a subject snapshot row is read from + /// `ControllerAssignment::Retired` specifically, not from + /// `mode().is_none()` — a mirror's mode is also `None`, and a mirror must + /// never be reported retired. + #[test] + fn a_mirror_is_not_reported_retired() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf35MirrorFlag"); + let mirror = declare_mirror(&mut kernel, &clockwork, "pa-f35-mirror"); + let snapshot = kernel.snapshot().unwrap(); + let row = snapshot.subjects.iter().find(|s| s.id == mirror).unwrap(); + assert!(!row.retired); + } + + /// PA.f35, MuD: the affordance-holdings candidate set is updated after + /// every grant and revoke in a patch, not only the first, so three + /// revokes in one patch still catch the one that would leave the subject + /// mute. + #[test] + fn three_revokes_in_one_patch_cannot_mute_the_subject() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf35ThreeRevokes"); + let speak = super::tests::speak_entry(&kernel); + let before = kernel.snapshot().unwrap(); + let error = reject_owner( + &mut kernel, + &before, + operations(vec![ + ComponentOp::RevokeAffordance { + subject: Ref::Existing(clockwork.reeve), + affordance: Ref::Existing(clockwork.threaten), + }, + ComponentOp::RevokeAffordance { + subject: Ref::Existing(clockwork.reeve), + affordance: Ref::Existing(clockwork.deliver), + }, + ComponentOp::RevokeAffordance { + subject: Ref::Existing(clockwork.reeve), + affordance: speak, + }, + ]), + ); + assert_eq!(error, vec![Mismatch::WouldLeaveSubjectMute { operation: 2 }]); + } + + /// PA.f35, MuE: the resolver's `Retire` arm inserts the subject into its + /// own-patch `retired` candidate set, so a second `Retire` of the same + /// subject in one patch is caught as a no-op rather than silently + /// re-resolving. + #[test] + fn retiring_the_same_subject_twice_in_one_patch_is_a_noop_the_second_time() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf35DoubleRetire"); + let before = kernel.snapshot().unwrap(); + let error = reject_owner( + &mut kernel, + &before, + operations(vec![ + ComponentOp::Retire { subject: Ref::Existing(clockwork.reeve) }, + ComponentOp::Retire { subject: Ref::Existing(clockwork.reeve) }, + ]), + ); + assert_eq!(error, vec![Mismatch::NoOperationEffect { operation: 1 }]); + } + + // ---- Retirement fix batch (PA.f36-PA.f38) ------------------------------ + + /// PA.f36: the resolver refuses a genesis patch that declares a + /// Human-controlled subject and retires it in the same patch. The + /// resolver's `humans` candidate set tracks a freshly declared human the + /// same way `mirrors` tracks a freshly declared mirror, so this is caught + /// before `open_owner` ever commits an empty `world.cc` for a human who + /// never approved anything. + #[test] + fn genesis_cannot_declare_and_retire_the_human_in_one_patch() { + let directory = tempfile::tempdir().unwrap(); + let mut genesis = creation(CommandId::new(), "PAf36GenesisRetire"); + genesis.patch.operations.push(ComponentOp::Retire { + subject: Ref::Draft(DraftHandle::new("human")), + }); + let Err(error) = WorldKernel::create( + directory.path().join("world.cc"), + genesis, + &auth_principal(owner()), + ) else { + panic!("genesis admitted a patch that declares and retires the human"); + }; + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RetiresAnApprover { operation: 0 })), + "{error:?}" + ); + } + + /// PA.f36: pins the apply-time re-check directly, beside the resolver's + /// refusal above, since resolution is speculative and this arm is the + /// actual commit. If the resolver's `humans` tracking were ever disabled + /// or bypassed, this is the arm that must still refuse removing a Draft + /// approver. + #[test] + fn apply_refuses_removing_a_draft_approver_directly() { + let directory = tempfile::tempdir().unwrap(); + let kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "PAf36ApplyArm"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let human = human_subject(&kernel.snapshot().unwrap()); + let mut state = kernel.state.clone(); + let resolves_to = state.revision + 1; + assert!( + matches!( + apply_operation( + &mut state, + &ResolvedOp::Retire { subject: human }, + &[], + resolves_to + ) + .unwrap_err(), + KernelError::Invariant(message) + if message == "retire operation would remove a Draft approver" + ), + "the apply-time arm no longer refuses removing the Draft human" + ); + } + + /// PA.f37: a retired subject cannot become a promisor. `CreateCommitment` + /// refuses it with `RetiredSubjectActed`, the same mismatch a retired + /// office incumbent draws. + #[test] + fn a_retired_subject_cannot_be_a_promisor() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf37Promisor"); + owner_retires(&mut kernel, clockwork.farmer).expect("retire"); + let before = kernel.snapshot().unwrap(); + let error = reject_owner( + &mut kernel, + &before, + operations(vec![ComponentOp::CreateCommitment { + subject: Ref::Existing(clockwork.farmer), + counterparty: None, + kind: CommitmentKind::Obligation, + due: FictionalMinutes(LATE_DUE + 1), + period: None, + checks: Vec::new(), + statement: Statement::new("What was promised, as the promisor would say it.") + .unwrap(), + }]), + ); + assert_eq!(error, vec![Mismatch::RetiredSubjectActed { operation: 0 }]); + } + + /// PA.f37: once a subject is retired, the clock stops moving what it + /// holds — its routine no longer rolls and its obligation no longer + /// presses — while a live subject's goal and dependency still move on the + /// same tick. Nothing is discharged or deleted; the retired subject's + /// commitments stay on record, un-fulfilled and un-pressed, exactly as + /// they were the moment it retired. + #[test] + fn after_retirement_a_tick_moves_none_of_the_retired_subjects_commitments() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf37Frozen"); + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(clockwork.gate), + }]), + ); + owner_retires(&mut kernel, clockwork.farmer).expect("retire the farmer"); + let routine_before = due(&kernel, clockwork.farmer, clockwork.routine); + let dependency_source = PressureSource::Dependency(DependencyTarget::Route(clockwork.gate)); + + tick(&mut kernel, ROUTINE_DUE as u32 + LATE_DUE as u32).expect("the tick commits"); + + assert_eq!( + due(&kernel, clockwork.farmer, clockwork.routine), + routine_before, + "a retired subject's routine still rolled" + ); + assert_eq!( + pressure( + &kernel, + clockwork.farmer, + PressureSource::Commitment { + subject: clockwork.farmer, + key: clockwork.obligation, + } + ), + 0, + "a retired subject's obligation still pressed" + ); + assert_eq!( + pressure( + &kernel, + clockwork.reeve, + PressureSource::Commitment { + subject: clockwork.reeve, + key: clockwork.goal, + } + ), + 1, + "the live subject's goal did not press" + ); + assert_eq!( + pressure(&kernel, clockwork.reeve, dependency_source), + 1, + "the live subject's dependency did not press" + ); + + assert!( + kernel.state.commitments[&clockwork.farmer].contains_key(&clockwork.routine), + "the frozen routine was discharged or deleted rather than left as history" + ); + assert!( + kernel.state.commitments[&clockwork.farmer].contains_key(&clockwork.obligation), + "the frozen obligation was discharged or deleted rather than left as history" + ); + } + + /// PA.f37, the other half: retiring the subject that holds the goal and + /// the dependency freezes those instead, while the still-live farmer's + /// routine and obligation keep moving. Soul's probe retired a subject + /// whose routine rolled and whose goal and dependency kept pressing; this + /// pins the dependency loop in `derive_motion` the first test above never + /// exercises, since the farmer it retires holds no dependency. + #[test] + fn after_retirement_a_tick_moves_none_of_the_retired_subjects_goal_or_dependency() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf37FrozenDep"); + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(clockwork.gate), + }]), + ); + owner_retires(&mut kernel, clockwork.reeve).expect("retire the reeve"); + let routine_before = due(&kernel, clockwork.farmer, clockwork.routine); + let dependency_source = PressureSource::Dependency(DependencyTarget::Route(clockwork.gate)); + + tick(&mut kernel, ROUTINE_DUE as u32 + LATE_DUE as u32).expect("the tick commits"); + + assert_eq!( + pressure( + &kernel, + clockwork.reeve, + PressureSource::Commitment { + subject: clockwork.reeve, + key: clockwork.goal, + } + ), + 0, + "a retired subject's goal still pressed" + ); + assert_eq!( + pressure(&kernel, clockwork.reeve, dependency_source), + 0, + "a retired subject's dependency still pressed" + ); + assert_ne!( + due(&kernel, clockwork.farmer, clockwork.routine), + routine_before, + "the live subject's routine did not roll" + ); + assert_eq!( + pressure( + &kernel, + clockwork.farmer, + PressureSource::Commitment { + subject: clockwork.farmer, + key: clockwork.obligation, + } + ), + 1, + "the live subject's obligation did not press" + ); + } + + /// PA.f37: the freeze survives a full reopen-and-replay, the same way + /// every other retirement effect in this batch does. + #[test] + fn a_retired_subjects_frozen_commitments_survive_reopen_and_replay() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (world_id, farmer, routine, obligation) = { + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf37Replay"); + owner_retires(&mut kernel, clockwork.farmer).expect("retire the farmer"); + tick(&mut kernel, ROUTINE_DUE as u32 + LATE_DUE as u32).expect("the tick commits"); + ( + kernel.state.world_id, + clockwork.farmer, + clockwork.routine, + clockwork.obligation, + ) + }; + let reopened = WorldKernel::open(&path, world_id).expect("the store replays"); + assert_eq!( + due(&reopened, farmer, routine), + FictionalMinutes(ROUTINE_DUE), + "the routine rolled somewhere along the replayed path" + ); + assert_eq!( + pressure( + &reopened, + farmer, + PressureSource::Commitment { + subject: farmer, + key: obligation, + } + ), + 0, + "the obligation pressed somewhere along the replayed path" + ); + } + + // ---- Retirement fix batch, test gaps (PA.f39) -------------------------- + + /// PA.f39, M2: `AcquireKnowledge` refuses a retired subject regardless of + /// source. `Evidenced` already carries its own provenance guard + /// (`EvidencedKnowledgeOfClaim`), which makes it plausible for a future + /// edit to narrow the retirement check to `source != Evidenced`; this + /// proves the retirement check still fires for an `Evidenced` acquire + /// too. + #[test] + fn a_retired_subject_cannot_acquire_evidenced_knowledge() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf39Evidenced"); + owner_retires(&mut kernel, clockwork.farmer).expect("retire"); + let patch = WorldPatch { + declarations: vec![Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("news"), + label: "The Harvest Report".into(), + statement: Statement::new("The winter grain is counted.").unwrap(), + standing: FactStandingRef::Canonical { + evidence: EvidenceRef::new("vault:count"), + }, + })], + operations: vec![ComponentOp::AcquireKnowledge { + subject: Ref::Existing(clockwork.farmer), + fact: Ref::Draft(DraftHandle::new("news")), + source: AuthoredSource::Evidenced, + confidence: Confidence::Certain, + }], + evidence: vec![EvidenceRef::new("vault:count")], + }; + let error = submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { answers: None, patch }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RetiredSubjectActed { operation: 0 })), + "{error:?}" + ); + } + + /// PA.f39, M6: `is_retired` reads `ControllerAssignment::Retired` + /// specifically. If it also matched `ExternallyControlled`, a mirror + /// would be silently dropped from `Reach::Subjects` audience derivation — + /// the same site PA.f33 fixed for an actually retired member. A mirror is + /// not retired, and stays in the audience. + #[test] + fn a_mirror_in_a_subjects_channel_stays_in_the_audience() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf39MirrorAudience"); + let mirror = declare_mirror(&mut kernel, &clockwork, "pa-f39-mirror"); + let mut patch = ruled_fact_patch("news"); + patch.declarations.push(Declaration::Channel(ChannelDeclaration { + handle: DraftHandle::new("wire"), + label: "The Wire".into(), + reach: ReachRef::Subjects(BTreeSet::from([ + Ref::Existing(mirror), + Ref::Existing(clockwork.farmer), + ])), + controller: None, + })); + patch.operations.push(ComponentOp::Communicate { + speaker: Ref::Existing(clockwork.farmer), + fact: Ref::Draft(DraftHandle::new("news")), + to: AudienceRef::Channel(Ref::Draft(DraftHandle::new("wire"))), + }); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { answers: None, patch }, + ) + .expect("admitted"); + let mirror_knows = kernel + .state + .knowledge + .get(&mirror) + .map(BTreeMap::len) + .unwrap_or(0); + assert_eq!( + mirror_knows, 1, + "a mirror was excluded from a Subjects-reach audience" + ); + } + + /// PA.f39, Soul's probe S2: `CanReach` to a placeless target reachable + /// only through a `Reach::Subjects` channel — no co-location is possible + /// — is refused once the target retires. This exercises `audience()`'s + /// channel side, which PA.f33's Colocated-only `CanReach` test + /// (`a_retired_subject_is_unreachable_through_can_reach`) never reaches, + /// and kills a mutation that removes `audience()`'s retired filter. + #[test] + fn a_retired_placeless_subject_is_unreachable_through_a_subjects_channel() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf39S2"); + let speak = super::tests::speak_entry(&kernel); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![ + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("outcast"), + label: "The Placeless Outcast".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([speak.clone()]), + position: None, + import_key: None, + }), + Declaration::Channel(ChannelDeclaration { + handle: DraftHandle::new("wire"), + label: "The Outcast Wire".into(), + reach: ReachRef::Subjects(BTreeSet::from([ + Ref::Draft(DraftHandle::new("outcast")), + Ref::Existing(clockwork.farmer), + ])), + controller: None, + }), + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("hail"), + kind: AffordanceKindName("hail".into()), + roles: vec![ + RoleSpec { + role: Role("target".into()), + kind: RefKind::Subject(None), + }, + RoleSpec { + role: Role("channel".into()), + kind: RefKind::Entity(EntityKind::Channel), + }, + ], + preconditions: vec![Precondition::CanReach { + subject: Role("target".into()), + via: AudienceSpec::Channel(Role("channel".into())), + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + }), + ], + operations: vec![ComponentOp::GrantAffordance { + subject: Ref::Existing(clockwork.farmer), + affordance: Ref::Draft(DraftHandle::new("hail")), + }], + evidence: Vec::new(), + }, + }, + ) + .expect("the play authority declares the placeless outcast and its channel"); + + let positions = kernel.state.positions.clone(); + let outcast = *kernel + .state + .subjects + .keys() + .find(|id| !positions.contains_key(id)) + .expect("the declared placeless outcast"); + let wire = *kernel.state.channels.keys().next().expect("the declared channel"); + let snapshot = kernel.snapshot().unwrap(); + let hail = affordance_named(&snapshot, "hail"); + let opportunity = opportunity_for(&snapshot, clockwork.farmer); + let invocation = DecisionInvocation { + affordance: hail, + bindings: vec![ + binding("target", Target::Subject(outcast)), + binding("channel", Target::Entity(wire)), + ], + proposed: Vec::new(), + speech: Some(Statement::new("Hail!").unwrap()), + display: None, + }; + submit_as( + &mut kernel, + CallerId::Controller(opportunity.controller_id), + CommandBody::ExerciseDecision { + invocation: invocation.clone(), + opportunity: opportunity.clone(), + }, + ) + .expect("the live outcast is reachable through the channel"); + + owner_retires(&mut kernel, outcast).expect("retire the outcast"); + let snapshot = kernel.snapshot().unwrap(); + let opportunity = opportunity_for(&snapshot, clockwork.farmer); + let error = submit_as( + &mut kernel, + CallerId::Controller(opportunity.controller_id), + CommandBody::ExerciseDecision { invocation, opportunity }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::ActionRejected(set) + if set.contains(&ActionMismatch::CannotReach { precondition: 0 })), + "{error:?}" + ); + } +} diff --git a/native/aetherlight/src/patch.rs b/native/aetherlight/src/patch.rs new file mode 100644 index 000000000..31485e2d6 --- /dev/null +++ b/native/aetherlight/src/patch.rs @@ -0,0 +1,7760 @@ +//! Closed-patch resolution: the one owner of draft handles, reference kinds, and +//! declaration-lane ID allocation. +//! +//! Only [`derive_id`] allocates a canonical ID, and it is called from exactly +//! two sites: [`resolve_patch`] here, and `action::exercise`, which mints one +//! referent per speech-carrying invocation — always a `Claimed` fact asserted by +//! the acting subject. +//! +//! A patch names structure two ways and no other way: an exact canonical ID that +//! already keys a partition, or a draft handle declared in the same patch. +//! Resolution accumulates the complete mismatch set first and allocates only +//! after that set is empty, so a rejected patch never mints an ID. + +use super::clock::{FictionalMinutes, TickMinutes}; +use super::tool_schema; +use super::grammar::GrammarRefusal; +use super::{ + AffordanceId, CommandId, ControllerAssignment, ControllerId, EdgeId, EntityId, LensWeights, + NewController, SubjectId, SubjectKind, SubjectState, WorldId, +}; +use codex_connector::CodexToolDefinition; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, BTreeSet, btree_map::Entry}; +use unicode_properties::{GeneralCategory, UnicodeGeneralCategory}; +use uuid::Uuid; + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum EntityKind { + Place, + Resource, + Fact, + Channel, +} + +/// Exactly the edge kinds that have a record shape. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum EdgeKind { + Route, +} + +/// Traversal rule. A `Restricted` route names the authority kind that opens it: +/// the door names its own key, and the kernel reads neither the door nor the key +/// beyond comparing the name. [`route_admits`] is the sole statement of who gets +/// through, reached identically by `resolve_patch`'s `Relocate` arm and by +/// `Precondition::Reachable`'s edge admission. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "access", rename_all = "snake_case")] +pub(crate) enum AccessKind { + Public, + Restricted { requires: AuthorityKindName }, +} + +/// A world-declared authority name: canonical text, `[a-z][a-z0-9_]{0,47}`. The +/// kernel carries it, compares it for equality, and reads it no other way. A +/// closed enum here would make "conscript" or "audit" a kernel change and put a +/// world's political vocabulary in the reducer. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct AuthorityKindName(pub(crate) String); + +/// What an authority covers. Distinct from `DecisionScope`, which says *whose* +/// authority it is and stays one field. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "over", content = "id", rename_all = "snake_case")] +pub(crate) enum AuthorityTarget { + Subject(SubjectId), + /// That place and everything contained in it, by `EntityRecord.container`. + PlaceSubtree(EntityId), +} + +impl AuthorityTarget { + /// The referent this target names, so "does grant A cover grant B's ground" + /// is the one covering predicate rather than a second one. + pub(super) fn as_referent(self) -> super::Target { + match self { + Self::Subject(subject_id) => super::Target::Subject(subject_id), + Self::PlaceSubtree(entity_id) => super::Target::Entity(entity_id), + } + } +} + +/// The proposal-time twin of [`AuthorityTarget`], carrying references. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "over", content = "ref", rename_all = "snake_case")] +pub(crate) enum AuthorityTargetRef { + Subject(Ref<SubjectId>), + PlaceSubtree(Ref<EntityId>), +} + +/// One jurisdiction: a kind and the ground it runs over. Ordered `(kind, over)` +/// so a subject's grant set has one canonical order. A jurisdiction is a set of +/// these, so revoking one place is not a restatement of the whole scope. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub(crate) struct AuthorityGrant { + pub(crate) kind: AuthorityKindName, + pub(crate) over: AuthorityTarget, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub(crate) struct AuthorityGrantRef { + pub(crate) kind: AuthorityKindName, + pub(crate) over: AuthorityTargetRef, +} + +/// Canonical text, scoped to its institution: the pair (institution, name) is +/// the identity, the same discipline a `Role` gets inside one affordance. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct OfficeName(pub(crate) String); + +/// A seat inside one institution. It carries no term and no selection method: +/// there is no clock, so nothing can expire, and a field nothing reads is a +/// decoration the next pass has to delete. `delegated` is the field that earns +/// its keep — `scope_components` reads it, `Authorized` resolves through it, and +/// the scope digest binds it. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct Office { + /// A person subject, or vacant. A vacancy is an ordinary state. + pub(crate) incumbent: Option<SubjectId>, + /// Which of the institution's authority kinds this office lends its + /// incumbent. Non-empty: an office lending nothing is inert. + pub(crate) delegated: BTreeSet<AuthorityKindName>, +} + +/// World-declared canonical text, kernel-opaque, `[a-z][a-z0-9_]{0,47}`. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct GrievanceKindName(pub(crate) String); + +/// Where one kind of grievance goes, and who may bring it. One forum per +/// grievance kind, world-wide; per-jurisdiction forums would key this on +/// `(GrievanceKindName, AuthorityTarget)`, and that key has no consumer yet. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct Forum { + /// Any subject. A one-person magistrate is a legitimate forum, so the + /// kernel branches on `SubjectKind` here as it does everywhere else: not at + /// all. + pub(crate) forum: SubjectId, + /// Who may bring this grievance. It reuses `AuthorityTarget`'s type and its + /// covering predicate and is emphatically not stored in the `authority` + /// partition, so `RevokeAuthority` cannot strip standing. + pub(crate) standing: AuthorityTarget, +} + +/// Whole minutes: the kernel's only time unit, so route cost adds and compares +/// with no converter. The valid range is checked, not typed, so a bad cost joins +/// the complete mismatch set instead of failing deserialization. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct Cost(pub(crate) u32); + +/// One year of minutes; bounds path sums. +pub(super) const MAX_ROUTE_COST: u32 = 525_600; + +/// A conserved count. Unsigned because a holding can never be negative: a signed +/// type would make "owes 3 iron" representable and push the real check to runtime +/// anyway. Subtraction is `checked_sub` and its failure is `InsufficientCustody`; +/// addition is `checked_add` and its failure is `QuantityOverflow`. No saturating +/// arithmetic anywhere, because a silent clamp is a silent conservation break. +/// There is no maximum: nothing sums quantities across resources, so the honest +/// bound is the type's. There is no unit, because a unit is where prices enter. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct Quantity(pub(crate) u64); + +/// What a subject depends on. A dependency is a bare relation: no magnitude, no +/// kind beyond its target namespace, no clock, no cost. The variant selects the +/// resolver, so the target kind is carried by the type rather than checked after +/// the fact. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "target", content = "id", rename_all = "snake_case")] +pub(crate) enum DependencyTarget { + Resource(EntityId), + Route(EdgeId), + Subject(SubjectId), +} + +/// The proposal-time twin of [`DependencyTarget`], carrying references rather +/// than canonical IDs. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "target", content = "ref", rename_all = "snake_case")] +pub(crate) enum DependencyRef { + Resource(Ref<EntityId>), + Route(Ref<EdgeId>), + Subject(Ref<SubjectId>), +} + +/// Where a subject stands. One place, derived from nothing else. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub(crate) struct Position { + pub(crate) place: EntityId, +} + +/// Namespace plus declared kind of a draft handle. A reference states the kind it +/// expects; resolution refuses a handle that answers with another one. A subject +/// expectation carries `None` where the referring position constrains the +/// namespace but not the kind. +/// +/// It is one predicate serving three readers: the resolution index, `Mismatch`, +/// and an affordance's `RoleSpec`, which persists inside the catalog and so +/// requires the serde derives. `Affordance` names the catalog namespace, which +/// carries no components and can never be a role's target. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "namespace", content = "kind", rename_all = "snake_case")] +pub enum RefKind { + Subject(Option<SubjectKind>), + Entity(EntityKind), + Edge(EdgeKind), + Affordance, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub struct DraftHandle(String); + +impl DraftHandle { + pub(super) fn new(value: impl Into<String>) -> Self { + Self(value.into()) + } +} + +/// A reference is an exact canonical ID or a handle resolved in the same patch. +/// There is no third form and no `From<String>`. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "ref", content = "value", rename_all = "snake_case")] +pub enum Ref<Id> { + Existing(Id), + Draft(DraftHandle), +} + +/// A referent in any of the three referent namespaces, or in the catalog. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "namespace", content = "ref", rename_all = "snake_case")] +pub enum RefName { + Subject(Ref<SubjectId>), + Entity(Ref<EntityId>), + Edge(Ref<EdgeId>), + Affordance(Ref<AffordanceId>), +} + +/// A world-declared affordance name. Canonical text, `[a-z][a-z0-9_]{0,47}`, +/// because it becomes a generated tool name and a tool name must be stable, +/// unique, and safe. The kernel carries it and branches on it nowhere; that is +/// what keeps genre out of the reducer. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub struct AffordanceKindName(pub String); + +/// A named slot in one affordance, bound to a referent at invocation time. +/// Canonical text, `[a-z][a-z0-9_]{0,31}` — it becomes a tool parameter name. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub struct Role(pub(crate) String); + +/// What a role must be bound to. `RefKind` is reused rather than mirrored: it +/// already spells subject, entity kind, and edge kind, so the binding kind-check +/// and the declaration kind-check are one predicate. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub(crate) struct RoleSpec { + pub(crate) role: Role, + pub(crate) kind: RefKind, +} + +/// Committed world text: canonical, non-empty. The kernel stores it, hands it to +/// a projection, and reads it no other way. Nothing compares two `Statement`s: +/// no dedup, no interning, no contradiction check, no similarity. Two facts with +/// byte-identical statements are two facts. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub struct Statement(String); + +impl Statement { + pub fn new(value: impl Into<String>) -> Option<Self> { + let value = value.into(); + is_canonical_text(&value).then_some(Self(value)) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// How a fact stands. Immutable after admission: there is no `SetStanding`. A +/// claim never becomes canon and canon never degrades to a claim, so nothing +/// ever has to decide which of two facts wins. A world in which a court rules on +/// a rumour declares a *new* `Canonical` fact; the rumour survives beside it, +/// which is what makes a later `Redress` reading possible at all. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "standing", rename_all = "snake_case")] +pub(crate) enum FactStanding { + /// Admitted with a receipt, through the same evidence gate `Admit` uses. + Canonical { evidence: EvidenceRef }, + /// Asserted by a subject. The kernel does not evaluate the assertion. + Claimed { by: SubjectId }, + /// Stated by the play table. The kernel does not evaluate it; only `Play` + /// may write it. + Ruled, +} + +/// The proposal-time twin of [`FactStanding`]. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "standing", rename_all = "snake_case")] +pub(crate) enum FactStandingRef { + Canonical { evidence: EvidenceRef }, + Claimed { by: Ref<SubjectId> }, + Ruled, +} + +/// One `EntityKind::Fact` row's payload. Write-once: only declaration and +/// `AssertClaim` ever write `facts`. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct FactRecord { + pub(crate) statement: Statement, + pub(crate) standing: FactStanding, +} + +/// Where a channel carries. A place reach is the subtree, through the same +/// [`covers_place`] walk a `PlaceSubtree` jurisdiction uses. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "reach", content = "of", rename_all = "snake_case")] +pub(crate) enum Reach { + /// Exactly these subjects. May be empty: an empty reach is the named + /// silenced state, which is the outcome this component exists to hold. + Subjects(BTreeSet<SubjectId>), + /// Everyone positioned at that place or anywhere inside it. + Place(EntityId), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "reach", content = "of", rename_all = "snake_case")] +pub(crate) enum ReachRef { + Subjects(BTreeSet<Ref<SubjectId>>), + Place(Ref<EntityId>), +} + +/// One `EntityKind::Channel` row's payload. It carries no latency: there is no +/// clock, so a latency field would be read by nothing and bound by nothing. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct ChannelRecord { + pub(crate) reach: Reach, + /// Who may speak on it besides those inside its reach, and whose scope + /// digest binds it. The horn belongs to the temple, not to whoever happens + /// to be within earshot of it. + pub(crate) controller: Option<SubjectId>, +} + +/// Lived meaning a subject carries: values, a voice, memories, and reads of +/// other subjects. It constrains no precondition, so it is outside every scope +/// digest and cannot interrupt a bound turn; it enriches projection and never +/// substitutes for authority, custody, topology, or knowledge. Set whole, so a +/// subject holds one value at one revision. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct PersonaMaterial { + pub(crate) values: Vec<Statement>, + pub(crate) voice: Statement, + pub(crate) memories: Vec<Statement>, + /// One read per subject, in canonical order. + pub(crate) reads: BTreeMap<SubjectId, Statement>, +} + +/// The proposal-time twin of a read: the subject by reference. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct PersonaReadRef { + pub(crate) subject: Ref<SubjectId>, + pub(crate) statement: Statement, +} + +/// A small closed ordinal. Ordered ascending by declaration order, so derived +/// `Ord` *is* the semantics and `Knows { at_least }` is one `>=`. Three levels: +/// two cannot express "I heard it but I doubt it", which is the state deception +/// produces; four or more is a scale nothing in the vocabulary distinguishes. +/// There is no zero — forgetting is a removed key, exactly as `Quantity(0)` is +/// unstorable. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub(crate) enum Confidence { + Doubted, + Believed, + Certain, +} + +/// Three sources with named writers: `Witnessed` is written by +/// `AcquireKnowledge` and by `Witness`, `Evidenced` by `AcquireKnowledge`, and +/// `Told` only by `Communicate`. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "source", rename_all = "snake_case")] +pub(crate) enum KnowledgeSource { + Witnessed, + /// `via: None` is co-location. + Told { + by: SubjectId, + via: Option<EntityId>, + }, + /// A visible act of `by`, perceived in the same place. Written only by + /// `ResolvedOp::Display`, which the kernel alone lowers. + Seen { + by: SubjectId, + }, + Evidenced, +} + +/// What one subject holds of one fact. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct Knowledge { + pub(crate) confidence: Confidence, + pub(crate) source: KnowledgeSource, + /// The revision at which this subject acquired this row: witnessed, + /// told, shown, or seeded by an author. Written by every writer of this + /// map (PA.f44), so the Projector's recency marker can tell a row minted + /// with no `minted_at` — a patch, a seed, a ruled fact — from one the + /// subject already held before its last act. + pub(crate) acquired_at: u64, +} + +/// The source an author may write. `Told` is unrepresentable here: only +/// `Communicate` writes it, so no author can forge a teller. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "source", rename_all = "snake_case")] +pub(crate) enum AuthoredSource { + Witnessed, + Evidenced, +} + +/// Where a telling lands. `Colocated` is derived from `positions` at check and +/// at apply; it is never a stored channel, so no entity is minted per place and +/// no world must enumerate a village to let people talk in a room. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub(crate) enum Audience { + Colocated, + Channel(EntityId), +} + +impl Audience { + pub(super) fn channel(self) -> Option<EntityId> { + match self { + Self::Colocated => None, + Self::Channel(entity_id) => Some(entity_id), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub(crate) enum AudienceRef { + Colocated, + Channel(Ref<EntityId>), +} + +/// The catalog form: a declared affordance names a role, the invoker binds a +/// channel to it, and `exercise` lowers this plus the bindings into the +/// canonical [`Audience`]. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub(crate) enum AudienceSpec { + Colocated, + Channel(Role), +} + +/// What a subject has promised. The kernel branches on this twice — the tick +/// behaves differently per kind and the scale count reads `Goal` — so it is a +/// closed enum rather than a world-declared name. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub(crate) enum CommitmentKind { + Routine, + Obligation, + Goal, +} + +/// Deterministic from the creating command and the operation's index within +/// that command's lowered operations. No `EdgeId`: nothing references a +/// commitment by identity, so a structural key is the whole answer. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub struct CommitmentKey { + pub(crate) command: CommandId, + pub(crate) index: u32, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct Commitment { + pub(crate) kind: CommitmentKind, + /// `None` is a promise to oneself: a personal `Goal`. A counterparty equal + /// to the subject is refused. + pub(crate) counterparty: Option<SubjectId>, + /// Absolute. "Past due" is `due <= now`: one comparison, no countdown + /// fanned across the partition. + pub(crate) due: FictionalMinutes, + /// Required for `Routine` — that is what makes it recur — and forbidden + /// otherwise. On auto-fulfilment `due` rolls forward by this. + pub(crate) period: Option<TickMinutes>, + /// What must hold for a `Routine` to auto-fulfil. Role-free canonical + /// checks. Empty for `Obligation` and `Goal`. + pub(crate) checks: Vec<BoundPrecondition>, + /// What is promised, as the promisor would state it. Without it a promise + /// is a clock and a name, and on the road both parties invented the rest. + pub(crate) statement: Statement, +} + +/// Nonzero by construction; saturating in both directions. A separate newtype +/// from [`super::Magnitude`], which is an effect ceiling and shares nothing with +/// this but a word. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct PressureMagnitude(pub(crate) u32); + +/// Target-major, because every reader is: the attention order reads pressure +/// *on* a subject and the typed view shows pressure on self. Source-major has no +/// reader. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "from", content = "of", rename_all = "snake_case")] +pub(crate) enum PressureSource { + /// A past-due commitment. Carries the promisor and the structural key. + Commitment { + subject: SubjectId, + key: CommitmentKey, + }, + /// An unavailable dependency of the pressed subject. This is how a closed + /// route in one realm becomes a political problem in another without anyone + /// deciding that it should be. + Dependency(DependencyTarget), + /// Another subject, pressing directly through an affordance effect. + Subject(SubjectId), +} + +/// The proposal-time twin of [`PressureSource`]. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "from", content = "of", rename_all = "snake_case")] +pub(crate) enum PressureSourceRef { + Commitment { + subject: Ref<SubjectId>, + key: CommitmentKey, + }, + Dependency(DependencyRef), + Subject(Ref<SubjectId>), +} + +/// The role-free canonical twin of [`Precondition`]. A `Precondition` names +/// roles; a `BoundPrecondition` names referents, so a commitment's checks are +/// storable with no second binding path and one evaluator serves both the +/// invocation pipeline and the tick. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "precondition", rename_all = "snake_case")] +pub(crate) enum BoundPrecondition { + Present { + at: EntityId, + }, + Reachable { + to: EntityId, + within: Cost, + }, + Holds { + resource: EntityId, + at_least: Quantity, + }, + Authorized { + over: super::Target, + kind: AuthorityKindName, + }, + HasStanding { + grievance: GrievanceKindName, + }, + Knows { + fact: EntityId, + at_least: Confidence, + }, + CanBroadcast { + via: Audience, + }, + CanReach { + subject: SubjectId, + via: Audience, + }, + Committed { + to: SubjectId, + kind: CommitmentKind, + }, +} + +/// The proposal-time twin of [`BoundPrecondition`], carried by +/// `CreateCommitment` so a patch may name a check over structure it declares. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "precondition", rename_all = "snake_case")] +pub(crate) enum PreconditionRef { + Present { + at: Ref<EntityId>, + }, + Reachable { + to: Ref<EntityId>, + within: Cost, + }, + Holds { + resource: Ref<EntityId>, + at_least: Quantity, + }, + Authorized { + over: AuthorityTargetRef, + kind: AuthorityKindName, + }, + HasStanding { + grievance: GrievanceKindName, + }, + Knows { + fact: Ref<EntityId>, + at_least: Confidence, + }, + CanBroadcast { + via: AudienceRef, + }, + CanReach { + subject: Ref<SubjectId>, + via: AudienceRef, + }, + Committed { + to: Ref<SubjectId>, + kind: CommitmentKind, + }, +} + +/// The authored scale target: how many qualified subjects of each kind the +/// world means to hold, and how that target distributes over jurisdiction +/// roots. Written once by genesis and never mutated. Not a component of any +/// referent, so not a `Declaration` and not a partition. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct WorldScaleIntent { + /// Target qualified subjects per kind, world-wide. + pub(crate) targets: BTreeMap<SubjectKind, u32>, + /// Jurisdiction roots and their share, in permille. Weights distribute the + /// target and never raise it: the sum is checked `<= 1000`. + pub(crate) jurisdictions: BTreeMap<EntityId, u32>, +} + +/// The genesis-lane twin: the intent names places the same patch declares, and +/// there is no other way to name them before they exist. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct WorldScaleIntentRef { + pub(crate) targets: BTreeMap<SubjectKind, u32>, + pub(crate) jurisdictions: BTreeMap<DraftHandle, u32>, +} + +/// One counted region of the scale deficit. `Uncovered` is the residual: a +/// subject with no jurisdiction root covering it — standing nowhere, or +/// standing somewhere outside every declared root's subtree — is counted and +/// visible while reducing no target. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "jurisdiction", content = "root", rename_all = "snake_case")] +pub enum JurisdictionKey { + PlaceSubtree(EntityId), + Uncovered, +} + +/// What must already be true of committed state before an invocation is +/// admitted. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "precondition", rename_all = "snake_case")] +pub(crate) enum Precondition { + /// The acting subject's Position names the place bound to `at`. + Present { at: Role }, + /// A path exists from the actor's place to the place bound to `to`, over + /// open routes this subject may traverse, with summed cost at most `within`. + Reachable { to: Role, within: Cost }, + /// The acting subject's own holding of the resource bound to `resource` is + /// at least `at_least`. + Holds { resource: Role, at_least: Quantity }, + /// The acting subject's effective authority — its own grants plus what + /// every office it occupies lends — holds a grant of `kind` whose target + /// covers the referent bound to `over`. + Authorized { over: Role, kind: AuthorityKindName }, + /// A forum takes `grievance` and the acting subject is inside its standing. + HasStanding { grievance: GrievanceKindName }, + /// The acting subject holds the fact bound to `fact` at `at_least` or + /// better. + Knows { fact: Role, at_least: Confidence }, + /// The acting subject has an audience at all: it is positioned, for + /// co-location, or it is inside the bound channel's reach or is its + /// controller. + CanBroadcast { via: AudienceSpec }, + /// The referent bound to `subject` is inside that audience. Addressing does + /// not narrow the audience: a telling still lands on everyone in it. + CanReach { subject: Role, via: AudienceSpec }, + /// The acting subject holds a commitment of `kind` to the referent bound to + /// `to`. This is what lets a world author an affordance whose legitimacy is + /// a promise rather than a jurisdiction. + Committed { to: Role, kind: CommitmentKind }, +} + +/// Exactly the operations an affordance may propose. `Admit` is absent because +/// minting quantity requires an `EvidenceRef` and an invocation carries no +/// evidence list, so admitting it here would be a second creation path beside +/// the single evidenced one. `OpenOffice`, `CloseOffice`, `OpenForum`, and +/// `CloseForum` are absent because constituting an office or a forum has no +/// live in-play reader an affordance would serve; they stay patch-lane only. +/// +/// `Witness` is a slot and `Communicate` is not, because a witnessed event is +/// world-caused and names no speaker, while speech is the actor's own act and +/// reaches an invocation only through the kernel-owned `carries_speech` +/// lowering: a proposer that could `Communicate` would choose a speaker, and a +/// proposer that `Witness`es chooses only where. +/// +/// The four civic variants carry their payload on the variant rather than on +/// the slot or the invocation: an authority kind and an office name are not +/// referents, so they cannot be roles, and a proposer's only degree of freedom +/// stays magnitude. The world fixes the kind when it authors the entry. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "op", rename_all = "snake_case")] +pub(crate) enum ComponentOpKind { + Relocate, + OpenRoute, + CloseRoute, + AlterCost, + Transfer, + Transform, + Consume, + Bind, + Release, + GrantAuthority { + kind: AuthorityKindName, + }, + RevokeAuthority { + kind: AuthorityKindName, + }, + InstallIncumbent { + office: OfficeName, + }, + VacateOffice { + office: OfficeName, + }, + /// Source is fixed to `Witnessed`: only `Communicate` writes a teller, and + /// `Evidenced` needs a patch's evidence list, which an invocation has not. + AcquireKnowledge { + confidence: Confidence, + }, + /// A world-authored event with no speaker: a beacon, a bell, a blast. The + /// slot names a fact and a place, never a subject, so a proposer's only + /// degree of freedom is which declared place the entry binds. The source is + /// `Witnessed` by construction — `ComponentOp::Witness` has no field a + /// teller could enter — so this lowering cannot forge one however it is + /// bound. + Witness { + confidence: Confidence, + }, + Forget, + /// The kind, the horizon, and the period are fixed on the variant, so a + /// proposer's only degree of freedom stays magnitude. `due` is + /// `now + horizon`, computed by the kernel at lowering: an absolute due on + /// a catalog entry would be a fixed date the world outgrows. + CreateCommitment { + kind: CommitmentKind, + horizon: TickMinutes, + period: Option<TickMinutes>, + }, + /// The source is fixed to the acting subject, so it cannot be forged. A + /// world authoring `threaten`, `reassure`, or `forgive` needs these three. + AdvancePressure { + by: PressureMagnitude, + }, + ReducePressure { + by: PressureMagnitude, + }, + ResolvePressure, +} + +/// The referent shape of one operation: the single source of both the +/// declaration check and the lowering. +pub(super) enum RoleKindRule { + Exact(RefKind), + AnyDependencyTarget, + AnyAuthorityTarget, +} + +/// Which magnitude, if any, an operation carries. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum BoundsDimension { + None, + Quantity, + Cost, +} + +impl ComponentOpKind { + pub(super) fn arity(&self) -> Vec<RoleKindRule> { + let subject = || RoleKindRule::Exact(ANY_SUBJECT); + let route = || RoleKindRule::Exact(ROUTE); + let resource = || RoleKindRule::Exact(RefKind::Entity(EntityKind::Resource)); + match self { + Self::Relocate => vec![subject(), route()], + Self::OpenRoute | Self::CloseRoute | Self::AlterCost => vec![route()], + Self::Transfer => vec![subject(), subject(), resource()], + Self::Transform => vec![subject(), resource(), resource()], + Self::Consume => vec![subject(), resource()], + Self::Bind | Self::Release => vec![subject(), RoleKindRule::AnyDependencyTarget], + Self::GrantAuthority { .. } | Self::RevokeAuthority { .. } => { + vec![subject(), RoleKindRule::AnyAuthorityTarget] + } + Self::InstallIncumbent { .. } => vec![subject(), subject()], + Self::VacateOffice { .. } => vec![subject()], + Self::AcquireKnowledge { .. } | Self::Forget => { + vec![subject(), RoleKindRule::Exact(FACT)] + } + Self::Witness { .. } => vec![RoleKindRule::Exact(FACT), RoleKindRule::Exact(PLACE)], + // Promisor and counterparty. A `Goal` slot is refused at admission + // with `GoalWithCounterparty`: a promise to oneself has no second + // referent to bind, so the action lane authors `Routine` and + // `Obligation` and the patch lane authors goals. + Self::CreateCommitment { .. } => vec![subject(), subject()], + Self::AdvancePressure { .. } | Self::ReducePressure { .. } | Self::ResolvePressure => { + vec![subject()] + } + } + } + + pub(super) fn dimension(&self) -> BoundsDimension { + match self { + Self::Transfer | Self::Transform | Self::Consume => BoundsDimension::Quantity, + Self::AlterCost => BoundsDimension::Cost, + _ => BoundsDimension::None, + } + } + + /// The civic names this variant carries, so one validator checks them all. + fn payload_names(&self) -> Vec<&str> { + match self { + Self::GrantAuthority { kind } | Self::RevokeAuthority { kind } => vec![&kind.0], + Self::InstallIncumbent { office } | Self::VacateOffice { office } => vec![&office.0], + _ => Vec::new(), + } + } +} + +/// Whether a declared role kind can serve a position governed by this rule. +pub(super) fn role_kind_fits(rule: &RoleKindRule, declared: RefKind) -> bool { + match rule { + RoleKindRule::Exact(RefKind::Subject(_)) => matches!(declared, RefKind::Subject(_)), + RoleKindRule::Exact(expected) => *expected == declared, + RoleKindRule::AnyDependencyTarget => matches!( + declared, + RefKind::Subject(_) | RefKind::Entity(EntityKind::Resource) | RefKind::Edge(_) + ), + RoleKindRule::AnyAuthorityTarget => { + matches!(declared, RefKind::Subject(_) | PLACE) + } + } +} + +/// The magnitude ceiling for one slot. A closed enum matched to the operation's +/// dimension rather than a struct of optional ceilings: an `Option` ceiling that +/// is `None` is not a ceiling, and a struct admits the nonsense of a cost +/// ceiling on a `Transfer`. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "bound", content = "max", rename_all = "snake_case")] +pub(crate) enum Bounds { + None, + Quantity(Quantity), + Cost(Cost), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct EffectSlot { + pub(crate) op_kind: ComponentOpKind, + /// Positional: exactly the referents `op_kind` takes, in `arity()` order. + pub(crate) roles: Vec<Role>, + pub(crate) bounds: Bounds, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct OutcomeBand { + /// At least 1. A zero-weight band is a branch that can never be selected. + pub(crate) weight: u32, + /// Indices into `effect_slots`, strictly increasing. Empty is legal and is + /// how a world expresses "the attempt does nothing". + pub(crate) effects: Vec<usize>, +} + +/// One catalog entry: what an affordance *is*. Who may use it is +/// `affordance_grants` and nothing else, so an entry carries no audience. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct Affordance { + pub kind: AffordanceKindName, + /// Ordered, so the generated tool's parameters are stable across builds. + pub(crate) roles: Vec<RoleSpec>, + pub(crate) preconditions: Vec<Precondition>, + pub(crate) effect_slots: Vec<EffectSlot>, + pub(crate) outcome_bands: Vec<OutcomeBand>, + /// Every invocation of this entry carries exactly one utterance. The + /// kernel's only behaviour is to record it in the event; any world may + /// declare a speaking affordance, so this is not a Speak special case. + pub(crate) carries_speech: bool, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct AffordanceDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) kind: AffordanceKindName, + pub(crate) roles: Vec<RoleSpec>, + pub(crate) preconditions: Vec<Precondition>, + pub(crate) effect_slots: Vec<EffectSlot>, + pub(crate) outcome_bands: Vec<OutcomeBand>, + pub(crate) carries_speech: bool, +} + +/// Where a failed check appeared. One way to say it, for declarations and +/// operations alike. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "site", content = "at", rename_all = "snake_case")] +pub enum Site { + Declaration(DraftHandle), + Operation(usize), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct EvidenceRef(String); + +impl EvidenceRef { + /// The elaborator's evidence receipts are built here, and `Deserialize` + /// already mints one from any string, so this constructor gates nothing. + /// Canonical text is checked by the resolver, in the complete mismatch set. + pub(super) fn new(value: impl Into<String>) -> Self { + Self(value.into()) + } + + pub(super) fn text(&self) -> &str { + &self.0 + } +} + +/// The Aetheria record a subject was imported from: the CultCache schema id and +/// the record key, compared exactly as two separate texts so no pair of +/// distinct records can spell one key. Admission keeps the mapping injective; +/// a key is never matched by prefix, case or normalisation. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub struct ImportKey { + schema: String, + record: String, +} + +/// The longest either part of an import key may be, in bytes. +const MAX_IMPORT_KEY_PART_BYTES: usize = 200; + +impl ImportKey { + pub fn new(schema: impl Into<String>, record: impl Into<String>) -> Self { + Self { + schema: schema.into(), + record: record.into(), + } + } + + pub fn schema(&self) -> &str { + &self.schema + } + + pub fn record(&self) -> &str { + &self.record + } + + /// The one predicate for an import key, called by the resolver and by the + /// load-time state gate alike. The record part is canonical free text: not + /// empty, at most 200 bytes, no leading, trailing or doubled space, already NFC + /// (refused, never normalised, so the kernel derives no second spelling), + /// no control or format character, and no whitespace but U+0020. The schema + /// part is a schema id: the same text with no space at all. + pub(super) fn is_canonical(&self) -> bool { + is_canonical_key_text(&self.record) + && is_canonical_key_text(&self.schema) + && !self.schema.contains(' ') + } +} + +fn is_canonical_key_text(part: &str) -> bool { + !part.is_empty() + && part.len() <= MAX_IMPORT_KEY_PART_BYTES + && !part.starts_with(' ') + && !part.ends_with(' ') + && !part.contains(" ") + && unicode_normalization::is_nfc(part) + && part.chars().all(|c| { + !c.is_control() + && c.general_category() != GeneralCategory::Format + && (c == ' ' || !c.is_whitespace()) + }) +} + +/// Why an import key cannot join a world: the resolver names these by draft +/// handle, the state gates by invariant text. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum ImportKeyFault { + Malformed, + Held, + Duplicate, +} + +/// The keys the subjects hold, retired ones included, so a key is never +/// reissued. Derived on demand; no stored index. +pub(super) fn held_import_keys<'a>( + subjects: impl IntoIterator<Item = &'a super::SubjectState>, +) -> BTreeSet<&'a ImportKey> { + subjects + .into_iter() + .filter_map(|subject| subject.import_key.as_ref()) + .collect() +} + +/// The one decision on a key: malformed, held by a subject already in the +/// world, or already claimed in `declared` (which it joins). Every door that +/// admits or loads subjects calls this, so none can decide otherwise. +pub(super) fn import_key_fault<'a>( + key: &'a ImportKey, + held: &BTreeSet<&ImportKey>, + declared: &mut BTreeSet<&'a ImportKey>, +) -> Option<ImportKeyFault> { + if !key.is_canonical() { + Some(ImportKeyFault::Malformed) + } else if held.contains(key) { + Some(ImportKeyFault::Held) + } else if !declared.insert(key) { + Some(ImportKeyFault::Duplicate) + } else { + None + } +} + +/// `position` is the subject's presence: one place it stands in. A subject +/// declared without one is unplaced until a later pass gives placement an owner. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct SubjectDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) label: String, + pub(crate) kind: SubjectKind, + pub(crate) controller: NewController, + /// The catalog entries this subject may exercise. Every entry is a + /// reference, so a genesis patch declares a catalog and grants from it + /// atomically. + pub(crate) affordances: BTreeSet<Ref<AffordanceId>>, + pub(crate) position: Option<Ref<EntityId>>, + /// The record this subject was imported from, if any. Absent from a + /// subject nobody imported, so such a world's state and digests are what + /// they were before import keys existed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) import_key: Option<ImportKey>, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct EntityDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) label: String, + pub(crate) kind: EntityKind, + /// Legal only for `EntityKind::Place`, and only ever names a place. + pub(crate) container: Option<Ref<EntityId>>, +} + +/// A declared route is open. A route that should start closed is `declare` plus +/// `CloseRoute` in the same patch, so `open` has one writer family. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct RouteDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) label: String, + pub(crate) from: Ref<EntityId>, + pub(crate) to: Ref<EntityId>, + pub(crate) access: AccessKind, + pub(crate) cost: Cost, +} + +/// A fact's label is a short authored name ("the flooding of the lower hinge"), +/// never a transcript: the statement is never copied into the label and the +/// label is never derived from the statement, so the utterance has exactly one +/// home in state. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct FactDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) label: String, + pub(crate) statement: Statement, + pub(crate) standing: FactStandingRef, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct ChannelDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) label: String, + pub(crate) reach: ReachRef, + pub(crate) controller: Option<Ref<SubjectId>>, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", rename_all = "snake_case")] +pub(crate) enum Declaration { + Subject(SubjectDeclaration), + /// Places and resources only. `Fact` and `Channel` carry a payload and have + /// their own declarations, so a referenceable empty one is unrepresentable. + Entity(EntityDeclaration), + Route(RouteDeclaration), + Affordance(AffordanceDeclaration), + Fact(FactDeclaration), + Channel(ChannelDeclaration), +} + +/// The operations that change a component of an already canonical structure. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "op", rename_all = "snake_case")] +pub(crate) enum ComponentOp { + Relocate { + subject: Ref<SubjectId>, + via: Ref<EdgeId>, + }, + OpenRoute { + route: Ref<EdgeId>, + }, + CloseRoute { + route: Ref<EdgeId>, + }, + AlterCost { + route: Ref<EdgeId>, + cost: Cost, + }, + Transfer { + from: Ref<SubjectId>, + to: Ref<SubjectId>, + resource: Ref<EntityId>, + qty: Quantity, + }, + /// One-for-one relabel: the same `qty` leaves `from_resource` and arrives in + /// `into_resource`, held by the same subject. A ratio would be a recipe, and + /// recipes belong to the consumer that owns production; the op shape makes a + /// non-conserving transform unrepresentable rather than merely checkable. A + /// world that needs lossy conversion writes `Transform` plus `Consume`, and + /// both terms then appear in the ledger. + Transform { + holder: Ref<SubjectId>, + from_resource: Ref<EntityId>, + into_resource: Ref<EntityId>, + qty: Quantity, + }, + Consume { + holder: Ref<SubjectId>, + resource: Ref<EntityId>, + qty: Quantity, + }, + /// The only creation path for quantity, in every lane including genesis. Its + /// `evidence` must appear in the same patch's `evidence` list, which makes + /// creation attributable; the commit chain then makes it tamper-evident. + Admit { + holder: Ref<SubjectId>, + resource: Ref<EntityId>, + qty: Quantity, + evidence: EvidenceRef, + }, + /// Creates quantity with no receipt. Only `Play` may write it; every other + /// author creates quantity through `Admit` and its evidence. + Mint { + holder: Ref<SubjectId>, + resource: Ref<EntityId>, + qty: Quantity, + }, + Bind { + subject: Ref<SubjectId>, + target: DependencyRef, + }, + Release { + subject: Ref<SubjectId>, + target: DependencyRef, + }, + /// Adds one grant. An identical grant is `NoOperationEffect`; one that + /// overlaps another the holder already has is `OverlappingJurisdiction`. + GrantAuthority { + holder: Ref<SubjectId>, + grant: AuthorityGrantRef, + }, + RevokeAuthority { + holder: Ref<SubjectId>, + grant: AuthorityGrantRef, + }, + /// Creates or reconstitutes an office, preserving any sitting incumbent. + /// Clipping an office's powers under a sitting incumbent is a political + /// act, and this is how it is written. + OpenOffice { + institution: Ref<SubjectId>, + office: OfficeName, + delegated: BTreeSet<AuthorityKindName>, + }, + CloseOffice { + institution: Ref<SubjectId>, + office: OfficeName, + }, + InstallIncumbent { + institution: Ref<SubjectId>, + office: OfficeName, + incumbent: Ref<SubjectId>, + }, + VacateOffice { + institution: Ref<SubjectId>, + office: OfficeName, + }, + OpenForum { + grievance: GrievanceKindName, + forum: Ref<SubjectId>, + standing: AuthorityTargetRef, + }, + CloseForum { + grievance: GrievanceKindName, + }, + /// Source is authored: `Witnessed` by an author or an affordance, + /// `Evidenced` only over a `Canonical` fact. + AcquireKnowledge { + subject: Ref<SubjectId>, + fact: Ref<EntityId>, + source: AuthoredSource, + confidence: Confidence, + }, + /// One telling. It stores the audience, never the recipients: the fan-out is + /// re-derived at apply from live `positions` and `channels`. + Communicate { + speaker: Ref<SubjectId>, + fact: Ref<EntityId>, + to: AudienceRef, + }, + /// One witnessed event over a place subtree: a beacon, a bell, a blast, an + /// asteroid. It names no speaker, because the row it lands is + /// `KnowledgeSource::Witnessed` — there is no teller to forge and none is + /// implied. It stores the place, never the recipients: the subtree is + /// re-derived at apply from live `positions`. Everyone already holding the + /// fact is untouched, and a witness that reaches nobody is refused. + Witness { + fact: Ref<EntityId>, + place: Ref<EntityId>, + confidence: Confidence, + }, + Forget { + subject: Ref<SubjectId>, + fact: Ref<EntityId>, + }, + SetReach { + channel: Ref<EntityId>, + reach: ReachRef, + }, + SetController { + channel: Ref<EntityId>, + controller: Option<Ref<SubjectId>>, + }, + /// Sets, whole, what a subject carries as lived meaning. Identical material + /// is `NoOperationEffect`; any non-canonical text is `NoncanonicalText`. + SetPersonaMaterial { + subject: Ref<SubjectId>, + values: Vec<Statement>, + voice: Statement, + memories: Vec<Statement>, + reads: Vec<PersonaReadRef>, + }, + /// Two identical creations are two commitments, not `NoOperationEffect`: + /// the key is command-derived so they cannot collide, and two promises of + /// the same thing to the same counterparty are two promises. This is where + /// a commitment differs from a grant, a holding, and a dependency, all of + /// which are set-shaped. + CreateCommitment { + subject: Ref<SubjectId>, + counterparty: Option<Ref<SubjectId>>, + kind: CommitmentKind, + due: FictionalMinutes, + period: Option<TickMinutes>, + checks: Vec<PreconditionRef>, + statement: Statement, + }, + /// Removes the commitment and every pressure row sourced by it. Fulfilment, + /// default, and release are one write: the kernel never learns who invoked + /// an operation, so three names would be three spellings of one removal + /// with a distinction only a consumer can read. + DischargeCommitment { + subject: Ref<SubjectId>, + key: CommitmentKey, + }, + /// Insert-or-add, saturating. With absence meaning zero, creation and + /// advance are the same write. + AdvancePressure { + source: PressureSourceRef, + target: Ref<SubjectId>, + by: PressureMagnitude, + }, + /// Saturating subtract; removal at zero. + ReducePressure { + source: PressureSourceRef, + target: Ref<SubjectId>, + by: PressureMagnitude, + }, + ResolvePressure { + source: PressureSourceRef, + target: Ref<SubjectId>, + }, + /// Ends a subject's turn for good: no opportunity, no position, no + /// audience, its history kept. Only the owner and `Play` may write it. + Retire { + subject: Ref<SubjectId>, + }, + /// Grants one more standing catalog entry to an existing subject. Only the + /// owner (including the seed lane, the owner in Draft) and `Play` may + /// write it: a grant is authority, not structure, so a confined author is + /// refused whatever ground the subject stands on. + GrantAffordance { + subject: Ref<SubjectId>, + affordance: Ref<AffordanceId>, + }, + /// Revokes a grant. Refused if it would leave a controlled subject with + /// none: `derive_opportunities` requires at least one. + RevokeAffordance { + subject: Ref<SubjectId>, + affordance: Ref<AffordanceId>, + }, +} + +/// What an Active `AdmitPatch` answers. Draft answers nothing; Active must +/// answer a boundary the kernel currently derives or a jurisdiction whose +/// deficit is nonzero, and the commit must satisfy what it answered. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "answer", rename_all = "snake_case")] +pub enum PatchAnswer { + Boundary(super::CausalBoundary), + Deficit(JurisdictionKey), +} + +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct WorldPatch { + pub(crate) declarations: Vec<Declaration>, + pub(crate) operations: Vec<ComponentOp>, + pub(crate) evidence: Vec<EvidenceRef>, +} + +impl WorldPatch { + /// Whether any `SetPersonaMaterial` operation in this patch targets a + /// subject the patch does not itself declare — an existing, canonical + /// subject (`Ref::Existing`) rather than a draft handle this same patch's + /// own declarations introduced (`Ref::Draft`). `WorldPatch`'s fields are + /// `pub(crate)`, so a consumer that must refuse this shape (PA.f61: the + /// play agent may author a brand-new Persona's material, but never + /// rewrite an existing one's) reads it through this query rather than + /// parsing the patch's own JSON to decide. + pub fn sets_persona_of_existing_subject(&self) -> bool { + self.operations.iter().any(|operation| { + matches!( + operation, + ComponentOp::SetPersonaMaterial { + subject: Ref::Existing(_), + .. + } + ) + }) + } +} + +/// The one byte bound on a `WorldPatch` frame from any external source, and +/// the three item bounds on a `WorldPatch` as a value. One owner, two +/// consumers: the consumer ingress decodes against them through +/// `decode_patch`, and the elaboration lane checks its own assembled draft +/// against the same three item caps through `check_patch_caps`, before +/// submission. +pub(crate) const MAX_PATCH_BYTES: usize = 256 * 1024; +pub(crate) const MAX_PATCH_DECLARATIONS: usize = 64; +pub(crate) const MAX_PATCH_OPERATIONS: usize = 128; +pub(crate) const MAX_PATCH_EVIDENCE: usize = 64; + +/// Why a patch was refused before the resolver ever saw it. Not a second +/// structural vocabulary: nothing here reads world state. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PatchDecodeError { + TooLarge { bytes: usize }, + NotCanonical, + Malformed, + TooManyDeclarations { count: usize }, + TooManyOperations { count: usize }, + TooManyEvidence { count: usize }, +} + +/// The one decode owner for a `WorldPatch` from a byte source. The byte cap is +/// applied to the frame before `rmp_serde` sees it, so no item is deserialized +/// out of a frame the world would not accept; the item caps are checked on the +/// decoded value before `resolve_patch`, which is the first thing that costs +/// `state ∪ patch`. +pub(crate) fn decode_patch(bytes: &[u8]) -> Result<WorldPatch, PatchDecodeError> { + if bytes.len() > MAX_PATCH_BYTES { + return Err(PatchDecodeError::TooLarge { bytes: bytes.len() }); + } + let patch: WorldPatch = + rmp_serde::from_slice(bytes).map_err(|_| PatchDecodeError::Malformed)?; + // The canonical round-trip the journal and the presence route already + // require, so one frame has one encoding. + if rmp_serde::to_vec_named(&patch).map_err(|_| PatchDecodeError::Malformed)? != bytes { + return Err(PatchDecodeError::NotCanonical); + } + check_patch_caps(&patch)?; + Ok(patch) +} + +/// The same three item caps against an in-memory draft, for the lane that +/// builds rather than decodes. +pub(crate) fn check_patch_caps(patch: &WorldPatch) -> Result<(), PatchDecodeError> { + if patch.declarations.len() > MAX_PATCH_DECLARATIONS { + return Err(PatchDecodeError::TooManyDeclarations { + count: patch.declarations.len(), + }); + } + if patch.operations.len() > MAX_PATCH_OPERATIONS { + return Err(PatchDecodeError::TooManyOperations { + count: patch.operations.len(), + }); + } + if patch.evidence.len() > MAX_PATCH_EVIDENCE { + return Err(PatchDecodeError::TooManyEvidence { + count: patch.evidence.len(), + }); + } + Ok(()) +} + +/// One named structural check that a patch failed. A rejection carries the +/// complete set, never the first failure. It never enters `WorldState`, +/// `WorldEffect`, `CommandEnvelope`, or `WorldCommit`; the serde derives exist +/// for exactly one reader, the elaboration checkpoint, which is +/// controller-owned telemetry under its own row type and its own schema. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "mismatch", rename_all = "snake_case")] +pub enum Mismatch { + EmptyHandle { + position: usize, + }, + DuplicateHandle { + handle: DraftHandle, + }, + EmptyLabel { + handle: DraftHandle, + }, + /// The world is bound to a grammar and this affordance's kind is not one of + /// its verbs. + AffordanceKindNotInGrammar { + handle: DraftHandle, + }, + /// The kind is a verb of the bound grammar, but the declared roles are not + /// its signature (name, referent kind or order). + AffordanceRolesDisagreeWithGrammar { + handle: DraftHandle, + }, + /// The grammar binds the kernel's speak verb as anything but a Conversation. + SpeakRenderPathDisagreesWithGrammar { + handle: DraftHandle, + }, + /// An import key is empty, has whitespace, or is longer than 200 bytes in + /// either part. + MalformedImportKey { + handle: DraftHandle, + }, + /// Two subjects in one patch declare the same import key. + DuplicateImportKey { + handle: DraftHandle, + }, + /// A subject already in the world, retired or not, holds this import key. + ImportKeyHeld { + handle: DraftHandle, + }, + UnresolvedDraft { + site: Site, + referent: DraftHandle, + expected: RefKind, + }, + WrongKind { + site: Site, + referent: RefName, + expected: RefKind, + actual: RefKind, + }, + UnknownCanonical { + site: Site, + expected: RefKind, + }, + UnadmittedController { + handle: DraftHandle, + }, + /// A declared subject's controller and affordance grant do not pair: a + /// mirror was granted an affordance, or an ordinary controller was granted + /// none. `admit_resolved` re-decides the same rule. + ControllerGrantMismatch { + site: Site, + }, + EmptyEvidence { + position: usize, + }, + CanonicalCollision { + handle: DraftHandle, + }, + NoCanonicalChange, + /// A genesis-lane resolution (the same empty-state case `admits_human` + /// tests) declared no subject, so the world would have no decision + /// subject to admit. This is a rejected patch, not a corrupt journal: the + /// mailbox actor must survive it. + NoDecisionSubject, + /// A declared place contains itself through its container chain. + ContainmentCycle { + referent: DraftHandle, + }, + RouteSelfLoop { + referent: DraftHandle, + }, + InvalidCost { + site: Site, + }, + SubjectNotAtOrigin { + operation: usize, + }, + RouteClosed { + operation: usize, + }, + RouteAccessRestricted { + operation: usize, + }, + UnplacedSubject { + operation: usize, + }, + /// An operation that changes nothing is not a canonical change. + NoOperationEffect { + operation: usize, + }, + /// The holder does not hold enough. Absence is zero, so "holds none at all" + /// is this variant at the boundary rather than a second name. + InsufficientCustody { + operation: usize, + }, + /// A custody operation naming `Quantity(0)`: it moves nothing. + ZeroQuantity { + operation: usize, + }, + /// A credit that would leave a holding above `u64::MAX`. + QuantityOverflow { + operation: usize, + }, + /// An `Admit` whose `EvidenceRef` is not listed in this patch's `evidence`. + AdmitWithoutEvidence { + operation: usize, + }, + /// A `Bind` or `Release` naming the acting subject as its own target. + SelfDependency { + operation: usize, + }, + /// The candidate ledger does not balance for this resource: the total after + /// the patch is not the total before plus what was admitted and gained, less + /// what was consumed and spent. + CustodyNotConserved { + resource: RefName, + }, + /// `kind` is not `[a-z][a-z0-9_]{0,47}`, or a `Role` is not + /// `[a-z][a-z0-9_]{0,31}`. Tool and parameter names must be safe. + InvalidAffordanceName { + handle: DraftHandle, + }, + /// Two entries in the candidate graph share one kind name; the generated + /// tool catalog would have two tools with one name. + DuplicateAffordanceKind { + handle: DraftHandle, + }, + DuplicateRole { + handle: DraftHandle, + role: Role, + }, + /// A precondition or a slot names a role the entry does not declare. + UnknownRole { + handle: DraftHandle, + role: Role, + }, + /// A declared role's `RefKind` cannot serve the position that reads it, or + /// names a namespace no invocation target can bind. + RoleKindUnfit { + handle: DraftHandle, + role: Role, + }, + SlotRoleArity { + handle: DraftHandle, + slot: usize, + }, + /// The slot's `Bounds` variant does not match its `op_kind`'s dimension, or + /// the ceiling is zero, or a cost ceiling is outside `1..=MAX_ROUTE_COST`. + SlotBoundMismatch { + handle: DraftHandle, + slot: usize, + }, + NoOutcomeBand { + handle: DraftHandle, + }, + ZeroBandWeight { + handle: DraftHandle, + band: usize, + }, + /// A band names a slot index the entry does not have. + DanglingBandEffect { + handle: DraftHandle, + band: usize, + }, + /// A band's `effects` are not strictly increasing. + BandEffectsNotCanonical { + handle: DraftHandle, + band: usize, + }, + /// No effect slots and no speech: the entry can never change anything. + InertAffordance { + handle: DraftHandle, + }, + /// An `OfficeName`, `AuthorityKindName`, or `GrievanceKindName` that is not + /// `[a-z][a-z0-9_]{0,47}`. + InvalidCivicName { + site: Site, + }, + /// `OpenOffice` lending no authority kind. + EmptyDelegation { + operation: usize, + }, + /// The institution named by an office operation is not + /// `SubjectKind::Institution`. + OfficeOnNonInstitution { + operation: usize, + }, + /// An incumbent that is not `SubjectKind::Person`. This is the check that + /// keeps an institution's operational organ and its person-shaped voice two + /// subjects joined by an office. + OfficeHolderNotPerson { + operation: usize, + }, + /// This person already occupies another office of this institution. + DuplicateIncumbency { + operation: usize, + }, + /// `InstallIncumbent`, `VacateOffice`, or `CloseOffice` naming an office the + /// institution does not have. + UnknownOffice { + operation: usize, + }, + /// `CloseForum` naming a grievance no forum takes. + UnknownForum { + operation: usize, + }, + /// One subject would hold two grants of the same kind over overlapping + /// targets, from any combination of direct grant and office delegation. + /// Overlap between *different* subjects is layered government and legal: + /// `Authorized` is a permission predicate, not an exclusivity claim, and + /// this rule exists so nothing ever has to arbitrate between two sources. + OverlappingJurisdiction { + operation: usize, + }, + /// A catalog entry declares a role named `actor`, which the kernel binds. + ReservedRole { + handle: DraftHandle, + }, + /// An `EntityDeclaration` naming `Fact` or `Channel`. Those kinds carry a + /// payload and have their own declaration; a payload-less one would make a + /// referenceable, empty fact a legal state. + PayloadEntityKind { + handle: DraftHandle, + }, + /// A `Canonical` fact declaration whose `EvidenceRef` is not listed in this + /// patch's `evidence`. + FactWithoutEvidence { + handle: DraftHandle, + }, + EmptyStatement { + handle: DraftHandle, + }, + /// A commitment statement or a piece of persona material that is empty, + /// padded, or spans lines. + NoncanonicalText { + operation: usize, + }, + /// `AcquireKnowledge { source: Evidenced }` over a `Claimed` fact. + EvidencedKnowledgeOfClaim { + operation: usize, + }, + /// A `Communicate` whose speaker is neither inside the audience nor the + /// channel's controller. + SpeakerOutsideAudience { + operation: usize, + }, + /// A catalog entry with `carries_speech` and no `CanBroadcast` or + /// `CanReach`: its speech would have no audience to lower. + SpeechWithoutAudience { + handle: DraftHandle, + }, + /// More than one, so the lowering could not choose. + AmbiguousSpeechAudience { + handle: DraftHandle, + }, + /// A `Routine` with no period, or a non-`Routine` with one. + CommitmentPeriodMismatch { + operation: usize, + }, + /// A non-`Routine` carrying checks. Nothing would ever evaluate them. + ChecksOnNonRoutine { + operation: usize, + }, + /// `due <= now` at creation. A promise cannot be born past due; it would + /// press on its subject on the very next tick with no chance to act. + CommitmentDueInThePast { + operation: usize, + }, + /// `counterparty == subject`. + SelfCommitment { + operation: usize, + }, + /// A goal is a promise to oneself, and a promise to another is an + /// obligation. This keeps the scale count's `Goal` clause meaning one thing. + GoalWithCounterparty { + operation: usize, + }, + /// `DischargeCommitment` naming a key the subject does not hold. + UnknownCommitment { + operation: usize, + }, + /// A scale-intent jurisdiction root that is not a declared place. + UnknownJurisdictionRoot { + handle: DraftHandle, + }, + /// The permille weights sum over 1000: weights distribute the target and + /// never raise it. + ScaleWeightsExceedWhole, + /// A lens weight set with no nonzero weight, at genesis or in + /// `SetLensWeights`. A single zero weight is admitted and never draws. + LensWeightsNeverDraw, + /// A jurisdictional author wrote outside its jurisdiction. The owner is + /// unconfined and never sees this. + OutsideJurisdiction { + site: Site, + }, + /// A `Ruled` fact or a `Mint` was written by a caller other than the play + /// authority. + RuledWithoutAuthority { + site: Site, + }, + /// `Retire` named an `ExternallyControlled` subject: a mirror is owned by + /// another world, so this one cannot retire it. + RetiresAMirror { + operation: usize, + }, + /// `Retire` named a `Human`-controlled subject while the world is still in + /// `Draft`. A human's Draft approval cannot be removed by removing the + /// human; the same retire is admitted once the world is `Active`. + RetiresAnApprover { + operation: usize, + }, + /// `Communicate`, `AcquireKnowledge`, `Forget`, or `InstallIncumbent` + /// named a retired subject as the one acting, learning, forgetting, or + /// taking office. A retired subject is a body, not an actor: it may still + /// be a holdings source (looted), a channel member, or a route endpoint, + /// but it cannot be the one who speaks, knows, or holds office. + RetiredSubjectActed { + operation: usize, + }, + /// `GrantAffordance` or `RevokeAffordance` named a retired or an + /// `ExternallyControlled` subject: neither holds a grant this patch may + /// touch. + GrantsOutsideControl { + operation: usize, + }, + /// A `RevokeAffordance` that would leave a controlled subject with no + /// affordance at all. `derive_opportunities` requires at least one; a + /// subject is never left mute. + WouldLeaveSubjectMute { + operation: usize, + }, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct EntityRecord { + pub(super) label: String, + pub(super) kind: EntityKind, + /// `Some` only for `EntityKind::Place`, and only ever a place. + pub(super) container: Option<EntityId>, +} + +/// One variant per edge kind that has a shape, so no record carries fields that +/// are meaningless for its discriminator. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub(super) enum EdgeRecord { + Route { + label: String, + from: EntityId, + to: EntityId, + access: AccessKind, + cost: Cost, + open: bool, + }, +} + +impl EdgeRecord { + pub(super) fn endpoints(&self) -> (EntityId, EntityId) { + match self { + Self::Route { from, to, .. } => (*from, *to), + } + } + + pub(super) fn label(&self) -> &str { + match self { + Self::Route { label, .. } => label, + } + } + + pub(super) fn cost(&self) -> Cost { + match self { + Self::Route { cost, .. } => *cost, + } + } + + pub(super) fn access(&self) -> &AccessKind { + match self { + Self::Route { access, .. } => access, + } + } + + pub(super) fn is_open(&self) -> bool { + match self { + Self::Route { open, .. } => *open, + } + } + + pub(super) fn set_open(&mut self, value: bool) { + match self { + Self::Route { open, .. } => *open = value, + } + } + + pub(super) fn set_cost(&mut self, value: Cost) { + match self { + Self::Route { cost, .. } => *cost = value, + } + } +} + +/// The handle-to-ID binding table for one subject. The handle is commit-scoped +/// provenance; it never enters `WorldState`. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedSubject { + pub(super) handle: DraftHandle, + pub(super) subject_id: SubjectId, + pub(super) subject: SubjectState, + pub(super) controller: ControllerAssignment, + pub(super) affordances: BTreeSet<AffordanceId>, + pub(super) position: Option<Position>, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedEntity { + pub(super) handle: DraftHandle, + pub(super) entity_id: EntityId, + pub(super) entity: EntityRecord, +} + +/// The handle-to-ID binding for one catalog entry. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedAffordance { + pub(super) handle: DraftHandle, + pub(super) affordance_id: AffordanceId, + pub(super) affordance: Affordance, +} + +/// A declared fact: one `entities` row and one `facts` row, allocated together +/// so the bijection has one writer. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedFact { + pub(super) handle: DraftHandle, + pub(super) entity_id: EntityId, + pub(super) entity: EntityRecord, + pub(super) fact: FactRecord, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedChannel { + pub(super) handle: DraftHandle, + pub(super) entity_id: EntityId, + pub(super) entity: EntityRecord, + pub(super) channel: ChannelRecord, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedRoute { + pub(super) handle: DraftHandle, + pub(super) edge_id: EdgeId, + pub(super) edge: EdgeRecord, +} + +/// A lowered operation. `Relocate` carries no endpoints: they are read from the +/// route at apply time, so a forged effect cannot assert a destination the route +/// does not have. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "op", rename_all = "snake_case")] +pub(crate) enum ResolvedOp { + Relocate { + subject_id: SubjectId, + edge_id: EdgeId, + }, + OpenRoute { + edge_id: EdgeId, + }, + CloseRoute { + edge_id: EdgeId, + }, + AlterCost { + edge_id: EdgeId, + cost: Cost, + }, + Transfer { + from: SubjectId, + to: SubjectId, + resource: EntityId, + qty: Quantity, + }, + Transform { + holder: SubjectId, + from_resource: EntityId, + into_resource: EntityId, + qty: Quantity, + }, + Consume { + holder: SubjectId, + resource: EntityId, + qty: Quantity, + }, + Admit { + holder: SubjectId, + resource: EntityId, + qty: Quantity, + evidence: EvidenceRef, + }, + Mint { + holder: SubjectId, + resource: EntityId, + qty: Quantity, + }, + Bind { + subject: SubjectId, + target: DependencyTarget, + }, + Release { + subject: SubjectId, + target: DependencyTarget, + }, + GrantAuthority { + holder: SubjectId, + grant: AuthorityGrant, + }, + RevokeAuthority { + holder: SubjectId, + grant: AuthorityGrant, + }, + OpenOffice { + institution: SubjectId, + office: OfficeName, + delegated: BTreeSet<AuthorityKindName>, + }, + CloseOffice { + institution: SubjectId, + office: OfficeName, + }, + InstallIncumbent { + institution: SubjectId, + office: OfficeName, + incumbent: SubjectId, + }, + VacateOffice { + institution: SubjectId, + office: OfficeName, + }, + OpenForum { + grievance: GrievanceKindName, + forum: SubjectId, + standing: AuthorityTarget, + }, + CloseForum { + grievance: GrievanceKindName, + }, + AcquireKnowledge { + subject: SubjectId, + fact: EntityId, + source: AuthoredSource, + confidence: Confidence, + }, + /// Stores the audience, never the recipients. `apply_operation` re-derives + /// the fan-out from live `positions`/`channels`, exactly as `Relocate` + /// stores `edge_id` and re-derives the destination, so a forged effect + /// cannot assert a landing the world does not have. + Communicate { + speaker: SubjectId, + fact: EntityId, + to: Audience, + }, + /// A visible act: the actor's own sentence, seen by everyone standing in + /// the actor's place. Lowered only by the kernel's speech path beside + /// `AssertClaim`, never by a patch, so no seed or elaborator can move a + /// person's body from outside the person. There is no audience field: a + /// display cannot go down a channel, and the room is re-derived from live + /// `positions` at apply, so a forged effect cannot assert a landing the + /// world does not have. + Display { + actor: SubjectId, + fact: EntityId, + }, + /// Stores the place, never the recipients. `apply_operation` re-derives the + /// subtree from live `positions`, so a forged effect cannot assert a + /// landing the world does not have. There is no speaker field, so this + /// operation cannot write `KnowledgeSource::Told` however it is forged. + Witness { + fact: EntityId, + place: EntityId, + confidence: Confidence, + }, + Forget { + subject: SubjectId, + fact: EntityId, + }, + SetReach { + channel: EntityId, + reach: Reach, + }, + SetController { + channel: EntityId, + controller: Option<SubjectId>, + }, + SetPersonaMaterial { + subject: SubjectId, + material: PersonaMaterial, + }, + /// Kernel-only: no [`ComponentOp`] twin, because no proposer may author one. + /// Synthesized by `action::exercise` for a speech-carrying invocation and by + /// nothing else. Inserts the entity row and the `facts` row; it writes no + /// knowledge, because a speaker's own knowledge of its claim is not implied. + AssertClaim { + fact: EntityId, + statement: Statement, + by: SubjectId, + }, + CreateCommitment { + subject: SubjectId, + key: CommitmentKey, + commitment: Commitment, + }, + DischargeCommitment { + subject: SubjectId, + key: CommitmentKey, + }, + AdvancePressure { + source: PressureSource, + target: SubjectId, + by: PressureMagnitude, + }, + ReducePressure { + source: PressureSource, + target: SubjectId, + by: PressureMagnitude, + }, + ResolvePressure { + source: PressureSource, + target: SubjectId, + }, + Retire { + subject: SubjectId, + }, + GrantAffordance { + subject: SubjectId, + affordance: AffordanceId, + }, + RevokeAffordance { + subject: SubjectId, + affordance: AffordanceId, + }, +} + +/// One resource's movement across a whole patch. Accumulators are `u128` so an +/// intermediate total cannot overflow while a stored per-holder `Quantity` stays +/// `u64`. +#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)] +pub(super) struct LedgerDelta { + pub(super) before: u128, + pub(super) after: u128, + pub(super) admitted: u128, + pub(super) consumed: u128, + pub(super) gained: u128, + pub(super) spent: u128, +} + +/// The only statement of custody conservation, called by the resolver over the +/// candidate map and again by `admit_resolved` over the committed partitions. +/// Returns the first resource whose ledger does not balance, in key order, so +/// the verdict is deterministic. +/// +/// `Transfer` contributes to no term: its correctness is *proven by* this +/// equation, because a transfer that moved a different amount out than in breaks +/// the total for that resource. `Transform` contributes the same `qty` to one +/// `spent` and one `gained`, so the one-for-one rule is this equation restricted +/// to a single operation. Nothing else states conservation anywhere. +pub(super) fn check_ledger<R: Ord + Clone>(deltas: &BTreeMap<R, LedgerDelta>) -> Option<R> { + deltas + .iter() + .find(|(_, delta)| { + let credited = delta + .before + .checked_add(delta.admitted) + .and_then(|total| total.checked_add(delta.gained)); + let expected = credited + .and_then(|total| total.checked_sub(delta.consumed)) + .and_then(|total| total.checked_sub(delta.spent)); + expected != Some(delta.after) + }) + .map(|(resource, _)| resource.clone()) +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedPatch { + pub(super) subjects: Vec<ResolvedSubject>, + pub(super) entities: Vec<ResolvedEntity>, + pub(super) routes: Vec<ResolvedRoute>, + pub(super) affordances: Vec<ResolvedAffordance>, + pub(super) facts: Vec<ResolvedFact>, + pub(super) channels: Vec<ResolvedChannel>, + pub(super) operations: Vec<ResolvedOp>, + pub(super) evidence: Vec<EvidenceRef>, + /// `Some` on the genesis lane and nowhere else: `CommandBody::AdmitPatch` + /// carries no intent, so the write-once rule is the command shape rather + /// than a check. + pub(super) scale_intent: Option<WorldScaleIntent>, + /// `Some` on the genesis lane and nowhere else, as `scale_intent` is. After + /// genesis the weights change only through `SetLensWeights`. + pub(super) lens_weights: Option<LensWeights>, +} + +impl ResolvedPatch { + pub(super) fn declares_nothing(&self) -> bool { + self.subjects.is_empty() + && self.entities.is_empty() + && self.routes.is_empty() + && self.affordances.is_empty() + && self.facts.is_empty() + && self.channels.is_empty() + && self.evidence.is_empty() + } +} + +const SUBJECT_NAMESPACE: &str = "ghostlight.id.subject.v1"; +pub(super) const ENTITY_NAMESPACE: &str = "ghostlight.id.entity.v1"; +const EDGE_NAMESPACE: &str = "ghostlight.id.edge.v1"; +const CONTROLLER_NAMESPACE: &str = "ghostlight.id.controller.v1"; +const AFFORDANCE_NAMESPACE: &str = "ghostlight.id.affordance.v1"; + +const PLACE: RefKind = RefKind::Entity(EntityKind::Place); +const FACT: RefKind = RefKind::Entity(EntityKind::Fact); +const CHANNEL: RefKind = RefKind::Entity(EntityKind::Channel); +const ROUTE: RefKind = RefKind::Edge(EdgeKind::Route); +const ANY_SUBJECT: RefKind = RefKind::Subject(None); + +/// A candidate-graph key: a structure this patch declares, or one the world +/// already holds. Candidate topology is checked before any ID is minted, so it +/// is keyed by reference rather than by canonical ID. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum Key<Id> { + Existing(Id), + Draft(DraftHandle), +} + +fn key_of<Id: Copy>(reference: &Ref<Id>) -> Key<Id> { + match reference { + Ref::Existing(id) => Key::Existing(*id), + Ref::Draft(handle) => Key::Draft(handle.clone()), + } +} + +/// [`DependencyTarget`] over candidate keys, so a dependency on a structure this +/// patch declares is checked before any ID is minted. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum TargetKey { + Resource(Key<EntityId>), + Route(Key<EdgeId>), + Subject(Key<SubjectId>), +} + +/// [`PressureSource`] over candidate keys. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum PressureSourceKey { + Commitment { + subject: Key<SubjectId>, + key: CommitmentKey, + }, + Dependency(TargetKey), + Subject(Key<SubjectId>), +} + +/// [`AuthorityTarget`] over candidate keys, so a grant over a place this patch +/// declares is checked before any ID is minted. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum AuthorityTargetKey { + Subject(Key<SubjectId>), + PlaceSubtree(Key<EntityId>), +} + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +struct GrantKey { + kind: AuthorityKindName, + over: AuthorityTargetKey, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct OfficeCandidate { + incumbent: Option<Key<SubjectId>>, + delegated: BTreeSet<AuthorityKindName>, +} + +/// Whether two jurisdictions of one kind cover common ground. Structural on +/// purpose: identity for named subordinates, containment for territory, and +/// never across the two, so the answer cannot decay when a subject walks +/// somewhere. Containment is fixed at declaration, so every way of creating an +/// overlap is a checked operation. +fn candidate_targets_overlap( + left: &AuthorityTargetKey, + right: &AuthorityTargetKey, + containers: &BTreeMap<Key<EntityId>, Key<EntityId>>, +) -> bool { + match (left, right) { + (AuthorityTargetKey::Subject(one), AuthorityTargetKey::Subject(other)) => one == other, + (AuthorityTargetKey::PlaceSubtree(one), AuthorityTargetKey::PlaceSubtree(other)) => { + key_covers_place(one, other, containers) || key_covers_place(other, one, containers) + } + _ => false, + } +} + +/// Whether a candidate `Subject` grant target and a candidate `PlaceSubtree` +/// grant target of one kind name overlapping ground: a `PlaceSubtree` grant +/// covers a `Subject` grant's target when the subject's committed position +/// sits under that subtree. Checked live against `state` rather than the +/// candidate graph, because `covers` reads committed position and +/// containment, not anything a patch declares; a target still in this +/// patch's drafts has no committed position and so cannot overlap here. This +/// is the one cross-shape case `candidate_targets_overlap` leaves alone by +/// construction — same-shape overlap is its job, not this one's. +fn grant_targets_nest( + state: &super::WorldState, + left: &AuthorityTargetKey, + right: &AuthorityTargetKey, +) -> bool { + let place_and_subject = |a: &AuthorityTargetKey, b: &AuthorityTargetKey| match (a, b) { + ( + AuthorityTargetKey::PlaceSubtree(Key::Existing(place)), + AuthorityTargetKey::Subject(Key::Existing(subject_id)), + ) => Some((*place, *subject_id)), + _ => None, + }; + place_and_subject(left, right) + .or_else(|| place_and_subject(right, left)) + .is_some_and(|(place, subject_id)| { + super::covers( + state, + AuthorityTarget::PlaceSubtree(place), + super::Target::Subject(subject_id), + ) + }) +} + +fn target_key_of(target: AuthorityTarget) -> AuthorityTargetKey { + match target { + AuthorityTarget::Subject(subject_id) => { + AuthorityTargetKey::Subject(Key::Existing(subject_id)) + } + AuthorityTarget::PlaceSubtree(entity_id) => { + AuthorityTargetKey::PlaceSubtree(Key::Existing(entity_id)) + } + } +} + +fn grant_key_of(grant: &AuthorityGrant) -> GrantKey { + GrantKey { + kind: grant.kind.clone(), + over: target_key_of(grant.over), + } +} + +/// The candidate authority of one subject, projected to the canonical referents +/// [`covers`](super::covers) reads. A grant naming structure this patch declares +/// cannot cover a place an already-canonical route reaches, so the projection +/// loses nothing the `Restricted` rule asks about. +fn canonical_grants(grants: &BTreeSet<GrantKey>) -> BTreeSet<AuthorityGrant> { + grants + .iter() + .filter_map(|grant| { + let over = match &grant.over { + AuthorityTargetKey::Subject(Key::Existing(subject_id)) => { + AuthorityTarget::Subject(*subject_id) + } + AuthorityTargetKey::PlaceSubtree(Key::Existing(entity_id)) => { + AuthorityTarget::PlaceSubtree(*entity_id) + } + _ => return None, + }; + Some(AuthorityGrant { + kind: grant.kind.clone(), + over, + }) + }) + .collect() +} + +/// Own grants plus what every held office lends, over the candidate graph. The +/// canonical twin is `scope_components` plus `effective_authority`; this one +/// answers the same question before any ID is minted. +fn candidate_effective_authority( + holder: &Key<SubjectId>, + authority: &BTreeMap<Key<SubjectId>, BTreeSet<GrantKey>>, + selection: &BTreeMap<(Key<SubjectId>, OfficeName), OfficeCandidate>, + retired: &BTreeSet<Key<SubjectId>>, +) -> BTreeSet<GrantKey> { + let mut effective = authority.get(holder).cloned().unwrap_or_default(); + for ((institution, _), office) in selection { + if office.incumbent.as_ref() != Some(holder) { + continue; + } + // A retired institution lends nothing, the same predicate + // `delegated_authority` reads canonically: `Retire` does not vacate + // offices, so the resolver and the kernel must not disagree about + // whether a dead institution's grants still reach its office-holders. + if retired.contains(institution) { + continue; + } + for grant in authority.get(institution).into_iter().flatten() { + if office.delegated.contains(&grant.kind) { + effective.insert(grant.clone()); + } + } + } + effective +} + +/// A fact in the candidate graph. Only its standing matters to resolution: the +/// statement is never read and never compared. +#[derive(Clone, Debug, PartialEq, Eq)] +enum FactCandidate { + Canonical, + Claimed(Key<SubjectId>), + Ruled, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +enum ReachKey { + Subjects(BTreeSet<Key<SubjectId>>), + Place(Key<EntityId>), +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct ChannelCandidate { + reach: ReachKey, + controller: Option<Key<SubjectId>>, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +enum KnowledgeSourceKey { + Witnessed, + Told { + by: Key<SubjectId>, + via: Option<Key<EntityId>>, + }, + Seen { + by: Key<SubjectId>, + }, + Evidenced, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct KnowledgeCandidate { + confidence: Confidence, + source: KnowledgeSourceKey, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +enum AudienceKey { + Colocated, + Channel(Key<EntityId>), +} + +/// Whether a subject is inside an audience over the candidate graph: the same +/// question `audience()` answers over committed state, asked before any ID is +/// minted. A controller is inside its own channel's audience for the purpose of +/// speaking on it — the horn belongs to the temple. +fn candidate_in_audience( + subject: &Key<SubjectId>, + audience: &AudienceKey, + speaker: &Key<SubjectId>, + positions: &BTreeMap<Key<SubjectId>, Key<EntityId>>, + channels: &BTreeMap<Key<EntityId>, ChannelCandidate>, + containers: &BTreeMap<Key<EntityId>, Key<EntityId>>, +) -> bool { + match audience { + AudienceKey::Colocated => match (positions.get(speaker), positions.get(subject)) { + (Some(here), Some(there)) => here == there, + _ => false, + }, + AudienceKey::Channel(channel) => { + let Some(record) = channels.get(channel) else { + return false; + }; + if record.controller.as_ref() == Some(subject) { + return true; + } + match &record.reach { + ReachKey::Subjects(members) => members.contains(subject), + ReachKey::Place(root) => positions + .get(subject) + .is_some_and(|place| key_covers_place(root, place, containers)), + } + } + } +} + +#[derive(Clone, Debug)] +struct RouteCandidate { + from: Key<EntityId>, + to: Key<EntityId>, + access: AccessKind, + cost: Cost, + open: bool, +} + +/// The only canonical ID allocator, called from exactly two sites: +/// [`resolve_patch`] and `action::exercise`. Deterministic on purpose: journal +/// replay recomputes `reduce` and requires effect equality, so a reduce arm can +/// never draw a `Uuid::new_v4`. Preimage fields are length-prefixed where they +/// are variable-width, so the concatenation is unambiguous — `discriminator` +/// included: a bare presence byte followed by a length prefix means +/// `Some("")` and `None` write different bytes, where an unprefixed +/// `Some("")` would have written nothing, same as `None`. +pub(super) fn derive_id( + namespace: &str, + world_id: WorldId, + command_id: CommandId, + handle: &DraftHandle, + discriminator: Option<&str>, +) -> Uuid { + let mut hasher = Sha256::new(); + hasher.update(namespace.as_bytes()); + hasher.update(world_id.0.as_bytes()); + hasher.update(command_id.0.as_bytes()); + hasher.update((handle.0.len() as u64).to_be_bytes()); + hasher.update(handle.0.as_bytes()); + match discriminator { + Some(discriminator) => { + hasher.update([1u8]); + hasher.update((discriminator.len() as u64).to_be_bytes()); + hasher.update(discriminator.as_bytes()); + } + None => hasher.update([0u8]), + } + let mut bytes = [0u8; 16]; + bytes.copy_from_slice(&hasher.finalize()[..16]); + Uuid::from_bytes(bytes) +} + +pub(super) fn is_canonical_text(value: &str) -> bool { + !value.trim().is_empty() && value.trim() == value +} + +pub(super) fn is_valid_cost(cost: Cost) -> bool { + (1..=MAX_ROUTE_COST).contains(&cost.0) +} + +/// The one role name the kernel owns. A catalog entry may not declare it and an +/// invocation may not bind it: stage 2 binds it to the acting subject, so a slot +/// that must land on the actor — the payee of a levy, say — says so instead of +/// letting the proposer point it at a friend. +pub(super) const ACTOR_ROLE: &str = "actor"; + +/// Authority kinds, office names, and grievance kinds share the affordance +/// alphabet: world-declared, kernel-opaque, and safe to surface in a generated +/// tool description. +pub(super) fn is_civic_name(value: &str) -> bool { + is_tool_name(value, 48) +} + +/// `[a-z][a-z0-9_]{0,max-1}`. Affordance kinds and roles become generated tool +/// and parameter names, so the alphabet is the safe one and the bound is stated +/// rather than assumed. +fn is_tool_name(value: &str, max: usize) -> bool { + let mut characters = value.chars(); + characters + .next() + .is_some_and(|first| first.is_ascii_lowercase()) + && value.len() <= max + && value.chars().all(|character| { + character.is_ascii_lowercase() || character.is_ascii_digit() || character == '_' + }) +} + +/// The handle of the kernel-built Speak entry. It is indexed in the same draft +/// index as world-declared entries, so a genesis subject grants it with an +/// ordinary `Ref::Draft` and there is no second grant path. +pub(super) const KERNEL_SPEAK_HANDLE: &str = "ghostlight.affordance.speak"; + +/// The grant every genesis subject carries: a draft reference to the +/// kernel-built entry, resolved by the ordinary handle index. World ingress and +/// every fixture name this rather than repeating the handle literal. +pub(super) fn kernel_speak_grant() -> BTreeSet<Ref<AffordanceId>> { + BTreeSet::from([Ref::Draft(DraftHandle::new(KERNEL_SPEAK_HANDLE))]) +} + +/// Zero roles, zero slots, one empty band, one utterance, and one audience: a +/// voice fills the room it is standing in. Zero roles is load-bearing — the +/// Interpreter lane submits no bindings and a consumer's speak payload carries +/// only +/// text. The precondition is not vacuous: an unplaced subject has no +/// co-location audience and fails with `NoAudience`. +pub(super) fn kernel_speak_entry() -> Affordance { + Affordance { + kind: AffordanceKindName("speak".into()), + roles: Vec::new(), + preconditions: vec![Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + } +} + +/// Whether a stored catalog entry would still be admitted by the declaration +/// validator. One validator, two readers: the resolver rejects a bad entry, and +/// journal recovery refuses a store that already holds one. +pub(super) fn entry_is_admissible(entry: &Affordance) -> bool { + let mut mismatches = Vec::new(); + validate_affordance( + &DraftHandle::new(""), + &entry.kind, + &entry.roles, + &entry.preconditions, + &entry.effect_slots, + &entry.outcome_bands, + entry.carries_speech, + &mut mismatches, + ); + mismatches.is_empty() +} + +/// The catalog-entry resolver, beside `resolve_entity`/`_subject`/`_route`. An +/// entry carries no components, so there is nothing to check past namespace +/// agreement. +fn resolve_affordance( + site: Site, + reference: &Ref<AffordanceId>, + index: &BTreeMap<DraftHandle, RefKind>, + catalog: &BTreeMap<AffordanceId, Affordance>, + mismatches: &mut Vec<Mismatch>, +) -> Option<Key<AffordanceId>> { + match reference { + Ref::Draft(named) => match index.get(named) { + None => { + mismatches.push(Mismatch::UnresolvedDraft { + site, + referent: named.clone(), + expected: RefKind::Affordance, + }); + None + } + Some(kind) if *kind != RefKind::Affordance => { + mismatches.push(Mismatch::WrongKind { + site, + referent: RefName::Affordance(reference.clone()), + expected: RefKind::Affordance, + actual: *kind, + }); + None + } + Some(_) => Some(Key::Draft(named.clone())), + }, + Ref::Existing(affordance_id) => { + if catalog.contains_key(affordance_id) { + Some(Key::Existing(*affordance_id)) + } else { + mismatches.push(Mismatch::UnknownCanonical { + site, + expected: RefKind::Affordance, + }); + None + } + } + } +} + +/// The one validator of a catalog entry, run per declared entry in declaration +/// order inside the resolver's accumulate-then-gate loop. +fn validate_affordance( + handle: &DraftHandle, + kind: &AffordanceKindName, + roles: &[RoleSpec], + preconditions: &[Precondition], + effect_slots: &[EffectSlot], + outcome_bands: &[OutcomeBand], + carries_speech: bool, + mismatches: &mut Vec<Mismatch>, +) { + let site = || Site::Declaration(handle.clone()); + if !is_tool_name(&kind.0, 48) || roles.iter().any(|spec| !is_tool_name(&spec.role.0, 32)) { + mismatches.push(Mismatch::InvalidAffordanceName { + handle: handle.clone(), + }); + } + let mut declared: BTreeMap<Role, RefKind> = BTreeMap::new(); + for spec in roles { + if spec.role.0 == ACTOR_ROLE { + mismatches.push(Mismatch::ReservedRole { + handle: handle.clone(), + }); + } + match declared.entry(spec.role.clone()) { + Entry::Vacant(slot) => { + slot.insert(spec.kind); + } + Entry::Occupied(_) => mismatches.push(Mismatch::DuplicateRole { + handle: handle.clone(), + role: spec.role.clone(), + }), + } + // No `Target` names the catalog namespace, so a role of that kind could + // never be bound. + if spec.kind == RefKind::Affordance { + mismatches.push(Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: spec.role.clone(), + }); + } + } + // The kernel binds `actor` to the acting subject, so preconditions and + // slots may name it like any role. + declared.insert(Role(ACTOR_ROLE.into()), ANY_SUBJECT); + let require = + |role: &Role, expected: RefKind, mismatches: &mut Vec<Mismatch>| match declared.get(role) { + None => mismatches.push(Mismatch::UnknownRole { + handle: handle.clone(), + role: role.clone(), + }), + Some(actual) if *actual != expected => mismatches.push(Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: role.clone(), + }), + Some(_) => {} + }; + let require_subject = |role: &Role, mismatches: &mut Vec<Mismatch>| match declared.get(role) { + None => mismatches.push(Mismatch::UnknownRole { + handle: handle.clone(), + role: role.clone(), + }), + Some(RefKind::Subject(_)) => {} + Some(_) => mismatches.push(Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: role.clone(), + }), + }; + let require_audience = |via: &AudienceSpec, mismatches: &mut Vec<Mismatch>| match via { + AudienceSpec::Colocated => {} + AudienceSpec::Channel(role) => require(role, CHANNEL, mismatches), + }; + for precondition in preconditions { + match precondition { + Precondition::Present { at } => { + require(at, RefKind::Entity(EntityKind::Place), mismatches); + } + Precondition::Reachable { to, within } => { + require(to, RefKind::Entity(EntityKind::Place), mismatches); + if !is_valid_cost(*within) { + mismatches.push(Mismatch::InvalidCost { site: site() }); + } + } + Precondition::Holds { resource, .. } => { + require(resource, RefKind::Entity(EntityKind::Resource), mismatches); + } + Precondition::Authorized { over, kind } => { + // Jurisdiction runs over subjects, places, and routes. A + // resource, fact, or channel is covered by nothing, so a role + // of that kind is refused at declaration rather than always + // failing at invocation. + match declared.get(over) { + None => mismatches.push(Mismatch::UnknownRole { + handle: handle.clone(), + role: over.clone(), + }), + Some(RefKind::Subject(_)) | Some(&PLACE) | Some(&ROUTE) => {} + Some(_) => mismatches.push(Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: over.clone(), + }), + } + if !is_civic_name(&kind.0) { + mismatches.push(Mismatch::InvalidCivicName { site: site() }); + } + } + Precondition::HasStanding { grievance } => { + if !is_civic_name(&grievance.0) { + mismatches.push(Mismatch::InvalidCivicName { site: site() }); + } + } + Precondition::Knows { fact, .. } => require(fact, FACT, mismatches), + Precondition::CanBroadcast { via } => require_audience(via, mismatches), + Precondition::CanReach { subject, via } => { + require_subject(subject, mismatches); + require_audience(via, mismatches); + } + Precondition::Committed { to, .. } => require_subject(to, mismatches), + } + } + // A speech-carrying entry must name exactly one audience: the lowering reads + // it, so none is unlowerable and two is unchoosable. + if carries_speech { + let audiences = preconditions + .iter() + .filter(|precondition| { + matches!( + precondition, + Precondition::CanBroadcast { .. } | Precondition::CanReach { .. } + ) + }) + .count(); + if audiences == 0 { + mismatches.push(Mismatch::SpeechWithoutAudience { + handle: handle.clone(), + }); + } else if audiences > 1 { + mismatches.push(Mismatch::AmbiguousSpeechAudience { + handle: handle.clone(), + }); + } + } + for (index, slot) in effect_slots.iter().enumerate() { + let arity = slot.op_kind.arity(); + if slot + .op_kind + .payload_names() + .iter() + .any(|name| !is_civic_name(name)) + { + mismatches.push(Mismatch::InvalidCivicName { site: site() }); + } + if slot.roles.len() != arity.len() { + mismatches.push(Mismatch::SlotRoleArity { + handle: handle.clone(), + slot: index, + }); + } + for (role, rule) in slot.roles.iter().zip(arity.iter()) { + match declared.get(role) { + None => mismatches.push(Mismatch::UnknownRole { + handle: handle.clone(), + role: role.clone(), + }), + Some(declared_kind) if !role_kind_fits(rule, *declared_kind) => { + mismatches.push(Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: role.clone(), + }); + } + Some(_) => {} + } + } + let fits = match (slot.op_kind.dimension(), slot.bounds) { + (BoundsDimension::None, Bounds::None) => true, + (BoundsDimension::Quantity, Bounds::Quantity(ceiling)) => ceiling.0 >= 1, + (BoundsDimension::Cost, Bounds::Cost(ceiling)) => is_valid_cost(ceiling), + _ => false, + }; + if !fits { + mismatches.push(Mismatch::SlotBoundMismatch { + handle: handle.clone(), + slot: index, + }); + } + } + if outcome_bands.is_empty() { + mismatches.push(Mismatch::NoOutcomeBand { + handle: handle.clone(), + }); + } + for (index, band) in outcome_bands.iter().enumerate() { + if band.weight == 0 { + mismatches.push(Mismatch::ZeroBandWeight { + handle: handle.clone(), + band: index, + }); + } + if band.effects.iter().any(|slot| *slot >= effect_slots.len()) { + mismatches.push(Mismatch::DanglingBandEffect { + handle: handle.clone(), + band: index, + }); + } + if band.effects.windows(2).any(|pair| pair[0] >= pair[1]) { + mismatches.push(Mismatch::BandEffectsNotCanonical { + handle: handle.clone(), + band: index, + }); + } + } + if effect_slots.is_empty() && !carries_speech { + mismatches.push(Mismatch::InertAffordance { + handle: handle.clone(), + }); + } +} + +/// The one entity resolver. `expected` names the kind the referring site +/// requires; a handle or ID that answers with another kind is `WrongKind`. +fn resolve_entity( + site: Site, + expected_kind: EntityKind, + reference: &Ref<EntityId>, + index: &BTreeMap<DraftHandle, RefKind>, + entities: &BTreeMap<EntityId, EntityRecord>, + mismatches: &mut Vec<Mismatch>, +) -> Option<Key<EntityId>> { + let expected = RefKind::Entity(expected_kind); + match reference { + Ref::Draft(named) => match index.get(named) { + None => { + mismatches.push(Mismatch::UnresolvedDraft { + site, + referent: named.clone(), + expected, + }); + None + } + Some(kind) if *kind != expected => { + mismatches.push(Mismatch::WrongKind { + site, + referent: RefName::Entity(reference.clone()), + expected, + actual: *kind, + }); + None + } + Some(_) => Some(Key::Draft(named.clone())), + }, + Ref::Existing(entity_id) => match entities.get(entity_id) { + None => { + mismatches.push(Mismatch::UnknownCanonical { site, expected }); + None + } + Some(record) if record.kind != expected_kind => { + mismatches.push(Mismatch::WrongKind { + site, + referent: RefName::Entity(reference.clone()), + expected, + actual: RefKind::Entity(record.kind), + }); + None + } + Some(_) => Some(Key::Existing(*entity_id)), + }, + } +} + +fn resolve_subject( + site: Site, + reference: &Ref<SubjectId>, + index: &BTreeMap<DraftHandle, RefKind>, + subjects: &BTreeMap<SubjectId, SubjectState>, + mismatches: &mut Vec<Mismatch>, +) -> Option<Key<SubjectId>> { + match reference { + Ref::Draft(named) => match index.get(named) { + None => { + mismatches.push(Mismatch::UnresolvedDraft { + site, + referent: named.clone(), + expected: ANY_SUBJECT, + }); + None + } + Some(RefKind::Subject(_)) => Some(Key::Draft(named.clone())), + Some(kind) => { + mismatches.push(Mismatch::WrongKind { + site, + referent: RefName::Subject(reference.clone()), + expected: ANY_SUBJECT, + actual: *kind, + }); + None + } + }, + Ref::Existing(subject_id) => { + if subjects.contains_key(subject_id) { + Some(Key::Existing(*subject_id)) + } else { + mismatches.push(Mismatch::UnknownCanonical { + site, + expected: ANY_SUBJECT, + }); + None + } + } + } +} + +fn resolve_route( + site: Site, + reference: &Ref<EdgeId>, + index: &BTreeMap<DraftHandle, RefKind>, + edges: &BTreeMap<EdgeId, EdgeRecord>, + mismatches: &mut Vec<Mismatch>, +) -> Option<Key<EdgeId>> { + match reference { + Ref::Draft(named) => match index.get(named) { + None => { + mismatches.push(Mismatch::UnresolvedDraft { + site, + referent: named.clone(), + expected: ROUTE, + }); + None + } + Some(kind) if *kind != ROUTE => { + mismatches.push(Mismatch::WrongKind { + site, + referent: RefName::Edge(reference.clone()), + expected: ROUTE, + actual: *kind, + }); + None + } + Some(_) => Some(Key::Draft(named.clone())), + }, + Ref::Existing(edge_id) => { + if edges.contains_key(edge_id) { + Some(Key::Existing(*edge_id)) + } else { + mismatches.push(Mismatch::UnknownCanonical { + site, + expected: ROUTE, + }); + None + } + } + } +} + +fn resolve_dependency_target( + site: Site, + target: &DependencyRef, + index: &BTreeMap<DraftHandle, RefKind>, + state: &super::WorldState, + mismatches: &mut Vec<Mismatch>, +) -> Option<TargetKey> { + match target { + DependencyRef::Resource(reference) => resolve_entity( + site, + EntityKind::Resource, + reference, + index, + &state.entities, + mismatches, + ) + .map(TargetKey::Resource), + DependencyRef::Route(reference) => { + resolve_route(site, reference, index, &state.edges, mismatches).map(TargetKey::Route) + } + DependencyRef::Subject(reference) => { + resolve_subject(site, reference, index, &state.subjects, mismatches) + .map(TargetKey::Subject) + } + } +} + +/// Whether any subject in the candidate graph holds two grants of one kind over +/// overlapping ground, from any combination of direct grant and office +/// delegation. +fn graph_overlaps( + authority: &BTreeMap<Key<SubjectId>, BTreeSet<GrantKey>>, + selection: &BTreeMap<(Key<SubjectId>, OfficeName), OfficeCandidate>, + containers: &BTreeMap<Key<EntityId>, Key<EntityId>>, + retired: &BTreeSet<Key<SubjectId>>, +) -> bool { + let holders: BTreeSet<&Key<SubjectId>> = authority + .keys() + .chain( + selection + .values() + .filter_map(|office| office.incumbent.as_ref()), + ) + .collect(); + holders.into_iter().any(|holder| { + let effective: Vec<GrantKey> = + candidate_effective_authority(holder, authority, selection, retired) + .into_iter() + .collect(); + effective.iter().enumerate().any(|(index, one)| { + effective[index + 1..].iter().any(|other| { + one.kind == other.kind + && candidate_targets_overlap(&one.over, &other.over, containers) + }) + }) + }) +} + +/// The candidate kind of a subject reference: the declared kind for a handle +/// this patch introduces, the committed kind otherwise. +fn subject_kind_of( + key: &Key<SubjectId>, + index: &BTreeMap<DraftHandle, RefKind>, + state: &super::WorldState, +) -> Option<SubjectKind> { + match key { + Key::Existing(subject_id) => state.subjects.get(subject_id).map(|subject| subject.kind), + Key::Draft(handle) => match index.get(handle) { + Some(RefKind::Subject(kind)) => *kind, + _ => None, + }, + } +} + +/// The institution half of every office operation: one subject reference, one +/// canonical office name, and the kind check that keeps an institution's +/// operational organ and its person-shaped voice two subjects. +fn resolve_office_institution( + position: usize, + institution: &Ref<SubjectId>, + office: &OfficeName, + index: &BTreeMap<DraftHandle, RefKind>, + state: &super::WorldState, + mismatches: &mut Vec<Mismatch>, +) -> Option<Key<SubjectId>> { + let named = is_civic_name(&office.0); + if !named { + mismatches.push(Mismatch::InvalidCivicName { + site: Site::Operation(position), + }); + } + let key = resolve_subject( + Site::Operation(position), + institution, + index, + &state.subjects, + mismatches, + )?; + if subject_kind_of(&key, index, state) != Some(SubjectKind::Institution) { + mismatches.push(Mismatch::OfficeOnNonInstitution { + operation: position, + }); + return None; + } + named.then_some(key) +} + +/// The one reach resolver: every member of a subject set, or one place. +fn resolve_reach( + site: Site, + reach: &ReachRef, + index: &BTreeMap<DraftHandle, RefKind>, + state: &super::WorldState, + mismatches: &mut Vec<Mismatch>, +) -> Option<ReachKey> { + match reach { + ReachRef::Subjects(members) => { + let mut resolved = BTreeSet::new(); + let mut complete = true; + for reference in members { + match resolve_subject(site.clone(), reference, index, &state.subjects, mismatches) { + Some(key) => { + resolved.insert(key); + } + None => complete = false, + } + } + complete.then_some(ReachKey::Subjects(resolved)) + } + ReachRef::Place(reference) => resolve_entity( + site, + EntityKind::Place, + reference, + index, + &state.entities, + mismatches, + ) + .map(ReachKey::Place), + } +} + +/// A channel controller is optional, so "declared none" and "named one that did +/// not resolve" are two answers, not one. +fn resolve_controller( + site: Site, + controller: &Option<Ref<SubjectId>>, + index: &BTreeMap<DraftHandle, RefKind>, + state: &super::WorldState, + mismatches: &mut Vec<Mismatch>, +) -> Option<Option<Key<SubjectId>>> { + match controller { + None => Some(None), + Some(reference) => { + resolve_subject(site, reference, index, &state.subjects, mismatches).map(Some) + } + } +} + +fn resolve_audience( + site: Site, + audience: &AudienceRef, + index: &BTreeMap<DraftHandle, RefKind>, + state: &super::WorldState, + mismatches: &mut Vec<Mismatch>, +) -> Option<AudienceKey> { + match audience { + AudienceRef::Colocated => Some(AudienceKey::Colocated), + AudienceRef::Channel(reference) => resolve_entity( + site, + EntityKind::Channel, + reference, + index, + &state.entities, + mismatches, + ) + .map(AudienceKey::Channel), + } +} + +fn resolve_authority_target( + site: Site, + target: &AuthorityTargetRef, + index: &BTreeMap<DraftHandle, RefKind>, + state: &super::WorldState, + mismatches: &mut Vec<Mismatch>, +) -> Option<AuthorityTargetKey> { + match target { + AuthorityTargetRef::Subject(reference) => { + resolve_subject(site, reference, index, &state.subjects, mismatches) + .map(AuthorityTargetKey::Subject) + } + AuthorityTargetRef::PlaceSubtree(reference) => resolve_entity( + site, + EntityKind::Place, + reference, + index, + &state.entities, + mismatches, + ) + .map(AuthorityTargetKey::PlaceSubtree), + } +} + +/// What a holder holds in the candidate map. Absence is zero, at both levels. +fn candidate_held( + holdings: &BTreeMap<(Key<SubjectId>, Key<EntityId>), Quantity>, + holder: &Key<SubjectId>, + resource: &Key<EntityId>, +) -> u64 { + holdings + .get(&(holder.clone(), resource.clone())) + .map_or(0, |quantity| quantity.0) +} + +/// Zero removes the slot, so one representation of nothing survives the patch. +fn candidate_set( + holdings: &mut BTreeMap<(Key<SubjectId>, Key<EntityId>), Quantity>, + holder: &Key<SubjectId>, + resource: &Key<EntityId>, + value: u64, +) { + let slot = (holder.clone(), resource.clone()); + if value == 0 { + holdings.remove(&slot); + } else { + holdings.insert(slot, Quantity(value)); + } +} + +/// A bound grammar is the whole catalog: a kind it lacks, or a role signature +/// it does not carry, is refused. A world with no grammar is not checked. +fn check_against_grammar( + state: &super::WorldState, + handle: &DraftHandle, + kind: &AffordanceKindName, + roles: &[RoleSpec], + mismatches: &mut Vec<Mismatch>, +) { + let Some(grammar) = &state.grammar else { + return; + }; + let handle = handle.clone(); + mismatches.extend(grammar.refusal(kind, roles).map(|refusal| match refusal { + GrammarRefusal::KindNotInGrammar => Mismatch::AffordanceKindNotInGrammar { handle }, + GrammarRefusal::RolesDisagree => Mismatch::AffordanceRolesDisagreeWithGrammar { handle }, + GrammarRefusal::SpeakNotConversation => { + Mismatch::SpeakRenderPathDisagreesWithGrammar { handle } + } + })); +} + +/// The one resolution owner for every admission lane: declarations, references, +/// topology admission, and operation preconditions. Every check runs against the +/// complete candidate graph — what the world already holds plus what this patch +/// declares — and the whole mismatch set closes before the first ID is minted. +pub(super) fn resolve_patch( + state: &super::WorldState, + command_id: CommandId, + patch: &WorldPatch, + scale_intent: Option<&WorldScaleIntentRef>, + lens_weights: Option<&LensWeights>, +) -> Result<ResolvedPatch, Vec<Mismatch>> { + let world_id = state.world_id; + let admits_human = super::admits_human(state.revision, &state.subjects); + let mut mismatches = Vec::new(); + let mut index: BTreeMap<DraftHandle, RefKind> = BTreeMap::new(); + + // The kernel-built Speak entry enters the same index as a world-declared + // one, before the declaration loop, so a world reusing its handle collides + // as a duplicate handle rather than through a reserved-name check. + let speak_handle = DraftHandle::new(KERNEL_SPEAK_HANDLE); + if admits_human { + index.insert(speak_handle.clone(), RefKind::Affordance); + } + if admits_human { + // The kernel-built entry is held to the grammar like any declaration. + let speak = kernel_speak_entry(); + check_against_grammar(state, &speak_handle, &speak.kind, &speak.roles, &mut mismatches); + } + let mut kind_names: BTreeSet<AffordanceKindName> = state + .affordance_catalog + .values() + .map(|entry| entry.kind.clone()) + .collect(); + if admits_human { + kind_names.insert(kernel_speak_entry().kind); + } + + let held_keys = held_import_keys(state.subjects.values()); + let mut declared_keys: BTreeSet<&ImportKey> = BTreeSet::new(); + for (position, declaration) in patch.declarations.iter().enumerate() { + let (handle, label, kind) = match declaration { + Declaration::Subject(subject) => ( + &subject.handle, + Some(&subject.label), + RefKind::Subject(Some(subject.kind)), + ), + Declaration::Entity(entity) => ( + &entity.handle, + Some(&entity.label), + RefKind::Entity(entity.kind), + ), + Declaration::Route(route) => (&route.handle, Some(&route.label), ROUTE), + // A catalog entry's name is its `kind`, checked by the entry + // validator against the tool-name alphabet rather than against the + // label rule. + Declaration::Affordance(affordance) => (&affordance.handle, None, RefKind::Affordance), + Declaration::Fact(fact) => (&fact.handle, Some(&fact.label), FACT), + Declaration::Channel(channel) => (&channel.handle, Some(&channel.label), CHANNEL), + }; + let named = is_canonical_text(&handle.0); + if !named { + mismatches.push(Mismatch::EmptyHandle { position }); + } + if label.is_some_and(|label| !is_canonical_text(label)) { + mismatches.push(Mismatch::EmptyLabel { + handle: handle.clone(), + }); + } + if named { + match index.entry(handle.clone()) { + Entry::Vacant(slot) => { + slot.insert(kind); + } + Entry::Occupied(_) => mismatches.push(Mismatch::DuplicateHandle { + handle: handle.clone(), + }), + } + } + if let Declaration::Subject(subject) = declaration + && let Some(key) = &subject.import_key + { + let handle = subject.handle.clone(); + match import_key_fault(key, &held_keys, &mut declared_keys) { + Some(ImportKeyFault::Malformed) => { + mismatches.push(Mismatch::MalformedImportKey { handle }); + } + Some(ImportKeyFault::Held) => mismatches.push(Mismatch::ImportKeyHeld { handle }), + Some(ImportKeyFault::Duplicate) => { + mismatches.push(Mismatch::DuplicateImportKey { handle }); + } + None => {} + } + } + if let Declaration::Affordance(affordance) = declaration { + validate_affordance( + &affordance.handle, + &affordance.kind, + &affordance.roles, + &affordance.preconditions, + &affordance.effect_slots, + &affordance.outcome_bands, + affordance.carries_speech, + &mut mismatches, + ); + check_against_grammar( + state, + &affordance.handle, + &affordance.kind, + &affordance.roles, + &mut mismatches, + ); + if !kind_names.insert(affordance.kind.clone()) { + mismatches.push(Mismatch::DuplicateAffordanceKind { + handle: affordance.handle.clone(), + }); + } + } + if let Declaration::Entity(entity) = declaration + && matches!(entity.kind, EntityKind::Fact | EntityKind::Channel) + { + mismatches.push(Mismatch::PayloadEntityKind { + handle: handle.clone(), + }); + } + if let Declaration::Fact(fact) = declaration { + if !is_canonical_text(fact.statement.as_str()) { + mismatches.push(Mismatch::EmptyStatement { + handle: handle.clone(), + }); + } + // The same predicate `Admit` uses, moved into the declaration loop so + // one rule serves evidenced quantity and evidenced canon alike. + if let FactStandingRef::Canonical { evidence } = &fact.standing + && !(is_canonical_text(&evidence.0) && patch.evidence.contains(evidence)) + { + mismatches.push(Mismatch::FactWithoutEvidence { + handle: handle.clone(), + }); + } + } + if let Declaration::Subject(subject) = declaration { + // Both ways. A mirror receives no opportunity, so it may hold no + // affordance; every other controller must hold one. + if matches!(subject.controller, NewController::External { .. }) + != subject.affordances.is_empty() + { + mismatches.push(Mismatch::ControllerGrantMismatch { + site: Site::Declaration(handle.clone()), + }); + } + if let NewController::Human { principal } = &subject.controller + && (!admits_human || super::validate_principal(principal).is_err()) + { + mismatches.push(Mismatch::UnadmittedController { + handle: handle.clone(), + }); + } + } + } + + for (position, evidence) in patch.evidence.iter().enumerate() { + if !is_canonical_text(&evidence.0) { + mismatches.push(Mismatch::EmptyEvidence { position }); + } + } + + // The candidate graph: canonical topology plus everything this patch + // declares. Containment, endpoints, and preconditions all read it. + let mut containers: BTreeMap<Key<EntityId>, Key<EntityId>> = state + .entities + .iter() + .filter_map(|(entity_id, record)| { + record + .container + .map(|container| (Key::Existing(*entity_id), Key::Existing(container))) + }) + .collect(); + let mut routes: BTreeMap<Key<EdgeId>, RouteCandidate> = state + .edges + .iter() + .map(|(edge_id, record)| { + let (from, to) = record.endpoints(); + ( + Key::Existing(*edge_id), + RouteCandidate { + from: Key::Existing(from), + to: Key::Existing(to), + access: record.access().clone(), + cost: record.cost(), + open: record.is_open(), + }, + ) + }) + .collect(); + let mut positions: BTreeMap<Key<SubjectId>, Key<EntityId>> = state + .positions + .iter() + .map(|(subject_id, position)| (Key::Existing(*subject_id), Key::Existing(position.place))) + .collect(); + let mut holdings: BTreeMap<(Key<SubjectId>, Key<EntityId>), Quantity> = state + .holdings + .iter() + .flat_map(|(subject_id, held)| { + held.iter().map(move |(entity_id, quantity)| { + ( + (Key::Existing(*subject_id), Key::Existing(*entity_id)), + *quantity, + ) + }) + }) + .collect(); + let seeded_holdings = holdings.clone(); + let mut dependencies: BTreeSet<(Key<SubjectId>, TargetKey)> = state + .dependencies + .iter() + .flat_map(|(subject_id, bound)| { + bound.iter().map(move |target| { + ( + Key::Existing(*subject_id), + match target { + DependencyTarget::Resource(id) => TargetKey::Resource(Key::Existing(*id)), + DependencyTarget::Route(id) => TargetKey::Route(Key::Existing(*id)), + DependencyTarget::Subject(id) => TargetKey::Subject(Key::Existing(*id)), + }, + ) + }) + }) + .collect(); + let mut authority: BTreeMap<Key<SubjectId>, BTreeSet<GrantKey>> = state + .authority + .iter() + .map(|(subject_id, grants)| { + ( + Key::Existing(*subject_id), + grants.iter().map(grant_key_of).collect(), + ) + }) + .collect(); + let mut selection: BTreeMap<(Key<SubjectId>, OfficeName), OfficeCandidate> = state + .selection + .iter() + .flat_map(|(institution, offices)| { + offices.iter().map(move |(name, office)| { + ( + (Key::Existing(*institution), name.clone()), + OfficeCandidate { + incumbent: office.incumbent.map(Key::Existing), + delegated: office.delegated.clone(), + }, + ) + }) + }) + .collect(); + let mut redress: BTreeMap<GrievanceKindName, (Key<SubjectId>, AuthorityTargetKey)> = state + .redress + .iter() + .map(|(grievance, forum)| { + ( + grievance.clone(), + (Key::Existing(forum.forum), target_key_of(forum.standing)), + ) + }) + .collect(); + let mut facts: BTreeMap<Key<EntityId>, FactCandidate> = state + .facts + .iter() + .map(|(entity_id, record)| { + ( + Key::Existing(*entity_id), + match &record.standing { + FactStanding::Canonical { .. } => FactCandidate::Canonical, + FactStanding::Claimed { by } => FactCandidate::Claimed(Key::Existing(*by)), + FactStanding::Ruled => FactCandidate::Ruled, + }, + ) + }) + .collect(); + // `Retire` and the affordance grant operations read and write these three + // candidates. `retired` and `mirrors` seed from the committed + // `ControllerAssignment`, which the resolver otherwise never reads: a + // declared subject can only ever be a fresh, unretired controller (or a + // freshly declared mirror, added below), so drafts start out of both sets. + // `affordance_holdings` seeds from committed `affordance_grants` and is + // extended below for a subject this same patch declares. + let mut retired: BTreeSet<Key<SubjectId>> = state + .controller_assignments + .keys() + .filter(|scope| super::is_retired(state, scope.subject_id)) + .map(|scope| Key::Existing(scope.subject_id)) + .collect(); + let mut mirrors: BTreeSet<Key<SubjectId>> = state + .controller_assignments + .iter() + .filter(|(_, assignment)| { + matches!(assignment, ControllerAssignment::ExternallyControlled { .. }) + }) + .map(|(scope, _)| Key::Existing(scope.subject_id)) + .collect(); + // Tracked the same way as `mirrors`: seeded from the committed human + // controller, extended below for a subject this same patch declares as + // `NewController::Human`. `Retire` refuses a Draft-phase approver out of + // this set instead of relying solely on the apply-time re-check, which + // otherwise only catches a genesis patch that declares and retires the + // human in the same breath after `open_owner` has already committed. + let mut humans: BTreeSet<Key<SubjectId>> = state + .controller_assignments + .iter() + .filter(|(_, assignment)| assignment.human_principal().is_some()) + .map(|(scope, _)| Key::Existing(scope.subject_id)) + .collect(); + let mut affordance_holdings: BTreeMap<Key<SubjectId>, BTreeSet<Key<AffordanceId>>> = state + .affordance_grants + .iter() + .map(|(scope, granted)| { + ( + Key::Existing(scope.subject_id), + granted.iter().map(|id| Key::Existing(*id)).collect(), + ) + }) + .collect(); + let mut channels: BTreeMap<Key<EntityId>, ChannelCandidate> = state + .channels + .iter() + .map(|(entity_id, record)| { + ( + Key::Existing(*entity_id), + ChannelCandidate { + reach: match &record.reach { + Reach::Subjects(members) => { + ReachKey::Subjects(members.iter().copied().map(Key::Existing).collect()) + } + Reach::Place(place) => ReachKey::Place(Key::Existing(*place)), + }, + controller: record.controller.map(Key::Existing), + }, + ) + }) + .collect(); + // Keys and payload, so an `AcquireKnowledge` that changes nothing is + // `NoOperationEffect` before any ID is minted. `Witness` is modelled here + // too: its landing is a subtree of `positions`, both maps are candidate + // maps, and so the fan-out it will perform at apply is derivable now — a + // subject this patch relocated into the subtree counts, and a witness that + // reaches nobody is refused at resolve exactly as `apply_operation` + // refuses it. + // + // `Communicate` never enters, and the difference is not scale. A telling is + // an act whose occurrence does not depend on its reception: its empty + // fan-out is legal, so there is nothing for this map to refuse and no + // refusal for it to predict. A witnessed event is only its reception, so + // its landing is its legality. + // + // Neither operation can write `Told`. This map can represent a `Told` + // entry, but no `ComponentOp` can construct one: `AcquireKnowledge` takes + // an `AuthoredSource`, `Witness` takes no source at all, and neither type + // has a `Told` variant — + // `action::no_component_op_kind_lowers_to_a_told_knowledge_write` pins both + // lowering sites that could otherwise drift. If a future operation is ever + // given the power to write `Told` directly — bypassing `Communicate`'s own + // apply-time fan-out — it must model that fan-out into this candidate graph + // first, or `resolve_patch` will silently reason about a knowledge state + // the apply pass will not produce. + let mut knowledge: BTreeMap<(Key<SubjectId>, Key<EntityId>), KnowledgeCandidate> = state + .knowledge + .iter() + .flat_map(|(subject_id, held)| { + held.iter().map(move |(fact, entry)| { + ( + (Key::Existing(*subject_id), Key::Existing(*fact)), + KnowledgeCandidate { + confidence: entry.confidence, + source: match entry.source { + KnowledgeSource::Witnessed => KnowledgeSourceKey::Witnessed, + KnowledgeSource::Evidenced => KnowledgeSourceKey::Evidenced, + KnowledgeSource::Told { by, via } => KnowledgeSourceKey::Told { + by: Key::Existing(by), + via: via.map(Key::Existing), + }, + KnowledgeSource::Seen { by } => KnowledgeSourceKey::Seen { + by: Key::Existing(by), + }, + }, + }, + ) + }) + }) + .collect(); + // Presence is all a discharge asks, and a create cannot collide: the key is + // command-derived and the index is unique within one patch. + let mut commitments: BTreeSet<(Key<SubjectId>, CommitmentKey)> = state + .commitments + .iter() + .flat_map(|(subject_id, held)| { + held.keys() + .map(move |key| (Key::Existing(*subject_id), *key)) + }) + .collect(); + let mut pressures: BTreeMap<(Key<SubjectId>, PressureSourceKey), u32> = state + .pressures + .iter() + .flat_map(|(target, held)| { + held.iter().map(move |(source, magnitude)| { + ( + ( + Key::Existing(*target), + match source { + PressureSource::Commitment { subject, key } => { + PressureSourceKey::Commitment { + subject: Key::Existing(*subject), + key: *key, + } + } + PressureSource::Dependency(DependencyTarget::Resource(entity_id)) => { + PressureSourceKey::Dependency(TargetKey::Resource(Key::Existing( + *entity_id, + ))) + } + PressureSource::Dependency(DependencyTarget::Route(edge_id)) => { + PressureSourceKey::Dependency(TargetKey::Route(Key::Existing( + *edge_id, + ))) + } + PressureSource::Dependency(DependencyTarget::Subject(subject_id)) => { + PressureSourceKey::Dependency(TargetKey::Subject(Key::Existing( + *subject_id, + ))) + } + PressureSource::Subject(subject_id) => { + PressureSourceKey::Subject(Key::Existing(*subject_id)) + } + }, + ), + magnitude.0, + ) + }) + }) + .collect(); + let mut deltas: BTreeMap<Key<EntityId>, LedgerDelta> = BTreeMap::new(); + let mut declared_places: Vec<(DraftHandle, Key<EntityId>)> = Vec::new(); + + for declaration in &patch.declarations { + match declaration { + Declaration::Entity(entity) => { + if entity.kind == EntityKind::Place { + declared_places + .push((entity.handle.clone(), Key::Draft(entity.handle.clone()))); + } + if let Some(reference) = &entity.container { + if entity.kind != EntityKind::Place { + mismatches.push(Mismatch::WrongKind { + site: Site::Declaration(entity.handle.clone()), + referent: RefName::Entity(reference.clone()), + expected: PLACE, + actual: RefKind::Entity(entity.kind), + }); + } else if let Some(parent) = resolve_entity( + Site::Declaration(entity.handle.clone()), + EntityKind::Place, + reference, + &index, + &state.entities, + &mut mismatches, + ) { + containers.insert(Key::Draft(entity.handle.clone()), parent); + } + } + } + Declaration::Affordance(_) => {} + Declaration::Fact(fact) => { + let standing = match &fact.standing { + FactStandingRef::Canonical { .. } => Some(FactCandidate::Canonical), + FactStandingRef::Claimed { by } => resolve_subject( + Site::Declaration(fact.handle.clone()), + by, + &index, + &state.subjects, + &mut mismatches, + ) + .map(FactCandidate::Claimed), + FactStandingRef::Ruled => Some(FactCandidate::Ruled), + }; + if let Some(standing) = standing { + facts.insert(Key::Draft(fact.handle.clone()), standing); + } + } + Declaration::Channel(channel) => { + let reach = resolve_reach( + Site::Declaration(channel.handle.clone()), + &channel.reach, + &index, + state, + &mut mismatches, + ); + let controller = resolve_controller( + Site::Declaration(channel.handle.clone()), + &channel.controller, + &index, + state, + &mut mismatches, + ); + if let (Some(reach), Some(controller)) = (reach, controller) { + channels.insert( + Key::Draft(channel.handle.clone()), + ChannelCandidate { reach, controller }, + ); + } + } + Declaration::Subject(subject) => { + let mut granted = BTreeSet::new(); + for reference in &subject.affordances { + if let Some(affordance_key) = resolve_affordance( + Site::Declaration(subject.handle.clone()), + reference, + &index, + &state.affordance_catalog, + &mut mismatches, + ) { + granted.insert(affordance_key); + } + } + if !granted.is_empty() { + affordance_holdings.insert(Key::Draft(subject.handle.clone()), granted); + } + if matches!(subject.controller, NewController::External { .. }) { + mirrors.insert(Key::Draft(subject.handle.clone())); + } + if matches!(subject.controller, NewController::Human { .. }) { + humans.insert(Key::Draft(subject.handle.clone())); + } + if let Some(reference) = &subject.position + && let Some(place) = resolve_entity( + Site::Declaration(subject.handle.clone()), + EntityKind::Place, + reference, + &index, + &state.entities, + &mut mismatches, + ) + { + positions.insert(Key::Draft(subject.handle.clone()), place); + } + } + Declaration::Route(route) => { + let from = resolve_entity( + Site::Declaration(route.handle.clone()), + EntityKind::Place, + &route.from, + &index, + &state.entities, + &mut mismatches, + ); + let to = resolve_entity( + Site::Declaration(route.handle.clone()), + EntityKind::Place, + &route.to, + &index, + &state.entities, + &mut mismatches, + ); + if !is_valid_cost(route.cost) { + mismatches.push(Mismatch::InvalidCost { + site: Site::Declaration(route.handle.clone()), + }); + } + if let (Some(from), Some(to)) = (from, to) { + if from == to { + mismatches.push(Mismatch::RouteSelfLoop { + referent: route.handle.clone(), + }); + } + routes.insert( + Key::Draft(route.handle.clone()), + RouteCandidate { + from, + to, + access: route.access.clone(), + cost: route.cost, + open: true, + }, + ); + } + } + } + } + + // Containment acyclicity. Containment is immutable after admission and + // admission already refused cycles, so every cycle contains a declared + // place; walking from each declared place names them all. + for (handle, start) in &declared_places { + if contains_itself(start, &containers) { + mismatches.push(Mismatch::ContainmentCycle { + referent: handle.clone(), + }); + } + } + + for (position, operation) in patch.operations.iter().enumerate() { + let site = Site::Operation(position); + match operation { + ComponentOp::CreateCommitment { + subject, + counterparty, + kind, + due, + period, + checks, + statement, + } => { + if !is_canonical_text(statement.as_str()) { + mismatches.push(Mismatch::NoncanonicalText { + operation: position, + }); + } + let subject_key = resolve_subject( + site.clone(), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let counterparty_key = counterparty.as_ref().map(|reference| { + resolve_subject( + site.clone(), + reference, + &index, + &state.subjects, + &mut mismatches, + ) + }); + let mut checks_resolve = true; + for check in checks { + checks_resolve &= + resolve_check(site.clone(), check, &index, state, &mut mismatches); + } + if (*kind == CommitmentKind::Routine) != period.is_some() { + mismatches.push(Mismatch::CommitmentPeriodMismatch { + operation: position, + }); + } + if let Some(period) = period + && !is_valid_cost(Cost(period.minutes())) + { + mismatches.push(Mismatch::InvalidCost { site: site.clone() }); + } + if *kind != CommitmentKind::Routine && !checks.is_empty() { + mismatches.push(Mismatch::ChecksOnNonRoutine { + operation: position, + }); + } + // A promise cannot be born past due: it would press on its + // subject on the very next tick with no chance to act. + if *due <= state.now { + mismatches.push(Mismatch::CommitmentDueInThePast { + operation: position, + }); + } + if counterparty.is_some() && *kind == CommitmentKind::Goal { + mismatches.push(Mismatch::GoalWithCounterparty { + operation: position, + }); + } + let Some(subject_key) = subject_key else { + continue; + }; + // A retired subject cannot act, and making a promise is + // acting: refused here the same way `RetiredSubjectActed` + // refuses a retired office incumbent below. + if retired.contains(&subject_key) { + mismatches.push(Mismatch::RetiredSubjectActed { + operation: position, + }); + continue; + } + if let Some(counterparty_key) = &counterparty_key { + match counterparty_key { + None => continue, + Some(counterparty_key) if *counterparty_key == subject_key => { + mismatches.push(Mismatch::SelfCommitment { + operation: position, + }); + continue; + } + Some(_) => {} + } + } + if !checks_resolve { + continue; + } + commitments.insert(( + subject_key, + CommitmentKey { + command: command_id, + index: position as u32, + }, + )); + } + ComponentOp::DischargeCommitment { subject, key } => { + let Some(subject_key) = resolve_subject( + site.clone(), + subject, + &index, + &state.subjects, + &mut mismatches, + ) else { + continue; + }; + if !commitments.remove(&(subject_key, *key)) { + mismatches.push(Mismatch::UnknownCommitment { + operation: position, + }); + } + } + ComponentOp::AdvancePressure { source, target, by } + | ComponentOp::ReducePressure { source, target, by } => { + let advancing = matches!(operation, ComponentOp::AdvancePressure { .. }); + let target_key = resolve_subject( + site.clone(), + target, + &index, + &state.subjects, + &mut mismatches, + ); + let source_key = + resolve_pressure_source(site.clone(), source, &index, state, &mut mismatches); + let (Some(target_key), Some(source_key)) = (target_key, source_key) else { + continue; + }; + let slot = (target_key, source_key); + let current = pressures.get(&slot).copied().unwrap_or_default(); + let next = if advancing { + current.saturating_add(by.0) + } else { + current.saturating_sub(by.0) + }; + // A zero step and a subtraction that hits a floor both change + // nothing, which is one name and not three. + if next == current { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else if next == 0 { + pressures.remove(&slot); + } else { + pressures.insert(slot, next); + } + } + ComponentOp::ResolvePressure { source, target } => { + let target_key = resolve_subject( + site.clone(), + target, + &index, + &state.subjects, + &mut mismatches, + ); + let source_key = + resolve_pressure_source(site.clone(), source, &index, state, &mut mismatches); + let (Some(target_key), Some(source_key)) = (target_key, source_key) else { + continue; + }; + if pressures.remove(&(target_key, source_key)).is_none() { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } + } + ComponentOp::Relocate { subject, via } => { + let subject_key = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let route_key = resolve_route( + Site::Operation(position), + via, + &index, + &state.edges, + &mut mismatches, + ); + let (Some(subject_key), Some(route_key)) = (subject_key, route_key) else { + continue; + }; + let Some(route) = routes.get(&route_key).cloned() else { + continue; + }; + let mut admitted = true; + match positions.get(&subject_key) { + None => { + mismatches.push(Mismatch::UnplacedSubject { + operation: position, + }); + admitted = false; + } + Some(place) if *place != route.from => { + mismatches.push(Mismatch::SubjectNotAtOrigin { + operation: position, + }); + admitted = false; + } + Some(_) => {} + } + if !route.open { + mismatches.push(Mismatch::RouteClosed { + operation: position, + }); + admitted = false; + } + // The resolver reads authority for the subject being moved, not + // for whoever proposed the patch, which is what keeps it + // actor-blind: the owner-admitted lane and the action lane get + // the same answer for the same move. A destination this patch + // declares is canonically unknown, so only a `Public` route + // reaches it. + let opened = match &route.to { + Key::Existing(destination) => route_admits( + state, + &canonical_grants(&candidate_effective_authority( + &subject_key, + &authority, + &selection, + &retired, + )), + &route.access, + *destination, + ), + Key::Draft(_) => route.access == AccessKind::Public, + }; + if !opened { + mismatches.push(Mismatch::RouteAccessRestricted { + operation: position, + }); + admitted = false; + } + if admitted { + positions.insert(subject_key, route.to); + } + } + ComponentOp::Retire { subject } => { + let Some(subject_key) = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ) else { + continue; + }; + if mirrors.contains(&subject_key) { + mismatches.push(Mismatch::RetiresAMirror { + operation: position, + }); + continue; + } + if retired.contains(&subject_key) { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + continue; + } + // A human's Draft approval cannot be removed by removing the + // human: `required_approvers` reads the live controller + // assignment and `Retired` carries no human principal, so an + // owner could otherwise retire the human, approve alone, and + // activate. Once the world is Active, approvals are frozen + // history judged by replay, and the human's subject may die. + // `humans` tracks a subject declared as `NewController::Human` + // in this same patch exactly as `mirrors` tracks a freshly + // declared mirror, so a genesis patch that declares and + // retires the human in one breath is refused here rather than + // only by the apply-time re-check after admission. + if state.phase == super::WorldPhase::Draft && humans.contains(&subject_key) { + mismatches.push(Mismatch::RetiresAnApprover { + operation: position, + }); + continue; + } + retired.insert(subject_key.clone()); + positions.remove(&subject_key); + affordance_holdings.remove(&subject_key); + } + ComponentOp::OpenRoute { route } | ComponentOp::CloseRoute { route } => { + let open = matches!(operation, ComponentOp::OpenRoute { .. }); + let Some(route_key) = resolve_route( + Site::Operation(position), + route, + &index, + &state.edges, + &mut mismatches, + ) else { + continue; + }; + let Some(candidate) = routes.get_mut(&route_key) else { + continue; + }; + if candidate.open == open { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + candidate.open = open; + } + } + ComponentOp::AlterCost { route, cost } => { + let route_key = resolve_route( + Site::Operation(position), + route, + &index, + &state.edges, + &mut mismatches, + ); + if !is_valid_cost(*cost) { + mismatches.push(Mismatch::InvalidCost { + site: Site::Operation(position), + }); + continue; + } + let Some(route_key) = route_key else { continue }; + let Some(candidate) = routes.get_mut(&route_key) else { + continue; + }; + if candidate.cost == *cost { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + candidate.cost = *cost; + } + } + ComponentOp::Transfer { + from, + to, + resource, + qty, + } => { + let from_key = resolve_subject( + Site::Operation(position), + from, + &index, + &state.subjects, + &mut mismatches, + ); + let to_key = resolve_subject( + Site::Operation(position), + to, + &index, + &state.subjects, + &mut mismatches, + ); + let resource_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + resource, + &index, + &state.entities, + &mut mismatches, + ); + if qty.0 == 0 { + mismatches.push(Mismatch::ZeroQuantity { + operation: position, + }); + } + let (Some(from_key), Some(to_key), Some(resource_key)) = + (from_key, to_key, resource_key) + else { + continue; + }; + if from_key == to_key { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + continue; + } + if qty.0 == 0 { + continue; + } + let held = candidate_held(&holdings, &from_key, &resource_key); + let Some(remaining) = held.checked_sub(qty.0) else { + mismatches.push(Mismatch::InsufficientCustody { + operation: position, + }); + continue; + }; + let Some(credited) = + candidate_held(&holdings, &to_key, &resource_key).checked_add(qty.0) + else { + mismatches.push(Mismatch::QuantityOverflow { + operation: position, + }); + continue; + }; + candidate_set(&mut holdings, &from_key, &resource_key, remaining); + candidate_set(&mut holdings, &to_key, &resource_key, credited); + // A transfer contributes to no ledger term: the equation proves + // it, because moving a different amount out than in breaks the + // resource's total. + deltas.entry(resource_key).or_default(); + } + ComponentOp::Transform { + holder, + from_resource, + into_resource, + qty, + } => { + let holder_key = resolve_subject( + Site::Operation(position), + holder, + &index, + &state.subjects, + &mut mismatches, + ); + let from_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + from_resource, + &index, + &state.entities, + &mut mismatches, + ); + let into_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + into_resource, + &index, + &state.entities, + &mut mismatches, + ); + if qty.0 == 0 { + mismatches.push(Mismatch::ZeroQuantity { + operation: position, + }); + } + let (Some(holder_key), Some(from_key), Some(into_key)) = + (holder_key, from_key, into_key) + else { + continue; + }; + if from_key == into_key { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + continue; + } + if qty.0 == 0 { + continue; + } + let Some(remaining) = + candidate_held(&holdings, &holder_key, &from_key).checked_sub(qty.0) + else { + mismatches.push(Mismatch::InsufficientCustody { + operation: position, + }); + continue; + }; + let Some(gained) = + candidate_held(&holdings, &holder_key, &into_key).checked_add(qty.0) + else { + mismatches.push(Mismatch::QuantityOverflow { + operation: position, + }); + continue; + }; + candidate_set(&mut holdings, &holder_key, &from_key, remaining); + candidate_set(&mut holdings, &holder_key, &into_key, gained); + deltas.entry(from_key).or_default().spent += u128::from(qty.0); + deltas.entry(into_key).or_default().gained += u128::from(qty.0); + } + ComponentOp::Consume { + holder, + resource, + qty, + } => { + let holder_key = resolve_subject( + Site::Operation(position), + holder, + &index, + &state.subjects, + &mut mismatches, + ); + let resource_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + resource, + &index, + &state.entities, + &mut mismatches, + ); + if qty.0 == 0 { + mismatches.push(Mismatch::ZeroQuantity { + operation: position, + }); + } + let (Some(holder_key), Some(resource_key)) = (holder_key, resource_key) else { + continue; + }; + if qty.0 == 0 { + continue; + } + let Some(remaining) = + candidate_held(&holdings, &holder_key, &resource_key).checked_sub(qty.0) + else { + mismatches.push(Mismatch::InsufficientCustody { + operation: position, + }); + continue; + }; + candidate_set(&mut holdings, &holder_key, &resource_key, remaining); + deltas.entry(resource_key).or_default().consumed += u128::from(qty.0); + } + ComponentOp::Admit { + holder, + resource, + qty, + evidence, + } => { + let holder_key = resolve_subject( + Site::Operation(position), + holder, + &index, + &state.subjects, + &mut mismatches, + ); + let resource_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + resource, + &index, + &state.entities, + &mut mismatches, + ); + if qty.0 == 0 { + mismatches.push(Mismatch::ZeroQuantity { + operation: position, + }); + } + let evidenced = is_canonical_text(&evidence.0) && patch.evidence.contains(evidence); + if !evidenced { + mismatches.push(Mismatch::AdmitWithoutEvidence { + operation: position, + }); + } + let (Some(holder_key), Some(resource_key)) = (holder_key, resource_key) else { + continue; + }; + if qty.0 == 0 || !evidenced { + continue; + } + let Some(admitted) = + candidate_held(&holdings, &holder_key, &resource_key).checked_add(qty.0) + else { + mismatches.push(Mismatch::QuantityOverflow { + operation: position, + }); + continue; + }; + candidate_set(&mut holdings, &holder_key, &resource_key, admitted); + deltas.entry(resource_key).or_default().admitted += u128::from(qty.0); + } + ComponentOp::Mint { + holder, + resource, + qty, + } => { + let holder_key = resolve_subject( + Site::Operation(position), + holder, + &index, + &state.subjects, + &mut mismatches, + ); + let resource_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + resource, + &index, + &state.entities, + &mut mismatches, + ); + if qty.0 == 0 { + mismatches.push(Mismatch::ZeroQuantity { + operation: position, + }); + } + let (Some(holder_key), Some(resource_key)) = (holder_key, resource_key) else { + continue; + }; + if qty.0 == 0 { + continue; + } + let Some(minted) = + candidate_held(&holdings, &holder_key, &resource_key).checked_add(qty.0) + else { + mismatches.push(Mismatch::QuantityOverflow { + operation: position, + }); + continue; + }; + candidate_set(&mut holdings, &holder_key, &resource_key, minted); + deltas.entry(resource_key).or_default().admitted += u128::from(qty.0); + } + ComponentOp::Bind { subject, target } | ComponentOp::Release { subject, target } => { + let bind = matches!(operation, ComponentOp::Bind { .. }); + let subject_key = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let target_key = resolve_dependency_target( + Site::Operation(position), + target, + &index, + state, + &mut mismatches, + ); + let (Some(subject_key), Some(target_key)) = (subject_key, target_key) else { + continue; + }; + if target_key == TargetKey::Subject(subject_key.clone()) { + mismatches.push(Mismatch::SelfDependency { + operation: position, + }); + continue; + } + let slot = (subject_key, target_key); + if dependencies.contains(&slot) == bind { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else if bind { + dependencies.insert(slot); + } else { + dependencies.remove(&slot); + } + } + ComponentOp::GrantAuthority { holder, grant } + | ComponentOp::RevokeAuthority { holder, grant } => { + let granting = matches!(operation, ComponentOp::GrantAuthority { .. }); + let holder_key = resolve_subject( + Site::Operation(position), + holder, + &index, + &state.subjects, + &mut mismatches, + ); + if !is_civic_name(&grant.kind.0) { + mismatches.push(Mismatch::InvalidCivicName { + site: Site::Operation(position), + }); + } + let over = resolve_authority_target( + Site::Operation(position), + &grant.over, + &index, + state, + &mut mismatches, + ); + let (Some(holder_key), Some(over)) = (holder_key, over) else { + continue; + }; + let entry = GrantKey { + kind: grant.kind.clone(), + over, + }; + // Admission-time only: a `Subject` grant landing inside a + // `PlaceSubtree` grant the holder already has, or the reverse, + // is a second source for the same kind of act. This does not + // reach `targets_overlap`/`verify_state_shape`, which stay + // structural and position-independent; a later `Relocate` + // that creates this shape is not re-derived as a violation. + if granting + && authority.get(&holder_key).is_some_and(|grants| { + grants.iter().any(|other| { + other.kind == entry.kind + && grant_targets_nest(state, &entry.over, &other.over) + }) + }) + { + mismatches.push(Mismatch::OverlappingJurisdiction { + operation: position, + }); + continue; + } + let held = authority + .get(&holder_key) + .is_some_and(|grants| grants.contains(&entry)); + if held == granting { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else if granting { + authority.entry(holder_key).or_default().insert(entry); + } else { + let empty = if let Some(grants) = authority.get_mut(&holder_key) { + grants.remove(&entry); + grants.is_empty() + } else { + false + }; + if empty { + authority.remove(&holder_key); + } + } + } + ComponentOp::GrantAffordance { subject, affordance } + | ComponentOp::RevokeAffordance { subject, affordance } => { + let granting = matches!(operation, ComponentOp::GrantAffordance { .. }); + let subject_key = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let affordance_key = resolve_affordance( + Site::Operation(position), + affordance, + &index, + &state.affordance_catalog, + &mut mismatches, + ); + let (Some(subject_key), Some(affordance_key)) = (subject_key, affordance_key) + else { + continue; + }; + // A grant is authority over the catalog, not structure over + // ground: retirement and a mirror both hold no grant a patch + // may touch, whatever confinement later decides. + if retired.contains(&subject_key) || mirrors.contains(&subject_key) { + mismatches.push(Mismatch::GrantsOutsideControl { + operation: position, + }); + continue; + } + let held = affordance_holdings + .get(&subject_key) + .is_some_and(|granted| granted.contains(&affordance_key)); + if held == granting { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + continue; + } + if granting { + affordance_holdings + .entry(subject_key) + .or_default() + .insert(affordance_key); + } else { + let granted = affordance_holdings.entry(subject_key).or_default(); + if granted.len() == 1 { + mismatches.push(Mismatch::WouldLeaveSubjectMute { + operation: position, + }); + continue; + } + granted.remove(&affordance_key); + } + } + ComponentOp::OpenOffice { + institution, + office, + delegated, + } => { + let institution_key = resolve_office_institution( + position, + institution, + office, + &index, + state, + &mut mismatches, + ); + if delegated.is_empty() { + mismatches.push(Mismatch::EmptyDelegation { + operation: position, + }); + } + if delegated.iter().any(|kind| !is_civic_name(&kind.0)) { + mismatches.push(Mismatch::InvalidCivicName { + site: Site::Operation(position), + }); + } + let Some(institution_key) = institution_key else { + continue; + }; + if delegated.is_empty() { + continue; + } + let slot = (institution_key, office.clone()); + let incumbent = selection + .get(&slot) + .and_then(|current| current.incumbent.clone()); + if selection + .get(&slot) + .is_some_and(|current| ¤t.delegated == delegated) + { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + selection.insert( + slot, + OfficeCandidate { + incumbent, + delegated: delegated.clone(), + }, + ); + } + } + ComponentOp::CloseOffice { + institution, + office, + } + | ComponentOp::VacateOffice { + institution, + office, + } => { + let closing = matches!(operation, ComponentOp::CloseOffice { .. }); + let Some(institution_key) = resolve_office_institution( + position, + institution, + office, + &index, + state, + &mut mismatches, + ) else { + continue; + }; + let slot = (institution_key, office.clone()); + let Some(current) = selection.get(&slot).cloned() else { + mismatches.push(Mismatch::UnknownOffice { + operation: position, + }); + continue; + }; + if closing { + selection.remove(&slot); + } else if current.incumbent.is_none() { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + selection.insert( + slot, + OfficeCandidate { + incumbent: None, + ..current + }, + ); + } + } + ComponentOp::InstallIncumbent { + institution, + office, + incumbent, + } => { + let institution_key = resolve_office_institution( + position, + institution, + office, + &index, + state, + &mut mismatches, + ); + let incumbent_key = resolve_subject( + Site::Operation(position), + incumbent, + &index, + &state.subjects, + &mut mismatches, + ); + if let Some(incumbent_key) = &incumbent_key + && subject_kind_of(incumbent_key, &index, state) != Some(SubjectKind::Person) + { + mismatches.push(Mismatch::OfficeHolderNotPerson { + operation: position, + }); + continue; + } + let (Some(institution_key), Some(incumbent_key)) = (institution_key, incumbent_key) + else { + continue; + }; + if retired.contains(&incumbent_key) { + mismatches.push(Mismatch::RetiredSubjectActed { + operation: position, + }); + continue; + } + let slot = (institution_key.clone(), office.clone()); + let Some(current) = selection.get(&slot).cloned() else { + mismatches.push(Mismatch::UnknownOffice { + operation: position, + }); + continue; + }; + if selection.iter().any(|((held_by, name), other)| { + *held_by == institution_key + && name != office + && other.incumbent.as_ref() == Some(&incumbent_key) + }) { + mismatches.push(Mismatch::DuplicateIncumbency { + operation: position, + }); + continue; + } + if current.incumbent.as_ref() == Some(&incumbent_key) { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + selection.insert( + slot, + OfficeCandidate { + incumbent: Some(incumbent_key), + ..current + }, + ); + } + } + ComponentOp::OpenForum { + grievance, + forum, + standing, + } => { + if !is_civic_name(&grievance.0) { + mismatches.push(Mismatch::InvalidCivicName { + site: Site::Operation(position), + }); + } + let forum_key = resolve_subject( + Site::Operation(position), + forum, + &index, + &state.subjects, + &mut mismatches, + ); + let standing_key = resolve_authority_target( + Site::Operation(position), + standing, + &index, + state, + &mut mismatches, + ); + let (Some(forum_key), Some(standing_key)) = (forum_key, standing_key) else { + continue; + }; + if redress.get(grievance) == Some(&(forum_key.clone(), standing_key.clone())) { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + redress.insert(grievance.clone(), (forum_key, standing_key)); + } + } + ComponentOp::CloseForum { grievance } => { + if redress.remove(grievance).is_none() { + mismatches.push(Mismatch::UnknownForum { + operation: position, + }); + } + } + ComponentOp::AcquireKnowledge { + subject, + fact, + source, + confidence, + } => { + let subject_key = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let fact_key = resolve_entity( + Site::Operation(position), + EntityKind::Fact, + fact, + &index, + &state.entities, + &mut mismatches, + ); + let (Some(subject_key), Some(fact_key)) = (subject_key, fact_key) else { + continue; + }; + if retired.contains(&subject_key) { + mismatches.push(Mismatch::RetiredSubjectActed { + operation: position, + }); + continue; + } + // Evidenced knowledge is knowledge of canon. A receipt cannot + // vouch for an assertion the kernel never evaluated. + if *source == AuthoredSource::Evidenced + && facts.get(&fact_key) != Some(&FactCandidate::Canonical) + { + mismatches.push(Mismatch::EvidencedKnowledgeOfClaim { + operation: position, + }); + continue; + } + let entry = KnowledgeCandidate { + confidence: *confidence, + source: match source { + AuthoredSource::Witnessed => KnowledgeSourceKey::Witnessed, + AuthoredSource::Evidenced => KnowledgeSourceKey::Evidenced, + }, + }; + let slot = (subject_key, fact_key); + if knowledge.get(&slot) == Some(&entry) { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + knowledge.insert(slot, entry); + } + } + ComponentOp::Forget { subject, fact } => { + let subject_key = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let fact_key = resolve_entity( + Site::Operation(position), + EntityKind::Fact, + fact, + &index, + &state.entities, + &mut mismatches, + ); + let (Some(subject_key), Some(fact_key)) = (subject_key, fact_key) else { + continue; + }; + if retired.contains(&subject_key) { + mismatches.push(Mismatch::RetiredSubjectActed { + operation: position, + }); + continue; + } + if knowledge.remove(&(subject_key, fact_key)).is_none() { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } + } + ComponentOp::Communicate { speaker, fact, to } => { + let speaker_key = resolve_subject( + Site::Operation(position), + speaker, + &index, + &state.subjects, + &mut mismatches, + ); + let fact_key = resolve_entity( + Site::Operation(position), + EntityKind::Fact, + fact, + &index, + &state.entities, + &mut mismatches, + ); + let audience = resolve_audience( + Site::Operation(position), + to, + &index, + state, + &mut mismatches, + ); + let (Some(speaker_key), Some(_), Some(audience)) = + (speaker_key, fact_key, audience) + else { + continue; + }; + if retired.contains(&speaker_key) { + mismatches.push(Mismatch::RetiredSubjectActed { + operation: position, + }); + continue; + } + // Ontology admission: communication reaches only subjects inside + // the channel's reach, and a speaker outside it is not speaking. + if !candidate_in_audience( + &speaker_key, + &audience, + &speaker_key, + &positions, + &channels, + &containers, + ) { + mismatches.push(Mismatch::SpeakerOutsideAudience { + operation: position, + }); + } + } + ComponentOp::Witness { + fact, + place, + confidence, + } => { + let fact_key = resolve_entity( + Site::Operation(position), + EntityKind::Fact, + fact, + &index, + &state.entities, + &mut mismatches, + ); + let place_key = resolve_entity( + Site::Operation(position), + EntityKind::Place, + place, + &index, + &state.entities, + &mut mismatches, + ); + let (Some(fact_key), Some(place_key)) = (fact_key, place_key) else { + continue; + }; + // The apply-time fan-out, modelled: every candidate subject + // standing under the place — canonical positions plus this + // patch's own declarations and its own relocations, which + // earlier arms have already written into `positions` — less + // everyone this map already has holding the fact, which is the + // same "already a knower" test `unheld` applies over committed + // state. + let entry = KnowledgeCandidate { + confidence: *confidence, + source: KnowledgeSourceKey::Witnessed, + }; + let recipients: Vec<Key<SubjectId>> = positions + .iter() + .filter(|(subject_key, standing)| { + key_covers_place(&place_key, standing, &containers) + && !knowledge.contains_key(&((*subject_key).clone(), fact_key.clone())) + }) + .map(|(subject_key, _)| (*subject_key).clone()) + .collect(); + if recipients.is_empty() { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + for subject_key in recipients { + knowledge.insert((subject_key, fact_key.clone()), entry.clone()); + } + } + } + ComponentOp::SetPersonaMaterial { + subject, + values, + voice, + memories, + reads, + } => { + let site = Site::Operation(position); + let subject_key = + resolve_subject(site.clone(), subject, &index, &state.subjects, &mut mismatches); + let mut read_keys = Vec::with_capacity(reads.len()); + for read in reads { + read_keys.push(resolve_subject( + site.clone(), + &read.subject, + &index, + &state.subjects, + &mut mismatches, + )); + } + let texts = values + .iter() + .chain(memories.iter()) + .chain(std::iter::once(voice)) + .chain(reads.iter().map(|read| &read.statement)); + let mut read_subjects: BTreeSet<&Ref<SubjectId>> = BTreeSet::new(); + let duplicate_read = reads.iter().any(|read| !read_subjects.insert(&read.subject)); + if texts.clone().any(|text| !is_canonical_text(text.as_str())) || duplicate_read { + mismatches.push(Mismatch::NoncanonicalText { + operation: position, + }); + } + let (Some(Key::Existing(subject_id)), true) = + (subject_key, read_keys.iter().all(Option::is_some)) + else { + continue; + }; + // Identical material on an existing subject changes nothing. A + // draft read can never equal a held one, so it is skipped here. + let held: Option<BTreeMap<SubjectId, Statement>> = read_keys + .iter() + .zip(reads) + .map(|(key, read)| match key { + Some(Key::Existing(id)) => Some((*id, read.statement.clone())), + _ => None, + }) + .collect(); + if let Some(held) = held + && state.persona_material.get(&subject_id) + == Some(&PersonaMaterial { + values: values.clone(), + voice: voice.clone(), + memories: memories.clone(), + reads: held, + }) + { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } + } + ComponentOp::SetReach { channel, reach } => { + let channel_key = resolve_entity( + Site::Operation(position), + EntityKind::Channel, + channel, + &index, + &state.entities, + &mut mismatches, + ); + let reach_key = resolve_reach( + Site::Operation(position), + reach, + &index, + state, + &mut mismatches, + ); + let (Some(channel_key), Some(reach_key)) = (channel_key, reach_key) else { + continue; + }; + let Some(candidate) = channels.get_mut(&channel_key) else { + continue; + }; + if candidate.reach == reach_key { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + candidate.reach = reach_key; + } + } + ComponentOp::SetController { + channel, + controller, + } => { + let channel_key = resolve_entity( + Site::Operation(position), + EntityKind::Channel, + channel, + &index, + &state.entities, + &mut mismatches, + ); + let controller_key = resolve_controller( + Site::Operation(position), + controller, + &index, + state, + &mut mismatches, + ); + let (Some(channel_key), Some(controller_key)) = (channel_key, controller_key) + else { + continue; + }; + let Some(candidate) = channels.get_mut(&channel_key) else { + continue; + }; + if candidate.controller == controller_key { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + candidate.controller = controller_key; + } + } + } + // Disjointness, checked against the complete candidate graph after each + // operation that could widen someone's jurisdiction, so two operations + // in one patch collide with each other and the failure names the one + // that created the collision. Only three operations can: a new grant, a + // widened office, and a new incumbency. + if matches!( + operation, + ComponentOp::GrantAuthority { .. } + | ComponentOp::OpenOffice { .. } + | ComponentOp::InstallIncumbent { .. } + ) && graph_overlaps(&authority, &selection, &containers, &retired) + { + mismatches.push(Mismatch::OverlappingJurisdiction { + operation: position, + }); + } + } + + // Conservation, over the complete candidate after every operation has been + // applied in order. Never per operation: a patch whose operations + // individually balance but whose net does not is impossible, and an + // intermediate negative was already caught above as `InsufficientCustody`. + for (resource_key, delta) in &mut deltas { + delta.before = seeded_holdings + .iter() + .filter(|((_, resource), _)| resource == resource_key) + .map(|(_, quantity)| u128::from(quantity.0)) + .sum(); + delta.after = holdings + .iter() + .filter(|((_, resource), _)| resource == resource_key) + .map(|(_, quantity)| u128::from(quantity.0)) + .sum(); + } + if let Some(resource) = check_ledger(&deltas) { + mismatches.push(Mismatch::CustodyNotConserved { + resource: RefName::Entity(match resource { + Key::Existing(entity_id) => Ref::Existing(entity_id), + Key::Draft(handle) => Ref::Draft(handle), + }), + }); + } + + if let Some(intent) = scale_intent { + for handle in intent.jurisdictions.keys() { + if index.get(handle) != Some(&PLACE) { + mismatches.push(Mismatch::UnknownJurisdictionRoot { + handle: handle.clone(), + }); + } + } + // Weights distribute the target and never raise it. + if intent + .jurisdictions + .values() + .map(|weight| u64::from(*weight)) + .sum::<u64>() + > 1000 + { + mismatches.push(Mismatch::ScaleWeightsExceedWhole); + } + } + + if let Some(weights) = lens_weights + && !weights.draws() + { + mismatches.push(Mismatch::LensWeightsNeverDraw); + } + + if patch.declarations.is_empty() && patch.operations.is_empty() { + mismatches.push(Mismatch::NoCanonicalChange); + } + + if admits_human + && !patch + .declarations + .iter() + .any(|declaration| matches!(declaration, Declaration::Subject(_))) + { + mismatches.push(Mismatch::NoDecisionSubject); + } + + if !mismatches.is_empty() { + mismatches.sort(); + return Err(mismatches); + } + + // No canonical ID exists above this line. Allocation starts only now. + let mut collisions = Vec::new(); + let mut entities = Vec::new(); + let mut allocated_entities: BTreeMap<DraftHandle, EntityId> = BTreeMap::new(); + for declaration in &patch.declarations { + let Declaration::Entity(entity) = declaration else { + continue; + }; + let entity_id = EntityId(derive_id( + ENTITY_NAMESPACE, + world_id, + command_id, + &entity.handle, + None, + )); + if state.entities.contains_key(&entity_id) { + collisions.push(Mismatch::CanonicalCollision { + handle: entity.handle.clone(), + }); + } + allocated_entities.insert(entity.handle.clone(), entity_id); + entities.push(ResolvedEntity { + handle: entity.handle.clone(), + entity_id, + entity: EntityRecord { + label: entity.label.clone(), + kind: entity.kind, + container: None, + }, + }); + } + // Facts and channels allocate through the same entity namespace and the same + // `derive_id`, so no namespace is added and `RefKind::Entity` types every + // reference to one. They stay out of `entities` above so that vector remains + // a zip over the place and resource declarations. + for declaration in &patch.declarations { + let handle = match declaration { + Declaration::Fact(fact) => &fact.handle, + Declaration::Channel(channel) => &channel.handle, + _ => continue, + }; + let entity_id = EntityId(derive_id( + ENTITY_NAMESPACE, + world_id, + command_id, + handle, + None, + )); + if state.entities.contains_key(&entity_id) { + collisions.push(Mismatch::CanonicalCollision { + handle: handle.clone(), + }); + } + allocated_entities.insert(handle.clone(), entity_id); + } + let entity_id_of = |key: &Key<EntityId>| -> EntityId { + match key { + Key::Existing(entity_id) => *entity_id, + Key::Draft(handle) => *allocated_entities + .get(handle) + .expect("a draft entity reference resolved above"), + } + }; + for (resolved, declaration) in entities + .iter_mut() + .zip( + patch + .declarations + .iter() + .filter_map(|declaration| match declaration { + Declaration::Entity(entity) => Some(entity), + _ => None, + }), + ) + { + resolved.entity.container = declaration + .container + .as_ref() + .map(|reference| entity_id_of(&key_of(reference))); + } + + let mut allocated_routes: BTreeMap<DraftHandle, EdgeId> = BTreeMap::new(); + let mut routes = Vec::new(); + for declaration in &patch.declarations { + let Declaration::Route(route) = declaration else { + continue; + }; + let edge_id = EdgeId(derive_id( + EDGE_NAMESPACE, + world_id, + command_id, + &route.handle, + None, + )); + if state.edges.contains_key(&edge_id) { + collisions.push(Mismatch::CanonicalCollision { + handle: route.handle.clone(), + }); + } + allocated_routes.insert(route.handle.clone(), edge_id); + routes.push(ResolvedRoute { + handle: route.handle.clone(), + edge_id, + edge: EdgeRecord::Route { + label: route.label.clone(), + from: entity_id_of(&key_of(&route.from)), + to: entity_id_of(&key_of(&route.to)), + access: route.access.clone(), + cost: route.cost, + open: true, + }, + }); + } + + let mut allocated_affordances: BTreeMap<DraftHandle, AffordanceId> = BTreeMap::new(); + let mut affordances = Vec::new(); + let allocate_affordance = |handle: &DraftHandle, + entry: Affordance, + affordances: &mut Vec<ResolvedAffordance>, + allocated: &mut BTreeMap<DraftHandle, AffordanceId>, + collisions: &mut Vec<Mismatch>| { + let affordance_id = AffordanceId(derive_id( + AFFORDANCE_NAMESPACE, + world_id, + command_id, + handle, + None, + )); + if state.affordance_catalog.contains_key(&affordance_id) { + collisions.push(Mismatch::CanonicalCollision { + handle: handle.clone(), + }); + } + allocated.insert(handle.clone(), affordance_id); + affordances.push(ResolvedAffordance { + handle: handle.clone(), + affordance_id, + affordance: entry, + }); + }; + if admits_human { + allocate_affordance( + &speak_handle, + kernel_speak_entry(), + &mut affordances, + &mut allocated_affordances, + &mut collisions, + ); + } + for declaration in &patch.declarations { + let Declaration::Affordance(input) = declaration else { + continue; + }; + allocate_affordance( + &input.handle, + Affordance { + kind: input.kind.clone(), + roles: input.roles.clone(), + preconditions: input.preconditions.clone(), + effect_slots: input.effect_slots.clone(), + outcome_bands: input.outcome_bands.clone(), + carries_speech: input.carries_speech, + }, + &mut affordances, + &mut allocated_affordances, + &mut collisions, + ); + } + let affordance_id_of = |key: &Key<AffordanceId>| -> AffordanceId { + match key { + Key::Existing(affordance_id) => *affordance_id, + Key::Draft(handle) => *allocated_affordances + .get(handle) + .expect("a draft affordance reference resolved above"), + } + }; + + let mut allocated_subjects: BTreeMap<DraftHandle, SubjectId> = BTreeMap::new(); + let mut subjects = Vec::new(); + for declaration in &patch.declarations { + let Declaration::Subject(input) = declaration else { + continue; + }; + let subject_id = SubjectId(derive_id( + SUBJECT_NAMESPACE, + world_id, + command_id, + &input.handle, + None, + )); + if state.subjects.contains_key(&subject_id) { + collisions.push(Mismatch::CanonicalCollision { + handle: input.handle.clone(), + }); + } + allocated_subjects.insert(input.handle.clone(), subject_id); + let mut controller_id = || { + ControllerId(derive_id( + CONTROLLER_NAMESPACE, + world_id, + command_id, + &input.handle, + None, + )) + }; + let controller = match input.controller.clone() { + NewController::Human { principal } => ControllerAssignment::Human { + controller_id: controller_id(), + principal, + }, + NewController::NarrativePersona => ControllerAssignment::NarrativePersona { + controller_id: controller_id(), + }, + NewController::OperationalAgent => ControllerAssignment::OperationalAgent { + controller_id: controller_id(), + }, + // No controller id is derived, because there is no controller. + NewController::External { consumer } => { + ControllerAssignment::ExternallyControlled { consumer } + } + }; + let granted = input + .affordances + .iter() + .map(|reference| affordance_id_of(&key_of(reference))) + .collect(); + subjects.push(ResolvedSubject { + handle: input.handle.clone(), + subject_id, + subject: SubjectState { + label: input.label.clone(), + kind: input.kind, + import_key: input.import_key.clone(), + }, + controller, + affordances: granted, + position: input.position.as_ref().map(|reference| Position { + place: entity_id_of(&key_of(reference)), + }), + }); + } + + let subject_id_of = |key: &Key<SubjectId>| -> SubjectId { + match key { + Key::Existing(subject_id) => *subject_id, + Key::Draft(handle) => *allocated_subjects + .get(handle) + .expect("a draft subject reference resolved above"), + } + }; + let edge_id_of = |key: &Key<EdgeId>| -> EdgeId { + match key { + Key::Existing(edge_id) => *edge_id, + Key::Draft(handle) => *allocated_routes + .get(handle) + .expect("a draft route reference resolved above"), + } + }; + let target_of = |target: &DependencyRef| -> DependencyTarget { + match target { + DependencyRef::Resource(reference) => { + DependencyTarget::Resource(entity_id_of(&key_of(reference))) + } + DependencyRef::Route(reference) => { + DependencyTarget::Route(edge_id_of(&key_of(reference))) + } + DependencyRef::Subject(reference) => { + DependencyTarget::Subject(subject_id_of(&key_of(reference))) + } + } + }; + let authority_target_of = |target: &AuthorityTargetRef| -> AuthorityTarget { + match target { + AuthorityTargetRef::Subject(reference) => { + AuthorityTarget::Subject(subject_id_of(&key_of(reference))) + } + AuthorityTargetRef::PlaceSubtree(reference) => { + AuthorityTarget::PlaceSubtree(entity_id_of(&key_of(reference))) + } + } + }; + let reach_of = |reach: &ReachRef| -> Reach { + match reach { + ReachRef::Subjects(members) => Reach::Subjects( + members + .iter() + .map(|reference| subject_id_of(&key_of(reference))) + .collect(), + ), + ReachRef::Place(reference) => Reach::Place(entity_id_of(&key_of(reference))), + } + }; + let controller_of = |controller: &Option<Ref<SubjectId>>| -> Option<SubjectId> { + controller + .as_ref() + .map(|reference| subject_id_of(&key_of(reference))) + }; + let audience_of = |audience: &AudienceRef| -> Audience { + match audience { + AudienceRef::Colocated => Audience::Colocated, + AudienceRef::Channel(reference) => Audience::Channel(entity_id_of(&key_of(reference))), + } + }; + let mut declared_facts = Vec::new(); + let mut declared_channels = Vec::new(); + for declaration in &patch.declarations { + match declaration { + Declaration::Fact(fact) => declared_facts.push(ResolvedFact { + handle: fact.handle.clone(), + entity_id: entity_id_of(&Key::Draft(fact.handle.clone())), + entity: EntityRecord { + label: fact.label.clone(), + kind: EntityKind::Fact, + container: None, + }, + fact: FactRecord { + statement: fact.statement.clone(), + standing: match &fact.standing { + FactStandingRef::Canonical { evidence } => FactStanding::Canonical { + evidence: evidence.clone(), + }, + FactStandingRef::Claimed { by } => FactStanding::Claimed { + by: subject_id_of(&key_of(by)), + }, + FactStandingRef::Ruled => FactStanding::Ruled, + }, + }, + }), + Declaration::Channel(channel) => declared_channels.push(ResolvedChannel { + handle: channel.handle.clone(), + entity_id: entity_id_of(&Key::Draft(channel.handle.clone())), + entity: EntityRecord { + label: channel.label.clone(), + kind: EntityKind::Channel, + container: None, + }, + channel: ChannelRecord { + reach: reach_of(&channel.reach), + controller: controller_of(&channel.controller), + }, + }), + _ => {} + } + } + let grant_of = |grant: &AuthorityGrantRef| -> AuthorityGrant { + AuthorityGrant { + kind: grant.kind.clone(), + over: authority_target_of(&grant.over), + } + }; + let precondition_of = |check: &PreconditionRef| -> BoundPrecondition { + match check { + PreconditionRef::Present { at } => BoundPrecondition::Present { + at: entity_id_of(&key_of(at)), + }, + PreconditionRef::Reachable { to, within } => BoundPrecondition::Reachable { + to: entity_id_of(&key_of(to)), + within: *within, + }, + PreconditionRef::Holds { resource, at_least } => BoundPrecondition::Holds { + resource: entity_id_of(&key_of(resource)), + at_least: *at_least, + }, + PreconditionRef::Authorized { over, kind } => BoundPrecondition::Authorized { + over: authority_target_of(over).as_referent(), + kind: kind.clone(), + }, + PreconditionRef::HasStanding { grievance } => BoundPrecondition::HasStanding { + grievance: grievance.clone(), + }, + PreconditionRef::Knows { fact, at_least } => BoundPrecondition::Knows { + fact: entity_id_of(&key_of(fact)), + at_least: *at_least, + }, + PreconditionRef::CanBroadcast { via } => BoundPrecondition::CanBroadcast { + via: audience_of(via), + }, + PreconditionRef::CanReach { subject, via } => BoundPrecondition::CanReach { + subject: subject_id_of(&key_of(subject)), + via: audience_of(via), + }, + PreconditionRef::Committed { to, kind } => BoundPrecondition::Committed { + to: subject_id_of(&key_of(to)), + kind: *kind, + }, + } + }; + let pressure_source_of = |source: &PressureSourceRef| -> PressureSource { + match source { + PressureSourceRef::Commitment { subject, key } => PressureSource::Commitment { + subject: subject_id_of(&key_of(subject)), + key: *key, + }, + PressureSourceRef::Dependency(target) => PressureSource::Dependency(target_of(target)), + PressureSourceRef::Subject(reference) => { + PressureSource::Subject(subject_id_of(&key_of(reference))) + } + } + }; + let operations = patch + .operations + .iter() + .enumerate() + .map(|(position, operation)| match operation { + ComponentOp::CreateCommitment { + subject, + counterparty, + kind, + due, + period, + checks, + statement, + } => ResolvedOp::CreateCommitment { + subject: subject_id_of(&key_of(subject)), + key: CommitmentKey { + command: command_id, + index: position as u32, + }, + commitment: Commitment { + kind: *kind, + counterparty: counterparty + .as_ref() + .map(|reference| subject_id_of(&key_of(reference))), + due: *due, + period: *period, + checks: checks.iter().map(precondition_of).collect(), + statement: statement.clone(), + }, + }, + ComponentOp::DischargeCommitment { subject, key } => ResolvedOp::DischargeCommitment { + subject: subject_id_of(&key_of(subject)), + key: *key, + }, + ComponentOp::AdvancePressure { source, target, by } => ResolvedOp::AdvancePressure { + source: pressure_source_of(source), + target: subject_id_of(&key_of(target)), + by: *by, + }, + ComponentOp::ReducePressure { source, target, by } => ResolvedOp::ReducePressure { + source: pressure_source_of(source), + target: subject_id_of(&key_of(target)), + by: *by, + }, + ComponentOp::ResolvePressure { source, target } => ResolvedOp::ResolvePressure { + source: pressure_source_of(source), + target: subject_id_of(&key_of(target)), + }, + ComponentOp::Retire { subject } => ResolvedOp::Retire { + subject: subject_id_of(&key_of(subject)), + }, + ComponentOp::GrantAffordance { + subject, + affordance, + } => ResolvedOp::GrantAffordance { + subject: subject_id_of(&key_of(subject)), + affordance: affordance_id_of(&key_of(affordance)), + }, + ComponentOp::RevokeAffordance { + subject, + affordance, + } => ResolvedOp::RevokeAffordance { + subject: subject_id_of(&key_of(subject)), + affordance: affordance_id_of(&key_of(affordance)), + }, + ComponentOp::Relocate { subject, via } => ResolvedOp::Relocate { + subject_id: subject_id_of(&key_of(subject)), + edge_id: edge_id_of(&key_of(via)), + }, + ComponentOp::OpenRoute { route } => ResolvedOp::OpenRoute { + edge_id: edge_id_of(&key_of(route)), + }, + ComponentOp::CloseRoute { route } => ResolvedOp::CloseRoute { + edge_id: edge_id_of(&key_of(route)), + }, + ComponentOp::AlterCost { route, cost } => ResolvedOp::AlterCost { + edge_id: edge_id_of(&key_of(route)), + cost: *cost, + }, + ComponentOp::Transfer { + from, + to, + resource, + qty, + } => ResolvedOp::Transfer { + from: subject_id_of(&key_of(from)), + to: subject_id_of(&key_of(to)), + resource: entity_id_of(&key_of(resource)), + qty: *qty, + }, + ComponentOp::Transform { + holder, + from_resource, + into_resource, + qty, + } => ResolvedOp::Transform { + holder: subject_id_of(&key_of(holder)), + from_resource: entity_id_of(&key_of(from_resource)), + into_resource: entity_id_of(&key_of(into_resource)), + qty: *qty, + }, + ComponentOp::Consume { + holder, + resource, + qty, + } => ResolvedOp::Consume { + holder: subject_id_of(&key_of(holder)), + resource: entity_id_of(&key_of(resource)), + qty: *qty, + }, + ComponentOp::Admit { + holder, + resource, + qty, + evidence, + } => ResolvedOp::Admit { + holder: subject_id_of(&key_of(holder)), + resource: entity_id_of(&key_of(resource)), + qty: *qty, + evidence: evidence.clone(), + }, + ComponentOp::Mint { + holder, + resource, + qty, + } => ResolvedOp::Mint { + holder: subject_id_of(&key_of(holder)), + resource: entity_id_of(&key_of(resource)), + qty: *qty, + }, + ComponentOp::Bind { subject, target } => ResolvedOp::Bind { + subject: subject_id_of(&key_of(subject)), + target: target_of(target), + }, + ComponentOp::Release { subject, target } => ResolvedOp::Release { + subject: subject_id_of(&key_of(subject)), + target: target_of(target), + }, + ComponentOp::GrantAuthority { holder, grant } => ResolvedOp::GrantAuthority { + holder: subject_id_of(&key_of(holder)), + grant: grant_of(grant), + }, + ComponentOp::RevokeAuthority { holder, grant } => ResolvedOp::RevokeAuthority { + holder: subject_id_of(&key_of(holder)), + grant: grant_of(grant), + }, + ComponentOp::OpenOffice { + institution, + office, + delegated, + } => ResolvedOp::OpenOffice { + institution: subject_id_of(&key_of(institution)), + office: office.clone(), + delegated: delegated.clone(), + }, + ComponentOp::CloseOffice { + institution, + office, + } => ResolvedOp::CloseOffice { + institution: subject_id_of(&key_of(institution)), + office: office.clone(), + }, + ComponentOp::InstallIncumbent { + institution, + office, + incumbent, + } => ResolvedOp::InstallIncumbent { + institution: subject_id_of(&key_of(institution)), + office: office.clone(), + incumbent: subject_id_of(&key_of(incumbent)), + }, + ComponentOp::VacateOffice { + institution, + office, + } => ResolvedOp::VacateOffice { + institution: subject_id_of(&key_of(institution)), + office: office.clone(), + }, + ComponentOp::OpenForum { + grievance, + forum, + standing, + } => ResolvedOp::OpenForum { + grievance: grievance.clone(), + forum: subject_id_of(&key_of(forum)), + standing: authority_target_of(standing), + }, + ComponentOp::CloseForum { grievance } => ResolvedOp::CloseForum { + grievance: grievance.clone(), + }, + ComponentOp::AcquireKnowledge { + subject, + fact, + source, + confidence, + } => ResolvedOp::AcquireKnowledge { + subject: subject_id_of(&key_of(subject)), + fact: entity_id_of(&key_of(fact)), + source: *source, + confidence: *confidence, + }, + ComponentOp::Communicate { speaker, fact, to } => ResolvedOp::Communicate { + speaker: subject_id_of(&key_of(speaker)), + fact: entity_id_of(&key_of(fact)), + to: audience_of(to), + }, + ComponentOp::Witness { + fact, + place, + confidence, + } => ResolvedOp::Witness { + fact: entity_id_of(&key_of(fact)), + place: entity_id_of(&key_of(place)), + confidence: *confidence, + }, + ComponentOp::Forget { subject, fact } => ResolvedOp::Forget { + subject: subject_id_of(&key_of(subject)), + fact: entity_id_of(&key_of(fact)), + }, + ComponentOp::SetReach { channel, reach } => ResolvedOp::SetReach { + channel: entity_id_of(&key_of(channel)), + reach: reach_of(reach), + }, + ComponentOp::SetPersonaMaterial { + subject, + values, + voice, + memories, + reads, + } => ResolvedOp::SetPersonaMaterial { + subject: subject_id_of(&key_of(subject)), + material: PersonaMaterial { + values: values.clone(), + voice: voice.clone(), + memories: memories.clone(), + reads: reads + .iter() + .map(|read| (subject_id_of(&key_of(&read.subject)), read.statement.clone())) + .collect(), + }, + }, + ComponentOp::SetController { + channel, + controller, + } => ResolvedOp::SetController { + channel: entity_id_of(&key_of(channel)), + controller: controller_of(controller), + }, + }) + .collect(); + + if !collisions.is_empty() { + collisions.sort(); + return Err(collisions); + } + + Ok(ResolvedPatch { + subjects, + entities, + routes, + affordances, + facts: declared_facts, + channels: declared_channels, + operations, + evidence: patch.evidence.clone(), + scale_intent: scale_intent.map(|intent| WorldScaleIntent { + targets: intent.targets.clone(), + jurisdictions: intent + .jurisdictions + .iter() + .map(|(handle, weight)| { + ( + *allocated_entities + .get(handle) + .expect("a jurisdiction root resolved above"), + *weight, + ) + }) + .collect(), + }), + lens_weights: lens_weights.cloned(), + }) +} + +/// Whether every referent one stored check names resolves. The canonical +/// lowering runs after allocation, so a check that does not resolve here would +/// have nothing to lower to. +fn resolve_check( + site: Site, + check: &PreconditionRef, + index: &BTreeMap<DraftHandle, RefKind>, + state: &super::WorldState, + mismatches: &mut Vec<Mismatch>, +) -> bool { + let entity = |kind: EntityKind, reference: &Ref<EntityId>, mismatches: &mut Vec<Mismatch>| { + resolve_entity( + site.clone(), + kind, + reference, + index, + &state.entities, + mismatches, + ) + .is_some() + }; + let audience = |via: &AudienceRef, mismatches: &mut Vec<Mismatch>| { + resolve_audience(site.clone(), via, index, state, mismatches).is_some() + }; + let subject = |reference: &Ref<SubjectId>, mismatches: &mut Vec<Mismatch>| { + resolve_subject(site.clone(), reference, index, &state.subjects, mismatches).is_some() + }; + match check { + PreconditionRef::Present { at } => entity(EntityKind::Place, at, mismatches), + PreconditionRef::Reachable { to, within } => { + let resolved = entity(EntityKind::Place, to, mismatches); + if !is_valid_cost(*within) { + mismatches.push(Mismatch::InvalidCost { site: site.clone() }); + return false; + } + resolved + } + PreconditionRef::Holds { resource, .. } => { + entity(EntityKind::Resource, resource, mismatches) + } + PreconditionRef::Authorized { over, kind } => { + let resolved = + resolve_authority_target(site.clone(), over, index, state, mismatches).is_some(); + if !is_civic_name(&kind.0) { + mismatches.push(Mismatch::InvalidCivicName { site: site.clone() }); + return false; + } + resolved + } + PreconditionRef::HasStanding { grievance } => { + if is_civic_name(&grievance.0) { + true + } else { + mismatches.push(Mismatch::InvalidCivicName { site: site.clone() }); + false + } + } + PreconditionRef::Knows { fact, .. } => entity(EntityKind::Fact, fact, mismatches), + PreconditionRef::CanBroadcast { via } => audience(via, mismatches), + PreconditionRef::CanReach { + subject: named, + via, + } => subject(named, mismatches) & audience(via, mismatches), + PreconditionRef::Committed { to, .. } => subject(to, mismatches), + } +} + +fn resolve_pressure_source( + site: Site, + source: &PressureSourceRef, + index: &BTreeMap<DraftHandle, RefKind>, + state: &super::WorldState, + mismatches: &mut Vec<Mismatch>, +) -> Option<PressureSourceKey> { + match source { + PressureSourceRef::Commitment { subject, key } => { + resolve_subject(site, subject, index, &state.subjects, mismatches) + .map(|subject| PressureSourceKey::Commitment { subject, key: *key }) + } + PressureSourceRef::Dependency(target) => { + resolve_dependency_target(site, target, index, state, mismatches) + .map(PressureSourceKey::Dependency) + } + PressureSourceRef::Subject(reference) => { + resolve_subject(site, reference, index, &state.subjects, mismatches) + .map(PressureSourceKey::Subject) + } + } +} + +/// Whether `place` is `root`, or reaches it through the candidate container +/// chain. The walk is bounded by the graph size, so a cycle that does not +/// include either end still terminates. +fn key_covers_place( + root: &Key<EntityId>, + place: &Key<EntityId>, + containers: &BTreeMap<Key<EntityId>, Key<EntityId>>, +) -> bool { + let mut current = Some(place); + for _ in 0..=containers.len() { + match current { + None => return false, + Some(node) if node == root => return true, + Some(node) => current = containers.get(node), + } + } + false +} + +/// Whether a place reaches itself through its container chain: the same walk, +/// started one link up so a place is not its own ancestor by definition. +fn contains_itself( + start: &Key<EntityId>, + containers: &BTreeMap<Key<EntityId>, Key<EntityId>>, +) -> bool { + containers + .get(start) + .is_some_and(|parent| key_covers_place(start, parent, containers)) +} + +/// Whether `place` is `root` or is contained in it, over canonical state: one +/// upward walk in the shape of [`containment_terminates`], bounded by the graph +/// size. It is total because `admit_resolved` refuses a non-terminating chain, +/// so the bound is belt-and-braces rather than a repair loop. There is no +/// downward enumeration and no child index: every jurisdictional question this +/// kernel asks is "is this target inside my ground". +pub(super) fn covers_place( + entities: &BTreeMap<EntityId, EntityRecord>, + root: EntityId, + place: EntityId, +) -> bool { + let mut current = Some(place); + for _ in 0..=entities.len() { + match current { + None => return false, + Some(node) if node == root => return true, + Some(node) => current = entities.get(&node).and_then(|record| record.container), + } + } + false +} + +/// The canonical twin of the candidate graph's `candidate_targets_overlap`: whether two +/// jurisdictions of one kind cover common ground. +pub(super) fn targets_overlap( + entities: &BTreeMap<EntityId, EntityRecord>, + left: AuthorityTarget, + right: AuthorityTarget, +) -> bool { + match (left, right) { + (AuthorityTarget::Subject(one), AuthorityTarget::Subject(other)) => one == other, + (AuthorityTarget::PlaceSubtree(one), AuthorityTarget::PlaceSubtree(other)) => { + covers_place(entities, one, other) || covers_place(entities, other, one) + } + _ => false, + } +} + +/// Whether a subject holding `grants` may traverse a route with this access +/// rule toward `destination`. The sole statement of the `Restricted` rule, +/// called by `resolve_patch`'s `Relocate` arm, by `apply_operation`'s, and by +/// `Precondition::Reachable`'s edge admission — one rule, three callers, no +/// drift. Openness is a separate claim with its own name, so it is not folded +/// in here. +pub(super) fn route_admits( + state: &super::WorldState, + grants: &BTreeSet<AuthorityGrant>, + access: &AccessKind, + destination: EntityId, +) -> bool { + match access { + AccessKind::Public => true, + AccessKind::Restricted { requires } => grants.iter().any(|grant| { + &grant.kind == requires + && super::covers(state, grant.over, super::Target::Entity(destination)) + }), + } +} + +/// The same containment walk over canonical state, for the admission and replay +/// invariants. `admit_resolved` runs it after inserting a place, so a container +/// chain that never terminates dies before the partition keeps it. +pub(super) fn containment_terminates( + start: EntityId, + entities: &BTreeMap<EntityId, EntityRecord>, +) -> bool { + let mut current = entities.get(&start).and_then(|record| record.container); + for _ in 0..=entities.len() { + match current { + None => return true, + Some(node) if node == start => return false, + Some(node) => current = entities.get(&node).and_then(|record| record.container), + } + } + false +} +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::{ + ADMIT_KIND, FIXTURE_ENTITIES, LEVY_KIND, activate, admit_topology, authority_kind, + auth_principal, civic_world, command, creation, grant_to, human_principal, office, + over_place, owner, reject_owner, speak_entry, submit_owner, + }; + use crate::{ + CallerId, CommandBody, CommandId, KernelError, SubmitReceipt, WorldKernel, WorldPhase, + }; + + /// Owner: `WorldPatch::sets_persona_of_existing_subject`. Consumer: + /// `ghostlight-dungeon`'s play agent (PA.f61, parked at + /// `parked/ghostlight-eve-surface`), which refuses a + /// `set_persona_material` run whose patch answers true here, since + /// `WorldPatch`'s own fields are `pub(crate)` and Dungeon may not parse + /// its JSON to decide the question itself. + #[test] + fn sets_persona_of_existing_subject_reads_the_subject_refs_own_shape() { + let empty = WorldPatch::default(); + assert!(!empty.sets_persona_of_existing_subject()); + + let existing = WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::SetPersonaMaterial { + subject: Ref::Existing(SubjectId::issue()), + values: Vec::new(), + voice: Statement::new("flat and even").unwrap(), + memories: Vec::new(), + reads: Vec::new(), + }], + evidence: Vec::new(), + }; + assert!(existing.sets_persona_of_existing_subject()); + + let draft = WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::SetPersonaMaterial { + subject: Ref::Draft(DraftHandle::new("npc")), + values: Vec::new(), + voice: Statement::new("flat and even").unwrap(), + memories: Vec::new(), + reads: Vec::new(), + }], + evidence: Vec::new(), + }; + assert!(!draft.sets_persona_of_existing_subject()); + } + + /// PA.f92/PA.f110: a fixture whose persona write sits at either end of + /// `operations` only ever exercises `.take(1)` (op 0) or `.rev().take(1)` + /// (the last op) — the prior version of this test put the write last, + /// so `.rev().take(1)` would still find it and pass undetected. Here the + /// persona write to an existing subject sits strictly in the *middle*, + /// with a harmless `Relocate` both before and after it: only a scan over + /// every operation, in either direction, reports `true`. + #[test] + fn sets_persona_of_existing_subject_scans_every_operation_not_just_an_end() { + let patch = WorldPatch { + declarations: Vec::new(), + operations: vec![ + ComponentOp::Relocate { + subject: Ref::Draft(DraftHandle::new("wanderer")), + via: Ref::Draft(DraftHandle::new("path")), + }, + ComponentOp::SetPersonaMaterial { + subject: Ref::Existing(SubjectId::issue()), + values: Vec::new(), + voice: Statement::new("flat and even").unwrap(), + memories: Vec::new(), + reads: Vec::new(), + }, + ComponentOp::Relocate { + subject: Ref::Draft(DraftHandle::new("wanderer")), + via: Ref::Draft(DraftHandle::new("second-path")), + }, + ], + evidence: Vec::new(), + }; + // Op 0 and the last op (index 2) are both the harmless `Relocate`; + // only op 1, strictly in the middle, is the persona write. A + // `.take(1)` mutation sees only op 0; a `.rev().take(1)` mutation + // sees only op 2. Both would report `false` here. + assert!(patch.sets_persona_of_existing_subject()); + } + + fn entity(handle: &str, label: &str, kind: EntityKind) -> Declaration { + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind, + container: None, + }) + } + + fn contained(handle: &str, label: &str, container: &str) -> Declaration { + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: EntityKind::Place, + container: Some(Ref::Draft(DraftHandle::new(container))), + }) + } + + fn route(handle: &str, label: &str, from: &str, to: &str, cost: u32) -> Declaration { + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + from: Ref::Draft(DraftHandle::new(from)), + to: Ref::Draft(DraftHandle::new(to)), + access: AccessKind::Public, + cost: Cost(cost), + }) + } + + /// Every fixture institution is declared by a post-genesis `AdmitPatch`, so + /// it grants the committed Speak entry by canonical reference: the kernel + /// synthesizes that entry once, at genesis, and a later patch names it like + /// any other structure a previous commit allocated. + fn institution( + kernel: &WorldKernel, + handle: &str, + label: &str, + position: Option<Ref<EntityId>>, + ) -> Declaration { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: SubjectKind::Institution, + controller: NewController::OperationalAgent, + affordances: BTreeSet::from([speak_entry(kernel)]), + position, + import_key: None, + }) + } + + fn patch_of(declarations: Vec<Declaration>) -> WorldPatch { + WorldPatch { + declarations, + operations: Vec::new(), + evidence: Vec::new(), + } + } + + fn operations_of(operations: Vec<ComponentOp>) -> WorldPatch { + WorldPatch { + declarations: Vec::new(), + operations, + evidence: Vec::new(), + } + } + + fn draft(handle: &str) -> DraftHandle { + DraftHandle::new(handle) + } + + fn at(handle: &str) -> Site { + Site::Declaration(DraftHandle::new(handle)) + } + + fn admit(patch: WorldPatch) -> CommandBody { + CommandBody::AdmitPatch { + answers: None, + patch, + } + } + + /// A minimal admissible entry, so a validation test changes exactly one + /// thing and names exactly one rejection. + fn catalog_entry( + handle: &str, + kind: &str, + roles: Vec<RoleSpec>, + effect_slots: Vec<EffectSlot>, + outcome_bands: Vec<OutcomeBand>, + ) -> Declaration { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new(handle), + kind: AffordanceKindName(kind.into()), + roles, + preconditions: Vec::new(), + effect_slots, + outcome_bands, + carries_speech: false, + }) + } + + fn role_spec(role: &str, kind: RefKind) -> RoleSpec { + RoleSpec { + role: Role(role.into()), + kind, + } + } + + fn transfer_slot(roles: Vec<&str>, bounds: Bounds) -> EffectSlot { + EffectSlot { + op_kind: ComponentOpKind::Transfer, + roles: roles.into_iter().map(|role| Role(role.into())).collect(), + bounds, + } + } + + fn transfer_roles() -> Vec<RoleSpec> { + vec![ + role_spec("from", RefKind::Subject(None)), + role_spec("to", RefKind::Subject(None)), + role_spec("goods", RefKind::Entity(EntityKind::Resource)), + ] + } + + fn band(effects: Vec<usize>) -> OutcomeBand { + OutcomeBand { weight: 1, effects } + } + + #[test] + fn a_catalog_entry_with_a_dangling_or_noncanonical_band_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + let slots = vec![ + transfer_slot(vec!["from", "to", "goods"], Bounds::Quantity(Quantity(2))), + transfer_slot(vec!["from", "to", "goods"], Bounds::Quantity(Quantity(2))), + ]; + let handle = DraftHandle::new("verb"); + + for (bands, expected) in [ + ( + vec![band(vec![2])], + Mismatch::DanglingBandEffect { + handle: handle.clone(), + band: 0, + }, + ), + ( + vec![band(vec![1, 0])], + Mismatch::BandEffectsNotCanonical { + handle: handle.clone(), + band: 0, + }, + ), + ( + vec![OutcomeBand { + weight: 0, + effects: vec![0], + }], + Mismatch::ZeroBandWeight { + handle: handle.clone(), + band: 0, + }, + ), + ( + Vec::new(), + Mismatch::NoOutcomeBand { + handle: handle.clone(), + }, + ), + ] { + let rejected = reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + transfer_roles(), + slots.clone(), + bands, + )])), + ); + assert_eq!(rejected, vec![expected]); + assert!(kernel.state.affordance_catalog.len() == before.affordances.len()); + } + + // No effect slots and no speech: the entry could never change anything. + let rejected = reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + Vec::new(), + Vec::new(), + vec![band(Vec::new())], + )])), + ); + assert_eq!(rejected, vec![Mismatch::InertAffordance { handle }]); + } + + #[test] + fn a_slot_whose_roles_do_not_match_its_operation_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + let handle = DraftHandle::new("verb"); + + // A `Transfer` takes three referents, not two. + assert_eq!( + reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + transfer_roles(), + vec![transfer_slot( + vec!["from", "to"], + Bounds::Quantity(Quantity(2)) + )], + vec![band(vec![0])], + )])), + ), + vec![Mismatch::SlotRoleArity { + handle: handle.clone(), + slot: 0 + }] + ); + + // Its third referent is a resource, not a place. + assert_eq!( + reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + vec![ + role_spec("from", RefKind::Subject(None)), + role_spec("to", RefKind::Subject(None)), + role_spec("goods", RefKind::Entity(EntityKind::Place)), + ], + vec![transfer_slot( + vec!["from", "to", "goods"], + Bounds::Quantity(Quantity(2)) + )], + vec![band(vec![0])], + )])), + ), + vec![Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: Role("goods".into()) + }] + ); + + // A `Transfer` carries a quantity, so an unbounded slot has no ceiling. + assert_eq!( + reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + transfer_roles(), + vec![transfer_slot(vec!["from", "to", "goods"], Bounds::None)], + vec![band(vec![0])], + )])), + ), + vec![Mismatch::SlotBoundMismatch { + handle: handle.clone(), + slot: 0 + }] + ); + + // A slot naming a role the entry does not declare. + assert_eq!( + reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + transfer_roles(), + vec![transfer_slot( + vec!["from", "to", "cargo"], + Bounds::Quantity(Quantity(2)) + )], + vec![band(vec![0])], + )])), + ), + vec![Mismatch::UnknownRole { + handle, + role: Role("cargo".into()) + }] + ); + } + + #[test] + fn a_grant_naming_an_undeclared_affordance_is_rejected_and_the_same_patch_commits() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + let entries_before = kernel.state.affordance_catalog.len(); + let subjects_before = kernel.state.subjects.len(); + + let granting = |handle: &str| { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("late-arrival"), + label: "A Late Arrival".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([Ref::Draft(DraftHandle::new(handle))]), + position: None, + import_key: None, + }) + }; + + assert_eq!( + reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![granting("verb")])) + ), + vec![Mismatch::UnresolvedDraft { + site: Site::Declaration(DraftHandle::new("late-arrival")), + referent: DraftHandle::new("verb"), + expected: RefKind::Affordance, + }] + ); + assert_eq!(kernel.state.affordance_catalog.len(), entries_before); + assert_eq!(kernel.state.subjects.len(), subjects_before); + + // Declaring the entry in the same patch commits both atomically. + let receipt = submit_owner( + &mut kernel, + &before, + admit(patch_of(vec![ + catalog_entry( + "verb", + "verb", + transfer_roles(), + vec![transfer_slot( + vec!["from", "to", "goods"], + Bounds::Quantity(Quantity(2)), + )], + vec![band(vec![0])], + ), + granting("verb"), + ])), + ); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert_eq!(kernel.state.affordance_catalog.len(), entries_before + 1); + assert_eq!(kernel.state.subjects.len(), subjects_before + 1); + let granted = kernel + .state + .affordance_grants + .values() + .find(|entries| entries.len() == 1) + .expect("the new subject's grant set"); + assert!( + granted + .iter() + .all(|id| kernel.state.affordance_catalog.contains_key(id)) + ); + } + + #[test] + fn two_entries_cannot_share_one_kind_name() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + let slot = transfer_slot(vec!["from", "to", "goods"], Bounds::Quantity(Quantity(2))); + let rejected = reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![ + catalog_entry( + "first", + "haul", + transfer_roles(), + vec![slot.clone()], + vec![band(vec![0])], + ), + catalog_entry( + "second", + "haul", + transfer_roles(), + vec![slot], + vec![band(vec![0])], + ), + ])), + ); + assert_eq!( + rejected, + vec![Mismatch::DuplicateAffordanceKind { + handle: DraftHandle::new("second") + }] + ); + + // A kind name outside the tool-name alphabet is refused for the same + // reason: it becomes a generated tool name. + let rejected = reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "loud", + "Haul It", + transfer_roles(), + vec![transfer_slot( + vec!["from", "to", "goods"], + Bounds::Quantity(Quantity(2)), + )], + vec![band(vec![0])], + )])), + ); + assert_eq!( + rejected, + vec![Mismatch::InvalidAffordanceName { + handle: DraftHandle::new("loud") + }] + ); + } + + fn draft_world(directory: &std::path::Path) -> WorldKernel { + WorldKernel::create( + directory.join("world.cc"), + creation(CommandId::new(), "Kharad"), + &auth_principal(owner()), + ) + .expect("draft world") + .0 + } + + /// The position reference names a place that no declaration and no partition + /// provides. Nothing commits and nothing is allocated. + #[test] + fn a_subject_declared_at_an_undeclared_place_is_rejected_and_allocates_nothing() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + let commits_before = kernel.journal.commit_count(); + + let error = kernel + .submit( + command( + &before, + CommandId::new(), + CallerId::Principal(owner()), + admit(patch_of(vec![institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("kharad-rhythm-road"))), + )])), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!( + mismatches, + vec![Mismatch::UnresolvedDraft { + site: at("rhythm-authority"), + referent: draft("kharad-rhythm-road"), + expected: PLACE, + }] + ); + assert_eq!(kernel.snapshot().unwrap(), before); + assert_eq!(kernel.journal.commit_count(), commits_before); + assert_eq!(kernel.state.entities.len(), FIXTURE_ENTITIES); + assert_eq!(kernel.state.subjects.len(), before.subjects.len()); + } + + /// A place, a route into it, and a subject standing there are one atomic + /// commit: every reference resolves to an ID the same patch allocated. + #[test] + fn a_declared_place_and_its_dependents_commit_atomically() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + let commits_before = kernel.journal.commit_count(); + + let patch = patch_of(vec![ + entity("cavity-yard", "The Cavity Yard", EntityKind::Place), + entity("kharad-rhythm-road", "The Rhythm Road", EntityKind::Place), + route( + "yard-road", + "The Yard Ramp", + "cavity-yard", + "kharad-rhythm-road", + 12, + ), + institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(draft("kharad-rhythm-road"))), + ), + ]); + let receipt = submit_owner(&mut kernel, &before, admit(patch)); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + + let after = kernel.snapshot().unwrap(); + assert_eq!(after.revision, before.revision + 1); + assert_eq!(kernel.journal.commit_count(), commits_before + 1); + assert_eq!(kernel.state.entities.len(), 3); + let road = *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "The Rhythm Road") + .expect("the road is admitted") + .0; + let yard = *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "The Cavity Yard") + .expect("the yard is admitted") + .0; + let (_, edge) = kernel.state.edges.iter().next().expect("the route lands"); + assert_eq!(edge.endpoints(), (yard, road)); + assert_eq!(edge.cost(), Cost(12)); + assert!(edge.is_open()); + let admitted = *kernel + .state + .subjects + .iter() + .find(|(_, subject)| subject.label == "The Rhythm Authority") + .expect("the institution is admitted") + .0; + assert_eq!( + kernel.state.positions.get(&admitted), + Some(&Position { place: road }) + ); + } + + /// A handle of the wrong namespace kind is a runtime mismatch. The + /// cross-namespace canonical case is a compile error instead: + /// `Ref::<EntityId>::Existing(subject_id)` does not compile, because + /// `SubjectId`, `EntityId`, and `EdgeId` are distinct newtypes with no + /// conversion between them and no public `Uuid` constructor. + #[test] + fn a_draft_handle_of_the_wrong_kind_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + let commits_before = kernel.journal.commit_count(); + + let error = kernel + .submit( + command( + &before, + CommandId::new(), + CallerId::Principal(owner()), + admit(patch_of(vec![ + entity("rhythm-tithe", "The Rhythm Tithe", EntityKind::Resource), + institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("rhythm-tithe"))), + ), + ])), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!( + mismatches, + vec![Mismatch::WrongKind { + site: at("rhythm-authority"), + referent: RefName::Entity(Ref::Draft(draft("rhythm-tithe"))), + expected: PLACE, + actual: RefKind::Entity(EntityKind::Resource), + }] + ); + assert_eq!(kernel.journal.commit_count(), commits_before); + assert_eq!(kernel.snapshot().unwrap(), before); + } + + /// Rejection carries the complete failed-check set, not the first failure, + /// and repairing exactly that set is enough to commit. + #[test] + fn rejection_returns_every_failed_check_and_repairing_exactly_those_commits() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + + let broken = patch_of(vec![ + entity("rhythm-road", "The Rhythm Road", EntityKind::Place), + entity("rhythm-road", " ", EntityKind::Place), + institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("cavity-yard"))), + ), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("late-arrival"), + label: "A Late Arrival".into(), + kind: SubjectKind::Person, + controller: NewController::Human { + principal: human_principal(), + }, + affordances: BTreeSet::from([speak_entry(&kernel)]), + position: None, + import_key: None, + }), + ]); + let error = kernel + .submit( + command( + &before, + CommandId::new(), + CallerId::Principal(owner()), + admit(broken), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + let mut expected = vec![ + Mismatch::DuplicateHandle { + handle: DraftHandle::new("rhythm-road"), + }, + Mismatch::EmptyLabel { + handle: DraftHandle::new("rhythm-road"), + }, + Mismatch::UnresolvedDraft { + site: at("rhythm-authority"), + referent: draft("cavity-yard"), + expected: PLACE, + }, + Mismatch::UnadmittedController { + handle: DraftHandle::new("late-arrival"), + }, + ]; + expected.sort(); + assert_eq!(mismatches, expected); + assert_eq!(kernel.journal.commit_count(), 1); + + let repaired = patch_of(vec![ + entity("rhythm-road", "The Rhythm Road", EntityKind::Place), + entity("cavity-yard", "The Cavity Yard", EntityKind::Place), + institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("cavity-yard"))), + ), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("late-arrival"), + label: "A Late Arrival".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([speak_entry(&kernel)]), + position: None, + import_key: None, + }), + ]); + let receipt = submit_owner(&mut kernel, &before, admit(repaired)); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert_eq!(kernel.state.entities.len(), 3); + } + + #[test] + fn an_empty_patch_is_no_canonical_change() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + + let error = kernel + .submit( + command( + &before, + CommandId::new(), + CallerId::Principal(owner()), + admit(patch_of(Vec::new())), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!(mismatches, vec![Mismatch::NoCanonicalChange]); + assert_eq!(kernel.snapshot().unwrap(), before); + assert_eq!(kernel.journal.commit_count(), 1); + } + + /// Active admits the four operations and nothing else, so it never mints a + /// canonical ID. + #[test] + fn an_active_patch_that_declares_anything_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let active = activate(&mut kernel); + let commits_before = kernel.journal.commit_count(); + let declaring = patch_of(vec![entity( + "rhythm-road", + "The Rhythm Road", + EntityKind::Place, + )]); + let bearing_evidence = WorldPatch { + declarations: Vec::new(), + operations: Vec::new(), + evidence: vec![EvidenceRef("run-115".into())], + }; + + for patch in [declaring, bearing_evidence] { + let error = kernel + .submit( + command( + &active, + CommandId::new(), + CallerId::Principal(owner()), + admit(patch), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + // Declaring in Active is elaboration, and elaboration answers a + // boundary. An unanswered one is refused before resolution. + assert!(matches!(error, KernelError::AnswerRequired)); + } + assert_eq!(kernel.journal.commit_count(), commits_before); + assert_eq!(kernel.snapshot().unwrap(), active); + assert_eq!(kernel.state.entities.len(), FIXTURE_ENTITIES); + } + + /// Three places whose containers form a cycle name themselves, and the + /// unrelated empty label joins the same complete set. + #[test] + fn a_containment_cycle_is_rejected_with_the_complete_set() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + + let error = kernel + .submit( + command( + &before, + CommandId::new(), + CallerId::Principal(owner()), + admit(patch_of(vec![ + contained("yard", "The Cavity Yard", "road"), + contained("road", "The Rhythm Road", "gate"), + contained("gate", "The Rain Gate", "yard"), + entity("orphan", " ", EntityKind::Place), + ])), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + let mut expected = vec![ + Mismatch::ContainmentCycle { + referent: draft("yard"), + }, + Mismatch::ContainmentCycle { + referent: draft("road"), + }, + Mismatch::ContainmentCycle { + referent: draft("gate"), + }, + Mismatch::EmptyLabel { + handle: draft("orphan"), + }, + ]; + expected.sort(); + assert_eq!(mismatches, expected); + assert_eq!(kernel.snapshot().unwrap(), before); + assert_eq!(kernel.state.entities.len(), FIXTURE_ENTITIES); + } + + #[test] + fn a_route_endpoint_that_is_not_a_place_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + + let error = kernel + .submit( + command( + &before, + CommandId::new(), + CallerId::Principal(owner()), + admit(patch_of(vec![ + entity("yard", "The Cavity Yard", EntityKind::Place), + entity("tithe", "The Rhythm Tithe", EntityKind::Resource), + route("ramp", "The Yard Ramp", "yard", "tithe", 12), + ])), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!( + mismatches, + vec![Mismatch::WrongKind { + site: at("ramp"), + referent: RefName::Entity(Ref::Draft(draft("tithe"))), + expected: PLACE, + actual: RefKind::Entity(EntityKind::Resource), + }] + ); + assert!(kernel.state.edges.is_empty()); + assert_eq!(kernel.snapshot().unwrap(), before); + } + + /// One name for one failed check, whether the cost arrives in a declaration + /// or in an operation. + #[test] + fn an_invalid_route_cost_is_rejected_from_declaration_and_from_alter_cost() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let topology = admit_topology(&mut kernel); + let before = kernel.snapshot().unwrap(); + + let error = kernel + .submit( + command( + &before, + CommandId::new(), + CallerId::Principal(owner()), + admit(WorldPatch { + declarations: vec![Declaration::Route(RouteDeclaration { + handle: draft("free-ride"), + label: "The Free Ride".into(), + from: Ref::Existing(topology.yard), + to: Ref::Existing(topology.road), + access: AccessKind::Public, + cost: Cost(0), + })], + operations: vec![ComponentOp::AlterCost { + route: Ref::Existing(topology.ramp), + cost: Cost(MAX_ROUTE_COST + 1), + }], + evidence: Vec::new(), + }), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + let mut expected = vec![ + Mismatch::InvalidCost { + site: at("free-ride"), + }, + Mismatch::InvalidCost { + site: Site::Operation(0), + }, + ]; + expected.sort(); + assert_eq!(mismatches, expected); + assert_eq!(kernel.snapshot().unwrap(), before); + } + + /// Each refusal has exactly one name: a closed route, a restricted one, and + /// a route that does not start where the subject stands. + #[test] + fn relocate_without_an_open_public_route_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let topology = admit_topology(&mut kernel); + let active = activate(&mut kernel); + let commits_before = kernel.journal.commit_count(); + + for (edge_id, expected) in [ + (topology.shutter, Mismatch::RouteClosed { operation: 0 }), + ( + topology.toll, + Mismatch::RouteAccessRestricted { operation: 0 }, + ), + (topology.span, Mismatch::SubjectNotAtOrigin { operation: 0 }), + ] { + let error = kernel + .submit( + command( + &active, + CommandId::new(), + CallerId::Principal(owner()), + admit(operations_of(vec![ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Existing(edge_id), + }])), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!(mismatches, vec![expected]); + } + assert_eq!(kernel.journal.commit_count(), commits_before); + assert_eq!(kernel.snapshot().unwrap(), active); + assert_eq!( + kernel.state.positions.get(&topology.walker), + Some(&Position { + place: topology.yard + }) + ); + } + + /// PA.f48: `candidate_effective_authority` is the resolver's twin of + /// `delegated_authority`, and must share its predicate for "is this + /// institution live". Retiring the lending institution and granting the + /// same ground directly to its former office-holder, in one patch, must + /// not be read as an overlap with a lend the retirement already killed. + #[test] + fn a_grant_after_retiring_the_lending_institution_is_admitted() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let (_, civic, before) = civic_world(&mut kernel); + + // The office lends levy over the whole hall; grant the reeve levy + // directly over the chamber the hall contains, so a resolver that + // still counted the dead lend would see two distinct, overlapping + // `GrantKey`s (not one collapsed duplicate) and refuse. + let receipt = submit_owner( + &mut kernel, + &before, + admit(operations_of(vec![ + ComponentOp::Retire { + subject: Ref::Existing(civic.treasury), + }, + grant_to(civic.reeve, LEVY_KIND, over_place(civic.chamber)), + ])), + ); + assert!( + matches!(receipt, SubmitReceipt::Applied(_)), + "a dead institution's lend must not collide with a fresh direct grant over the same ground" + ); + } + + /// PA.f48: a `Relocate` through a restricted route open only through a + /// dead institution's delegated authority is refused by the resolver + /// itself, as an ordinary `RouteAccessRestricted` mismatch — not + /// admitted by the resolver and then blown up as a `KernelError::Invariant` + /// when canonical apply recomputes the same authority, correctly finds it + /// gone, and refuses the already-applied `Retire`'s sibling operation. + #[test] + fn a_relocate_relying_only_on_a_retiring_institutions_authority_is_refused_by_the_resolver() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let (topology, civic, before) = civic_world(&mut kernel); + + // `topology.walker` already exists and already stands at `yard`, so + // this delegation patch is operations-only: no declaration, no + // `AnswerRequired` elaboration boundary to clear. + let delegated = submit_owner( + &mut kernel, + &before, + admit(operations_of(vec![ + grant_to(civic.treasury, ADMIT_KIND, over_place(civic.chamber)), + ComponentOp::OpenOffice { + institution: Ref::Existing(civic.treasury), + office: office("portal"), + delegated: BTreeSet::from([authority_kind(ADMIT_KIND)]), + }, + ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office("portal"), + incumbent: Ref::Existing(topology.walker), + }, + ])), + ); + assert!( + matches!(delegated, SubmitReceipt::Applied(_)), + "expected the delegation patch to apply, got {delegated:?}" + ); + let after_delegation = kernel.snapshot().unwrap(); + + let commits_before = kernel.journal.commit_count(); + let mismatches = reject_owner( + &mut kernel, + &after_delegation, + admit(operations_of(vec![ + ComponentOp::Retire { + subject: Ref::Existing(civic.treasury), + }, + ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Existing(civic.postern), + }, + ])), + ); + assert_eq!( + mismatches, + vec![Mismatch::RouteAccessRestricted { operation: 1 }], + "the resolver must refuse the dead institution's lend itself, not let apply blow up" + ); + assert_eq!(kernel.journal.commit_count(), commits_before); + assert_eq!(kernel.snapshot().unwrap(), after_delegation); + } + + #[test] + fn relocate_moves_the_subject_and_nothing_else() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let topology = admit_topology(&mut kernel); + let active = activate(&mut kernel); + let entities_before = kernel.state.entities.clone(); + let edges_before = kernel.state.edges.clone(); + + let receipt = submit_owner( + &mut kernel, + &active, + admit(operations_of(vec![ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Existing(topology.ramp), + }])), + ); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert_eq!( + kernel.state.positions.get(&topology.walker), + Some(&Position { + place: topology.road + }) + ); + assert_eq!(kernel.state.entities, entities_before); + assert_eq!(kernel.state.edges, edges_before); + let after = kernel.snapshot().unwrap(); + assert_eq!( + after + .subjects + .iter() + .find(|subject| subject.id == topology.walker) + .expect("the walker is in the snapshot") + .position, + Some(topology.road) + ); + } + + #[test] + fn restart_replay_after_a_relocate_is_exact() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Kharad"), + &auth_principal(owner()), + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let active = activate(&mut kernel); + let envelope = command( + &active, + CommandId::new(), + CallerId::Principal(owner()), + admit(operations_of(vec![ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Existing(topology.ramp), + }])), + ); + kernel + .submit(envelope.clone(), &auth_principal(owner())) + .unwrap(); + let committed = kernel.snapshot().unwrap(); + let world_id = committed.world_id; + drop(kernel); + + let mut reopened = WorldKernel::open(&path, world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), committed); + assert_eq!( + reopened.state.positions.get(&topology.walker), + Some(&Position { + place: topology.road + }) + ); + assert!(matches!( + reopened.submit(envelope, &auth_principal(owner())).unwrap(), + SubmitReceipt::AlreadyApplied(_) + )); + } + + #[test] + fn the_snapshot_exposes_places_routes_and_positions_deterministically() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let topology = admit_topology(&mut kernel); + let snapshot = kernel.snapshot().unwrap(); + assert_eq!(snapshot, kernel.snapshot().unwrap()); + + assert_eq!(snapshot.places.len(), 4); + let place_ids: Vec<_> = snapshot.places.iter().map(|place| place.id).collect(); + let mut sorted_places = place_ids.clone(); + sorted_places.sort(); + assert_eq!(place_ids, sorted_places); + assert!(place_ids.contains(&topology.gate)); + + assert_eq!(snapshot.routes.len(), 4); + let route_ids: Vec<_> = snapshot.routes.iter().map(|route| route.id).collect(); + let mut sorted_routes = route_ids.clone(); + sorted_routes.sort(); + assert_eq!(route_ids, sorted_routes); + let shutter = snapshot + .routes + .iter() + .find(|route| route.id == topology.shutter) + .expect("the shutter is in the snapshot"); + assert!(!shutter.open); + assert_eq!(shutter.cost, Cost(5)); + assert_eq!(shutter.from, topology.yard); + + for subject in &snapshot.subjects { + assert_eq!( + subject.position, + kernel + .state + .positions + .get(&subject.id) + .map(|position| position.place) + ); + } + } + + #[test] + fn admit_patch_from_a_non_owner_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + let commits_before = kernel.journal.commit_count(); + + let error = kernel + .submit( + command( + &before, + CommandId::new(), + CallerId::Principal(human_principal()), + admit(patch_of(vec![entity( + "rhythm-road", + "The Rhythm Road", + EntityKind::Place, + )])), + ), + &auth_principal(human_principal()), + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized)); + assert_eq!(kernel.journal.commit_count(), commits_before); + assert_eq!(kernel.snapshot().unwrap(), before); + } + + #[test] + fn restart_replay_after_a_committed_patch_is_exact() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Kharad"), + &auth_principal(owner()), + ) + .unwrap(); + let before = kernel.snapshot().unwrap(); + let envelope = command( + &before, + CommandId::new(), + CallerId::Principal(owner()), + admit(patch_of(vec![ + entity("rhythm-road", "The Rhythm Road", EntityKind::Place), + institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("rhythm-road"))), + ), + ])), + ); + kernel + .submit(envelope.clone(), &auth_principal(owner())) + .unwrap(); + let committed = kernel.snapshot().unwrap(); + let world_id = committed.world_id; + drop(kernel); + + let mut reopened = WorldKernel::open(&path, world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), committed); + assert!(matches!( + reopened.submit(envelope, &auth_principal(owner())).unwrap(), + SubmitReceipt::AlreadyApplied(_) + )); + } + + /// One allocator, a pure function of `(world_id, command_id, handle)`: the + /// same handle text under two commands gets two IDs, and the same command + /// re-resolved gets the same ones. + #[test] + fn genesis_and_admit_patch_share_one_allocator() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + let genesis_human = before + .subjects + .iter() + .find(|subject| subject.label == "The Human") + .expect("the genesis human subject") + .id; + + let patch = patch_of(vec![Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("human"), + label: "Another Human".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([speak_entry(&kernel)]), + position: None, + import_key: None, + })]); + submit_owner(&mut kernel, &before, admit(patch.clone())); + let admitted = *kernel + .state + .subjects + .iter() + .find(|(_, subject)| subject.label == "Another Human") + .expect("the admitted subject") + .0; + assert_ne!(admitted, genesis_human); + + let command_id = CommandId::new(); + let first = resolve_patch(&kernel.state, command_id, &patch, None, None).unwrap(); + let second = resolve_patch(&kernel.state, command_id, &patch, None, None).unwrap(); + assert_eq!(first, second); + } + + /// The durable half of "a rejected patch mints nothing": the store on disk, + /// not just the in-memory head, carries no row and no byte of any ID the + /// rejected patch would have allocated. + #[test] + fn a_rejected_patch_leaves_no_row_and_no_id_in_the_store() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Kharad"), + &auth_principal(owner()), + ) + .unwrap(); + let before = kernel.snapshot().unwrap(); + let command_id = CommandId::new(); + let handle = DraftHandle::new("rhythm-authority"); + + let error = kernel + .submit( + command( + &before, + command_id, + CallerId::Principal(owner()), + admit(patch_of(vec![institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("kharad-rhythm-road"))), + )])), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + assert!(matches!(error, KernelError::PatchRejected(_))); + + // Every ID the patch would have allocated, had resolution closed. + let would_be = [ + derive_id( + SUBJECT_NAMESPACE, + before.world_id, + command_id, + &handle, + None, + ), + derive_id( + CONTROLLER_NAMESPACE, + before.world_id, + command_id, + &handle, + None, + ), + derive_id( + AFFORDANCE_NAMESPACE, + before.world_id, + command_id, + &handle, + Some("speak"), + ), + ]; + + drop(kernel); + let raw = std::fs::read(&path).unwrap(); + for id in would_be { + assert!( + !raw.windows(16).any(|window| window == id.as_bytes()), + "a rejected patch left {id} in the store" + ); + } + + let reopened = WorldKernel::open(&path, before.world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), before); + assert_eq!(reopened.journal.commit_count(), 1); + assert_eq!(reopened.state.entities.len(), FIXTURE_ENTITIES); + assert!( + !reopened + .state + .subjects + .contains_key(&SubjectId(would_be[0])) + ); + } + + /// `discriminator` is length-prefixed like `handle`, so `Some("")` and + /// `None` write different bytes into the preimage and cannot collide — + /// and neither can any other pair of discriminators whose bytes would + /// otherwise concatenate to the same string. + #[test] + fn derive_id_does_not_collide_some_empty_discriminator_with_none() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, _) = WorldKernel::create( + &directory.path().join("world.cc"), + creation(CommandId::new(), "DeriveId"), + &auth_principal(owner()), + ) + .unwrap(); + let world_id = kernel.state.world_id; + let command_id = CommandId::new(); + let handle = DraftHandle::new("a-handle"); + assert_ne!( + derive_id(SUBJECT_NAMESPACE, world_id, command_id, &handle, None), + derive_id(SUBJECT_NAMESPACE, world_id, command_id, &handle, Some("")), + ); + // A concatenation-style collision across the handle/discriminator + // boundary: without a length prefix on the discriminator, "ab" + "" + // and "a" + "b" would hash identically. + assert_ne!( + derive_id( + SUBJECT_NAMESPACE, + world_id, + command_id, + &DraftHandle::new("ab"), + Some(""), + ), + derive_id( + SUBJECT_NAMESPACE, + world_id, + command_id, + &DraftHandle::new("a"), + Some("b"), + ), + ); + } + + /// The `PatchAdmitted` arm is not a trusting applier. A forged effect, a + /// replayed one, a non-owner caller, and the Active phase each die inside + /// `apply_effect`, without the journal's reduce-equality check running. + #[test] + fn apply_effect_rejects_a_forged_stale_unauthorized_or_active_patch_effect() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + let patch = patch_of(vec![ + entity("rhythm-road", "The Rhythm Road", EntityKind::Place), + institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("rhythm-road"))), + ), + ]); + let resolved = resolve_patch(&kernel.state, CommandId::new(), &patch, None, None).unwrap(); + let honest = super::super::WorldEffect::PatchAdmitted { + resolved: resolved.clone(), + answers: None, + }; + + // Forged: the position names a place no partition holds, and the effect + // no longer carries the entity that would have created it. + let mut forged = resolved.clone(); + forged.entities.clear(); + forged.subjects[0].position = Some(Position { + place: super::super::EntityId::issue(), + }); + let mut candidate = kernel.state.clone(); + let forged_error = super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Principal(owner()), + &super::super::WorldEffect::PatchAdmitted { + answers: None, + resolved: forged, + }, + ) + .unwrap_err(); + assert!(matches!(forged_error, KernelError::Invariant(_))); + + // Stale: the honest effect applied twice collides on its own IDs. + let mut candidate = kernel.state.clone(); + super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Principal(owner()), + &honest, + ) + .unwrap(); + let stale_error = super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Principal(owner()), + &honest, + ) + .unwrap_err(); + assert!(matches!(stale_error, KernelError::Invariant(_))); + + // A non-owner caller never reaches admission. + let mut candidate = kernel.state.clone(); + let unauthorized = super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Principal(human_principal()), + &honest, + ) + .unwrap_err(); + assert!(matches!(unauthorized, KernelError::Invariant(_))); + assert_eq!(candidate, kernel.state); + + // And an unanswered declaring effect is refused in Active before any + // partition is touched. + let active = activate(&mut kernel); + assert_eq!(active.revision, before.revision + 3); + let mut candidate = kernel.state.clone(); + let unanswered = super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Principal(owner()), + &honest, + ) + .unwrap_err(); + assert!(matches!(unanswered, KernelError::AnswerRequired)); + assert_eq!(candidate, kernel.state); + } + + /// Soul falsification: the three pass-2 `Mismatch` variants that no landed + /// test names are each reachable from a real patch. + #[test] + fn soul_self_loop_unplaced_subject_and_no_effect_are_each_reachable() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + + // A route whose two endpoints resolve to one place. + let error = kernel + .submit( + command( + &before, + CommandId::new(), + CallerId::Principal(owner()), + admit(patch_of(vec![ + entity("hollow", "The Hollow", EntityKind::Place), + route("noose", "The Noose", "hollow", "hollow", 4), + ])), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!( + mismatches, + vec![Mismatch::RouteSelfLoop { + referent: draft("noose") + }] + ); + + let topology = admit_topology(&mut kernel); + // Every fixture subject stands somewhere now, so the unplaced case is + // declared here rather than borrowed from a genesis accident. + let before = kernel.snapshot().unwrap(); + let speak = speak_entry(&kernel); + submit_owner( + &mut kernel, + &before, + admit(patch_of(vec![Declaration::Subject(SubjectDeclaration { + handle: draft("nowhere"), + label: "The Unplaced".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([speak]), + position: None, + import_key: None, + })])), + ); + let active = activate(&mut kernel); + let commits_before = kernel.journal.commit_count(); + let unplaced = *kernel + .state + .subjects + .iter() + .find(|(subject_id, _)| !kernel.state.positions.contains_key(*subject_id)) + .expect("the unplaced subject this test declared") + .0; + + // Relocating a subject that stands nowhere. + let error = kernel + .submit( + command( + &active, + CommandId::new(), + CallerId::Principal(owner()), + admit(operations_of(vec![ComponentOp::Relocate { + subject: Ref::Existing(unplaced), + via: Ref::Existing(topology.ramp), + }])), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!(mismatches, vec![Mismatch::UnplacedSubject { operation: 0 }]); + + // Three operations that each change nothing: the ramp is already open, + // the shutter already closed, and the ramp already costs twelve. + let error = kernel + .submit( + command( + &active, + CommandId::new(), + CallerId::Principal(owner()), + admit(operations_of(vec![ + ComponentOp::OpenRoute { + route: Ref::Existing(topology.ramp), + }, + ComponentOp::CloseRoute { + route: Ref::Existing(topology.shutter), + }, + ComponentOp::AlterCost { + route: Ref::Existing(topology.ramp), + cost: Cost(12), + }, + ])), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!( + mismatches, + vec![ + Mismatch::NoOperationEffect { operation: 0 }, + Mismatch::NoOperationEffect { operation: 1 }, + Mismatch::NoOperationEffect { operation: 2 }, + ] + ); + assert_eq!(kernel.snapshot().unwrap(), active); + assert_eq!(kernel.journal.commit_count(), commits_before); + } + + /// Soul falsification: `admit_resolved` re-derives every relocate + /// precondition, so a forged effect naming a route the subject does not + /// stand on, a closed route, or a restricted one dies at apply time. + #[test] + fn soul_a_forged_relocate_effect_is_refused_at_apply_time() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let topology = admit_topology(&mut kernel); + activate(&mut kernel); + for edge_id in [topology.span, topology.shutter, topology.toll] { + let forged = super::super::WorldEffect::PatchAdmitted { + resolved: ResolvedPatch { + lens_weights: None, + subjects: Vec::new(), + entities: Vec::new(), + routes: Vec::new(), + affordances: Vec::new(), + facts: Vec::new(), + channels: Vec::new(), + operations: vec![ResolvedOp::Relocate { + subject_id: topology.walker, + edge_id, + }], + evidence: Vec::new(), + scale_intent: None, + }, + answers: None, + }; + let mut candidate = kernel.state.clone(); + let error = super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Principal(owner()), + &forged, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + assert_eq!(candidate, kernel.state); + } + } +} diff --git a/native/aetherlight/tests/fixtures/base_world.cc b/native/aetherlight/tests/fixtures/base_world.cc new file mode 100644 index 0000000000000000000000000000000000000000..d4c8eadacb211bc0c98b7e5b6f9ea2f6c229eeae GIT binary patch literal 557056 zcmeI*4U}Y6eIW4e85DuAnQY_)b5v0Lilk@j`(rk4h{TAC8lreiQ0(*Sy;svE)m6P! z)ibc>WCsxNfLZy_9HYseh)mA_1Ia)noR}yc2Uion63%fmV%&|#U5x8y*GNvxt~h&N zRabXUcRSMq!)JaqbGxdm?z`{a-+NWn_tpFVtCuE?pFa84Q%`=@#KgpwP==S$jcdlg z9^rcP<mB+tA78BV`RBjz=G)KtiBm7S>Uke|)kj|bkE2JI8+gUN|8#BfegFOazy0@r zecDauH{P^)`Jp4;dd}jb|L3Cf{-|=p>Hp*PCq6uw-FrfDqw62{<Imqwe)m6CYj6Kz zWB)^qPrWfY;fQNpe(<Eln+G30_@D1S<G{Y}eDkI+-1x{TFI}$T76AeT2oNAZfB*pk z1PBm#>IzIA+B}g9-TS3b-Vw@|LOCZ)miLE}M1yF0F4~^<r=xbe8%KjQS#jTdr<X?Y zOw?$n{mc4;bat`siu*S@yPuetTsroU&D68<;_SK?4o_^`c405-^rLvt>ULh2ytOr$ zxggr!>O|S^i#5U>>FZnl!RBnq>@vA&bUpD~=YH?di(j{JdjB^zefv8%|H`MADjcU3 zF0SV2SI23Dhg=8{AV7cs0RjXF5FkK+z_ANV9y(#77$&c;4dvoc=0kZPlwS<<<d22& zvM`Tcocwot)BQnq4B)XJ78oBFm>l2uo6lZ)%4c@`%9ZC`@u^=u|DK5p$M;WWrzH$8 z*}Od~r)Srr!veoBIw;ZYy*caF`RQeoFMHd3?c(vW!^MvH<2X&ppZFDK5ZPt&UyQCN z&R%%=zyH$Dd}n9j-2H#J>*xQ=_m?UhpQ9YdzF%2_009C72oNAZfB*pk1fE&~lZPfJ zKJ;S~6XWyi7w3}`CrpfI-s36exW==`Ra_GwK!5-N0t5&UAVA<a2|TstNqR%znJBO+ z%>T1-z3ES1@#=4#@o&%W|NYl*t89Jnt(z;)Tlm6FpQ>H@-Rtgu_5<|~kB<hNy!h-M ze&+p51TiK81PBlyK!5-N0t5&UAn*(n$UgsnW0=#Q7Czp;@sD?Qd+lU&mjBkY9W}bW zVUYdS9r=SViOR)NqgaThN=Ys^RVviusYbIBPsM3IDVK}2@IUu~ja56sdhS25{`H9$ zE%f7=bT&Hp;_Wlt{-E93J~P<5vTt#>)1RMBds}x@_KxmvB?q?bF5UggH%z?xcRtzv z;tSqVd-JZny>v&bACd%Y-aR)H_0xqcg}{z<cXwwe?cFu}c}{w1G&|Q$w+_<&VE3Rk zXs35x(CT#3<jh|focZdo(C$XBl{SCx_mf`K985=ZbG`14sNKKuu9^ASsB_rz>omEy zKi_y~8V~wc9@w(&zVBUo%PX(`pO^pchraQ5pZkYLuGk%f)AsEb&ZK9a+nw*kt@bUK zv^vS{txiAmWIju8aA3>%J0HCJ{_6Yw^#k=+owxG^{l8qfR7i!;N&EfbQVVlwub(aO z-p_yJ<9Gh2uRia+jjP`O>(^fWvx^Jdnyu!%tj{Z}?@c>lRjsst`GGAboL&EKzxd&Y z_TBwc-~5*k{@Mrr=E}qRH#-~5hl}o>Ye#W<YuE;Zs1+pd+npvMN5rmM=eqsSR;ael zU@spnwRSCQM|gy)tH<^utL~lYwv$$8dw<uyB%Mn;Ng8-VA9pvyKG5H_H>9ly8@U}i zeMzUgvz-lK*R9d~V5Zw^4KCYtYd>v=tro_zYfp$Z=>_Cnx5wSt+16k-i1l~<!ALur zo(+*Fy;jr?qt9y1habD{Zb$vWba!s9+Z)VxLVMHEVAn^(dM5Vu<EWiZw>pE+$`yMC zQEz)1TD#+&^SxF-X${vHy4+4X{pp=)w%hmLvoIH)gPmw{Pv~<mtZZ^&*xhhFlZHEH zCKm=#XL~!Hyk$q)YESM?XB(l??oN1qbSCe~wo<R#Zl}HJsNZjG?+p8Y<>j|6?wHfr z6KBnydCTCkxpaRw408DVkJ{5AzeZ<p$BNdn<u3TsAHMBf?>hG<zw`aM&;8ePe)xmK zTV1o~j#}+Ry{y$8>GY!E>Q?_%=Ztr!3tuUI|FrMF_uiWy+<ADbt9OAbhpp}&J{woJ zboJHmyC(m)*F~M*{NjV}`tz?8!!~M#{a`L?ulMYYn$2!6i8^sQ9a5b{?e6v~4s3b$ zTmJakgFpWhH=K0Z-@WcdrEi{e_2?<kpG%`lb_dwBfBhX{%LkZbwC~?=#lDrl-w{Wh z=|-;`C2`m(KDwh7g(uEpE|q<0vl;fX>3+LA2+efo2VoaWryEfx>ECe0!e|GW+%u}x zzy8iR$c3GFI;=d6XFh#k%R|qfdG-%#ulc<Xzws0O-zrVKdDOW*p))(uPWmKwZ~qF< z?ID3ncnv&!ORnDQZd|Lqc8G^Jv3eJ~VQmwKFR*&=S!aQTG~k8pv2PgcHl4J>Yun)9 zYx^@%p<LP4sOBooay4$0^3_VNSgcf{e6v)I%1M%|*PG!TvDOG1H7+*_X)USblR_<D zDdwv6e3DP9mE^ABYs2WJWOdtxT(Mp+SE52CE+*whu3Aj;xqMo#)oW2)jw-pRo;E7Q zsMx3%o262<QAlddYAtP+;;31#)(@Ul$Q3G6`CRyaVXm~TRM?iUZY|{V<yx&+E}Wgq zZOi30@}Bw({5!{x2oNAZfB=DIfo%SNYWOgJ_<8<w!-0S->Hi;u@`F%vA&fi;<%6Mo zJ_{)i$pA{BoEOU5LzxTZ-JyIilzpMx8_I!Dz8uQeLituG4~LSqo+a8pGnAhVr54JC zp=3>tyR!0j)|v7BS%1d2S6{Dg^Yx2u{&2Bk*5>$j){P%5-hXbm{m|m=|F?LZt@HVz zydsoRC@Ys;dHY4-v22m7-Sw7PY%Z`a_d5&1AK$;;GUGn3Tu&Bm@yOyr8(k*zIM!t{ zmm@7R?)S>^th}8qpN%iucgB||;=Zg8A#P=OIbOHNV|7h{009C72oNAZfB=DKpg=bN zKO;<{E(s-`Zx7;-(LbF|!v{$1@bO=N^Z5JmmNLzK;otq)_Iuy?$cuJ9bnS24^ulkS zKCUpDiDf^t*;rPxL;<6We50SwKs`euK!5-N0t5&UAV7cs0Rm4Cfuqg;vyYy$%j7ul z|MYJRI@dL3U;3NxsGa!h-#*kER~S_rR?Vu1V*da1*ah^G009C72oNAZfB*pk1pXNa zWb^-D4wLmShk5*sA0NfikD?RTBmgLva^*%b3K9RMW@)NaDOacJNwG8)*NeG0%16~) zk`D<0Hd5_KE4qKvcdr}A|DUxc{(rG=A;fh92>?PQ>}&{lPp%lo2;Z?hx^Un4v8!&* zBAG9I*4_IKJp4;<{oT^%a)0*IbANG!tOEPfOXot=ZkkMw(+f;2gsAQiVLe*Sa*%Oo zd7YF1w=}xRWtWe7G)gCsP7jj{><@9nJ6hfO{&K^2g>dq4Qbq`5U%GGdV@uW64Ny%B z)p8uy;-s0@s+AC^8lqK`Tr;gEX}Q?UrS&)qRjpRiC|7Fc(`vO+s5Gl-nl?&Fy^-eb zSzhJ3?Z?GZl!itdl_XycEhpt9jq8nS9MubHcr2{6k~ZpbtzNE0)p9+p*NY)NL?u@! z)r!?Lxo4^S>j%Nsn#ClEtBq1xZ04J}QY~MK>LIGOP;RF6Brb%g+e#cog=(W5_PZ#o zrIAmH)lwxbHIrJYxiAWs9&L*|S7vQUljTjb&UV>1>QA;|qroTEi=@rh>bX*`o-1Co zuqrCJPzfQsr9e_FRFg(pZX~s|(5TkSxk4?e)hoGN7)laV;!3_zjLW4$J_PDk<7%^z zRztjSW&OzAd_7+Yp}X~Q<nBhE4gU;YvJ8;`0RjXF5FkK+0D(s-FrNSSLoD@C=Ko<z zQ;sXS+Egx=)Tc^uF`A0PRBbAailvaHC@B?l#W4ThNVOx*|4(`U<1_!?7x&VTt!;XE z7+^g8zh*f7|Bo;I%yT9VzJA*sU;B3Hg%_W@`B9|^+#M3N#WPoigmZB_8YNEaf8eU& zM1LV<lnQy^7DCp!q@51e9S&e@G{4?^hHc!ooKI`HonfM{VM?;l=u;u<*EPew?pe$( zx7g89cDB)Q*Uv+ETj>2_p1RS@eYD7m3H#b~i?=U>gmh^i?WN7#!|DF+ke_ir{rHMQ zN6Qtr4imTS9cL<Bv($LgtUHW7iwWyiY`1kXFs>NN=qS(rH5u=o@Sg7-rSj|cR&@PG zrJP*b|2264SN8wL^$dr5;+h8@+a|efsT=+4_l5&ySxUz=WNCYXGb*k<N_XEnN9iWk zKT3Ds(T=V?=A(D(A6>g|@u=A7)o6Smbog?ZJgV2akXp6hZSP2vYnL*d-gNb0&-TL- zOs-D5H-3FMVs6qEJK}Lm^0;!(T_^Y7(hI|nOe{Jc<oLDVuwkxFN4RR3!%VM7e#IEQ z_^o}#Se@B&b&kyAHm;>tio*uBI#uI(1KYss$>Qjip2!=`E4p%Y8_E)S^zFEm`1Xb? zm)}i?Ic{$qy;lztqpnVgyZAo7;mo)Ty^z#1qzFB10OJ)N>E-Z_<+rS1M^>jHUGc}j zQz#?pcx2<hMOKeub-vOyqZlvvB&RMNWeL81DNFG6Pm%YYjeJB=s^m-MYIV&=6p!_D zl^^jDMJ;>^Q>hg4i^)ZOMDZx+VHP9sWC%<i+BEUiAD@``MkvEj{^1w>ofggr_>;$> zWNSDxlyMTkY#mvsz<LSrvZQk3`@a>=P8i>QGL*7)>id%;&z<|R3fO0kRqXiG=YD(~ zkF^!<$0~Mw>T^Fnj>p;x_hS`1KJ~dDAID>Dh5NCJ9iRG7XZMrB{5iWESz=R2VxQG` zc=D{v=I8(R=l<faE_vNKpS|r<-@D+iUi0vkZ+p{g-u0|q_ul)OGhTAd4<DG=^88&_ zo&MQB`TAMYr~I2oK6C0^;pHd)_Wu0!7hiP6f5@b=%Qz+bsiR*fu3o&pCtUwiC_fjb z`;Yy529I*4!bU<6j?%<N&SE&StVanDAV7cs0RjXF5FkK+z*9#c`~3f{VP5{BY@Qw_ z@t2=?)Hr}*z8M0$%W?RY;aY8~lvImTjb^Pn)eO-A`4GL`%ohqrnO$#Wf*wK%HnOH8 zh7xT0%HtDCFg}BJlwM$X(s($tf0Rlf|9|J-zU4h{=zsE>fB4K9ulnwbk13VFrbnAf z;Lh;9_N^UD;SFogQr@)AS<0K&KTCP(%dXRWtyrtp%B51HR;*V`wPvMR$>)l-LM?3n zxKgSVLS%nFAL8(<wUBZkS1i=3`Ka8C%7tdgJaDwLogeF$X&)_@KqY*8cCA@1=i>0S z+O?!uDb?%wW<3|Bxm>fJ)+$LZO$u=-WEzMX)hIk(&6mTscxPXy9isG$i)T%bPUHXm zQTm9nb8_^P@j{e;unBn&)|`y@xP8-iC0DNJa>sBoo`fCga*&CH9TIj(*zwf)<3vvg z5FkK+0D;FvK>UA}{!jdW+--N`aQGnEH_D$k-EVgX{p;@t@rxlZUOL?f$2UTh{ld<) zwS8tVxo1?XfBl_t)a$j<{&WbePve<SuNyco{y$3xu_K*cOdzl_9P|mvT(A_?EB=4b zf6qcl)Y0lhlY8Qss5eM^lMC%M*`8g`q~VU4$%R4G+1^ekZ`qNy+LOD}*+zJ9cV~V! z?M$vcvL^ojogp7;U;O_T@&B#%Fd5D5txi8AyqO=gx}6ni9K`>}Y5&G?l)U(V@&Cv6 z-gESi9P%~s|BuT&Nuvawi2~XD|Dy0sedB0>>@<MvvMKy?AwYlt0RqP^@JxKSG$sNB z2oNAZfWXsVAe;Z65&pQlB$POO)m$9KGwF015_q>mn%@5AVLHI@*yJgTe*ym5m;U;z zC;#sUK6w5Ew>{@)-hWRtuCVxUR&}w2qY4v~FMHd3?c&kTr$3ev5FkK+009C72oNAZ zfB=D~slf8I-7NwH2oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZ zfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&U zAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C7 z2oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N z0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+ z009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBly zK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF z5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk z1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs z0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZ zfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&U zAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C7 z2oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N z0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+ z009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBly zK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF z5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk z1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs z0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZ zfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&U zAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C7 z2oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N z0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+ z009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBly zK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF z5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk z1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs z0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZ zfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&U zAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C7 z2oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N z0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+ z009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBly zK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF z5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk z1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs z0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZ zfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&U zAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C7 z2oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5;& zr=q~*p~;C4{n*6BiK{wy!qV?2FWx$7@p^U5rHXD4AV7cs0RjXF5FkL{Q3@P#Awb}9 z7I>6TPKyyBK!5-N0t5&UAV7cs0Rm4Wf$a1DUk?5K^5%(&8$Z6Y+iNG&ad&pMHQ1WA zqeizE4O-pK)*bnSFG-VHE-K|qQ<XT0r%H`Rb1JG-N>hbgzEsW?a+ON6`GJj9JJO2o z-}K$<7W(l_IvX84Yx_*MKWMkM&kVL6*0;FZ>Cexmy{$Vcdq)qnk^@_Im+pS$8zx@; zJD+TS@da<Gy?NK3Y$Q=9x#E_=Wpn8r%PoZa#*bZfbGGFF+I7ow+h05XlMBh2&%NNx z=Ak1rx<9>iE{z9iGTlpewE973av_e|?X)*q&8>62Rwr)FMeWe?T{H8c1LvfdMzeG6 zbn77P4{m96lgln2^(dN~>veae(@8IC4))Jw4R+`I%MIVvOZ)TfL94TU>Ap=LTdLL{ zM1!zwYkO$*;A{IcQK4Mf78grV+Gv&=l_X!SCb^`Xq;b7bjiY)Y4Ug5Tl}g&E$F+L7 z7FEmjv|cZk%f(8rP^uNHX>!l<D%Wj4&DV;xYOP!<HEP9rwNz_Xnw5O6SS!@Z<v6aC zDuvKmK3~j5)mkl1a>YWenvcrOs9b2qjpjW|-5>2{tNUN5RKgHK?~8?M(n!mVq?Q&M z)q2>&YDukL$>s9RToP5{O1@Ey%cVj-SEy9uYO|15YmH`QA#FCp<{52^JBP5-i_FRL zrdemZ>>Kqb+py8#6NS*~R6ZB}UzjUxD;2iot6K}XQaPWm*XtK8tU|Bk@@cJEF6ZKU zxl&7tl~TQ)Z`N~Bn#(ooX|0mv(xecVip_k~s7B%OYQ9{rH{+;T4`V1EJZt^+Rr19` kDOWl>m)n-hZRpwXI3F(5JOKg(2oNAZfB*pkPh)}q4-`KIBLDyZ literal 0 HcmV?d00001 diff --git a/native/aetherlight/tests/fixtures/base_world.digests b/native/aetherlight/tests/fixtures/base_world.digests new file mode 100644 index 000000000..ab9edc3ea --- /dev/null +++ b/native/aetherlight/tests/fixtures/base_world.digests @@ -0,0 +1,3 @@ +3 +sha256:b706f57cb417603366a1f47a5dd099fbf68bfecc5b2e8d61d281630791d1d76d +sha256:2039956a26c3d5b073d101e5898ac5a60a9eb63a3b93f447b2d8f78ef4caf979 diff --git a/native/aetherlight/tests/fixtures/base_world.id b/native/aetherlight/tests/fixtures/base_world.id new file mode 100644 index 000000000..f23316a4c --- /dev/null +++ b/native/aetherlight/tests/fixtures/base_world.id @@ -0,0 +1 @@ +"a534b32a-4d00-429c-bf6c-ce1d55385380" From dbdaf64c4dd8f6d90afd5eed2fa6071bf890a312 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Thu, 19 Nov 2026 19:53:27 +0100 Subject: [PATCH 116/190] Make the aetherlight take-set compile and its doc-tests honest lib.rs drops the leave-set modules and re-exports, renames the compile_fail doc-tests to aetherlight::, retitles the crate doc, and allows dead code until AL4 adds the ABI. patch.rs drops the tool_schema and codex_connector imports. lens.rs drops the test that read the dropped PATCH_TOOLS catalog. Imports and `mut` bindings that only the dropped code used are removed or gated to tests so `cargo build` is warning-free. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/lens.rs | 20 +------ native/aetherlight/src/lib.rs | 92 ++++++++------------------------- native/aetherlight/src/patch.rs | 5 +- 3 files changed, 24 insertions(+), 93 deletions(-) diff --git a/native/aetherlight/src/lens.rs b/native/aetherlight/src/lens.rs index c14de9d8e..ae3f39a8a 100644 --- a/native/aetherlight/src/lens.rs +++ b/native/aetherlight/src/lens.rs @@ -65,7 +65,7 @@ impl Lens { } } - /// Existing `PATCH_TOOLS` names in emphasis order. Emphasis is prompt text + /// Existing patch tool names in emphasis order. Emphasis is prompt text /// only: the catalog, its order, and its schemas are the same for every lens. pub(crate) fn leads_with(self) -> &'static [&'static str] { match self { @@ -225,7 +225,6 @@ pub(crate) fn draw( #[cfg(test)] mod tests { use super::*; - use crate::patch::PATCH_TOOLS; use crate::tests::stock_weights; use std::collections::BTreeSet; @@ -244,23 +243,6 @@ mod tests { counts } - #[test] - fn every_lead_names_a_patch_tool() { - let catalog: BTreeSet<&str> = PATCH_TOOLS.iter().map(|entry| entry.name).collect(); - for lens in Lens::ALL { - let leads = lens.leads_with(); - assert!(!leads.is_empty(), "{lens:?} leads with nothing"); - let distinct: BTreeSet<&str> = leads.iter().copied().collect(); - assert_eq!(distinct.len(), leads.len(), "{lens:?} repeats a lead"); - for name in leads { - assert!( - catalog.contains(name), - "{lens:?} leads with unknown tool {name}" - ); - } - } - } - #[test] fn the_draw_is_a_function_of_world_and_session() { let weights = stock_weights(); diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index 3f64965c6..ca84c51a4 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -1,4 +1,4 @@ -//! The Ghostlight world library. +//! The Aetherlight world library, a fork of Ghostlight c43eb54 (see `PROVENANCE.md`). //! //! The world owner is one deterministic authority: authenticated commands enter, //! one reducer decides, and one journal atomically commits the resulting state. @@ -16,118 +16,84 @@ //! stand exactly where a consumer stands. //! //! ```compile_fail,E0603 -//! use ghostlight::WorldKernel; +//! use aetherlight::WorldKernel; //! ``` //! //! ```compile_fail,E0603 -//! use ghostlight::reduce; +//! use aetherlight::reduce; //! ``` //! //! ```compile_fail,E0603 -//! use ghostlight::WorldState; +//! use aetherlight::WorldState; //! ``` //! //! ```compile_fail,E0603 -//! use ghostlight::CommandEnvelope; +//! use aetherlight::CommandEnvelope; //! ``` //! //! ```compile_fail,E0603 -//! use ghostlight::AuthenticatedCaller; +//! use aetherlight::AuthenticatedCaller; //! ``` //! //! ```compile_fail,E0603 -//! use ghostlight::journal::WorldJournal; +//! use aetherlight::journal::WorldJournal; //! ``` //! //! ```compile_fail,E0599 -//! let _ = ghostlight::SubjectId::issue(); +//! let _ = aetherlight::SubjectId::issue(); //! ``` //! //! ```compile_fail,E0603 -//! let _ = ghostlight::ScopeDigest::fixture("x"); +//! let _ = aetherlight::ScopeDigest::fixture("x"); //! ``` //! //! ```compile_fail,E0425 -//! let _ = ghostlight::fixture_controller_opportunities(&[]); +//! let _ = aetherlight::fixture_controller_opportunities(&[]); //! ``` //! //! ```compile_fail,E0425 -//! let _ = ghostlight::fixture_inference_output("prose", "receipt"); +//! let _ = aetherlight::fixture_inference_output("prose", "receipt"); //! ``` +// The kernel has no entry point until AL4 adds the ABI, so most of it is unreachable +// from the public surface. AL4 removes this attribute. +#![allow(dead_code)] + mod action; -mod aetheria; mod clock; -mod consumer; -mod controllers; mod cover; -mod elaboration; mod grammar; #[cfg(test)] mod import_key_tests; mod journal; mod lens; -mod local_inference; -mod mailbox; mod patch; -mod sdk_inference; -mod table; -mod tool_schema; -mod vault; -mod verse; pub(crate) use action::ActionMismatch; pub(crate) use clock::Motion; pub use clock::{FictionalMinutes, TickMinutes}; -pub use consumer::{ - CONSUMER_BODY_LIMIT, CONSUMER_CREDENTIALS_ENVIRONMENT, CONSUMER_PATCH_SCHEMA, - CONSUMER_RECEIPT_SCHEMA, ConsumerRegistry, admit_document, encode_receipt, -}; -pub use controllers::{ - CONTROLLER_WORK_SCHEMA, CellRun, ConnectorBinding, ControllerError, ControllerModels, - ControllerOpenError, - ControllerNeed, ControllerPendingReason, ControllerRunner, ControllerWork, - ControllerWorkCustody, ControllerWorkLookup, ControllerWorkStore, ControllerWorkStoreError, - ControllerWorkWrite, - GroupedCheckpoint, InferenceEvent, InferenceFault, InferenceFaultClass, InferenceFaultDisposition, InferenceOutput, - InferencePort, - InferencePurpose, InferenceRequest, NarrativeCheckpoint, NarrativeRun, OperationalCheckpoint, - OperationalRun, PersonaLane, PreparedInference, SubmissionDisposition, TokenUsage, ToolResultOracle, - TracingInferencePort, open_controller_work, open_inference, -}; -pub(crate) use cover::{CellId, Constituent, Resolution}; -pub use aetheria::{ - AetheriaCatalog, AetheriaFaction, CatalogReadError, VerbRule, read_aetheria_catalog, -}; pub use cover::{AgencyGraph, Cell, Cover, CoverBudget, CoverBudgetError, TickIndex, derive_cover}; -pub use elaboration::{ - ElaborationCheckpoint, ElaborationRunner, ElaboratorSession, EvidenceError, EvidenceQuery, - EvidenceReceipt, EvidenceSource, SeedCheckpoint, SeedOutcome, SeedRunner, select_row, -}; pub use grammar::{ GrammarBinding, GrammarError, GrammarIdentity, GrammarReferentKind, GrammarRole, GrammarVerb, RenderPath, }; pub use lens::{Lens, LensWeights}; -pub use local_inference::{DEFAULT_HOSTED_MODEL_PREFIX, DEFAULT_LOCAL_MODEL_PREFIX, HostedBinding, LocalBinding}; -#[cfg(feature = "test-support")] -pub use local_inference::open_local_port_with_timeout; -pub(crate) use mailbox::ElaborationPort; -pub use mailbox::{ConsumerPort, ControllerPort, MailboxError, PlayPort, SeedPort, WorldMailbox}; pub use patch::{ CommitmentKey, DraftHandle, JurisdictionKey, Mismatch, PatchAnswer, Ref, RefKind, RefName, Role, Site, Statement, WorldPatch, }; pub(crate) use patch::{ AccessKind, Affordance, Audience, AuthoredSource, AuthorityGrant, AuthorityTarget, - BoundPrecondition, Bounds, ChannelRecord, Commitment, CommitmentKind, Confidence, Cost, - Declaration, DependencyTarget, EntityDeclaration, EntityKind, EvidenceRef, FactRecord, + BoundPrecondition, ChannelRecord, Commitment, CommitmentKind, Confidence, Cost, + DependencyTarget, EntityKind, EvidenceRef, FactRecord, FactStanding, Forum, GrievanceKindName, Knowledge, KnowledgeSource, Office, OfficeName, PersonaMaterial, Position, PressureMagnitude, PressureSource, Quantity, Reach, - SubjectDeclaration, WorldScaleIntent, WorldScaleIntentRef, + WorldScaleIntent, WorldScaleIntentRef, }; pub use patch::ImportKey; #[cfg(test)] +pub(crate) use patch::{Bounds, Declaration, EntityDeclaration, SubjectDeclaration}; +#[cfg(test)] use patch::{ AffordanceDeclaration, AudienceRef, AudienceSpec, ChannelDeclaration, ComponentOp, DependencyRef, FactDeclaration, FactStandingRef, ReachRef, RouteDeclaration, @@ -137,20 +103,6 @@ pub(crate) use patch::{ AffordanceKindName, AuthorityGrantRef, AuthorityKindName, AuthorityTargetRef, ComponentOpKind, EffectSlot, OutcomeBand, Precondition, RoleSpec, }; -pub use sdk_inference::{DEFAULT_SDK_MODEL_PREFIX, SdkBinding}; -pub use table::{ - DecodedBatch, PatchSite, TableError, actor_tools, authoring_tools, decode_actor_call, - decode_authoring_call, decode_authoring_calls, describe_refusal, describe_refusal_to_actor, - id_text, id_text_matches, table_view, -}; -pub use vault::{VaultError, VaultEvidenceSource}; -pub use verse::{ - CALL_RECORD_SCHEMA, CallRecordError, CallRecordStore, CreateVerseWorldIntent, ProviderCallRecord, - RUN_RECORD_SCHEMA, RecordedCoverBudget, RecordingInferencePort, Refusal, RefusalReason, RunClaim, - ReplayInferencePort, RunField, RunId, RunOutcome, RunStart, RunStatus, TickCheckpoint, - TickReport, UnattributedCall, VerseGenesisError, VerseRunConfig, VerseRunError, VerseRunRecord, VerseRunStore, - call_run_id, run_manual, -}; use patch::{EdgeRecord, EntityRecord, LedgerDelta, ResolvedOp, ResolvedPatch}; use chrono::{DateTime, Utc}; @@ -4956,7 +4908,7 @@ fn confine_to_ground( } let mut mismatches = Vec::new(); - let mut confine_subject = |site: &Site, subject: SubjectId, mismatches: &mut Vec<Mismatch>| { + let confine_subject = |site: &Site, subject: SubjectId, mismatches: &mut Vec<Mismatch>| { let admitted = match held { PatchGround::Jurisdiction(jurisdiction) => { match positions.get(&subject).copied().flatten() { @@ -4974,7 +4926,7 @@ fn confine_to_ground( mismatches.push(Mismatch::OutsideJurisdiction { site: site.clone() }); } }; - let mut confine_place = |site: &Site, place: EntityId, mismatches: &mut Vec<Mismatch>| { + let confine_place = |site: &Site, place: EntityId, mismatches: &mut Vec<Mismatch>| { if !inside(place) { mismatches.push(Mismatch::OutsideJurisdiction { site: site.clone() }); } diff --git a/native/aetherlight/src/patch.rs b/native/aetherlight/src/patch.rs index 31485e2d6..06f4dd936 100644 --- a/native/aetherlight/src/patch.rs +++ b/native/aetherlight/src/patch.rs @@ -12,15 +12,12 @@ //! after that set is empty, so a rejected patch never mints an ID. use super::clock::{FictionalMinutes, TickMinutes}; -use super::tool_schema; use super::grammar::GrammarRefusal; use super::{ AffordanceId, CommandId, ControllerAssignment, ControllerId, EdgeId, EntityId, LensWeights, NewController, SubjectId, SubjectKind, SubjectState, WorldId, }; -use codex_connector::CodexToolDefinition; use serde::{Deserialize, Serialize}; -use serde_json::{Value, json}; use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet, btree_map::Entry}; use unicode_properties::{GeneralCategory, UnicodeGeneralCategory}; @@ -5374,7 +5371,7 @@ pub(super) fn resolve_patch( }); } allocated_subjects.insert(input.handle.clone(), subject_id); - let mut controller_id = || { + let controller_id = || { ControllerId(derive_id( CONTROLLER_NAMESPACE, world_id, From 96f553a00dccb5b0ab0f5effd8ea0bf0d2c8d01f Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Thu, 19 Nov 2026 19:53:48 +0100 Subject: [PATCH 117/190] Record aetherlight provenance Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/PROVENANCE.md | 106 +++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 native/aetherlight/PROVENANCE.md diff --git a/native/aetherlight/PROVENANCE.md b/native/aetherlight/PROVENANCE.md new file mode 100644 index 000000000..5f4fd29eb --- /dev/null +++ b/native/aetherlight/PROVENANCE.md @@ -0,0 +1,106 @@ +# Aetherlight provenance + +Aetherlight is a fork of the synchronous world kernel of Ghostlight. + +- Upstream: `GameCult/Ghostlight`, `crates/ghostlight/` +- Commit: `c43eb54962ed4a09cc737ecac73a16b0d7ce62b4` (origin/main) +- Taken: 2026-11-19 +- Authority: cut `aetherlight-fork-import` r1 of campaign `aetheria-release`; + rulings `aetherlight-narrative-state-owner` and `dialogue-is-world-action`. + +Every file below was copied as a raw git blob (`git show`), never `git archive`, +and committed with `-text` (`.gitattributes`) so no checkout converts newlines. +Line ranges are in the c43eb54 file. + +## Taken + +| c43eb54 path (under `crates/ghostlight/`) | Here | Range | Edits | +| --- | --- | --- | --- | +| `src/lib.rs` | `src/lib.rs` | all | E1-E5 | +| `src/action.rs` | `src/action.rs` | all | none | +| `src/clock.rs` | `src/clock.rs` | all | none | +| `src/journal.rs` | `src/journal.rs` | all | none | +| `src/grammar.rs` | `src/grammar.rs` | all | none | +| `src/grammar/tests.rs` | `src/grammar/tests.rs` | all | none | +| `src/lens.rs` | `src/lens.rs` | all | E8, E9 | +| `src/cover.rs` | `src/cover.rs` | all | none | +| `src/import_key_tests.rs` | `src/import_key_tests.rs` | all | none | +| `src/patch.rs` | `src/patch.rs` | 1-6059 and 7906-9606 (dropped 6060-7905: the patch tool catalog, `PATCH_TOOLS`, `patch_tools()`, the `field_example` helpers, `mod catalog_tests`) | E6, E7 | +| `tests/fixtures/base_world.cc` | same | all | none | +| `tests/fixtures/base_world.digests` | same | all | none | +| `tests/fixtures/base_world.id` | same | all | none | +| `Cargo.lock` | `Cargo.lock` | all | pruned by cargo to the dependencies below | + +`Cargo.toml` is new: package `aetherlight`, its own `[workspace]`, no features, +dependencies chrono, cultcache-rs, rmp-serde, serde, serde_json, sha2, thiserror, +unicode-normalization, unicode-properties, uuid; dev tempfile. + +## Edits + +- E1. `lib.rs`: dropped the `mod` lines and every `pub`/`pub(crate) use` of + aetheria, consumer, controllers, elaboration, local_inference (with its + `cfg(feature = "test-support")` re-export), mailbox, sdk_inference, table, + tool_schema, vault, verse. +- E2. `lib.rs` crate docs: retitled to Aetherlight with a pointer to this file; + the `compile_fail` doc-tests name `aetherlight::` instead of `ghostlight::`. + The sealing prose is kept. +- E3. `lib.rs`: `#![allow(dead_code)]`. The kernel has no entry point until AL4 + adds the ABI; AL4 removes the attribute. +- E4. `lib.rs`: imports that only dropped code used are removed + (`cover::{CellId, Constituent, Resolution}`), or moved under `#[cfg(test)]` + because only tests use them (`patch::{Bounds, Declaration, EntityDeclaration, + SubjectDeclaration}`). +- E5. `lib.rs`: `let mut` removed from the closures `confine_subject` and + `confine_place` (unused-mut in the non-test build). +- E6. `patch.rs`: deleted `use super::tool_schema;`, + `use codex_connector::CodexToolDefinition;` and `use serde_json::{Value, json};` + (only the dropped catalog used the last one); `let mut` removed from the + `controller_id` closure. +- E7. `patch.rs`: lines 6060-7905 dropped as above. +- E8. `lens.rs`: deleted test `every_lead_names_a_patch_tool` and its + `use crate::patch::PATCH_TOOLS;`, which read the dropped catalog. +- E9. `lens.rs`: the doc comment on `leads_with` says "patch tool names" instead + of naming `PATCH_TOOLS`. + +Not renamed: the `ghostlight.*` schema ids and namespaces in the code +(`STATE_SCHEMA`, `COMMIT_SCHEMA`, journal schema rows, `ghostlight.speech`, +`ghostlight.cover.v1`). They enter derived ids and digests; the golden replay +`grammar::tests::existing_world_reopens_with_unchanged_digests` proves them +unchanged. AL3 owns the format rename. + +## Left behind + +| Upstream file | Why it is not here | +| --- | --- | +| `mailbox.rs` | the async port/mailbox lane around the kernel; AL4's ABI replaces it | +| `controllers.rs` | model decider lane; composes an invocation's speech text, which Aetheria's player and C# brains do themselves | +| `elaboration.rs` | model elaboration lane | +| `consumer.rs` | consumer patch admission over HTTP-shaped ports; speech only in its fixtures | +| `table.rs` | encodes actor calls as model tools | +| `vault.rs` | evidence source over a vault | +| `local_inference.rs`, `sdk_inference.rs` | model backends (tokio, reqwest, codex-connector) | +| `tool_schema.rs` | tool schemas for model calls | +| `aetheria.rs`, `aetheria/` | Ghostlight's Aetheria catalog reader; Aetheria content is read by Aetheria | +| `verse/` | one example world; its speech affordances are a pattern to copy into Aetheria content, not a kernel dependency | +| `tests/external_admission.rs` | exercises the dropped consumer lane | +| crates `ghostlight-persona-projection`, `ghostlight-verse`; `sidecar/` | outside the synchronous kernel | + +Speech as world action stays whole: affordance declarations with `carries_speech`, +preconditions, audience, effect slots and outcome bands, `Communicate` and +`Display`, `Knowledge` and `Told`, commitments (`patch.rs`); exercise, role +binding, preconditions, audience, band selection and lowering (`action.rs`); +`DecisionInvocation`, `DecisionEvent` and `ResolvedOp::Communicate` apply +(`lib.rs`); the `SpeakRenderPath` check (`grammar.rs`). + +## Dependency pin + +`cultcache-rs` is pinned at Ghostlight's rev +`85f7024a35ea42cf9f0a0199a064526427150191`, the rev that wrote +`tests/fixtures/base_world.cc`, not Aetheria's C# CultLib pin. The fork +reproduces Ghostlight first; AL3 removes cultcache-rs. + +## Pulling a later Ghostlight fix + +By hand, against this file: read the upstream diff for the taken files, apply it +here, and record it in this file with its upstream commit and the files it +touched. A fix that lands in a left-behind file is not pulled. From cd2f45ff99441369191a976a02ee251b8c65c686 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Thu, 19 Nov 2026 20:35:59 +0100 Subject: [PATCH 118/190] Pin the aetherlight seal and the precondition gates; make the crate docs true Delete the two compile_fail doc-tests that named items absent from the fork and drop the error codes stable rustdoc does not check; each remaining doc-test was shown to fail when its item is made public. Add tests that kill four mutants which survived upstream too: Committed ignoring kind, Committed ignoring counterparty, Holds >= turned into >, and the apply-time can_broadcast guard. Rewrite the crate docs for the fork as it is and remove the two unresolved links. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/.gitattributes | 2 - native/aetherlight/src/action.rs | 25 +++++ native/aetherlight/src/lib.rs | 167 ++++++++++++++++++++++++------ 3 files changed, 162 insertions(+), 32 deletions(-) delete mode 100644 native/aetherlight/.gitattributes diff --git a/native/aetherlight/.gitattributes b/native/aetherlight/.gitattributes deleted file mode 100644 index 14b915993..000000000 --- a/native/aetherlight/.gitattributes +++ /dev/null @@ -1,2 +0,0 @@ -# Verbatim fork of Ghostlight: bytes are the contract (digests, fixtures). No newline conversion. -* -text diff --git a/native/aetherlight/src/action.rs b/native/aetherlight/src/action.rs index bbfddae96..71ec12318 100644 --- a/native/aetherlight/src/action.rs +++ b/native/aetherlight/src/action.rs @@ -1210,6 +1210,31 @@ mod tests { ); } + /// `at_least` is inclusive: holding exactly the threshold passes. The clerk + /// spends down to one ingot-equivalent, and `carry_holds` asks for one. + #[test] + fn holding_exactly_the_threshold_satisfies_holds() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = bench(directory.path(), "HoldsBoundary"); + for _ in 0..2 { + bench.commit(bench.carry(3, bench.yard)); + bench.refresh(); + } + assert_eq!(bench.held(bench.clerk), OPENING_BALANCE - 6); + let exact = bench.variant(&bench.carry(1, bench.yard), "carry_holds"); + bench + .try_exercise(&exact) + .expect("one held satisfies at_least one"); + + bench.commit(bench.carry(1, bench.yard)); + bench.refresh(); + assert_eq!(bench.held(bench.clerk), 0); + assert_eq!( + bench.rejections(&bench.variant(&bench.carry(1, bench.yard), "carry_holds")), + vec![ActionMismatch::InsufficientHolding { precondition: 0 }] + ); + } + #[test] fn a_reachable_precondition_reads_only_open_public_routes() { let directory = tempfile::tempdir().unwrap(); diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index ca84c51a4..074a1b03d 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -2,58 +2,53 @@ //! //! The world owner is one deterministic authority: authenticated commands enter, //! one reducer decides, and one journal atomically commits the resulting state. -//! Controllers may use models, but models never own lifecycle, scope, affordances, -//! opportunities, reduction, or persistence. +//! The fork keeps only that synchronous kernel: no async runtime, no network, no +//! model controllers and no ports. A decision arrives as an invocation the caller +//! built, a player or a brain; nothing in this crate composes one. //! -//! A consumer reaches this crate through create/open, immutable snapshots, -//! command submission, typed receipts, and the runner and port entry points -//! below. The kernel itself is sealed: there is no mutable state, no canonical -//! ID allocator, no reducer entry, no journal writer, and no authenticated-caller -//! constructor on the public surface, under every configuration. This crate -//! declares no cargo features, so no build can lift the seal. +//! The crate has no entry point yet: the ABI that creates, opens and drives a +//! world arrives in AL4. Until then the kernel itself is sealed: there is no +//! mutable state, no canonical ID allocator, no reducer entry, no journal writer, +//! and no authenticated-caller constructor on the public surface, under every +//! configuration. This crate declares no cargo features, so no build can lift +//! the seal. //! //! The negative proofs are doc-tests, which compile as an external crate and so -//! stand exactly where a consumer stands. +//! stand exactly where a consumer stands. Stable rustdoc does not check the error +//! code of a `compile_fail` test, so none is claimed: each test passes only +//! because its item is not public, and fails once the item is made public. //! -//! ```compile_fail,E0603 +//! ```compile_fail //! use aetherlight::WorldKernel; //! ``` //! -//! ```compile_fail,E0603 +//! ```compile_fail //! use aetherlight::reduce; //! ``` //! -//! ```compile_fail,E0603 +//! ```compile_fail //! use aetherlight::WorldState; //! ``` //! -//! ```compile_fail,E0603 +//! ```compile_fail //! use aetherlight::CommandEnvelope; //! ``` //! -//! ```compile_fail,E0603 +//! ```compile_fail //! use aetherlight::AuthenticatedCaller; //! ``` //! -//! ```compile_fail,E0603 +//! ```compile_fail //! use aetherlight::journal::WorldJournal; //! ``` //! -//! ```compile_fail,E0599 +//! ```compile_fail //! let _ = aetherlight::SubjectId::issue(); //! ``` //! -//! ```compile_fail,E0603 +//! ```compile_fail //! let _ = aetherlight::ScopeDigest::fixture("x"); //! ``` -//! -//! ```compile_fail,E0425 -//! let _ = aetherlight::fixture_controller_opportunities(&[]); -//! ``` -//! -//! ```compile_fail,E0425 -//! let _ = aetherlight::fixture_inference_output("prose", "receipt"); -//! ``` // The kernel has no entry point until AL4 adds the ABI, so most of it is unreachable // from the public surface. AL4 removes this attribute. @@ -117,11 +112,11 @@ use uuid::Uuid; /// Proof that the consumer verified a live principal, and the moment that /// proof stops being worth anything. /// -/// The consumer verifies; this library only bounds. `valid_until` is the -/// consumer's own session expiry, not a fresh clock read at construction, and -/// [`WorldMailbox::submit_principal`] refuses evidence presented after it — so -/// a long-lived holder such as [`SeedPort`] is bounded by the session that -/// vouched for it rather than by one request's lifetime. +/// The consumer verifies; this library carries the proof. `valid_until` is the +/// consumer's own session expiry, not a fresh clock read at construction. +/// Nothing in this crate enforces it yet: Ghostlight's mailbox refused evidence +/// presented after it, and the mailbox is not part of the fork, so the ABI that +/// AL4 adds must carry that check. /// /// Keeping this type here, rather than taking the consumer's own session type, /// is what keeps the consumer's principal format out of the kernel. @@ -11248,6 +11243,45 @@ mod soul_knowledge_tests { } } + /// The reducer re-derives the audience gate from committed state, so a forged + /// `Communicate` for a speaker with no standing in the room is refused even + /// when the fact is live and the event carries no mismatch. The same telling + /// by a speaker who is in the room applies. + #[test] + fn a_telling_by_a_speaker_outside_its_audience_does_not_apply() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, speech, _) = speech_kernel(directory.path(), "OutsideAudience"); + let resolves_to = kernel.state.revision + 1; + + let mut candidate = kernel.state.clone(); + let error = apply_operation( + &mut candidate, + &ResolvedOp::Communicate { + speaker: speech.stranger, + fact: speech.flood, + to: Audience::Colocated, + }, + &[], + resolves_to, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + assert_eq!(candidate, kernel.state); + + let mut candidate = kernel.state.clone(); + apply_operation( + &mut candidate, + &ResolvedOp::Communicate { + speaker: speech.speaker, + fact: speech.flood, + to: Audience::Colocated, + }, + &[], + resolves_to, + ) + .expect("a speaker inside its audience tells"); + } + /// A speech act that lands nothing moves no digest at all, the speaker's own /// included. `AssertClaim` writes `entities` and `facts`, and neither is a /// scope component, so an in-flight proposal held by anyone in the world @@ -14801,6 +14835,79 @@ mod clock_tests { ); } + /// `Committed` is a conjunction: the actor holds a commitment to this very + /// counterparty and of this very kind. The farmer owes the treasury an + /// obligation and nobody else, so naming the reeve fails the counterparty + /// half while the kind half holds. + #[test] + fn committed_requires_the_named_counterparty() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "CommittedCounterparty"); + let error = exercise( + &mut kernel, + clockwork.farmer, + clockwork.deliver, + vec![binding("creditor", Target::Subject(clockwork.reeve))], + ) + .unwrap_err(); + assert!(matches!( + error, + KernelError::ActionRejected(ref mismatches) + if *mismatches == vec![ActionMismatch::NotCommitted { precondition: 0 }] + )); + } + + /// The other half: the reeve holds a routine toward the treasury, a kind + /// `deliver` does not ask for, so the counterparty half holds and the kind + /// half fails. The farmer's own obligation to the same treasury still passes. + #[test] + fn committed_requires_the_named_kind() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "CommittedKind"); + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CreateCommitment { + subject: Ref::Existing(clockwork.reeve), + counterparty: Some(Ref::Existing(clockwork.treasury)), + kind: CommitmentKind::Routine, + due: FictionalMinutes(ROUTINE_DUE), + period: Some(minutes(10)), + checks: vec![PreconditionRef::Present { + at: Ref::Existing(clockwork.yard), + }], + statement: Statement::new("A routine held toward the treasury.").unwrap(), + }]), + ); + assert!( + kernel.state.commitments[&clockwork.reeve] + .values() + .any(|held| held.kind == CommitmentKind::Routine + && held.counterparty == Some(clockwork.treasury)), + "the fixture reeve holds a routine to the treasury" + ); + let error = exercise( + &mut kernel, + clockwork.reeve, + clockwork.deliver, + vec![binding("creditor", Target::Subject(clockwork.treasury))], + ) + .unwrap_err(); + assert!(matches!( + error, + KernelError::ActionRejected(ref mismatches) + if *mismatches == vec![ActionMismatch::NotCommitted { precondition: 0 }] + )); + exercise( + &mut kernel, + clockwork.farmer, + clockwork.deliver, + vec![binding("creditor", Target::Subject(clockwork.treasury))], + ) + .expect("an obligation to the same counterparty passes"); + } + /// A tick that only advances pressure moves nobody's scope digest; a tick /// that fulfils a routine moves exactly that subject's. #[test] From 6ef5f51a42a2aa92b053987df33cc73da8db4849 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Thu, 19 Nov 2026 20:35:59 +0100 Subject: [PATCH 119/190] Correct aetherlight provenance: drop .gitattributes, list leave-set residue and AL4 duties The -text pin was not needed (the fixtures absorb CRLF and the .cc is binary), so the file goes. external_admission.rs is described as the cross-crate forgery proof it is, and the dead-code vocabulary and AL4 obligations are listed. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/PROVENANCE.md | 52 ++++++++++++++++++++++++++++---- 1 file changed, 46 insertions(+), 6 deletions(-) diff --git a/native/aetherlight/PROVENANCE.md b/native/aetherlight/PROVENANCE.md index 5f4fd29eb..b3405c47c 100644 --- a/native/aetherlight/PROVENANCE.md +++ b/native/aetherlight/PROVENANCE.md @@ -8,16 +8,19 @@ Aetherlight is a fork of the synchronous world kernel of Ghostlight. - Authority: cut `aetherlight-fork-import` r1 of campaign `aetheria-release`; rulings `aetherlight-narrative-state-owner` and `dialogue-is-world-action`. -Every file below was copied as a raw git blob (`git show`), never `git archive`, -and committed with `-text` (`.gitattributes`) so no checkout converts newlines. -Line ranges are in the c43eb54 file. +Every file below was copied as a raw git blob (`git show`), never `git archive`. +The blobs are LF, as upstream. A Windows checkout with `core.autocrlf` turns the +`.rs` files and the two text fixtures into CRLF; rustc, the fixture readers +(`lines()`, `trim()`) and the golden test absorb that, so no `.gitattributes` is +kept (a first commit had one; its stated reason did not hold). `base_world.cc` is +binary and no newline rule touches it. Line ranges are in the c43eb54 file. ## Taken | c43eb54 path (under `crates/ghostlight/`) | Here | Range | Edits | | --- | --- | --- | --- | -| `src/lib.rs` | `src/lib.rs` | all | E1-E5 | -| `src/action.rs` | `src/action.rs` | all | none | +| `src/lib.rs` | `src/lib.rs` | all | E1-E5, E10, E11 | +| `src/action.rs` | `src/action.rs` | all | E11 | | `src/clock.rs` | `src/clock.rs` | all | none | | `src/journal.rs` | `src/journal.rs` | all | none | | `src/grammar.rs` | `src/grammar.rs` | all | none | @@ -61,6 +64,17 @@ unicode-normalization, unicode-properties, uuid; dev tempfile. `use crate::patch::PATCH_TOOLS;`, which read the dropped catalog. - E9. `lens.rs`: the doc comment on `leads_with` says "patch tool names" instead of naming `PATCH_TOOLS`. +- E10. `lib.rs` crate docs describe the fork as it is (no runner, no ports, no + controllers); the compile_fail doc-tests keep no error code (stable rustdoc does + not check one) and the two that named items absent from the fork + (`fixture_controller_opportunities`, `fixture_inference_output`) are deleted. + The `VerifiedPrincipalEvidence` doc no longer links `WorldMailbox`/`SeedPort` + and says nothing here enforces `valid_until`; the ABI must (AL4). +- E11. New tests, not upstream, each killing a mutant that survived upstream's 810 + tests: `action::tests::holding_exactly_the_threshold_satisfies_holds`, + `clock_tests::committed_requires_the_named_counterparty`, + `clock_tests::committed_requires_the_named_kind`, + `soul_knowledge_tests::a_telling_by_a_speaker_outside_its_audience_does_not_apply`. Not renamed: the `ghostlight.*` schema ids and namespaces in the code (`STATE_SCHEMA`, `COMMIT_SCHEMA`, journal schema rows, `ghostlight.speech`, @@ -82,7 +96,7 @@ unchanged. AL3 owns the format rename. | `tool_schema.rs` | tool schemas for model calls | | `aetheria.rs`, `aetheria/` | Ghostlight's Aetheria catalog reader; Aetheria content is read by Aetheria | | `verse/` | one example world; its speech affordances are a pattern to copy into Aetheria content, not a kernel dependency | -| `tests/external_admission.rs` | exercises the dropped consumer lane | +| `tests/external_admission.rs` | the cross-crate proof that forged, serde-minted opportunities and ids are refused at the public surface; dropped with the consumer lane it drove. AL4 must carry an equivalent proof against the ABI's own surface | | crates `ghostlight-persona-projection`, `ghostlight-verse`; `sidecar/` | outside the synchronous kernel | Speech as world action stays whole: affordance declarations with `carries_speech`, @@ -104,3 +118,29 @@ reproduces Ghostlight first; AL3 removes cultcache-rs. By hand, against this file: read the upstream diff for the taken files, apply it here, and record it in this file with its upstream commit and the files it touched. A fix that lands in a left-behind file is not pulled. + +## Leave-set vocabulary still compiled (AL2a's triage list) + +`#![allow(dead_code)]` hides about 248 dead-code warnings, among them vocabulary +that only the left-behind lanes used. AL2a decides each as delete, keep or rename. +Several enter derived ids or digests, so a removal is a format change (AL3), not +a cleanup. + +- Consumer lane: `ConsumerId`, `consumer_id`, `consumer_caller`, + `bound_to_consumer`, `CONSUMER_ID_NAMESPACE`, `VerifiedPrincipalEvidence`. +- Controller lane: `verified_controller`, `resolve_controller`, `controller_mode`, + `controller_receipt`, `controller_decline_receipt`, `controller_key`. +- Elaborator lane: `Elaborator`, `GrantElaborator`, `RetireElaborator`, + `ElaboratorEvidence`, `ElaboratorUnanswered`, `elaborator_error`, + `UnelaboratedDestination` and its preimage, and the tests that name them. +- Mailbox and vault comments (`WorldMailbox`, `vault:` evidence strings). + +Reproduce the full list with `RUSTFLAGS=--force-warn dead_code cargo build`. + +## Obligations this cut hands to AL4 + +- A cross-crate proof that forged opportunities and ids are refused, equivalent to + the dropped `tests/external_admission.rs`, against the ABI's surface. +- Enforcement of `VerifiedPrincipalEvidence::valid_until`, which Ghostlight's + mailbox did and the fork does not. +- Removal of `#![allow(dead_code)]`. From 10f487dc16d64dd92309e455145fdd09858a48fd Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Thu, 19 Nov 2026 21:57:37 +0100 Subject: [PATCH 120/190] Aetherlight AL2a.1: delete the lens lane and the Ghostlight golden fixture Remove lens.rs, LensWeights in genesis input, WorldState, snapshot and creation, SetLensWeights, LensWeightsReplaced, LensWeightsNeverDraw and the draw-rule shape check. The journal's lens replay tests are rewritten over an owner AdvanceTime history (replays exactly; a forged caller fails replay). The state shape changed, so Ghostlight's base_world fixture no longer decodes: the golden replay test and its three fixtures go (AL4 adds Aetherlight's own). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/action.rs | 1 - native/aetherlight/src/grammar/tests.rs | 31 +- native/aetherlight/src/import_key_tests.rs | 2 - native/aetherlight/src/journal.rs | 179 ++------ native/aetherlight/src/lens.rs | 361 ---------------- native/aetherlight/src/lib.rs | 388 +----------------- native/aetherlight/src/patch.rs | 23 +- .../aetherlight/tests/fixtures/base_world.cc | Bin 557056 -> 0 bytes .../tests/fixtures/base_world.digests | 3 - .../aetherlight/tests/fixtures/base_world.id | 1 - 10 files changed, 50 insertions(+), 939 deletions(-) delete mode 100644 native/aetherlight/src/lens.rs delete mode 100644 native/aetherlight/tests/fixtures/base_world.cc delete mode 100644 native/aetherlight/tests/fixtures/base_world.digests delete mode 100644 native/aetherlight/tests/fixtures/base_world.id diff --git a/native/aetherlight/src/action.rs b/native/aetherlight/src/action.rs index 71ec12318..ca0c16a6c 100644 --- a/native/aetherlight/src/action.rs +++ b/native/aetherlight/src/action.rs @@ -172,7 +172,6 @@ pub(super) fn exercise( evidence: Vec::new(), }, None, - None, ) .map_err(KernelError::PatchRejected)? .operations diff --git a/native/aetherlight/src/grammar/tests.rs b/native/aetherlight/src/grammar/tests.rs index 85b3b1e19..4b1373709 100644 --- a/native/aetherlight/src/grammar/tests.rs +++ b/native/aetherlight/src/grammar/tests.rs @@ -6,7 +6,7 @@ use crate::patch::{ use crate::tests::{auth_principal, command, creation, owner}; use crate::{ CallerId, CommandBody, CommandId, CreateWorld, KernelError, SubjectKind, SubmitReceipt, - WorldId, WorldKernel, WorldPatch, + WorldKernel, WorldPatch, }; fn verb(path: RenderPath, roles: &[(&str, GrammarReferentKind)]) -> GrammarVerb { @@ -484,34 +484,6 @@ fn a_grammar_names_each_verb_once_and_has_a_schema() { ); } -/// The fixture world was written by the code at base 367e2eb, which has no -/// grammar field anywhere. Reopening it must reproduce the digests that code -/// recorded. -#[test] -fn existing_world_reopens_with_unchanged_digests() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - std::fs::write(&path, include_bytes!("../../tests/fixtures/base_world.cc")).unwrap(); - let world_id: WorldId = - serde_json::from_str(include_str!("../../tests/fixtures/base_world.id").trim()).unwrap(); - let kernel = WorldKernel::open(&path, world_id).expect("a base-written world reopens"); - let snapshot = kernel.snapshot().unwrap(); - let recorded = include_str!("../../tests/fixtures/base_world.digests"); - let mut lines = recorded.lines(); - assert_eq!(snapshot.revision.to_string(), lines.next().unwrap()); - assert_eq!(snapshot.state_digest, lines.next().unwrap()); - assert_eq!( - snapshot.last_commit_digest.as_deref(), - Some(lines.next().unwrap()) - ); - assert!(snapshot.grammar.is_none()); - // Its state still derives the recorded digest from its bytes. - assert_eq!( - crate::state_digest(&kernel.state).unwrap(), - snapshot.state_digest - ); -} - fn submit_as( kernel: &mut WorldKernel, caller: CallerId, @@ -711,7 +683,6 @@ fn an_effect_resolved_elsewhere_cannot_install_an_entry_outside_the_grammar() { CommandId::new(), &patch_of(vec![declare("probe", kind, roles)]), None, - None, ) .expect("the unbound twin admits any canonical kind") }; diff --git a/native/aetherlight/src/import_key_tests.rs b/native/aetherlight/src/import_key_tests.rs index 43ca2bb9a..41800eab9 100644 --- a/native/aetherlight/src/import_key_tests.rs +++ b/native/aetherlight/src/import_key_tests.rs @@ -463,7 +463,6 @@ fn the_subjects_map_refuses_a_second_subject_for_one_key_even_when_resolved_else place, )]), None, - None, ) .expect("the key is unheld at the revision both were resolved against") }; @@ -680,7 +679,6 @@ fn admitting_a_resolved_effect_refuses_two_subjects_with_one_key() { mirror("second", Some(key("aetheria.ship", "Gamma")), place), ]), None, - None, ) .expect("two distinct keys resolve") }; diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index a2d36fbb2..31f22fad5 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -759,11 +759,6 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> "the scale intent names a non-place root or distributes more than the whole".into(), )); } - // The third statement of the draw rule, beside genesis and - // `SetLensWeights`: no stored world holds weights that never draw. - if !state.lens_weights.draws() { - return Err(JournalError::Corrupt("the lens weights never draw".into())); - } // The civic subgraph, in the slot the deleted `authority_scope` check // occupied: a jurisdiction names live ground under a canonical kind, an // office sits on an institution and lends something to a person who holds @@ -1109,7 +1104,6 @@ mod tests { let owner = PrincipalId::new("owner@example.test"); let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); let creation = CreateWorld { - lens_weights: crate::tests::stock_weights(), id: CommandId::new(), owner: owner.clone(), title: "Before".into(), @@ -1194,7 +1188,6 @@ mod tests { let owner = PrincipalId::new("owner@example.test"); let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); let creation = CreateWorld { - lens_weights: crate::tests::stock_weights(), id: CommandId::new(), owner: owner.clone(), title: "Kharad".into(), @@ -1319,11 +1312,10 @@ mod tests { } } - /// Lens weights entered both rows — the state row holds them and a commit - /// row carries `LensWeightsReplaced` — so both schemas bumped and both - /// `consumer.v4` strings are refused at open. No migration, no dual read. + /// A store written under an older schema is refused at open: both + /// `consumer.v4` strings. No migration, no dual read. #[test] - fn a_store_written_before_the_lens_schema_is_refused() { + fn a_store_written_under_an_older_schema_is_refused() { for (row_type, schema) in [ (STATE_ROW, "ghostlight.world_state.consumer.v4"), (COMMIT_ROW, "ghostlight.world_commit.consumer.v4"), @@ -1346,34 +1338,28 @@ mod tests { } } - /// A world whose history includes an owner's `SetLensWeights`, reopened - /// from its own store rows. - fn lens_history() -> (tempfile::TempDir, WorldKernel, crate::LensWeights) { - use crate::tests::{auth_principal, creation, owner, submit_owner}; - use crate::{Lens, LensWeights}; + /// A world whose history includes an owner's clock advance, reopened from + /// its own store rows. + fn clock_history() -> (tempfile::TempDir, WorldKernel) { + use crate::tests::{activate, auth_principal, creation, owner, submit_owner}; + use crate::TickMinutes; let directory = tempfile::tempdir().unwrap(); let (mut kernel, _) = WorldKernel::create( directory.path().join("world.cc"), - creation(CommandId::new(), "Lens History"), + creation(CommandId::new(), "Clock History"), &auth_principal(owner()), ) .unwrap(); - let replaced = LensWeights::new(BTreeMap::from([ - (Lens::Patina, 0), - (Lens::Charter, 4), - (Lens::Ledger, 1), - (Lens::Numen, 2), - ])); - let snapshot = kernel.snapshot().unwrap(); + let snapshot = activate(&mut kernel); submit_owner( &mut kernel, &snapshot, - CommandBody::SetLensWeights { - weights: replaced.clone(), + CommandBody::AdvanceTime { + minutes: TickMinutes::new(30).unwrap(), }, ); - (directory, kernel, replaced) + (directory, kernel) } fn rows_of(state: &WorldState, commits: &[WorldCommit]) -> Vec<CultCacheEnvelope> { @@ -1387,151 +1373,69 @@ mod tests { rows } - /// Replay re-derives the owner's weight change: the honest history reopens - /// to the same state digest and weights, and the store on disk does too. + /// Replay re-derives the owner's clock advance: the honest history reopens + /// to the same state digest and reading, and the store on disk does too. #[test] - fn a_history_with_a_lens_weight_change_replays_exactly() { - let (directory, kernel, replaced) = lens_history(); + fn a_history_with_an_owner_clock_advance_replays_exactly() { + let (directory, kernel) = clock_history(); let honest: Vec<WorldCommit> = kernel.journal.commits.values().cloned().collect(); let (_, replayed, commits) = recover(rows_of(&kernel.state, &honest), None).expect("the honest history replays"); assert_eq!(commits.len(), honest.len()); assert_eq!(replayed.state_digest, kernel.state.state_digest); - assert_eq!(replayed.lens_weights, replaced); + assert_eq!(replayed.now, kernel.state.now); - let (world_id, digest) = (kernel.state.world_id, kernel.state.state_digest.clone()); + let (world_id, digest, now) = + (kernel.state.world_id, kernel.state.state_digest.clone(), kernel.state.now); drop(kernel); let reopened = WorldKernel::open(directory.path().join("world.cc"), world_id).unwrap(); assert_eq!(reopened.state.state_digest, digest); - assert_eq!(reopened.state.lens_weights, replaced); + assert_eq!(reopened.state.now, now); } - /// A stored weight change is not believed about who made it or what it - /// wrote. Each forgery re-seals the whole store around its rewrite: the - /// head state takes the effect's weights, its state digest is recomputed, - /// the commit's resulting state digest and its own digest follow, and the - /// head's last commit digest names the re-sealed commit. No digest can - /// answer for the check, which the drawing control proves: the same - /// re-sealing around a set that draws replays. + /// A stored command is not believed about who made it. The forgery re-seals + /// the commit around its rewrite and the head's last commit digest names the + /// re-sealed commit, so no digest can answer for the check; the control, the + /// same re-sealing around the honest caller, replays. #[test] - fn a_forged_lens_weights_row_fails_replay() { + fn a_clock_advance_forged_to_another_caller_fails_replay() { use crate::tests::human_principal; - use crate::{Lens, LensWeights}; - let (_directory, kernel, _) = lens_history(); + let (_directory, kernel) = clock_history(); let honest: Vec<WorldCommit> = kernel.journal.commits.values().cloned().collect(); let forge = |rewrite: &dyn Fn(&mut WorldCommit)| -> (WorldState, Vec<WorldCommit>) { let mut head = kernel.state.clone(); let mut forged: Vec<WorldCommit> = honest.clone(); - let lens_row = forged + let clock_row = forged .iter_mut() - .filter(|commit| matches!(commit.effect, WorldEffect::LensWeightsReplaced { .. })) + .filter(|commit| matches!(commit.effect, WorldEffect::TimeAdvanced { .. })) .collect::<Vec<_>>(); - let [commit] = <[&mut WorldCommit; 1]>::try_from(lens_row) - .expect("the history holds exactly one lens weights row"); + let [commit] = <[&mut WorldCommit; 1]>::try_from(clock_row) + .expect("the history holds exactly one clock row"); assert_eq!( commit.resulting_revision, head.revision, - "the lens weights row is the head commit" + "the clock row is the head commit" ); rewrite(commit); - let WorldEffect::LensWeightsReplaced { weights } = &commit.effect else { - unreachable!("a lens weights row stays one"); - }; - head.lens_weights = weights.clone(); - head.state_digest = crate::state_digest(&head).unwrap(); - commit.resulting_state_digest = head.state_digest.clone(); commit.digest = commit_digest(commit).unwrap(); head.last_commit_digest = Some(commit.digest.clone()); - - // Every seal agrees with what it seals. - assert_eq!(crate::state_digest(&head).unwrap(), head.state_digest); - assert_eq!(commit_digest(commit).unwrap(), commit.digest); - assert_eq!(commit.resulting_state_digest, head.state_digest); - assert_eq!(head.last_commit_digest.as_deref(), Some(commit.digest.as_str())); (head, forged) }; - let set = |weights: LensWeights| { - move |commit: &mut WorldCommit| { - if let CommittedCommand::WorldCommand(command) = &mut commit.command { - command.body = CommandBody::SetLensWeights { - weights: weights.clone(), - }; - } - commit.effect = WorldEffect::LensWeightsReplaced { - weights: weights.clone(), - }; - } - }; - let refused = |(head, forged): (WorldState, Vec<WorldCommit>)| -> String { - let error = - recover(rows_of(&head, &forged), None).expect_err("a forged lens weights row replayed"); - let JournalError::Corrupt(detail) = error else { - panic!("unexpected refusal: {error:?}"); - }; - detail - }; - // The control: a re-sealed store around a different set that draws - // replays, so the re-sealing leaves nothing for a digest to catch. - let drawing = LensWeights::new(BTreeMap::from([(Lens::Veil, 2), (Lens::Ember, 1)])); - let (head, forged) = forge(&set(drawing.clone())); - let (_, replayed, _) = - recover(rows_of(&head, &forged), None).expect("a consistent re-sealed store replays"); - assert_eq!(replayed.lens_weights, drawing); + let (head, control) = forge(&|_| {}); + recover(rows_of(&head, &control), None).expect("a consistent re-sealed store replays"); - // A non-owner principal with a live approver role in this world. - let detail = refused(forge(&|commit| { + let (head, forged) = forge(&|commit| { if let CommittedCommand::WorldCommand(command) = &mut commit.command { command.caller = CallerId::Principal(human_principal()); } - })); - assert!(detail.contains("Unauthorized") || detail.contains("does not own"), "{detail}"); - // The clock capability. - let detail = refused(forge(&|commit| { - if let CommittedCommand::WorldCommand(command) = &mut commit.command { - command.caller = CallerId::System(crate::SystemCapability::Clock); - } - })); - assert!(detail.contains("Unauthorized") || detail.contains("does not own"), "{detail}"); - // Every lens named, all at zero, in the command, its effect and the - // head: only the draw rule is left to refuse it. - let never = LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 0)).collect()); - let detail = refused(forge(&set(never))); - assert!( - detail.contains("never draw") || detail.contains("LensWeightsNeverDraw"), - "something other than the draw rule refused the all-zero row: {detail}" - ); - } - - /// The third statement of the draw rule: a state row whose weights never - /// draw is refused by the shape check itself, not only by replay. - #[test] - fn a_state_row_whose_lens_weights_never_draw_is_refused() { - use crate::{Lens, LensWeights}; - - let (_directory, kernel, _) = lens_history(); - let mut forged = kernel.state.clone(); - forged.lens_weights = - LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 0)).collect()); - let JournalError::Corrupt(detail) = - verify_state_shape(&forged).expect_err("an all-zero weight set passed the shape check") - else { - unreachable!("the shape check only reports corruption") + }); + let error = recover(rows_of(&head, &forged), None) + .expect_err("a clock advance forged to a non-owner replayed"); + let JournalError::Corrupt(detail) = error else { + panic!("unexpected refusal: {error:?}"); }; - assert!(detail.contains("lens weights"), "unexpected refusal: {detail}"); - - forged.lens_weights = LensWeights::default(); - assert!(verify_state_shape(&forged).is_err()); - assert!(verify_state_shape(&kernel.state).is_ok()); - - let commits: Vec<WorldCommit> = kernel.journal.commits.values().cloned().collect(); - let mut zeroed = kernel.state.clone(); - zeroed.lens_weights = - LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 0)).collect()); - assert!(matches!( - recover(rows_of(&zeroed, &commits), None), - Err(JournalError::Corrupt(_)) - )); + assert!(detail.contains("Unauthorized") || detail.contains("does not own"), "{detail}"); } /// The tick is re-derived at replay by the same function that produced it, @@ -1764,7 +1668,6 @@ mod tests { let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); let creation_id = CommandId::new(); let creation = CreateWorld { - lens_weights: crate::tests::stock_weights(), id: creation_id, owner: owner.clone(), title: "Admitted".into(), diff --git a/native/aetherlight/src/lens.rs b/native/aetherlight/src/lens.rs deleted file mode 100644 index ae3f39a8a..000000000 --- a/native/aetherlight/src/lens.rs +++ /dev/null @@ -1,361 +0,0 @@ -//! The stock lenses. A lens is the flavor an elaborator session reaches for: -//! prompt emphasis over the one fixed tool catalog, never admission, authority, -//! or quota. This module owns the stock table, each lens's instruction text, -//! and the draw recipe; it reads no world state and writes nothing. - -use super::{CommandId, KernelError, WorldId, digest}; -use serde::{Deserialize, Serialize}; -use std::collections::BTreeMap; - -/// The sentence every lens's instructions begin with. -const ELABORATION_INSTRUCTIONS: &str = "Use only the supplied tools to author structure inside your jurisdiction. Answer the boundary or deficit you were given, then submit. Recording a gap changes nothing."; - -/// The library's stock lens set. Serialized by snake_case name, so a name the -/// library does not know cannot be represented at any deserialization boundary. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum Lens { - Patina, - Charter, - Ledger, - Hearth, - Tangle, - Veil, - Ember, - Numen, -} - -impl Lens { - /// Every lens, in declaration order. The draw walks this order. - pub const ALL: [Lens; 8] = [ - Lens::Patina, - Lens::Charter, - Lens::Ledger, - Lens::Hearth, - Lens::Tangle, - Lens::Veil, - Lens::Ember, - Lens::Numen, - ]; - - pub fn name(self) -> &'static str { - match self { - Lens::Patina => "Patina", - Lens::Charter => "Charter", - Lens::Ledger => "Ledger", - Lens::Hearth => "Hearth", - Lens::Tangle => "Tangle", - Lens::Veil => "Veil", - Lens::Ember => "Ember", - Lens::Numen => "Numen", - } - } - - /// What kind of structure the lens reaches for. - pub(crate) fn reaches_for(self) -> &'static str { - match self { - Lens::Patina => "ordinary objects, customs, nicknames, local jokes", - Lens::Charter => "government, law, offices, selection, succession, redress", - Lens::Ledger => "resources, labor, trade, infrastructure, scarcity, class pressure", - Lens::Hearth => "kinship, daily life, care, obligation, belonging", - Lens::Tangle => "factions, alliances, rivalries, leverage", - Lens::Veil => "secrets, rumors, misinformation, taboos, unevenly held knowledge", - Lens::Ember => "disputes, hazards, instability, escalation, urgent pressure", - Lens::Numen => "religion, magic, ritual, awe, cosmology, the genuinely strange", - } - } - - /// Existing patch tool names in emphasis order. Emphasis is prompt text - /// only: the catalog, its order, and its schemas are the same for every lens. - pub(crate) fn leads_with(self) -> &'static [&'static str] { - match self { - Lens::Patina => &[ - "set_persona_material", - "declare_affordance", - "declare_resource", - "declare_place", - ], - Lens::Charter => &[ - "grant_authority", - "open_office", - "install_incumbent", - "open_forum", - "declare_subject", - ], - Lens::Ledger => &[ - "transfer", - "bind", - "declare_resource", - "alter_cost", - "declare_route", - ], - Lens::Hearth => &[ - "create_commitment", - "set_persona_material", - "declare_subject", - ], - Lens::Tangle => &[ - "advance_pressure", - "create_commitment", - "grant_authority", - "declare_subject", - "bind", - ], - Lens::Veil => &[ - "acquire_knowledge", - "communicate", - "declare_channel", - "set_reach", - "declare_fact", - "forget", - ], - Lens::Ember => &[ - "advance_pressure", - "create_commitment", - "close_route", - "consume", - ], - Lens::Numen => &[ - "declare_fact", - "declare_affordance", - "set_persona_material", - "witness", - ], - } - } - - /// The elaborator's instructions under this lens: the shared sentence, then - /// the lens clause. Read once, when a session is first built; the session - /// then carries the text, and nothing rebuilds it from here. - pub(crate) fn instructions(self) -> String { - format!( - "{ELABORATION_INSTRUCTIONS} Lens: {}. Reach for {}. Lead with {}; every supplied tool remains available.", - self.name(), - self.reaches_for(), - self.leads_with().join(", "), - ) - } -} - -/// A world's lens weights. Validity is decided where weights are admitted; -/// `Default` is the empty map a world holds before genesis writes its weights, -/// and it never draws. -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(transparent)] -pub struct LensWeights(BTreeMap<Lens, u32>); - -impl LensWeights { - pub fn new(weights: BTreeMap<Lens, u32>) -> Self { - Self(weights) - } - - /// A lens the map does not name weighs zero. - pub fn get(&self, lens: Lens) -> u32 { - self.0.get(&lens).copied().unwrap_or(0) - } - - pub fn iter(&self) -> impl Iterator<Item = (Lens, u32)> + '_ { - self.0.iter().map(|(lens, weight)| (*lens, *weight)) - } - - /// Some weight is nonzero, so a draw has somewhere to land. - pub(crate) fn draws(&self) -> bool { - self.0.values().any(|weight| *weight > 0) - } - - /// Every stock lens weighs the same in both sets. A lens a map does not - /// name weighs zero, so `{charter: 3}` and `{patina: 0, charter: 3}` are - /// one set spelled two ways: they draw identically and neither replaces - /// the other. - pub(crate) fn weighs_the_same_as(&self, other: &LensWeights) -> bool { - Lens::ALL - .into_iter() - .all(|lens| self.get(lens) == other.get(lens)) - } -} - -/// The draw's whole input: the world and the session's fixed identity. The -/// weights select over it; they are not part of it. -#[derive(Serialize)] -struct LensPreimage { - world_id: WorldId, - command_id: CommandId, -} - -/// One digest, one modulo, one cumulative walk over `Lens::ALL` — the recipe -/// `select_band` uses, not a second entropy shape. The same world, session -/// identity, and weights draw the same lens. Modulo rather than rejection -/// sampling: the bias is bounded by `total_weight / 2^64`. -pub(crate) fn draw( - weights: &LensWeights, - world_id: WorldId, - command_id: CommandId, -) -> Result<Lens, KernelError> { - // The guard is on the divisor itself, as `select_band`'s is: no other - // statement of "these weights draw" can let the modulo below divide by zero. - let total: u128 = Lens::ALL - .iter() - .map(|lens| u128::from(weights.get(*lens))) - .sum(); - if total == 0 { - return Err(KernelError::Invariant("lens weights never draw".into())); - } - let preimage = digest(&LensPreimage { - world_id, - command_id, - })?; - let head = preimage - .strip_prefix("sha256:") - .and_then(|hex| hex.get(..16)) - .and_then(|head| u64::from_str_radix(head, 16).ok()) - .ok_or_else(|| KernelError::Invariant("lens draw digest is not hex".into()))?; - let mut position = u128::from(head) % total; - for lens in Lens::ALL { - let weight = u128::from(weights.get(lens)); - if position < weight { - return Ok(lens); - } - position -= weight; - } - Err(KernelError::Invariant( - "lens weights did not cover the draw".into(), - )) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::tests::stock_weights; - use std::collections::BTreeSet; - - fn ids() -> Vec<CommandId> { - (0..200) - .map(|i| CommandId::derived("l1-probe", &[&i.to_string()])) - .collect() - } - - fn tally(weights: &LensWeights) -> BTreeMap<Lens, usize> { - let mut counts = BTreeMap::new(); - for id in ids() { - let lens = draw(weights, WorldId::nil_for_test(), id).unwrap(); - *counts.entry(lens).or_insert(0) += 1; - } - counts - } - - #[test] - fn the_draw_is_a_function_of_world_and_session() { - let weights = stock_weights(); - let world = WorldId::nil_for_test(); - for id in ids() { - assert_eq!( - draw(&weights, world, id).unwrap(), - draw(&weights, world, id).unwrap() - ); - } - let expected: BTreeMap<Lens, usize> = BTREE_STOCK_TALLY.into_iter().collect(); - assert_eq!(tally(&weights), expected); - } - - /// Computed at Cut 1 and pinned: the replay proof for 200 derived ids under - /// stock weights. - const BTREE_STOCK_TALLY: [(Lens, usize); 8] = [ - (Lens::Patina, 22), - (Lens::Charter, 37), - (Lens::Ledger, 26), - (Lens::Hearth, 19), - (Lens::Tangle, 23), - (Lens::Veil, 29), - (Lens::Ember, 18), - (Lens::Numen, 26), - ]; - - #[test] - fn a_zero_weight_never_draws() { - let weights = LensWeights::new(BTreeMap::from([ - (Lens::Patina, 0), - (Lens::Charter, 3), - (Lens::Ledger, 1), - ])); - let counts = tally(&weights); - assert_eq!(counts.get(&Lens::Patina), None, "a zero weight drew"); - let expected: BTreeMap<Lens, usize> = ZERO_WEIGHT_TALLY.into_iter().collect(); - assert_eq!(counts, expected); - } - - /// Computed at Cut 1 and pinned; near 3:1 over the same 200 ids. - const ZERO_WEIGHT_TALLY: [(Lens, usize); 2] = [(Lens::Charter, 155), (Lens::Ledger, 45)]; - - #[test] - fn all_zero_weights_are_an_error() { - let world = WorldId::nil_for_test(); - let id = CommandId::derived("l1-probe", &["0"]); - let all_zero = LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 0)).collect()); - assert_eq!(all_zero.iter().count(), 8); - for weights in [LensWeights::default(), all_zero] { - assert!(matches!( - draw(&weights, world, id), - Err(KernelError::Invariant(_)) - )); - } - } - - #[test] - fn an_unknown_lens_name_does_not_deserialize() { - for refused in [ - r#"{"Patina":1}"#, - r#"{"patina ":1}"#, - r#"{"patinaa":1}"#, - r#"{"patina":1,"tribunal":1}"#, - ] { - assert!( - serde_json::from_str::<LensWeights>(refused).is_err(), - "{refused} deserialized" - ); - } - let accepted = serde_json::from_str::<LensWeights>(r#"{"patina":1}"#).unwrap(); - assert_eq!(accepted.get(Lens::Patina), 1); - assert_eq!(accepted.iter().count(), 1); - - let stock = stock_weights(); - let bytes = rmp_serde::to_vec_named(&stock).unwrap(); - let back: LensWeights = rmp_serde::from_slice(&bytes).unwrap(); - assert_eq!(back, stock); - assert_eq!(rmp_serde::to_vec_named(&back).unwrap(), bytes); - } - - #[test] - fn each_lens_text_names_its_own_leads() { - let mut texts = BTreeSet::new(); - for lens in Lens::ALL { - let text = lens.instructions(); - assert!(text.contains(lens.name()), "{lens:?} text omits its name"); - for name in lens.leads_with() { - assert!(text.contains(name), "{lens:?} text omits {name}"); - } - texts.insert(text); - } - assert_eq!(texts.len(), 8, "two lenses share a text"); - } - - #[test] - fn lenses_serialize_as_snake_case_names() { - let names: Vec<String> = Lens::ALL - .iter() - .map(|lens| serde_json::to_string(lens).unwrap()) - .collect(); - assert_eq!( - names, - [ - r#""patina""#, - r#""charter""#, - r#""ledger""#, - r#""hearth""#, - r#""tangle""#, - r#""veil""#, - r#""ember""#, - r#""numen""#, - ] - ); - } -} diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index 074a1b03d..b8869262c 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -61,7 +61,6 @@ mod grammar; #[cfg(test)] mod import_key_tests; mod journal; -mod lens; mod patch; pub(crate) use action::ActionMismatch; @@ -72,7 +71,6 @@ pub use grammar::{ GrammarBinding, GrammarError, GrammarIdentity, GrammarReferentKind, GrammarRole, GrammarVerb, RenderPath, }; -pub use lens::{Lens, LensWeights}; pub use patch::{ CommitmentKey, DraftHandle, JurisdictionKey, Mismatch, PatchAnswer, Ref, RefKind, RefName, Role, Site, Statement, WorldPatch, @@ -390,9 +388,6 @@ struct CreateWorld { /// Authored once, here, and never mutated: `CommandBody::AdmitPatch` carries /// no intent, so write-once is the command shape rather than a check. scale_intent: WorldScaleIntentRef, - /// The world's flavor as genesis writes it. `SetLensWeights` may replace - /// it later; this command carries what the world began with. - lens_weights: LensWeights, /// The grammar the world is bound to for its whole life, or none for an /// open-catalog world. Authored here and nowhere else: genesis installs it. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -418,9 +413,6 @@ pub struct CreateWorldIntent { /// The jurisdiction roots genesis declares beside the commons, because /// `resolve_patch` only resolves roots the same patch declares. pub jurisdictions: Vec<CreateJurisdictionIntent>, - /// Required. The library holds no default weights; a consumer states the - /// world's flavor or is refused. - pub lens_weights: LensWeights, } /// One jurisdiction root as ingress states it. The handle is a string here and @@ -666,15 +658,6 @@ pub enum CommandBody { AdvanceTime { minutes: TickMinutes, }, - /// Replaces the world's whole lens weight set. Owner only, in any phase, - /// under genesis admission: a set that never draws is refused, and a zero - /// weight is admitted and never draws. A set that weighs every lens as - /// the current one does, however its map is spelled, changes nothing - /// canonical and is refused with `NoCanonicalChange` after admission, so - /// nothing commits. A session that already drew keeps its recorded lens. - SetLensWeights { - weights: LensWeights, - }, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] @@ -865,10 +848,6 @@ struct WorldState { now: FictionalMinutes, /// The authored scale target, written once by genesis and never mutated. scale_intent: WorldScaleIntent, - /// Written by genesis and replaced only by `SetLensWeights`; read by the - /// elaborator's draw and by nothing that admits. It enters `state_digest` - /// and no `ScopePreimage`. - lens_weights: LensWeights, controller_assignments: BTreeMap<DecisionScope, ControllerAssignment>, /// What an affordance *is*. World-authored, Draft-only, written by /// `admit_resolved` alone. @@ -920,11 +899,6 @@ enum WorldEffect { to: FictionalMinutes, motion: Motion, }, - /// The owner replaced the world's lens weights. `apply_effect` re-decides - /// the owner and the draw rule. - LensWeightsReplaced { - weights: LensWeights, - }, } /// The exact raw command admitted by the world owner. This is the sole @@ -1211,7 +1185,6 @@ pub struct WorldSnapshot { /// commitment gazetteer. pub boundaries: Vec<CausalBoundary>, pub scale_deficit: Vec<ScaleDeficitRow>, - pub lens_weights: LensWeights, pub state_digest: String, pub last_commit_digest: Option<String>, } @@ -1437,7 +1410,6 @@ fn prepare_creation( input.id, &input.patch, Some(&input.scale_intent), - Some(&input.lens_weights), ) .map_err(KernelError::PatchRejected)?; require_ruler(&CallerId::Principal(input.owner.clone()), &resolved) @@ -1799,7 +1771,7 @@ fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result<WorldEffect, !(patch.declarations.is_empty() && patch.evidence.is_empty()), )?; let confinement = require_patch_author(state, &command.caller, answers.as_ref())?; - let resolved = patch::resolve_patch(state, command.id, patch, None, None) + let resolved = patch::resolve_patch(state, command.id, patch, None) .map_err(KernelError::PatchRejected)?; require_ruler(&command.caller, &resolved).map_err(KernelError::PatchRejected)?; if let Some(ground) = confinement { @@ -1810,25 +1782,6 @@ fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result<WorldEffect, resolved, }) } - CommandBody::SetLensWeights { weights } => { - require_owner(state, &command.caller)?; - if !weights.draws() { - return Err(KernelError::PatchRejected(vec![ - Mismatch::LensWeightsNeverDraw, - ])); - } - // Admission first, then effect: a caller who may not set weights, - // or a set that never draws, is refused as such even when it - // equals the current set. Only an admitted set can be a no-op. - if weights.weighs_the_same_as(&state.lens_weights) { - return Err(KernelError::PatchRejected(vec![ - Mismatch::NoCanonicalChange, - ])); - } - Ok(WorldEffect::LensWeightsReplaced { - weights: weights.clone(), - }) - } } } @@ -1974,9 +1927,6 @@ impl WorldState { last_opportunity_at: BTreeMap::new(), now: FictionalMinutes::default(), scale_intent: WorldScaleIntent::default(), - // Never persisted: genesis overwrites it, and `verify_state_shape` - // refuses a stored set that never draws. - lens_weights: LensWeights::default(), controller_assignments: BTreeMap::new(), affordance_catalog: BTreeMap::new(), affordance_grants: BTreeMap::new(), @@ -2019,7 +1969,6 @@ impl WorldState { command.id, &command.patch, Some(&command.scale_intent), - Some(&command.lens_weights), ) .map_err(KernelError::PatchRejected)?; if &expected != resolved { @@ -2296,9 +2245,6 @@ fn admit_resolved( if let Some(intent) = &resolved.scale_intent { state.scale_intent = intent.clone(); } - if let Some(weights) = &resolved.lens_weights { - state.lens_weights = weights.clone(); - } apply_operations(state, &resolved.operations, &resolved.evidence, resolves_to) } @@ -4217,7 +4163,6 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> { now: state.now, boundaries: derive_boundaries(state)?, scale_deficit: derive_scale_deficit(state)?, - lens_weights: state.lens_weights.clone(), state_digest: state.state_digest.clone(), last_commit_digest: state.last_commit_digest.clone(), }) @@ -5482,14 +5427,6 @@ fn apply_effect( .insert(written.source, written.magnitude); } } - WorldEffect::LensWeightsReplaced { weights } => { - if caller != &CallerId::Principal(state.owner.clone()) || !weights.draws() { - return Err(KernelError::Invariant( - "lens weights effect does not satisfy owner admission".into(), - )); - } - state.lens_weights = weights.clone(); - } } Ok(()) } @@ -5595,11 +5532,6 @@ mod tests { .expect("the fixture world declares this affordance") } - /// Every stock lens at weight one. - pub(crate) fn stock_weights() -> LensWeights { - LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 1)).collect()) - } - pub(crate) fn creation(id: CommandId, title: &str) -> CreateWorld { CreateWorld { id, @@ -5664,7 +5596,6 @@ mod tests { ], }, scale_intent: WorldScaleIntentRef::default(), - lens_weights: stock_weights(), grammar: None, } } @@ -8899,7 +8830,6 @@ mod custody_tests { let mut candidate = kernel.state.clone(); let forged = WorldEffect::PatchAdmitted { resolved: ResolvedPatch { - lens_weights: None, subjects: Vec::new(), entities: Vec::new(), routes: Vec::new(), @@ -9495,7 +9425,6 @@ mod custody_tests { let forge = |operations: Vec<ResolvedOp>| WorldEffect::PatchAdmitted { resolved: ResolvedPatch { - lens_weights: None, subjects: Vec::new(), entities: Vec::new(), routes: Vec::new(), @@ -12210,7 +12139,6 @@ mod witness_tests { evidence: Vec::new(), }, None, - None, ) .expect("the witness resolves over committed state"); for ground in [ @@ -15271,7 +15199,7 @@ mod clock_tests { panic!("the operations helper builds an admitted patch"); }; let resolved = - patch::resolve_patch(&kernel.state, CommandId::new(), patch, None, None).expect("resolves"); + patch::resolve_patch(&kernel.state, CommandId::new(), patch, None).expect("resolves"); assert!( resolved.scale_intent.is_none(), "an Active patch resolved a scale intent" @@ -15281,54 +15209,6 @@ mod clock_tests { assert_eq!(kernel.state.scale_intent, authored); } - // ---- lens weights: world data, genesis, and the owner command -------- - - fn every_lens_at_zero() -> LensWeights { - LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 0)).collect()) - } - - #[test] - fn genesis_writes_the_lens_weights_it_was_given() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let given = LensWeights::new(BTreeMap::from([(Lens::Patina, 2), (Lens::Numen, 1)])); - let mut input = creation(CommandId::new(), "Flavored"); - input.lens_weights = given.clone(); - let (kernel, _) = WorldKernel::create(&path, input, &auth_principal(owner())).unwrap(); - let created = kernel.snapshot().unwrap(); - assert_eq!(created.lens_weights, given); - assert_eq!(kernel.state.lens_weights, given); - - let world_id = created.world_id; - drop(kernel); - let replayed = WorldKernel::open(&path, world_id).unwrap(); - assert_eq!(replayed.snapshot().unwrap(), created); - assert_eq!(replayed.state.state_digest, created.state_digest); - } - - #[test] - fn a_genesis_lens_set_that_never_draws_is_refused() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let mut input = creation(CommandId::new(), "Flavorless"); - input.lens_weights = every_lens_at_zero(); - let Err(error) = WorldKernel::create(&path, input, &auth_principal(owner())) else { - panic!("a genesis lens set that never draws was admitted"); - }; - let KernelError::PatchRejected(mismatches) = error else { - panic!("expected a rejected genesis patch, got {error:?}"); - }; - assert_eq!(mismatches, vec![Mismatch::LensWeightsNeverDraw]); - assert!(!path.exists(), "a refused genesis wrote a world file"); - - // The same creation with one real weight among the zeros is admitted. - let mut input = creation(CommandId::new(), "Flavorless"); - let mut weights = BTreeMap::from_iter(every_lens_at_zero().iter()); - weights.insert(Lens::Veil, 1); - input.lens_weights = LensWeights::new(weights); - WorldKernel::create(&path, input, &auth_principal(owner())).expect("one nonzero weight"); - } - // ---- PA.f26: the genesis lane obeys `require_ruler` too ------------ /// PA.f26: `prepare_creation` and `WorldState::genesis` both call @@ -15415,7 +15295,6 @@ mod clock_tests { input.id, &input.patch, Some(&input.scale_intent), - Some(&input.lens_weights), ) .expect("the resolver is actor-blind and accepts a Ruled fact"); let effect = WorldEffect::WorldCreated { @@ -15444,7 +15323,6 @@ mod clock_tests { input.id, &input.patch, Some(&input.scale_intent), - Some(&input.lens_weights), ) .expect("the resolver is actor-blind and accepts a Mint"); let effect = WorldEffect::WorldCreated { @@ -15457,223 +15335,6 @@ mod clock_tests { assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); } - /// Soul falsification, the lens twin of the scale intent's write-once - /// test: an Active patch resolves no weights; only the owner's - /// `SetLensWeights` replaces them, in Draft and in Active; every other - /// caller is `Unauthorized`; a set that never draws is refused; and - /// `apply_effect` re-decides the owner against a hand-built effect. - #[test] - fn soul_the_lens_weights_are_replaced_only_by_the_owner_command() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, _) = WorldKernel::create( - directory.path().join("world.cc"), - creation(CommandId::new(), "Owner Flavor"), - &auth_principal(owner()), - ) - .unwrap(); - let draft_weights = LensWeights::new(BTreeMap::from([ - (Lens::Patina, 0), - (Lens::Charter, 3), - (Lens::Ledger, 1), - ])); - let draft = kernel.snapshot().unwrap(); - submit_owner( - &mut kernel, - &draft, - CommandBody::SetLensWeights { - weights: draft_weights.clone(), - }, - ); - assert_eq!(kernel.state.revision, draft.revision + 1); - assert_eq!(kernel.state.lens_weights, draft_weights); - - let active = activate(&mut kernel); - let active_weights = LensWeights::new(BTreeMap::from([ - (Lens::Hearth, 5), - (Lens::Tangle, 0), - (Lens::Ember, 2), - ])); - submit_owner( - &mut kernel, - &active, - CommandBody::SetLensWeights { - weights: active_weights.clone(), - }, - ); - assert_eq!(kernel.state.revision, active.revision + 1); - assert_eq!(kernel.state.lens_weights, active_weights); - - // An Active patch is handed no weights, so it cannot resolve any. - let resolved = patch::resolve_patch( - &kernel.state, - CommandId::new(), - &operations_patch(&kernel), - None, - None, - ) - .expect("resolves"); - assert!(resolved.lens_weights.is_none(), "an Active patch resolved lens weights"); - let after_patch = kernel.snapshot().unwrap(); - let patch = operations_patch(&kernel); - submit_owner( - &mut kernel, - &after_patch, - CommandBody::AdmitPatch { - answers: None, - patch, - }, - ); - assert_eq!(kernel.state.lens_weights, active_weights); - - // Every caller but the owner, with real weights. - let proposed = super::tests::stock_weights(); - let before = kernel.state.clone(); - for caller in [ - CallerId::Principal(human_principal()), - CallerId::Principal(PrincipalId::new("stranger@example.test")), - elaborator(JurisdictionKey::Uncovered), - CallerId::System(SystemCapability::Clock), - CallerId::System(SystemCapability::Consumer { - consumer: ConsumerId::of_name("lens-consumer"), - }), - ] { - let result = submit_as( - &mut kernel, - caller.clone(), - CommandBody::SetLensWeights { - weights: proposed.clone(), - }, - ); - assert!( - matches!(result, Err(KernelError::Unauthorized)), - "{caller:?} replaced the lens weights: {result:?}" - ); - } - assert_eq!(kernel.state, before); - - // The owner, with every lens named at zero. - let result = submit_as( - &mut kernel, - CallerId::Principal(owner()), - CommandBody::SetLensWeights { - weights: every_lens_at_zero(), - }, - ); - let Err(KernelError::PatchRejected(mismatches)) = result else { - panic!("a lens set that never draws was admitted: {result:?}"); - }; - assert_eq!(mismatches, vec![Mismatch::LensWeightsNeverDraw]); - assert_eq!(kernel.state, before); - - // The owner, with valid weights, against the revision before the - // last commit. - let stale = command( - &draft, - CommandId::new(), - CallerId::Principal(owner()), - CommandBody::SetLensWeights { - weights: proposed.clone(), - }, - ); - assert!(matches!( - kernel.submit(stale, &auth_principal(owner())), - Err(KernelError::RevisionMismatch { .. }) - )); - assert_eq!(kernel.state, before); - - // `apply_effect` re-decides: a hand-built effect under a non-owner or - // a system caller never applies, and neither does one that never draws. - for (caller, weights) in [ - (CallerId::Principal(human_principal()), proposed.clone()), - (CallerId::System(SystemCapability::Clock), proposed.clone()), - (CallerId::Principal(owner()), every_lens_at_zero()), - ] { - let mut candidate = kernel.state.clone(); - let error = apply_effect( - &mut candidate, - CommandId::new(), - &caller, - &WorldEffect::LensWeightsReplaced { weights }, - ) - .unwrap_err(); - assert!( - matches!( - error, - KernelError::Invariant(_) | KernelError::Unauthorized - ), - "{caller:?}: {error:?}" - ); - assert_eq!(candidate, kernel.state); - } - // The honest effect applies through the same arm. - let mut candidate = kernel.state.clone(); - apply_effect( - &mut candidate, - CommandId::new(), - &CallerId::Principal(owner()), - &WorldEffect::LensWeightsReplaced { - weights: proposed.clone(), - }, - ) - .expect("the owner's effect applies"); - assert_eq!(candidate.lens_weights, proposed); - - // Identical weights from the owner change nothing canonical: refused - // as `NoCanonicalChange`, and nothing commits. - let result = submit_as( - &mut kernel, - CallerId::Principal(owner()), - CommandBody::SetLensWeights { - weights: active_weights.clone(), - }, - ); - let Err(KernelError::PatchRejected(mismatches)) = result else { - panic!("identical lens weights were admitted: {result:?}"); - }; - assert_eq!(mismatches, vec![Mismatch::NoCanonicalChange]); - assert_eq!(kernel.state, before); - - // The order is admission, then effect. Identical weights from a - // non-owner are `Unauthorized`; and against a state whose own set - // never draws (no store holds one, so the state is built by hand), an - // identical all-zero set is `LensWeightsNeverDraw`, not a no-op. - let result = submit_as( - &mut kernel, - CallerId::Principal(human_principal()), - CommandBody::SetLensWeights { - weights: active_weights.clone(), - }, - ); - assert!( - matches!(result, Err(KernelError::Unauthorized)), - "a non-owner's identical set: {result:?}" - ); - assert_eq!(kernel.state, before); - let mut never = kernel.state.clone(); - never.lens_weights = every_lens_at_zero(); - let current = kernel.snapshot().unwrap(); - let identical_zero = command( - ¤t, - CommandId::new(), - CallerId::Principal(owner()), - CommandBody::SetLensWeights { - weights: every_lens_at_zero(), - }, - ); - let result = reduce(&never, &identical_zero); - let Err(KernelError::PatchRejected(mismatches)) = result else { - panic!("an identical set that never draws: {result:?}"); - }; - assert_eq!(mismatches, vec![Mismatch::LensWeightsNeverDraw]); - - // Replay across that history is unchanged: the refused attempts wrote - // nothing, and the store reopens to the same head. - let (path, world_id) = (directory.path().join("world.cc"), kernel.state.world_id); - drop(kernel); - let reopened = WorldKernel::open(path, world_id).expect("the history reopens"); - assert_eq!(reopened.state, before); - } - /// An owner commit that adds a commitment to the first person: a real /// Active patch with no answer, and nothing to do with lenses. fn operations_patch(kernel: &WorldKernel) -> WorldPatch { @@ -15698,46 +15359,6 @@ mod clock_tests { patch } - #[test] - fn lens_weights_enter_the_state_digest_and_no_scope_digest() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, _) = WorldKernel::create( - directory.path().join("world.cc"), - creation(CommandId::new(), "Digest Flavor"), - &auth_principal(owner()), - ) - .unwrap(); - let active = activate(&mut kernel); - - let mut other = kernel.state.clone(); - other.lens_weights = - LensWeights::new(BTreeMap::from([(Lens::Patina, 1), (Lens::Veil, 7)])); - assert_ne!( - state_digest(&other).unwrap(), - state_digest(&kernel.state).unwrap(), - "lens weights did not enter the state digest" - ); - - let digests = |kernel: &WorldKernel| -> BTreeMap<SubjectId, ScopeDigest> { - derive_opportunities(&kernel.state) - .unwrap() - .into_iter() - .map(|opportunity| (opportunity.scope.subject_id, opportunity.scope_digest)) - .collect() - }; - let before = digests(&kernel); - assert!(!before.is_empty(), "the active fixture derives opportunities"); - submit_owner( - &mut kernel, - &active, - CommandBody::SetLensWeights { - weights: other.lens_weights.clone(), - }, - ); - assert_ne!(kernel.state.state_digest, active.state_digest); - assert_eq!(digests(&kernel), before, "lens weights entered a scope digest"); - } - /// Soul falsification: a discharge names one subject's own live key. #[test] fn soul_discharging_a_foreign_or_already_discharged_commitment_is_refused() { @@ -16385,7 +16006,6 @@ mod clock_tests { command_id, &shed_under(clockwork.dead_end, "shed"), None, - None, ) .expect("the patch resolves"); let effect = WorldEffect::PatchAdmitted { @@ -17532,7 +17152,7 @@ mod clock_tests { }], evidence: Vec::new(), }; - let resolved = patch::resolve_patch(&kernel.state, command_id, &patch, None, None) + let resolved = patch::resolve_patch(&kernel.state, command_id, &patch, None) .expect("the patch resolves; the resolver is actor-blind"); let effect = WorldEffect::PatchAdmitted { answers: Some(PatchAnswer::Boundary(answered)), @@ -17569,7 +17189,7 @@ mod clock_tests { let answered = dead_end_boundary(&kernel); let command_id = CommandId::issue(); let patch = ruled_fact_patch("rule"); - let resolved = patch::resolve_patch(&kernel.state, command_id, &patch, None, None) + let resolved = patch::resolve_patch(&kernel.state, command_id, &patch, None) .expect("the patch resolves; the resolver is actor-blind"); let effect = WorldEffect::PatchAdmitted { answers: Some(PatchAnswer::Boundary(answered)), diff --git a/native/aetherlight/src/patch.rs b/native/aetherlight/src/patch.rs index 06f4dd936..583713a79 100644 --- a/native/aetherlight/src/patch.rs +++ b/native/aetherlight/src/patch.rs @@ -14,7 +14,7 @@ use super::clock::{FictionalMinutes, TickMinutes}; use super::grammar::GrammarRefusal; use super::{ - AffordanceId, CommandId, ControllerAssignment, ControllerId, EdgeId, EntityId, LensWeights, + AffordanceId, CommandId, ControllerAssignment, ControllerId, EdgeId, EntityId, NewController, SubjectId, SubjectKind, SubjectState, WorldId, }; use serde::{Deserialize, Serialize}; @@ -1737,9 +1737,6 @@ pub enum Mismatch { /// The permille weights sum over 1000: weights distribute the target and /// never raise it. ScaleWeightsExceedWhole, - /// A lens weight set with no nonzero weight, at genesis or in - /// `SetLensWeights`. A single zero weight is admitted and never draws. - LensWeightsNeverDraw, /// A jurisdictional author wrote outside its jurisdiction. The owner is /// unconfined and never sees this. OutsideJurisdiction { @@ -2141,9 +2138,6 @@ pub(super) struct ResolvedPatch { /// carries no intent, so the write-once rule is the command shape rather /// than a check. pub(super) scale_intent: Option<WorldScaleIntent>, - /// `Some` on the genesis lane and nowhere else, as `scale_intent` is. After - /// genesis the weights change only through `SetLensWeights`. - pub(super) lens_weights: Option<LensWeights>, } impl ResolvedPatch { @@ -3219,7 +3213,6 @@ pub(super) fn resolve_patch( command_id: CommandId, patch: &WorldPatch, scale_intent: Option<&WorldScaleIntentRef>, - lens_weights: Option<&LensWeights>, ) -> Result<ResolvedPatch, Vec<Mismatch>> { let world_id = state.world_id; let admits_human = super::admits_human(state.revision, &state.subjects); @@ -5151,12 +5144,6 @@ pub(super) fn resolve_patch( } } - if let Some(weights) = lens_weights - && !weights.draws() - { - mismatches.push(Mismatch::LensWeightsNeverDraw); - } - if patch.declarations.is_empty() && patch.operations.is_empty() { mismatches.push(Mismatch::NoCanonicalChange); } @@ -5854,7 +5841,6 @@ pub(super) fn resolve_patch( }) .collect(), }), - lens_weights: lens_weights.cloned(), }) } @@ -7378,8 +7364,8 @@ mod tests { assert_ne!(admitted, genesis_human); let command_id = CommandId::new(); - let first = resolve_patch(&kernel.state, command_id, &patch, None, None).unwrap(); - let second = resolve_patch(&kernel.state, command_id, &patch, None, None).unwrap(); + let first = resolve_patch(&kernel.state, command_id, &patch, None).unwrap(); + let second = resolve_patch(&kernel.state, command_id, &patch, None).unwrap(); assert_eq!(first, second); } @@ -7522,7 +7508,7 @@ mod tests { Some(Ref::Draft(DraftHandle::new("rhythm-road"))), ), ]); - let resolved = resolve_patch(&kernel.state, CommandId::new(), &patch, None, None).unwrap(); + let resolved = resolve_patch(&kernel.state, CommandId::new(), &patch, None).unwrap(); let honest = super::super::WorldEffect::PatchAdmitted { resolved: resolved.clone(), answers: None, @@ -7726,7 +7712,6 @@ mod tests { for edge_id in [topology.span, topology.shutter, topology.toll] { let forged = super::super::WorldEffect::PatchAdmitted { resolved: ResolvedPatch { - lens_weights: None, subjects: Vec::new(), entities: Vec::new(), routes: Vec::new(), diff --git a/native/aetherlight/tests/fixtures/base_world.cc b/native/aetherlight/tests/fixtures/base_world.cc deleted file mode 100644 index d4c8eadacb211bc0c98b7e5b6f9ea2f6c229eeae..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 557056 zcmeI*4U}Y6eIW4e85DuAnQY_)b5v0Lilk@j`(rk4h{TAC8lreiQ0(*Sy;svE)m6P! z)ibc>WCsxNfLZy_9HYseh)mA_1Ia)noR}yc2Uion63%fmV%&|#U5x8y*GNvxt~h&N zRabXUcRSMq!)JaqbGxdm?z`{a-+NWn_tpFVtCuE?pFa84Q%`=@#KgpwP==S$jcdlg z9^rcP<mB+tA78BV`RBjz=G)KtiBm7S>Uke|)kj|bkE2JI8+gUN|8#BfegFOazy0@r zecDauH{P^)`Jp4;dd}jb|L3Cf{-|=p>Hp*PCq6uw-FrfDqw62{<Imqwe)m6CYj6Kz zWB)^qPrWfY;fQNpe(<Eln+G30_@D1S<G{Y}eDkI+-1x{TFI}$T76AeT2oNAZfB*pk z1PBm#>IzIA+B}g9-TS3b-Vw@|LOCZ)miLE}M1yF0F4~^<r=xbe8%KjQS#jTdr<X?Y zOw?$n{mc4;bat`siu*S@yPuetTsroU&D68<;_SK?4o_^`c405-^rLvt>ULh2ytOr$ zxggr!>O|S^i#5U>>FZnl!RBnq>@vA&bUpD~=YH?di(j{JdjB^zefv8%|H`MADjcU3 zF0SV2SI23Dhg=8{AV7cs0RjXF5FkK+z_ANV9y(#77$&c;4dvoc=0kZPlwS<<<d22& zvM`Tcocwot)BQnq4B)XJ78oBFm>l2uo6lZ)%4c@`%9ZC`@u^=u|DK5p$M;WWrzH$8 z*}Od~r)Srr!veoBIw;ZYy*caF`RQeoFMHd3?c(vW!^MvH<2X&ppZFDK5ZPt&UyQCN z&R%%=zyH$Dd}n9j-2H#J>*xQ=_m?UhpQ9YdzF%2_009C72oNAZfB*pk1fE&~lZPfJ zKJ;S~6XWyi7w3}`CrpfI-s36exW==`Ra_GwK!5-N0t5&UAVA<a2|TstNqR%znJBO+ z%>T1-z3ES1@#=4#@o&%W|NYl*t89Jnt(z;)Tlm6FpQ>H@-Rtgu_5<|~kB<hNy!h-M ze&+p51TiK81PBlyK!5-N0t5&UAn*(n$UgsnW0=#Q7Czp;@sD?Qd+lU&mjBkY9W}bW zVUYdS9r=SViOR)NqgaThN=Ys^RVviusYbIBPsM3IDVK}2@IUu~ja56sdhS25{`H9$ zE%f7=bT&Hp;_Wlt{-E93J~P<5vTt#>)1RMBds}x@_KxmvB?q?bF5UggH%z?xcRtzv z;tSqVd-JZny>v&bACd%Y-aR)H_0xqcg}{z<cXwwe?cFu}c}{w1G&|Q$w+_<&VE3Rk zXs35x(CT#3<jh|focZdo(C$XBl{SCx_mf`K985=ZbG`14sNKKuu9^ASsB_rz>omEy zKi_y~8V~wc9@w(&zVBUo%PX(`pO^pchraQ5pZkYLuGk%f)AsEb&ZK9a+nw*kt@bUK zv^vS{txiAmWIju8aA3>%J0HCJ{_6Yw^#k=+owxG^{l8qfR7i!;N&EfbQVVlwub(aO z-p_yJ<9Gh2uRia+jjP`O>(^fWvx^Jdnyu!%tj{Z}?@c>lRjsst`GGAboL&EKzxd&Y z_TBwc-~5*k{@Mrr=E}qRH#-~5hl}o>Ye#W<YuE;Zs1+pd+npvMN5rmM=eqsSR;ael zU@spnwRSCQM|gy)tH<^utL~lYwv$$8dw<uyB%Mn;Ng8-VA9pvyKG5H_H>9ly8@U}i zeMzUgvz-lK*R9d~V5Zw^4KCYtYd>v=tro_zYfp$Z=>_Cnx5wSt+16k-i1l~<!ALur zo(+*Fy;jr?qt9y1habD{Zb$vWba!s9+Z)VxLVMHEVAn^(dM5Vu<EWiZw>pE+$`yMC zQEz)1TD#+&^SxF-X${vHy4+4X{pp=)w%hmLvoIH)gPmw{Pv~<mtZZ^&*xhhFlZHEH zCKm=#XL~!Hyk$q)YESM?XB(l??oN1qbSCe~wo<R#Zl}HJsNZjG?+p8Y<>j|6?wHfr z6KBnydCTCkxpaRw408DVkJ{5AzeZ<p$BNdn<u3TsAHMBf?>hG<zw`aM&;8ePe)xmK zTV1o~j#}+Ry{y$8>GY!E>Q?_%=Ztr!3tuUI|FrMF_uiWy+<ADbt9OAbhpp}&J{woJ zboJHmyC(m)*F~M*{NjV}`tz?8!!~M#{a`L?ulMYYn$2!6i8^sQ9a5b{?e6v~4s3b$ zTmJakgFpWhH=K0Z-@WcdrEi{e_2?<kpG%`lb_dwBfBhX{%LkZbwC~?=#lDrl-w{Wh z=|-;`C2`m(KDwh7g(uEpE|q<0vl;fX>3+LA2+efo2VoaWryEfx>ECe0!e|GW+%u}x zzy8iR$c3GFI;=d6XFh#k%R|qfdG-%#ulc<Xzws0O-zrVKdDOW*p))(uPWmKwZ~qF< z?ID3ncnv&!ORnDQZd|Lqc8G^Jv3eJ~VQmwKFR*&=S!aQTG~k8pv2PgcHl4J>Yun)9 zYx^@%p<LP4sOBooay4$0^3_VNSgcf{e6v)I%1M%|*PG!TvDOG1H7+*_X)USblR_<D zDdwv6e3DP9mE^ABYs2WJWOdtxT(Mp+SE52CE+*whu3Aj;xqMo#)oW2)jw-pRo;E7Q zsMx3%o262<QAlddYAtP+;;31#)(@Ul$Q3G6`CRyaVXm~TRM?iUZY|{V<yx&+E}Wgq zZOi30@}Bw({5!{x2oNAZfB=DIfo%SNYWOgJ_<8<w!-0S->Hi;u@`F%vA&fi;<%6Mo zJ_{)i$pA{BoEOU5LzxTZ-JyIilzpMx8_I!Dz8uQeLituG4~LSqo+a8pGnAhVr54JC zp=3>tyR!0j)|v7BS%1d2S6{Dg^Yx2u{&2Bk*5>$j){P%5-hXbm{m|m=|F?LZt@HVz zydsoRC@Ys;dHY4-v22m7-Sw7PY%Z`a_d5&1AK$;;GUGn3Tu&Bm@yOyr8(k*zIM!t{ zmm@7R?)S>^th}8qpN%iucgB||;=Zg8A#P=OIbOHNV|7h{009C72oNAZfB=DKpg=bN zKO;<{E(s-`Zx7;-(LbF|!v{$1@bO=N^Z5JmmNLzK;otq)_Iuy?$cuJ9bnS24^ulkS zKCUpDiDf^t*;rPxL;<6We50SwKs`euK!5-N0t5&UAV7cs0Rm4Cfuqg;vyYy$%j7ul z|MYJRI@dL3U;3NxsGa!h-#*kER~S_rR?Vu1V*da1*ah^G009C72oNAZfB*pk1pXNa zWb^-D4wLmShk5*sA0NfikD?RTBmgLva^*%b3K9RMW@)NaDOacJNwG8)*NeG0%16~) zk`D<0Hd5_KE4qKvcdr}A|DUxc{(rG=A;fh92>?PQ>}&{lPp%lo2;Z?hx^Un4v8!&* zBAG9I*4_IKJp4;<{oT^%a)0*IbANG!tOEPfOXot=ZkkMw(+f;2gsAQiVLe*Sa*%Oo zd7YF1w=}xRWtWe7G)gCsP7jj{><@9nJ6hfO{&K^2g>dq4Qbq`5U%GGdV@uW64Ny%B z)p8uy;-s0@s+AC^8lqK`Tr;gEX}Q?UrS&)qRjpRiC|7Fc(`vO+s5Gl-nl?&Fy^-eb zSzhJ3?Z?GZl!itdl_XycEhpt9jq8nS9MubHcr2{6k~ZpbtzNE0)p9+p*NY)NL?u@! z)r!?Lxo4^S>j%Nsn#ClEtBq1xZ04J}QY~MK>LIGOP;RF6Brb%g+e#cog=(W5_PZ#o zrIAmH)lwxbHIrJYxiAWs9&L*|S7vQUljTjb&UV>1>QA;|qroTEi=@rh>bX*`o-1Co zuqrCJPzfQsr9e_FRFg(pZX~s|(5TkSxk4?e)hoGN7)laV;!3_zjLW4$J_PDk<7%^z zRztjSW&OzAd_7+Yp}X~Q<nBhE4gU;YvJ8;`0RjXF5FkK+0D(s-FrNSSLoD@C=Ko<z zQ;sXS+Egx=)Tc^uF`A0PRBbAailvaHC@B?l#W4ThNVOx*|4(`U<1_!?7x&VTt!;XE z7+^g8zh*f7|Bo;I%yT9VzJA*sU;B3Hg%_W@`B9|^+#M3N#WPoigmZB_8YNEaf8eU& zM1LV<lnQy^7DCp!q@51e9S&e@G{4?^hHc!ooKI`HonfM{VM?;l=u;u<*EPew?pe$( zx7g89cDB)Q*Uv+ETj>2_p1RS@eYD7m3H#b~i?=U>gmh^i?WN7#!|DF+ke_ir{rHMQ zN6Qtr4imTS9cL<Bv($LgtUHW7iwWyiY`1kXFs>NN=qS(rH5u=o@Sg7-rSj|cR&@PG zrJP*b|2264SN8wL^$dr5;+h8@+a|efsT=+4_l5&ySxUz=WNCYXGb*k<N_XEnN9iWk zKT3Ds(T=V?=A(D(A6>g|@u=A7)o6Smbog?ZJgV2akXp6hZSP2vYnL*d-gNb0&-TL- zOs-D5H-3FMVs6qEJK}Lm^0;!(T_^Y7(hI|nOe{Jc<oLDVuwkxFN4RR3!%VM7e#IEQ z_^o}#Se@B&b&kyAHm;>tio*uBI#uI(1KYss$>Qjip2!=`E4p%Y8_E)S^zFEm`1Xb? zm)}i?Ic{$qy;lztqpnVgyZAo7;mo)Ty^z#1qzFB10OJ)N>E-Z_<+rS1M^>jHUGc}j zQz#?pcx2<hMOKeub-vOyqZlvvB&RMNWeL81DNFG6Pm%YYjeJB=s^m-MYIV&=6p!_D zl^^jDMJ;>^Q>hg4i^)ZOMDZx+VHP9sWC%<i+BEUiAD@``MkvEj{^1w>ofggr_>;$> zWNSDxlyMTkY#mvsz<LSrvZQk3`@a>=P8i>QGL*7)>id%;&z<|R3fO0kRqXiG=YD(~ zkF^!<$0~Mw>T^Fnj>p;x_hS`1KJ~dDAID>Dh5NCJ9iRG7XZMrB{5iWESz=R2VxQG` zc=D{v=I8(R=l<faE_vNKpS|r<-@D+iUi0vkZ+p{g-u0|q_ul)OGhTAd4<DG=^88&_ zo&MQB`TAMYr~I2oK6C0^;pHd)_Wu0!7hiP6f5@b=%Qz+bsiR*fu3o&pCtUwiC_fjb z`;Yy529I*4!bU<6j?%<N&SE&StVanDAV7cs0RjXF5FkK+z*9#c`~3f{VP5{BY@Qw_ z@t2=?)Hr}*z8M0$%W?RY;aY8~lvImTjb^Pn)eO-A`4GL`%ohqrnO$#Wf*wK%HnOH8 zh7xT0%HtDCFg}BJlwM$X(s($tf0Rlf|9|J-zU4h{=zsE>fB4K9ulnwbk13VFrbnAf z;Lh;9_N^UD;SFogQr@)AS<0K&KTCP(%dXRWtyrtp%B51HR;*V`wPvMR$>)l-LM?3n zxKgSVLS%nFAL8(<wUBZkS1i=3`Ka8C%7tdgJaDwLogeF$X&)_@KqY*8cCA@1=i>0S z+O?!uDb?%wW<3|Bxm>fJ)+$LZO$u=-WEzMX)hIk(&6mTscxPXy9isG$i)T%bPUHXm zQTm9nb8_^P@j{e;unBn&)|`y@xP8-iC0DNJa>sBoo`fCga*&CH9TIj(*zwf)<3vvg z5FkK+0D;FvK>UA}{!jdW+--N`aQGnEH_D$k-EVgX{p;@t@rxlZUOL?f$2UTh{ld<) zwS8tVxo1?XfBl_t)a$j<{&WbePve<SuNyco{y$3xu_K*cOdzl_9P|mvT(A_?EB=4b zf6qcl)Y0lhlY8Qss5eM^lMC%M*`8g`q~VU4$%R4G+1^ekZ`qNy+LOD}*+zJ9cV~V! z?M$vcvL^ojogp7;U;O_T@&B#%Fd5D5txi8AyqO=gx}6ni9K`>}Y5&G?l)U(V@&Cv6 z-gESi9P%~s|BuT&Nuvawi2~XD|Dy0sedB0>>@<MvvMKy?AwYlt0RqP^@JxKSG$sNB z2oNAZfWXsVAe;Z65&pQlB$POO)m$9KGwF015_q>mn%@5AVLHI@*yJgTe*ym5m;U;z zC;#sUK6w5Ew>{@)-hWRtuCVxUR&}w2qY4v~FMHd3?c&kTr$3ev5FkK+009C72oNAZ zfB=D~slf8I-7NwH2oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZ zfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&U zAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C7 z2oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N z0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+ z009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBly zK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF z5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk z1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs z0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZ zfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&U zAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C7 z2oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N z0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+ z009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBly zK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF z5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk z1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs z0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZ zfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&U zAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C7 z2oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N z0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+ z009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBly zK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF z5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk z1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs z0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZ zfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&U zAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C7 z2oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N z0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+ z009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBly zK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF z5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk z1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs z0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZ zfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&U zAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C7 z2oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5;& zr=q~*p~;C4{n*6BiK{wy!qV?2FWx$7@p^U5rHXD4AV7cs0RjXF5FkL{Q3@P#Awb}9 z7I>6TPKyyBK!5-N0t5&UAV7cs0Rm4Wf$a1DUk?5K^5%(&8$Z6Y+iNG&ad&pMHQ1WA zqeizE4O-pK)*bnSFG-VHE-K|qQ<XT0r%H`Rb1JG-N>hbgzEsW?a+ON6`GJj9JJO2o z-}K$<7W(l_IvX84Yx_*MKWMkM&kVL6*0;FZ>Cexmy{$Vcdq)qnk^@_Im+pS$8zx@; zJD+TS@da<Gy?NK3Y$Q=9x#E_=Wpn8r%PoZa#*bZfbGGFF+I7ow+h05XlMBh2&%NNx z=Ak1rx<9>iE{z9iGTlpewE973av_e|?X)*q&8>62Rwr)FMeWe?T{H8c1LvfdMzeG6 zbn77P4{m96lgln2^(dN~>veae(@8IC4))Jw4R+`I%MIVvOZ)TfL94TU>Ap=LTdLL{ zM1!zwYkO$*;A{IcQK4Mf78grV+Gv&=l_X!SCb^`Xq;b7bjiY)Y4Ug5Tl}g&E$F+L7 z7FEmjv|cZk%f(8rP^uNHX>!l<D%Wj4&DV;xYOP!<HEP9rwNz_Xnw5O6SS!@Z<v6aC zDuvKmK3~j5)mkl1a>YWenvcrOs9b2qjpjW|-5>2{tNUN5RKgHK?~8?M(n!mVq?Q&M z)q2>&YDukL$>s9RToP5{O1@Ey%cVj-SEy9uYO|15YmH`QA#FCp<{52^JBP5-i_FRL zrdemZ>>Kqb+py8#6NS*~R6ZB}UzjUxD;2iot6K}XQaPWm*XtK8tU|Bk@@cJEF6ZKU zxl&7tl~TQ)Z`N~Bn#(ooX|0mv(xecVip_k~s7B%OYQ9{rH{+;T4`V1EJZt^+Rr19` kDOWl>m)n-hZRpwXI3F(5JOKg(2oNAZfB*pkPh)}q4-`KIBLDyZ diff --git a/native/aetherlight/tests/fixtures/base_world.digests b/native/aetherlight/tests/fixtures/base_world.digests deleted file mode 100644 index ab9edc3ea..000000000 --- a/native/aetherlight/tests/fixtures/base_world.digests +++ /dev/null @@ -1,3 +0,0 @@ -3 -sha256:b706f57cb417603366a1f47a5dd099fbf68bfecc5b2e8d61d281630791d1d76d -sha256:2039956a26c3d5b073d101e5898ac5a60a9eb63a3b93f447b2d8f78ef4caf979 diff --git a/native/aetherlight/tests/fixtures/base_world.id b/native/aetherlight/tests/fixtures/base_world.id deleted file mode 100644 index f23316a4c..000000000 --- a/native/aetherlight/tests/fixtures/base_world.id +++ /dev/null @@ -1 +0,0 @@ -"a534b32a-4d00-429c-bf6c-ce1d55385380" From 98282a07af59c3cf882d5efb23408b6a56f4beaa Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Thu, 19 Nov 2026 21:59:27 +0100 Subject: [PATCH 121/190] Aetherlight AL2a.2: delete the gestalt cover and the agency graph Remove cover.rs (Cell, Cover, CoverBudget, derive_cover, AgencyGraph), the kernel's agency_graph projection and CommandId::for_cell and for_cell_constituent. Nothing in the kept lanes read them. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/cover.rs | 1105 ------------------------------- native/aetherlight/src/lib.rs | 189 +----- 2 files changed, 1 insertion(+), 1293 deletions(-) delete mode 100644 native/aetherlight/src/cover.rs diff --git a/native/aetherlight/src/cover.rs b/native/aetherlight/src/cover.rs deleted file mode 100644 index 5d1ce4233..000000000 --- a/native/aetherlight/src/cover.rs +++ /dev/null @@ -1,1105 +0,0 @@ -//! The budgeted connected cover: one tick's partition of the active -//! opportunities into cells. -//! -//! This organ owns the partition and nothing else. [`derive_cover`] is pure -//! over its arguments — no clock, no entropy, no mailbox, no filesystem — and -//! the [`Cover`] it returns is derived and disposable. A cell never enters -//! `WorldState`, a `CommandEnvelope`, a `ScopePreimage`, a `DecisionOpportunity`, -//! or any `Declaration`; the kernel never learns a tick happened except through -//! `AdvanceTime` and ordinary one-opportunity submissions. -//! -//! The cover is a partition, never a filter: every active subject is in exactly -//! one cell every tick. The budget decides at what resolution, not whether. - -use super::{ControllerMode, DecisionOpportunity, SubjectId, WorldId}; -use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; -use std::collections::{BTreeMap, BTreeSet}; -use uuid::Uuid; - -/// A place, resource, or channel with more associated subjects than this -/// contributes a star centred on its lowest member instead of a clique. -/// Connectivity is identical for component purposes and the edge count stops -/// being quadratic in a crowded room. -pub(crate) const AGENCY_STAR_THRESHOLD: usize = 16; - -/// The namespace every derived cover id is salted with. A fixed constant, never -/// regenerated: two worlds in one process are separated by the world id inside -/// the name, not by a second namespace. -const COVER_NAMESPACE: &str = "ghostlight.cover.v1"; - -/// A tick's ordinal: the number of clock advances the world had committed when -/// the tick opened. The driver reads it from the world and freezes it in the -/// tick document; it is never derived from `now`, so it does not depend on the -/// span. It is threaded into every derived command id, so a resumed tick -/// re-submits the same ids and the kernel's idempotency ledger answers with the -/// original receipts instead of double-committing. -#[derive( - Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Default, -)] -#[serde(transparent)] -pub struct TickIndex(pub u64); - -/// How a subject was represented this tick. Derived from the cell, carried -/// nowhere in world state: representation is a compute budget, not world truth. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "resolution", rename_all = "snake_case")] -pub enum Resolution { - Detail, - Coarse { constituents: usize }, -} - -/// Derived from the partition, so a replayed tick over the same inputs produces -/// byte-identical ids. sha256 over `(namespace, world, tick, size, lowest -/// member)`; no `uuid/v5`. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] -#[serde(transparent)] -pub struct CellId(Uuid); - -impl std::fmt::Display for CellId { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(formatter, "{}", self.0) - } -} - -fn derive_uuid(name: &str) -> Uuid { - let mut hasher = Sha256::new(); - hasher.update(COVER_NAMESPACE.as_bytes()); - hasher.update([0u8]); - hasher.update(name.as_bytes()); - let bytes: [u8; 16] = hasher.finalize()[..16] - .try_into() - .expect("sha256 yields at least sixteen bytes"); - Uuid::from_bytes(bytes) -} - -/// `members.len()` is in the name so a component that splits differently under -/// a different cap yields a different cell, and a resumed tick over the same -/// inputs yields the same one. -fn cell_id(world: WorldId, tick: TickIndex, members: &[SubjectId]) -> CellId { - let lowest = members - .first() - .copied() - .expect("a cell always has at least one member"); - CellId(derive_uuid(&format!( - "cell|{world:?}|{}|{}|{lowest:?}", - tick.0, - members.len() - ))) -} - -/// The stable, derived identity a cell's controller-work row is keyed by. -pub(crate) fn cell_work_uuid(world: WorldId, cell: CellId, tick: TickIndex) -> Uuid { - derive_uuid(&format!("cell-work|{world:?}|{cell}|{}", tick.0)) -} - -/// One constituent's submission id. Deterministic, so a resumed cell re-submits -/// the same id and the kernel answers from its idempotency ledger. -pub(crate) fn cell_constituent_uuid( - world: WorldId, - cell: CellId, - subject: SubjectId, - tick: TickIndex, -) -> Uuid { - derive_uuid(&format!("cell-act|{world:?}|{cell}|{subject:?}|{}", tick.0)) -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Constituent { - pub subject: SubjectId, - pub(crate) opportunity: DecisionOpportunity, -} - -/// One inference's worth of the world. A singleton keeps the detail path and its -/// membrane; a group is one inference over N labeled, never-unioned views. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Cell { - Singleton { - id: CellId, - tick: TickIndex, - member: Constituent, - }, - /// `members` is ascending by `SubjectId`; the index into it is the - /// constituent handle the model-facing tool names carry. - Group { - id: CellId, - tick: TickIndex, - members: Vec<Constituent>, - }, -} - -impl Cell { - pub(crate) fn members(&self) -> &[Constituent] { - match self { - Self::Singleton { member, .. } => std::slice::from_ref(member), - Self::Group { members, .. } => members, - } - } -} - -/// Derived, disposable, dropped at the end of a tick. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Cover { - pub tick: TickIndex, - pub cells: Vec<Cell>, - /// True when the constituent cap could not hold every active subject inside - /// the cell budget, so the cap yielded and every cell grew. "Every active - /// subject is in the cover every tick" is an ontology invariant; the cap is - /// a prompt-size preference. Rendered read-only: it is the honest signal - /// that the world outgrew its prompt budget rather than a truncation nobody - /// sees. - pub oversubscribed: bool, -} - -impl Cover { - pub fn singletons(&self) -> usize { - self.cells - .iter() - .filter(|cell| matches!(cell, Cell::Singleton { .. })) - .count() - } - - pub fn groups(&self) -> usize { - self.cells.len() - self.singletons() - } -} - -/// How many inferences one tick may spend, and how large one prompt may get. -/// Two budgets, deliberately not one: only the second bounds tokens. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct CoverBudget { - /// B: cells per tick. - pub cells: u16, - /// C: the per-cell constituent cap. At least two, or a group is a singleton - /// with extra steps. - pub constituent_cap: u16, - /// U: singleton slots reserved for the head of the attention order. The - /// rest of the singleton slots carry the rotation window. - pub urgency_slots: u16, -} - -#[derive(Debug, thiserror::Error, PartialEq, Eq)] -pub enum CoverBudgetError { - #[error("cover cell budget must be at least one")] - NoCells, - #[error("cover constituent cap must be at least two")] - CapTooSmall, -} - -impl CoverBudget { - pub fn validated(self) -> Result<Self, CoverBudgetError> { - if self.cells < 1 { - return Err(CoverBudgetError::NoCells); - } - if self.constituent_cap < 2 { - return Err(CoverBudgetError::CapTooSmall); - } - Ok(self) - } -} - -/// The scheduler's own projection, wider than any subject view and reachable -/// from no prompt builder: it is constructed by the tick driver, handed to -/// [`derive_cover`], and dropped. `run_cell` takes a `&Cell`, which contains no -/// graph, so a controller organ that could read adjacency fails to compile -/// rather than failing a test. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct AgencyGraph { - /// Ascending. Exactly the subjects with a non-Human controller assignment. - pub(crate) subjects: Vec<SubjectId>, - /// Undirected, canonicalised `(lo, hi)` with `lo < hi`. - pub(crate) edges: BTreeSet<(SubjectId, SubjectId)>, -} - -impl AgencyGraph { - /// A clique below the star threshold, a star above it. Connectivity for - /// component purposes is identical either way. - pub(crate) fn relate(&mut self, group: &BTreeSet<SubjectId>) { - let members: Vec<SubjectId> = group.iter().copied().collect(); - if members.len() < 2 { - return; - } - if members.len() > AGENCY_STAR_THRESHOLD { - let centre = members[0]; - for member in &members[1..] { - self.link(centre, *member); - } - return; - } - for (index, one) in members.iter().enumerate() { - for other in &members[index + 1..] { - self.link(*one, *other); - } - } - } - - pub(crate) fn link(&mut self, one: SubjectId, other: SubjectId) { - if one == other { - return; - } - let pair = if one < other { - (one, other) - } else { - (other, one) - }; - self.edges.insert(pair); - } -} - -/// The partition. Pure over `(world, tick, opportunities, graph, budget)`. -/// -/// `opportunities` arrives in the kernel's one attention order (pressure, then -/// attention debt, then id) and is never re-sorted and never filtered here: a -/// Human opportunity is skipped because a human turn is not an inference, which -/// is a fact about cognition rather than a scheduling preference. -pub fn derive_cover( - world: WorldId, - tick: TickIndex, - opportunities: &[DecisionOpportunity], - graph: &AgencyGraph, - budget: CoverBudget, -) -> Cover { - let active: Vec<&DecisionOpportunity> = opportunities - .iter() - .filter(|opportunity| opportunity.controller_mode != ControllerMode::Human) - .collect(); - let count = active.len(); - if count == 0 { - return Cover { - tick, - cells: Vec::new(), - oversubscribed: false, - }; - } - let constituent = |opportunity: &DecisionOpportunity| Constituent { - subject: opportunity.scope.subject_id, - opportunity: opportunity.clone(), - }; - let cell_budget = usize::from(budget.cells).max(1); - let cap = usize::from(budget.constituent_cap).max(2); - - if count <= cell_budget { - let cells = active - .iter() - .map(|opportunity| { - let member = constituent(opportunity); - Cell::Singleton { - id: cell_id(world, tick, &[member.subject]), - tick, - member, - } - }) - .collect(); - return Cover { - tick, - cells, - oversubscribed: false, - }; - } - - // Step 2. Group cells must hold the non-singletons under the cap: - // `K + ceil((N - K) / C) <= B`. The cap yields when no such partition - // exists, because coverage is the invariant and the cap is a preference. - let capacity = cap.saturating_mul(cell_budget); - let mut oversubscribed = capacity < count; - let (singleton_slots, effective_cap) = if oversubscribed { - (0usize, count.div_ceil(cell_budget)) - } else { - ((capacity - count) / (cap - 1), cap) - }; - let singleton_slots = singleton_slots.min(count); - let group_budget = cell_budget - singleton_slots; - - // Step 3. The rotation window. A stable order that does not move with - // pressure is what lets it carry a guarantee: a subject at index `i` is in - // the window exactly when `phase == i / R`, and `phase` cycles once every - // `ceil(N / R)` consecutive ticks because `now` only advances. - let urgency = usize::from(budget.urgency_slots).min(singleton_slots); - let reserve = singleton_slots - urgency; - let ascending: Vec<SubjectId> = { - let mut ids: Vec<SubjectId> = active - .iter() - .map(|opportunity| opportunity.scope.subject_id) - .collect(); - ids.sort_unstable(); - ids - }; - let mut chosen: BTreeSet<SubjectId> = BTreeSet::new(); - if reserve > 0 { - let cycle = count.div_ceil(reserve); - let phase = usize::try_from(tick.0 % cycle as u64).unwrap_or(0); - let lo = phase * reserve; - let hi = (lo + reserve).min(count); - for subject in &ascending[lo.min(count)..hi] { - chosen.insert(*subject); - } - } - // Step 4. Urgency, then backfill in the attention order. A subject in both - // reserves consumes one slot, not two, and every slot is spent. - for opportunity in active.iter().take(urgency) { - chosen.insert(opportunity.scope.subject_id); - } - for opportunity in &active { - if chosen.len() >= singleton_slots { - break; - } - chosen.insert(opportunity.scope.subject_id); - } - - let mut cells: Vec<Cell> = Vec::new(); - for opportunity in &active { - let subject = opportunity.scope.subject_id; - if !chosen.contains(&subject) { - continue; - } - let member = constituent(opportunity); - cells.push(Cell::Singleton { - id: cell_id(world, tick, &[subject]), - tick, - member, - }); - } - - // Step 5. Connected components over the remainder. - let rest: Vec<&DecisionOpportunity> = active - .iter() - .copied() - .filter(|opportunity| !chosen.contains(&opportunity.scope.subject_id)) - .collect(); - let rank: BTreeMap<SubjectId, usize> = active - .iter() - .enumerate() - .map(|(index, opportunity)| (opportunity.scope.subject_id, index)) - .collect(); - let mut groups = components(&rest, graph); - - // Step 6. A component larger than the cap is cut in id order. A chunk of a - // connected component is still a legitimate coarse group, and a graph-aware - // cut would be a second partitioning heuristic whose only payoff is - // adjacency inside a prompt that never mentions adjacency. - let mut split: Vec<Vec<SubjectId>> = Vec::new(); - for component in groups.drain(..) { - for chunk in component.chunks(effective_cap) { - split.push(chunk.to_vec()); - } - } - - // Step 7. Merge the lowest-ranked cells until the group budget is met. The - // choke falls on the quietest cells; the highest-pressure groups keep the - // smallest, sharpest prompts. Priority is read from the attention order, - // which is its one owner — the scheduler computes no second ranking. - let priority = |members: &Vec<SubjectId>| { - members - .iter() - .filter_map(|subject| rank.get(subject).copied()) - .min() - .unwrap_or(usize::MAX) - }; - split.sort_by_key(|members| (priority(members), members[0])); - let mut head = split.len(); - let mut packed: Vec<Vec<SubjectId>> = Vec::new(); - let mut bucket: Vec<SubjectId> = Vec::new(); - while head > 0 { - let open = usize::from(!bucket.is_empty()); - if head + packed.len() + open <= group_budget { - break; - } - head -= 1; - let component = split[head].clone(); - if !bucket.is_empty() && bucket.len() + component.len() > effective_cap { - packed.push(std::mem::take(&mut bucket)); - } - bucket.extend(component); - } - if !bucket.is_empty() { - packed.push(bucket); - } - split.truncate(head); - split.append(&mut packed); - // Component sizes need not pack perfectly into the cap, so the packing pass - // can end above budget. The cap yields here for the same reason it yields in - // step 2: coverage is the invariant, prompt size is the preference, and the - // operator is told rather than shown a silent truncation. - while split.len() > group_budget && split.len() >= 2 { - split.sort_by_key(|members| (priority(members), members[0])); - let last = split.pop().expect("two or more cells were established"); - let previous = split.pop().expect("two or more cells were established"); - let mut merged = previous; - merged.extend(last); - split.push(merged); - oversubscribed = true; - } - - for members in &mut split { - members.sort_unstable(); - } - split.sort_by_key(|members| (priority(members), members[0])); - let by_subject: BTreeMap<SubjectId, &DecisionOpportunity> = rest - .iter() - .map(|opportunity| (opportunity.scope.subject_id, *opportunity)) - .collect(); - for members in split { - let constituents: Vec<Constituent> = members - .iter() - .filter_map(|subject| by_subject.get(subject).map(|entry| constituent(entry))) - .collect(); - if constituents.is_empty() { - continue; - } - cells.push(Cell::Group { - id: cell_id(world, tick, &members), - tick, - members: constituents, - }); - } - - debug_assert_eq!( - cells - .iter() - .flat_map(Cell::members) - .map(|member| member.subject) - .collect::<BTreeSet<_>>() - .len(), - count, - "the cover is a partition: every active subject appears exactly once" - ); - debug_assert!(cells.len() <= cell_budget, "the cover respects its budget"); - - Cover { - tick, - cells, - oversubscribed, - } -} - -/// Union-find over the remainder's induced subgraph. Deterministic by -/// construction: a `BTreeSet` of edges in `SubjectId` order, components keyed by -/// their lowest member, members ascending. -fn components(rest: &[&DecisionOpportunity], graph: &AgencyGraph) -> Vec<Vec<SubjectId>> { - let present: BTreeSet<SubjectId> = rest - .iter() - .map(|opportunity| opportunity.scope.subject_id) - .collect(); - let mut parent: BTreeMap<SubjectId, SubjectId> = - present.iter().map(|subject| (*subject, *subject)).collect(); - - fn find(parent: &mut BTreeMap<SubjectId, SubjectId>, node: SubjectId) -> SubjectId { - let mut root = node; - while let Some(next) = parent.get(&root).copied() { - if next == root { - break; - } - root = next; - } - let mut cursor = node; - while let Some(next) = parent.get(&cursor).copied() { - if next == cursor { - break; - } - parent.insert(cursor, root); - cursor = next; - } - root - } - - for (one, other) in &graph.edges { - if !present.contains(one) || !present.contains(other) { - continue; - } - let left = find(&mut parent, *one); - let right = find(&mut parent, *other); - if left != right { - let (low, high) = if left < right { - (left, right) - } else { - (right, left) - }; - parent.insert(high, low); - } - } - - let mut buckets: BTreeMap<SubjectId, Vec<SubjectId>> = BTreeMap::new(); - for subject in &present { - let root = find(&mut parent, *subject); - buckets.entry(root).or_default().push(*subject); - } - buckets - .into_values() - .map(|mut members| { - members.sort_unstable(); - members - }) - .collect() -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{DecisionScope, ScopeDigest}; - - fn subject(index: u128) -> SubjectId { - serde_json::from_value(serde_json::json!(Uuid::from_u128(index).to_string())) - .expect("a subject id parses from its canonical uuid") - } - - fn opportunity(index: u128, mode: ControllerMode) -> DecisionOpportunity { - let subject_id = subject(index); - DecisionOpportunity { - world_id: WorldId::nil_for_test(), - revision: 1, - scope_digest: ScopeDigest::fixture(&format!("scope-{index}")), - scope: DecisionScope { subject_id }, - controller_id: serde_json::from_value(serde_json::json!( - Uuid::from_u128(index + 1_000_000).to_string() - )) - .expect("a controller id parses from its canonical uuid"), - controller_mode: mode, - affordance_ids: Vec::new(), - } - } - - fn active(count: u128) -> Vec<DecisionOpportunity> { - (1..=count) - .map(|index| opportunity(index, ControllerMode::OperationalAgent)) - .collect() - } - - fn budget(cells: u16, cap: u16, urgency: u16) -> CoverBudget { - CoverBudget { - cells, - constituent_cap: cap, - urgency_slots: urgency, - } - } - - fn covered(cover: &Cover) -> Vec<SubjectId> { - let mut subjects: Vec<SubjectId> = cover - .cells - .iter() - .flat_map(Cell::members) - .map(|member| member.subject) - .collect(); - subjects.sort_unstable(); - subjects - } - - fn derive( - opportunities: &[DecisionOpportunity], - graph: &AgencyGraph, - budget: CoverBudget, - tick: u64, - ) -> Cover { - derive_cover( - WorldId::nil_for_test(), - TickIndex(tick), - opportunities, - graph, - budget, - ) - } - - /// Verification 21, at the design profile: 2,400 subjects, 240 cells, a cap - /// of 24, 36 urgency slots. Every subject exactly once, the budget held, and - /// the head of the attention order attended in detail. - #[test] - fn soul_the_design_profile_covers_every_subject_exactly_once_inside_its_budget() { - let opportunities = active(2_400); - let cover = derive( - &opportunities, - &AgencyGraph::default(), - budget(240, 24, 36), - 0, - ); - - assert_eq!(covered(&cover).len(), 2_400); - assert_eq!( - covered(&cover).iter().collect::<BTreeSet<_>>().len(), - 2_400, - "no subject is covered twice" - ); - assert!(cover.cells.len() <= 240); - assert!(!cover.oversubscribed); - // K = floor((24*240 - 2400) / 23) = 146 singleton slots. - assert_eq!(cover.singletons(), 146); - assert_eq!(cover.groups(), 94); - assert!( - cover.cells.iter().all(|cell| cell.members().len() <= 24), - "no cell exceeds the constituent cap" - ); - - let head = opportunities[0].scope.subject_id; - let urgent: BTreeSet<SubjectId> = opportunities[..36] - .iter() - .map(|entry| entry.scope.subject_id) - .collect(); - let singletons: BTreeSet<SubjectId> = cover - .cells - .iter() - .filter_map(|cell| match cell { - Cell::Singleton { member, .. } => Some(member.subject), - Cell::Group { .. } => None, - }) - .collect(); - assert!( - singletons.contains(&head), - "the head of the order is a singleton" - ); - assert!( - urgent.is_subset(&singletons), - "every urgency slot is spent on the head of the order" - ); - } - - /// A human opportunity is not an inference. It is skipped, and skipping it - /// is not a filter on the cover: it never was a candidate. - #[test] - fn a_human_opportunity_is_never_in_a_cell() { - let opportunities = vec![ - opportunity(1, ControllerMode::Human), - opportunity(2, ControllerMode::OperationalAgent), - opportunity(3, ControllerMode::NarrativePersona), - ]; - let cover = derive(&opportunities, &AgencyGraph::default(), budget(8, 4, 1), 0); - assert_eq!(covered(&cover), vec![subject(2), subject(3)]); - } - - /// Below the budget every opportunity is its own cell and the detail path is - /// untouched. - #[test] - fn a_small_world_is_all_singletons() { - let opportunities = active(5); - let cover = derive( - &opportunities, - &AgencyGraph::default(), - budget(240, 24, 36), - 0, - ); - assert_eq!(cover.singletons(), 5); - assert_eq!(cover.groups(), 0); - assert!(!cover.oversubscribed); - } - - /// The cap yields, the budget does not. Every subject is still covered - /// exactly once and the operator learns the world outgrew the prompt bound. - #[test] - fn soul_an_oversubscribed_world_relaxes_the_cap_rather_than_dropping_a_subject() { - let opportunities = active(100); - let cover = derive(&opportunities, &AgencyGraph::default(), budget(10, 4, 2), 0); - assert!(cover.oversubscribed); - assert_eq!(covered(&cover).len(), 100); - assert_eq!(covered(&cover).iter().collect::<BTreeSet<_>>().len(), 100); - assert!(cover.cells.len() <= 10); - assert_eq!(cover.singletons(), 0, "no slot is spent on detail here"); - } - - /// The fairness arithmetic, with no persisted field behind it: a subject - /// continuously active for `ceil(N / R)` ticks is a singleton at least once. - #[test] - fn soul_every_subject_reaches_a_singleton_within_the_rotation_window() { - // N = 25, B = 12, C = 8, U = 1 → K = floor((96 - 25) / 7) = 10, R = 9. - let opportunities = active(25); - let budget = budget(12, 8, 1); - let cycle = 25usize.div_ceil(9); - let mut seen: BTreeSet<SubjectId> = BTreeSet::new(); - for tick in 0..cycle as u64 { - let cover = derive(&opportunities, &AgencyGraph::default(), budget, tick); - for cell in &cover.cells { - if let Cell::Singleton { member, .. } = cell { - seen.insert(member.subject); - } - } - } - let all: BTreeSet<SubjectId> = opportunities - .iter() - .map(|entry| entry.scope.subject_id) - .collect(); - assert_eq!(seen, all, "the window closes over every subject"); - } - - /// A narrow reserve still closes, it just takes longer. The guarantee is - /// `ceil(N / R)`, never `ceil(N / B)`: giving every cell to a singleton - /// would leave subjects out of the cover, which the ontology forbids. - #[test] - fn the_rotation_guarantee_is_over_the_reserve_not_the_cell_budget() { - let opportunities = active(25); - // K = floor((8*10 - 25) / 7) = 7, U = 6 → R = 1, cycle = 25. - let budget = budget(10, 8, 6); - let mut seen: BTreeSet<SubjectId> = BTreeSet::new(); - for tick in 0..25u64 { - let cover = derive(&opportunities, &AgencyGraph::default(), budget, tick); - for cell in &cover.cells { - if let Cell::Singleton { member, .. } = cell { - seen.insert(member.subject); - } - } - } - assert_eq!(seen.len(), 25); - } - - /// The cover is derived, not remembered: the same inputs yield the same - /// partition, the same ids, and the same order. - #[test] - fn soul_the_same_inputs_derive_an_identical_partition() { - let opportunities = active(60); - let mut graph = AgencyGraph::default(); - graph.link(subject(3), subject(4)); - graph.link(subject(4), subject(5)); - let one = derive(&opportunities, &graph, budget(10, 8, 2), 7); - let other = derive(&opportunities, &graph, budget(10, 8, 2), 7); - assert_eq!(one, other); - } - - /// Connected subjects land in one cell when the budget allows it. - #[test] - fn a_connected_component_becomes_one_coarse_cell() { - let opportunities = active(20); - let mut graph = AgencyGraph::default(); - for index in 10..20 { - graph.link(subject(10), subject(index)); - } - let cover = derive(&opportunities, &graph, budget(4, 12, 0), 0); - let component: BTreeSet<SubjectId> = (10..20).map(subject).collect(); - let together = cover.cells.iter().any(|cell| { - let members: BTreeSet<SubjectId> = - cell.members().iter().map(|entry| entry.subject).collect(); - component.is_subset(&members) - }); - assert!(together, "one component was not split across cells"); - } - - /// Property sweep: the budget and the cap hold, and coverage is exact. - #[test] - fn soul_cell_count_and_cap_hold_across_profiles() { - for count in [1u128, 3, 7, 25, 100, 401] { - for cells in [1u16, 2, 5, 12, 240] { - for cap in [2u16, 3, 8, 24] { - let opportunities = active(count); - let cover = derive( - &opportunities, - &AgencyGraph::default(), - budget(cells, cap, 3), - 11, - ); - assert!( - cover.cells.len() <= usize::from(cells), - "count {count} cells {cells} cap {cap} exceeded its budget" - ); - assert_eq!( - covered(&cover).len(), - usize::try_from(count).expect("a test fixture fits usize"), - "count {count} cells {cells} cap {cap} lost a subject" - ); - if usize::from(cap) * usize::from(cells) - >= usize::try_from(count).expect("a test fixture fits usize") - { - assert!(!cover.oversubscribed); - assert!( - cover - .cells - .iter() - .all(|cell| cell.members().len() <= usize::from(cap)), - "count {count} cells {cells} cap {cap} exceeded the cap" - ); - } else { - assert!(cover.oversubscribed); - } - } - } - } - } - - /// A crowded referent contributes a star, not a clique: connectivity is the - /// same and the edge count stops being quadratic. - #[test] - fn a_crowded_referent_relates_as_a_star() { - let crowd: BTreeSet<SubjectId> = (1..=40).map(subject).collect(); - let mut graph = AgencyGraph::default(); - graph.relate(&crowd); - assert_eq!(graph.edges.len(), 39); - - let small: BTreeSet<SubjectId> = (1..=4).map(subject).collect(); - let mut clique = AgencyGraph::default(); - clique.relate(&small); - assert_eq!(clique.edges.len(), 6); - } - - /// Derived ids are a pure function of their tuple, and distinct tuples do - /// not collide. - #[test] - fn derived_ids_are_pure_and_distinct() { - let world = WorldId::nil_for_test(); - let cell = cell_id(world, TickIndex(4), &[subject(1), subject(2)]); - assert_eq!( - cell, - cell_id(world, TickIndex(4), &[subject(1), subject(2)]) - ); - assert_ne!( - cell, - cell_id(world, TickIndex(5), &[subject(1), subject(2)]) - ); - assert_ne!(cell, cell_id(world, TickIndex(4), &[subject(1)])); - - assert_eq!( - cell_constituent_uuid(world, cell, subject(1), TickIndex(4)), - cell_constituent_uuid(world, cell, subject(1), TickIndex(4)) - ); - assert_ne!( - cell_constituent_uuid(world, cell, subject(1), TickIndex(4)), - cell_constituent_uuid(world, cell, subject(2), TickIndex(4)) - ); - assert_ne!( - cell_constituent_uuid(world, cell, subject(1), TickIndex(4)), - cell_work_uuid(world, cell, TickIndex(4)) - ); - } - - #[test] - fn a_budget_without_cells_or_with_a_singleton_cap_is_refused() { - assert_eq!(budget(0, 4, 0).validated(), Err(CoverBudgetError::NoCells)); - assert_eq!( - budget(4, 1, 0).validated(), - Err(CoverBudgetError::CapTooSmall) - ); - assert!(budget(4, 2, 0).validated().is_ok()); - } - - /// The rotation guarantee at the design profile rather than at a toy size. - /// `K = 146`, `U = 36`, so the reserve is `R = 110` and the window closes in - /// `ceil(2400 / 110) = 22` ticks. Membership is stable across the sweep, - /// which is the precondition the tight bound is stated under. - #[test] - fn soul_b_the_profile_rotation_closes_over_every_subject_in_ceil_n_over_reserve_ticks() { - let opportunities = active(2_400); - let budget = budget(240, 24, 36); - let reserve = 146 - 36; - let cycle = 2_400usize.div_ceil(reserve); - assert_eq!(cycle, 22, "the profile's window is not 22 ticks wide"); - - let mut seen: BTreeSet<SubjectId> = BTreeSet::new(); - for tick in 0..cycle as u64 { - let cover = derive(&opportunities, &AgencyGraph::default(), budget, tick); - assert_eq!(cover.singletons(), 146); - for cell in &cover.cells { - if let Cell::Singleton { member, .. } = cell { - seen.insert(member.subject); - } - } - } - assert_eq!( - seen.len(), - 2_400, - "{} subjects never reached detail inside the window", - 2_400 - seen.len() - ); - - // One tick short of the cycle must not already close it, or the bound - // is being read off a coincidence rather than the arithmetic. - let mut short: BTreeSet<SubjectId> = BTreeSet::new(); - for tick in 0..(cycle - 1) as u64 { - for cell in &derive(&opportunities, &AgencyGraph::default(), budget, tick).cells { - if let Cell::Singleton { member, .. } = cell { - short.insert(member.subject); - } - } - } - assert!(short.len() < 2_400, "the window closed a tick early"); - } - - /// The urgency slots go to the head of the attention order the kernel - /// already owns, and the rotation window goes to ascending id order. The - /// fixture arrives in descending id order so the two rankings cannot be - /// confused with each other, and no third ranking exists to explain the - /// result. - #[test] - fn soul_b_urgency_slots_follow_the_attention_order_not_the_id_order() { - let mut opportunities = active(40); - opportunities.reverse(); - // N = 40, B = 10, C = 8 → K = floor((80 - 40) / 7) = 5, U = 3, R = 2. - let cover = derive(&opportunities, &AgencyGraph::default(), budget(10, 8, 3), 0); - let singletons: BTreeSet<SubjectId> = cover - .cells - .iter() - .filter_map(|cell| match cell { - Cell::Singleton { member, .. } => Some(member.subject), - Cell::Group { .. } => None, - }) - .collect(); - assert_eq!(singletons.len(), 5); - - let head: BTreeSet<SubjectId> = opportunities[..3] - .iter() - .map(|entry| entry.scope.subject_id) - .collect(); - assert!( - head.is_subset(&singletons), - "the urgency slots did not follow the attention order" - ); - // The window is the ascending-id reserve, which here is the tail of the - // attention order: two rankings, both honoured, neither invented. - assert!( - singletons.contains(&subject(1)) && singletons.contains(&subject(2)), - "the rotation window did not follow ascending id order" - ); - } - - /// The partition is a pure function of its arguments, and the attention - /// order is one of those arguments rather than an incidental input. Equal - /// inputs derive an equal cover; a permuted order derives a different one, - /// because urgency and backfill read that order and `order_opportunities` - /// is its one owner. - #[test] - fn soul_b_the_cover_is_pure_and_the_attention_order_is_a_real_input() { - let opportunities = active(40); - let mut graph = AgencyGraph::default(); - graph.link(subject(11), subject(12)); - let budget = budget(10, 8, 3); - let ids = |cover: &Cover| -> Vec<CellId> { - cover - .cells - .iter() - .map(|cell| match cell { - Cell::Singleton { id, .. } | Cell::Group { id, .. } => *id, - }) - .collect() - }; - - let one = derive(&opportunities, &graph, budget, 5); - let other = derive(&opportunities, &graph, budget, 5); - assert_eq!(one, other, "identical inputs derived different covers"); - assert_eq!( - serde_json::to_string(&ids(&one)).unwrap(), - serde_json::to_string(&ids(&other)).unwrap(), - "identical inputs derived different cell ids" - ); - - let mut reversed = opportunities.clone(); - reversed.reverse(); - let permuted = derive(&reversed, &graph, budget, 5); - assert_eq!( - covered(&one), - covered(&permuted), - "a permutation lost or duplicated a subject" - ); - let singletons = |cover: &Cover| -> BTreeSet<SubjectId> { - cover - .cells - .iter() - .filter_map(|cell| match cell { - Cell::Singleton { member, .. } => Some(member.subject), - Cell::Group { .. } => None, - }) - .collect() - }; - assert_ne!( - singletons(&one), - singletons(&permuted), - "the attention order is not an input to the partition" - ); - // Coverage survives a permutation, but so does the sizing decision - // that partition made: shuffling the same subjects must not change - // how many cells they filled, only which subjects the singleton slots - // picked out. - assert_eq!( - one.cells.len(), - permuted.cells.len(), - "a permutation changed how many cells the same subjects filled" - ); - } - - /// Every cell in one cover carries that cover's tick index. This is what the - /// driver's "advance the clock after the cells" ordering buys: one `now`, - /// one phase, one set of derived command ids per tick. - #[test] - fn soul_b_every_cell_shares_the_covers_tick_index() { - let opportunities = active(60); - for tick in [0u64, 1, 7, 4_000] { - let cover = derive( - &opportunities, - &AgencyGraph::default(), - budget(10, 8, 2), - tick, - ); - assert_eq!(cover.tick, TickIndex(tick)); - for cell in &cover.cells { - let carried = match cell { - Cell::Singleton { tick, .. } | Cell::Group { tick, .. } => *tick, - }; - assert_eq!(carried, cover.tick, "a cell carried another tick's index"); - } - } - } - - /// Derived ids are collision-free across every cell of every tick in a full - /// sweep, and a cell key never collides with a constituent key. - #[test] - fn soul_b_derived_ids_do_not_collide_across_a_sweep_of_ticks() { - let world = WorldId::nil_for_test(); - let opportunities = active(600); - let budget = budget(60, 24, 6); - let mut cells: BTreeSet<CellId> = BTreeSet::new(); - let mut keys: BTreeSet<Uuid> = BTreeSet::new(); - let mut cell_count = 0usize; - let mut key_count = 0usize; - for tick in 0..12u64 { - let cover = derive(&opportunities, &AgencyGraph::default(), budget, tick); - for cell in &cover.cells { - let id = match cell { - Cell::Singleton { id, .. } | Cell::Group { id, .. } => *id, - }; - cells.insert(id); - cell_count += 1; - keys.insert(cell_work_uuid(world, id, cover.tick)); - key_count += 1; - for member in cell.members() { - keys.insert(cell_constituent_uuid(world, id, member.subject, cover.tick)); - key_count += 1; - } - } - } - assert!( - cell_count >= 700, - "the sweep was too small to mean anything" - ); - assert_eq!(cells.len(), cell_count, "two cells share one id"); - assert_eq!(keys.len(), key_count, "two derived command keys collide"); - } - - /// The cap yields for exactly one reason: no partition inside the budget - /// respects it. Token capacity alone does not decide that — component shapes - /// do. Here `C * B = 12 >= N = 9`, and the cap still yields, because two - /// three-member components and two isolates cannot pack into two cells of - /// four. Coverage holds and the operator is told. - #[test] - fn soul_b_the_cap_yields_when_component_shapes_cannot_pack_inside_the_budget() { - let opportunities = active(9); - let mut graph = AgencyGraph::default(); - graph.link(subject(2), subject(3)); - graph.link(subject(3), subject(4)); - graph.link(subject(5), subject(6)); - graph.link(subject(6), subject(7)); - let cover = derive(&opportunities, &graph, budget(3, 4, 0), 0); - - assert_eq!(covered(&cover).len(), 9); - assert_eq!(covered(&cover).iter().collect::<BTreeSet<_>>().len(), 9); - assert!(cover.cells.len() <= 3); - assert!( - cover.cells.iter().any(|cell| cell.members().len() > 4), - "the cap did not yield: {:?}", - cover - .cells - .iter() - .map(|cell| cell.members().len()) - .collect::<Vec<_>>() - ); - assert!( - cover.oversubscribed, - "the cap yielded without telling the operator" - ); - - // The same subjects with no edges pack cleanly and the flag stays down, - // so the flag tracks the partition rather than the subject count. - let loose = derive(&opportunities, &AgencyGraph::default(), budget(3, 4, 0), 0); - assert!(!loose.oversubscribed); - assert!(loose.cells.iter().all(|cell| cell.members().len() <= 4)); - } -} diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index b8869262c..03d47c3dc 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -56,7 +56,6 @@ mod action; mod clock; -mod cover; mod grammar; #[cfg(test)] mod import_key_tests; @@ -66,7 +65,6 @@ mod patch; pub(crate) use action::ActionMismatch; pub(crate) use clock::Motion; pub use clock::{FictionalMinutes, TickMinutes}; -pub use cover::{AgencyGraph, Cell, Cover, CoverBudget, CoverBudgetError, TickIndex, derive_cover}; pub use grammar::{ GrammarBinding, GrammarError, GrammarIdentity, GrammarReferentKind, GrammarRole, GrammarVerb, RenderPath, @@ -203,26 +201,6 @@ impl CommandId { .map_err(|_| KernelError::InvalidCommandId) } - /// The cell's own controller-work key. One row per cell per tick, derived so - /// a resumed tick reopens the row it wrote rather than starting a second - /// cognition chain over the same opportunities. - pub(crate) fn for_cell(world: WorldId, cell: cover::CellId, tick: cover::TickIndex) -> Self { - Self(cover::cell_work_uuid(world, cell, tick)) - } - - /// One constituent's submission id. Deterministic over - /// `(world, cell, subject, tick)`, so a resumed cell re-submits the same id - /// and the kernel's idempotency ledger answers with the original receipt - /// instead of committing a second time. - pub(crate) fn for_cell_constituent( - world: WorldId, - cell: cover::CellId, - subject: SubjectId, - tick: cover::TickIndex, - ) -> Self { - Self(cover::cell_constituent_uuid(world, cell, subject, tick)) - } - /// sha256 over a namespace and its ordered, length-prefixed parts, first /// sixteen bytes. A command key, not a referent id: `patch::derive_id` /// still has exactly two call sites. No `uuid/v5`. @@ -1519,8 +1497,7 @@ impl WorldKernel { } /// The tick driver's opportunity list, in the same order a snapshot - /// carries it. Separate from `snapshot` for the reason `agency_graph` is: - /// only the tick driver reads it. + /// carries it. Separate from `snapshot`: only the tick driver reads it. fn opportunities(&self) -> Result<Vec<DecisionOpportunity>, KernelError> { self.journal.ensure_healthy()?; Ok(order_opportunities( @@ -1542,15 +1519,6 @@ impl WorldKernel { .count() as u64) } - /// The scheduler's adjacency projection. Separate from `snapshot` for the - /// same reason `operator_log` is: it is wider than any subject view, so a - /// `WorldSnapshot` field carrying it would be reachable from every prompt - /// builder in the process. - fn agency_graph(&self) -> Result<AgencyGraph, KernelError> { - self.journal.ensure_healthy()?; - Ok(agency_graph(&self.state)) - } - fn submit( &mut self, command: CommandEnvelope, @@ -3748,161 +3716,6 @@ fn operator_log( .collect() } -/// The scheduler's adjacency projection. It is deliberately wider than any -/// subject view — channel reach and place containment are in no subject's -/// snapshot at all — which is exactly why it is derived here, beside -/// `operator_log`, and handed to the cover rather than assembled by a -/// controller organ out of the union of what subjects can see. -/// -/// Nothing here is authority. Two subjects are adjacent when a decision by one -/// can plausibly land on the other, and adjacency only decides which prompt -/// they share. -fn agency_graph(state: &WorldState) -> AgencyGraph { - let active: BTreeSet<SubjectId> = state - .controller_assignments - .iter() - .filter(|(_, controller)| { - matches!(controller.mode(), Some(mode) if mode != ControllerMode::Human) - }) - .map(|(scope, _)| scope.subject_id) - .collect(); - let mut graph = AgencyGraph { - subjects: active.iter().copied().collect(), - edges: BTreeSet::new(), - }; - if active.len() < 2 { - return graph; - } - let live = |subject: &SubjectId| active.contains(subject); - - // Place containment, which subsumes "standing in the same room": a place - // covers itself, so one closure states both. - let mut in_place: BTreeMap<EntityId, BTreeSet<SubjectId>> = BTreeMap::new(); - for (place, record) in &state.entities { - if record.kind != EntityKind::Place { - continue; - } - let occupants: BTreeSet<SubjectId> = state - .positions - .iter() - .filter(|(subject, position)| { - live(subject) && patch::covers_place(&state.entities, *place, position.place) - }) - .map(|(subject, _)| *subject) - .collect(); - if occupants.len() >= 2 { - graph.relate(&occupants); - } - if !occupants.is_empty() { - in_place.insert(*place, occupants); - } - } - - // An open route makes two rooms one neighbourhood. One representative per - // side is enough: each side is already related internally. - for edge in state.edges.values() { - let EdgeRecord::Route { from, to, open, .. } = edge; - if !open { - continue; - } - if let (Some(here), Some(there)) = (in_place.get(from), in_place.get(to)) - && let (Some(one), Some(other)) = (here.first(), there.first()) - { - graph.link(*one, *other); - } - } - - // Dependencies: a named subject is a direct edge, a shared resource or - // route is a star over everyone leaning on it. - let mut shared: BTreeMap<DependencyTarget, BTreeSet<SubjectId>> = BTreeMap::new(); - for (subject, targets) in &state.dependencies { - if !live(subject) { - continue; - } - for target in targets { - match target { - DependencyTarget::Subject(other) if live(other) => graph.link(*subject, *other), - DependencyTarget::Subject(_) => {} - other => { - shared.entry(*other).or_default().insert(*subject); - } - } - } - } - for group in shared.values() { - graph.relate(group); - } - - // Authority and office: an institution and the people who hold its seats, - // and a jurisdiction that names one subject as its ground. - for (institution, offices) in &state.selection { - let mut seated: BTreeSet<SubjectId> = offices - .values() - .filter_map(|office| office.incumbent) - .filter(live) - .collect(); - if live(institution) { - seated.insert(*institution); - } - graph.relate(&seated); - } - for (holder, grants) in &state.authority { - if !live(holder) { - continue; - } - for grant in grants { - if let AuthorityTarget::Subject(over) = grant.over - && live(&over) - { - graph.link(*holder, over); - } - } - } - - // Channel reach. This is the edge no union of subject views could produce: - // a subject sees the channels it controls, never who else is in earshot. - for record in state.channels.values() { - let mut reached: BTreeSet<SubjectId> = match &record.reach { - Reach::Subjects(subjects) => subjects.iter().copied().filter(live).collect(), - Reach::Place(place) => in_place.get(place).cloned().unwrap_or_default(), - }; - if let Some(controller) = record.controller.filter(live) { - reached.insert(controller); - } - graph.relate(&reached); - } - - // Pressure, and the promises that raise it. - for (target, sources) in &state.pressures { - if !live(target) { - continue; - } - for source in sources.keys() { - let other = match source { - PressureSource::Commitment { subject, .. } => Some(*subject), - PressureSource::Dependency(DependencyTarget::Subject(subject)) => Some(*subject), - PressureSource::Subject(subject) => Some(*subject), - PressureSource::Dependency(_) => None, - }; - if let Some(other) = other.filter(live) { - graph.link(*target, other); - } - } - } - for (subject, promises) in &state.commitments { - if !live(subject) { - continue; - } - for commitment in promises.values() { - if let Some(counterparty) = commitment.counterparty.filter(live) { - graph.link(*subject, counterparty); - } - } - } - - graph -} - fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> { // One pass over the causal record so each subject's own knowledge map can be // stamped with the revision that minted each claim it holds. From 58493253b63a55e6679ca5bd0b85c0085de17c42 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Thu, 19 Nov 2026 22:01:10 +0100 Subject: [PATCH 122/190] Aetherlight AL2a.3: delete persona material Remove PersonaMaterial, PersonaReadRef, ComponentOp and ResolvedOp SetPersonaMaterial with its resolution, apply and confinement arms, WorldState.persona_material, the subject snapshot's material field and WorldPatch::sets_persona_of_existing_subject, with the tests whose subject they were. The op set goes from 34 to 33. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/lib.rs | 143 +-------------------- native/aetherlight/src/patch.rs | 215 +------------------------------- 2 files changed, 2 insertions(+), 356 deletions(-) diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index 03d47c3dc..ba5453027 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -78,7 +78,7 @@ pub(crate) use patch::{ BoundPrecondition, ChannelRecord, Commitment, CommitmentKind, Confidence, Cost, DependencyTarget, EntityKind, EvidenceRef, FactRecord, FactStanding, Forum, GrievanceKindName, Knowledge, KnowledgeSource, Office, OfficeName, - PersonaMaterial, Position, PressureMagnitude, PressureSource, Quantity, Reach, + Position, PressureMagnitude, PressureSource, Quantity, Reach, WorldScaleIntent, WorldScaleIntentRef, }; pub use patch::ImportKey; @@ -811,7 +811,6 @@ struct WorldState { commitments: BTreeMap<SubjectId, BTreeMap<CommitmentKey, Commitment>>, /// Lived meaning per subject. Read by projection and by nothing that /// decides, so it enters `state_digest` and no `ScopePreimage`. - persona_material: BTreeMap<SubjectId, PersonaMaterial>, /// Pressure *on* each subject, keyed target-major then source. Never empty /// for a present key; no stored zero magnitude. pressures: BTreeMap<SubjectId, BTreeMap<PressureSource, PressureMagnitude>>, @@ -975,8 +974,6 @@ pub struct SubjectSnapshot { /// itself. View-only, covered by no digest of its own: it is already bound /// through `components`. pub(crate) dependencies: Vec<DependencyTarget>, - /// What the subject carries as lived meaning, if anything was authored. - pub(crate) material: Option<PersonaMaterial>, /// A projection of `qualifies`, not a stored flag and not a second count: /// whether this subject already reduces its jurisdiction's scale deficit. /// The seed brief needs to say which subjects count; recomputing the @@ -1890,7 +1887,6 @@ impl WorldState { selection: BTreeMap::new(), redress: BTreeMap::new(), commitments: BTreeMap::new(), - persona_material: BTreeMap::new(), pressures: BTreeMap::new(), last_opportunity_at: BTreeMap::new(), now: FictionalMinutes::default(), @@ -2951,22 +2947,6 @@ fn apply_operation( ); } } - ResolvedOp::SetPersonaMaterial { subject, material } => { - if !state.subjects.contains_key(subject) - || material - .reads - .keys() - .any(|other| !state.subjects.contains_key(other)) - { - return Err(unknown()); - } - if state.persona_material.get(subject) == Some(material) { - return Err(KernelError::Invariant( - "persona material changes nothing".into(), - )); - } - state.persona_material.insert(*subject, material.clone()); - } ResolvedOp::SetReach { channel, reach } => { let current = state .channels @@ -3860,7 +3840,6 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> { .collect(), dependencies: components.dependencies.iter().copied().collect(), components, - material: state.persona_material.get(subject_id).cloned(), pressures: state .pressures .get(subject_id) @@ -4910,13 +4889,6 @@ fn operation_ground( // recipients here would be a second statement of the same rule, // computed from state this function does not read. ResolvedOp::Witness { place, .. } => (Vec::new(), places(vec![*place]), Vec::new()), - ResolvedOp::SetPersonaMaterial { subject, material } => ( - std::iter::once(*subject) - .chain(material.reads.keys().copied()) - .collect(), - Vec::new(), - Vec::new(), - ), ResolvedOp::SetReach { channel, reach } => { let mut subjects = Vec::new(); let mut named = Vec::new(); @@ -12673,119 +12645,6 @@ mod witness_tests { assert_eq!(reopened.snapshot().unwrap(), created); } - /// Persona material is set whole, refused when any text is non-canonical - /// or a read names a subject twice, refused when identical to what the - /// subject holds, and outside the scope digest: setting it moves no - /// opportunity's binding. - #[test] - fn soul_persona_material_is_set_whole_and_outside_the_scope_digest() { - use crate::patch::PersonaReadRef; - - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, world, active) = nesting_kernel(directory.path(), "Material"); - let text = |value: &str| Statement::new(value).unwrap(); - let material = |voice: Statement, reads: Vec<PersonaReadRef>| ComponentOp::SetPersonaMaterial { - subject: Ref::Existing(world.villager), - values: vec![text("Water is owed upward.")], - voice, - memories: vec![text("The gate froze the winter the ferry sank.")], - reads, - }; - let read = |subject: SubjectId| PersonaReadRef { - subject: Ref::Existing(subject), - statement: text("Counts every jar twice."), - }; - let digest_of = |snapshot: &WorldSnapshot| { - snapshot - .opportunities - .iter() - .find(|opportunity| opportunity.scope.subject_id == world.villager) - .map(|opportunity| opportunity.scope_digest.clone()) - }; - let before = digest_of(&active); - - // Padded text is refused at resolve, as is a subject read twice. - let padded: Statement = serde_json::from_value(serde_json::json!(" padded ")).unwrap(); - assert_eq!( - reject_owner( - &mut kernel, - &active, - operations(vec![material(padded, vec![read(world.neighbour)])]), - ), - vec![Mismatch::NoncanonicalText { operation: 0 }] - ); - assert_eq!( - reject_owner( - &mut kernel, - &active, - operations(vec![material( - text("Dry and exact."), - vec![read(world.neighbour), read(world.neighbour)], - )]), - ), - vec![Mismatch::NoncanonicalText { operation: 0 }] - ); - // A read of a subject the world does not hold is refused. - assert!( - !reject_owner( - &mut kernel, - &active, - operations(vec![material( - text("Dry and exact."), - vec![read(SubjectId::issue())], - )]), - ) - .is_empty() - ); - - let receipt = submit_owner( - &mut kernel, - &active, - operations(vec![material(text("Dry and exact."), vec![read(world.neighbour)])]), - ); - assert!(matches!(receipt, SubmitReceipt::Applied(_)), "{receipt:?}"); - let held = kernel.snapshot().unwrap(); - let villager = held - .subjects - .iter() - .find(|subject| subject.id == world.villager) - .unwrap(); - let carried = villager.material.as_ref().expect("material was set"); - assert_eq!(carried.voice.as_str(), "Dry and exact."); - assert_eq!( - carried.reads.get(&world.neighbour).map(Statement::as_str), - Some("Counts every jar twice.") - ); - assert_eq!(digest_of(&held), before, "material moved a scope digest"); - - // Identical material changes nothing; different material replaces all. - assert_eq!( - reject_owner( - &mut kernel, - &held, - operations(vec![material(text("Dry and exact."), vec![read(world.neighbour)])]), - ), - vec![Mismatch::NoOperationEffect { operation: 0 }] - ); - let held = kernel.snapshot().unwrap(); - submit_owner( - &mut kernel, - &held, - operations(vec![material(text("Slow and courteous."), Vec::new())]), - ); - let replaced = kernel.snapshot().unwrap(); - let carried = replaced - .subjects - .iter() - .find(|subject| subject.id == world.villager) - .unwrap() - .material - .clone() - .unwrap(); - assert_eq!(carried.voice.as_str(), "Slow and courteous."); - assert!(carried.reads.is_empty(), "a whole-value set kept an old read"); - } - /// What a witness hands the narrative lane's interruption renderer. The /// renderer takes a subject's own `ScopeComponents` and its own knowledge /// rows and nothing else, so both of its inputs are pinned here rather than diff --git a/native/aetherlight/src/patch.rs b/native/aetherlight/src/patch.rs index 583713a79..4023addea 100644 --- a/native/aetherlight/src/patch.rs +++ b/native/aetherlight/src/patch.rs @@ -353,29 +353,6 @@ pub(crate) struct ChannelRecord { pub(crate) controller: Option<SubjectId>, } -/// Lived meaning a subject carries: values, a voice, memories, and reads of -/// other subjects. It constrains no precondition, so it is outside every scope -/// digest and cannot interrupt a bound turn; it enriches projection and never -/// substitutes for authority, custody, topology, or knowledge. Set whole, so a -/// subject holds one value at one revision. -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub(crate) struct PersonaMaterial { - pub(crate) values: Vec<Statement>, - pub(crate) voice: Statement, - pub(crate) memories: Vec<Statement>, - /// One read per subject, in canonical order. - pub(crate) reads: BTreeMap<SubjectId, Statement>, -} - -/// The proposal-time twin of a read: the subject by reference. -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub(crate) struct PersonaReadRef { - pub(crate) subject: Ref<SubjectId>, - pub(crate) statement: Statement, -} - /// A small closed ordinal. Ordered ascending by declaration order, so derived /// `Ord` *is* the semantics and `Knows { at_least }` is one `>=`. Three levels: /// two cannot express "I heard it but I doubt it", which is the state deception @@ -1260,15 +1237,6 @@ pub(crate) enum ComponentOp { channel: Ref<EntityId>, controller: Option<Ref<SubjectId>>, }, - /// Sets, whole, what a subject carries as lived meaning. Identical material - /// is `NoOperationEffect`; any non-canonical text is `NoncanonicalText`. - SetPersonaMaterial { - subject: Ref<SubjectId>, - values: Vec<Statement>, - voice: Statement, - memories: Vec<Statement>, - reads: Vec<PersonaReadRef>, - }, /// Two identical creations are two commitments, not `NoOperationEffect`: /// the key is command-derived so they cannot collide, and two promises of /// the same thing to the same counterparty are two promises. This is where @@ -1347,28 +1315,6 @@ pub struct WorldPatch { pub(crate) evidence: Vec<EvidenceRef>, } -impl WorldPatch { - /// Whether any `SetPersonaMaterial` operation in this patch targets a - /// subject the patch does not itself declare — an existing, canonical - /// subject (`Ref::Existing`) rather than a draft handle this same patch's - /// own declarations introduced (`Ref::Draft`). `WorldPatch`'s fields are - /// `pub(crate)`, so a consumer that must refuse this shape (PA.f61: the - /// play agent may author a brand-new Persona's material, but never - /// rewrite an existing one's) reads it through this query rather than - /// parsing the patch's own JSON to decide. - pub fn sets_persona_of_existing_subject(&self) -> bool { - self.operations.iter().any(|operation| { - matches!( - operation, - ComponentOp::SetPersonaMaterial { - subject: Ref::Existing(_), - .. - } - ) - }) - } -} - /// The one byte bound on a `WorldPatch` frame from any external source, and /// the three item bounds on a `WorldPatch` as a value. One owner, two /// consumers: the consumer ingress decodes against them through @@ -1681,8 +1627,7 @@ pub enum Mismatch { EmptyStatement { handle: DraftHandle, }, - /// A commitment statement or a piece of persona material that is empty, - /// padded, or spans lines. + /// A commitment statement that is empty, padded, or spans lines. NoncanonicalText { operation: usize, }, @@ -2036,10 +1981,6 @@ pub(crate) enum ResolvedOp { channel: EntityId, controller: Option<SubjectId>, }, - SetPersonaMaterial { - subject: SubjectId, - material: PersonaMaterial, - }, /// Kernel-only: no [`ComponentOp`] twin, because no proposer may author one. /// Synthesized by `action::exercise` for a speech-carrying invocation and by /// nothing else. Inserts the entity row and the `facts` row; it writes no @@ -4955,67 +4896,6 @@ pub(super) fn resolve_patch( } } } - ComponentOp::SetPersonaMaterial { - subject, - values, - voice, - memories, - reads, - } => { - let site = Site::Operation(position); - let subject_key = - resolve_subject(site.clone(), subject, &index, &state.subjects, &mut mismatches); - let mut read_keys = Vec::with_capacity(reads.len()); - for read in reads { - read_keys.push(resolve_subject( - site.clone(), - &read.subject, - &index, - &state.subjects, - &mut mismatches, - )); - } - let texts = values - .iter() - .chain(memories.iter()) - .chain(std::iter::once(voice)) - .chain(reads.iter().map(|read| &read.statement)); - let mut read_subjects: BTreeSet<&Ref<SubjectId>> = BTreeSet::new(); - let duplicate_read = reads.iter().any(|read| !read_subjects.insert(&read.subject)); - if texts.clone().any(|text| !is_canonical_text(text.as_str())) || duplicate_read { - mismatches.push(Mismatch::NoncanonicalText { - operation: position, - }); - } - let (Some(Key::Existing(subject_id)), true) = - (subject_key, read_keys.iter().all(Option::is_some)) - else { - continue; - }; - // Identical material on an existing subject changes nothing. A - // draft read can never equal a held one, so it is skipped here. - let held: Option<BTreeMap<SubjectId, Statement>> = read_keys - .iter() - .zip(reads) - .map(|(key, read)| match key { - Some(Key::Existing(id)) => Some((*id, read.statement.clone())), - _ => None, - }) - .collect(); - if let Some(held) = held - && state.persona_material.get(&subject_id) - == Some(&PersonaMaterial { - values: values.clone(), - voice: voice.clone(), - memories: memories.clone(), - reads: held, - }) - { - mismatches.push(Mismatch::NoOperationEffect { - operation: position, - }); - } - } ComponentOp::SetReach { channel, reach } => { let channel_key = resolve_entity( Site::Operation(position), @@ -5784,24 +5664,6 @@ pub(super) fn resolve_patch( channel: entity_id_of(&key_of(channel)), reach: reach_of(reach), }, - ComponentOp::SetPersonaMaterial { - subject, - values, - voice, - memories, - reads, - } => ResolvedOp::SetPersonaMaterial { - subject: subject_id_of(&key_of(subject)), - material: PersonaMaterial { - values: values.clone(), - voice: voice.clone(), - memories: memories.clone(), - reads: reads - .iter() - .map(|read| (subject_id_of(&key_of(&read.subject)), read.statement.clone())) - .collect(), - }, - }, ComponentOp::SetController { channel, controller, @@ -6052,81 +5914,6 @@ mod tests { CallerId, CommandBody, CommandId, KernelError, SubmitReceipt, WorldKernel, WorldPhase, }; - /// Owner: `WorldPatch::sets_persona_of_existing_subject`. Consumer: - /// `ghostlight-dungeon`'s play agent (PA.f61, parked at - /// `parked/ghostlight-eve-surface`), which refuses a - /// `set_persona_material` run whose patch answers true here, since - /// `WorldPatch`'s own fields are `pub(crate)` and Dungeon may not parse - /// its JSON to decide the question itself. - #[test] - fn sets_persona_of_existing_subject_reads_the_subject_refs_own_shape() { - let empty = WorldPatch::default(); - assert!(!empty.sets_persona_of_existing_subject()); - - let existing = WorldPatch { - declarations: Vec::new(), - operations: vec![ComponentOp::SetPersonaMaterial { - subject: Ref::Existing(SubjectId::issue()), - values: Vec::new(), - voice: Statement::new("flat and even").unwrap(), - memories: Vec::new(), - reads: Vec::new(), - }], - evidence: Vec::new(), - }; - assert!(existing.sets_persona_of_existing_subject()); - - let draft = WorldPatch { - declarations: Vec::new(), - operations: vec![ComponentOp::SetPersonaMaterial { - subject: Ref::Draft(DraftHandle::new("npc")), - values: Vec::new(), - voice: Statement::new("flat and even").unwrap(), - memories: Vec::new(), - reads: Vec::new(), - }], - evidence: Vec::new(), - }; - assert!(!draft.sets_persona_of_existing_subject()); - } - - /// PA.f92/PA.f110: a fixture whose persona write sits at either end of - /// `operations` only ever exercises `.take(1)` (op 0) or `.rev().take(1)` - /// (the last op) — the prior version of this test put the write last, - /// so `.rev().take(1)` would still find it and pass undetected. Here the - /// persona write to an existing subject sits strictly in the *middle*, - /// with a harmless `Relocate` both before and after it: only a scan over - /// every operation, in either direction, reports `true`. - #[test] - fn sets_persona_of_existing_subject_scans_every_operation_not_just_an_end() { - let patch = WorldPatch { - declarations: Vec::new(), - operations: vec![ - ComponentOp::Relocate { - subject: Ref::Draft(DraftHandle::new("wanderer")), - via: Ref::Draft(DraftHandle::new("path")), - }, - ComponentOp::SetPersonaMaterial { - subject: Ref::Existing(SubjectId::issue()), - values: Vec::new(), - voice: Statement::new("flat and even").unwrap(), - memories: Vec::new(), - reads: Vec::new(), - }, - ComponentOp::Relocate { - subject: Ref::Draft(DraftHandle::new("wanderer")), - via: Ref::Draft(DraftHandle::new("second-path")), - }, - ], - evidence: Vec::new(), - }; - // Op 0 and the last op (index 2) are both the harmless `Relocate`; - // only op 1, strictly in the middle, is the persona write. A - // `.take(1)` mutation sees only op 0; a `.rev().take(1)` mutation - // sees only op 2. Both would report `false` here. - assert!(patch.sets_persona_of_existing_subject()); - } - fn entity(handle: &str, label: &str, kind: EntityKind) -> Declaration { Declaration::Entity(EntityDeclaration { handle: DraftHandle::new(handle), From f17a8147f886fef453e3db95efe379220c6209e8 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Thu, 19 Nov 2026 22:02:14 +0100 Subject: [PATCH 123/190] Aetherlight AL2a.4: delete the genesis brief Remove the brief string (prompt guidance for model lanes) from CreateWorld, CreateWorldIntent, WorldState, WorldEffect::WorldCreated, the snapshot and the journal's state-shape checks, with its replay test. The grammar test's absent-grammar-key control now reads the title key. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/grammar/tests.rs | 2 +- native/aetherlight/src/journal.rs | 9 ------ native/aetherlight/src/lib.rs | 41 ------------------------- 3 files changed, 1 insertion(+), 51 deletions(-) diff --git a/native/aetherlight/src/grammar/tests.rs b/native/aetherlight/src/grammar/tests.rs index 4b1373709..c5219f807 100644 --- a/native/aetherlight/src/grammar/tests.rs +++ b/native/aetherlight/src/grammar/tests.rs @@ -311,7 +311,7 @@ fn unbound_world_keeps_the_open_catalog() { let keys: std::collections::BTreeMap<String, serde::de::IgnoredAny> = rmp_serde::from_slice(&encoded).unwrap(); assert!(!keys.contains_key("grammar")); - assert!(keys.contains_key("brief")); + assert!(keys.contains_key("title")); } #[test] diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index 31f22fad5..e8064175f 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -496,12 +496,6 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> "world title is empty or noncanonical".into(), )); } - if state.brief.trim() != state.brief { - return Err(JournalError::Corrupt("world brief is noncanonical".into())); - } - if state.brief.trim() != state.brief { - return Err(JournalError::Corrupt("world brief is noncanonical".into())); - } super::validate_principal(&state.owner).map_err(kernel_error)?; if state.subjects.is_empty() || state.controller_assignments.len() != state.subjects.len() @@ -1107,7 +1101,6 @@ mod tests { id: CommandId::new(), owner: owner.clone(), title: "Before".into(), - brief: String::new(), patch: owner_patch(SubjectDeclaration { handle: DraftHandle::new("owner"), label: "Owner".into(), @@ -1191,7 +1184,6 @@ mod tests { id: CommandId::new(), owner: owner.clone(), title: "Kharad".into(), - brief: String::new(), patch: owner_patch(SubjectDeclaration { handle: DraftHandle::new("owner"), label: "Owner".into(), @@ -1671,7 +1663,6 @@ mod tests { id: creation_id, owner: owner.clone(), title: "Admitted".into(), - brief: String::new(), patch: owner_patch(SubjectDeclaration { handle: DraftHandle::new("owner"), label: "Owner".into(), diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index ba5453027..63fcc0b8b 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -359,9 +359,6 @@ struct CreateWorld { id: CommandId, owner: PrincipalId, title: String, - /// The world's authored premise, in the owner's words. Every lane reads it - /// as its guidance; nothing derives it and nothing writes it later. - brief: String, patch: WorldPatch, /// Authored once, here, and never mutated: `CommandBody::AdmitPatch` carries /// no intent, so write-once is the command shape rather than a check. @@ -378,9 +375,6 @@ struct CreateWorld { pub struct CreateWorldIntent { pub id: CommandId, pub title: String, - /// The premise, verbatim from the owner. May be empty: a world with no - /// brief is a deliberate choice, and its lanes then get no guidance. - pub brief: String, pub human_subject_label: String, pub narrative_persona_label: Option<String>, pub operational_agent_label: Option<String>, @@ -762,9 +756,6 @@ struct WorldState { phase: WorldPhase, owner: PrincipalId, title: String, - /// Authored at creation and never mutated; the one prose the world says - /// about itself, projected as guidance to every lane. - brief: String, /// Bound by genesis and never written again; absent from a world with no /// grammar, so such a world's state and digests are what they were before /// grammars existed. @@ -843,7 +834,6 @@ enum WorldEffect { WorldCreated { owner: PrincipalId, title: String, - brief: String, resolved: ResolvedPatch, }, PatchAdmitted { @@ -1131,7 +1121,6 @@ pub struct WorldSnapshot { pub phase: WorldPhase, pub owner: PrincipalId, pub title: String, - pub brief: String, /// The bound grammar's identity; none for a world with an open catalog. pub grammar: Option<GrammarIdentity>, pub draft_approvals: BTreeSet<PrincipalId>, @@ -1355,7 +1344,6 @@ struct PreparedCreation { world_id: WorldId, owner: PrincipalId, title: String, - brief: String, resolved: ResolvedPatch, } @@ -1371,7 +1359,6 @@ fn prepare_creation( return Err(KernelError::AuthenticationMismatch); } let title = normalize_title(&input.title)?; - let brief = input.brief.trim().to_owned(); // The world's own identity is not world structure, and it feeds every // derived ID, so it is minted before resolution rather than by it. let world_id = WorldId::issue(); @@ -1393,7 +1380,6 @@ fn prepare_creation( world_id, owner: input.owner.clone(), title, - brief, resolved, command: input, }) @@ -1408,7 +1394,6 @@ impl WorldKernel { let effect = WorldEffect::WorldCreated { owner: prepared.owner, title: prepared.title, - brief: prepared.brief, resolved: prepared.resolved, }; let mut state = WorldState::genesis(world_id, &prepared.command, &effect)?; @@ -1871,7 +1856,6 @@ impl WorldState { phase: WorldPhase::Draft, owner, title, - brief: String::new(), grammar, draft_approvals: BTreeSet::new(), subjects: BTreeMap::new(), @@ -1908,7 +1892,6 @@ impl WorldState { let WorldEffect::WorldCreated { owner, title, - brief, resolved, } = effect else { @@ -1927,7 +1910,6 @@ impl WorldState { // every other command. Deterministic allocation is what lets one // equality replace a field-by-field binding zip. let mut state = Self::empty(world_id, owner.clone(), title.clone(), command.grammar.clone()); - state.brief = brief.clone(); let expected = patch::resolve_patch( &state, command.id, @@ -3928,7 +3910,6 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> { phase: state.phase, owner: state.owner.clone(), title: state.title.clone(), - brief: state.brief.clone(), grammar: state.grammar.as_ref().map(GrammarBinding::identity), draft_approvals: state.draft_approvals.clone(), required_approvers: required_approvers(state), @@ -5322,7 +5303,6 @@ mod tests { id, owner: owner(), title: title.into(), - brief: String::new(), patch: WorldPatch { operations: Vec::new(), evidence: Vec::new(), @@ -12626,25 +12606,6 @@ mod witness_tests { ); } - /// The brief is the world's authored premise: trimmed at ingress, carried - /// on the state and its snapshot, and identical after replay. - #[test] - fn the_world_brief_is_authored_once_trimmed_and_replayed() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let mut creation = creation(CommandId::new(), "Low Sere"); - creation.brief = " A dry basin town that owes its water to the gate above it. ".into(); - let (kernel, _) = WorldKernel::create(&path, creation, &auth_principal(owner())).unwrap(); - let created = kernel.snapshot().unwrap(); - assert_eq!( - created.brief, - "A dry basin town that owes its water to the gate above it." - ); - drop(kernel); - let reopened = WorldKernel::open(&path, created.world_id).unwrap(); - assert_eq!(reopened.snapshot().unwrap(), created); - } - /// What a witness hands the narrative lane's interruption renderer. The /// renderer takes a subject's own `ScopeComponents` and its own knowledge /// rows and nothing else, so both of its inputs are pinned here rather than @@ -14972,7 +14933,6 @@ mod clock_tests { let effect = WorldEffect::WorldCreated { owner: input.owner.clone(), title, - brief: input.brief.clone(), resolved, }; let error = WorldState::genesis(world_id, &input, &effect).unwrap_err(); @@ -15000,7 +14960,6 @@ mod clock_tests { let effect = WorldEffect::WorldCreated { owner: input.owner.clone(), title, - brief: input.brief.clone(), resolved, }; let error = WorldState::genesis(world_id, &input, &effect).unwrap_err(); From 1919828a7e72fedf7d6abaca6cad7abc6dbd498b Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Thu, 19 Nov 2026 22:16:54 +0100 Subject: [PATCH 124/190] Aetherlight AL2a.5: delete the elaborator lane, the answer gate and the scale intent Remove SystemCapability::Elaborator, PatchAnswer, CausalBoundary and its derivation, the AnswerRequired gate (require_answer, the answers field of AdmitPatch and PatchAdmitted, the three Answer* errors), ground_covers and the jurisdiction ground, WorldScaleIntent and its refs, JurisdictionKey, the scale deficit and the subject snapshot's qualified flag. require_play_active keeps the one rule require_answer also held: Play authors nothing in Draft. The owner now declares in Active unanswered. Tests whose subject was the lane go. Kept-lane tests that used the elaborator as setup are rewritten over the owner, Play or a consumer: the import-key and grammar door tests, the capability-admission test, the ruler re-decision tests, the confined-author retire/grant/revoke tests, the orphan-claim test, and the witness-arrival test. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/action.rs | 2 - native/aetherlight/src/grammar/tests.rs | 44 +- native/aetherlight/src/import_key_tests.rs | 62 +- native/aetherlight/src/journal.rs | 174 +- native/aetherlight/src/lib.rs | 2677 +------------------- native/aetherlight/src/patch.rs | 173 +- 6 files changed, 138 insertions(+), 2994 deletions(-) diff --git a/native/aetherlight/src/action.rs b/native/aetherlight/src/action.rs index ca0c16a6c..031579623 100644 --- a/native/aetherlight/src/action.rs +++ b/native/aetherlight/src/action.rs @@ -171,7 +171,6 @@ pub(super) fn exercise( operations, evidence: Vec::new(), }, - None, ) .map_err(KernelError::PatchRejected)? .operations @@ -2094,7 +2093,6 @@ mod tests { &mut draft, &before, CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: vec![Declaration::Affordance(AffordanceDeclaration { handle: handle.clone(), diff --git a/native/aetherlight/src/grammar/tests.rs b/native/aetherlight/src/grammar/tests.rs index c5219f807..ec9115e82 100644 --- a/native/aetherlight/src/grammar/tests.rs +++ b/native/aetherlight/src/grammar/tests.rs @@ -104,7 +104,6 @@ fn admit(kernel: &mut WorldKernel, patch: WorldPatch) -> Result<SubmitReceipt, K CommandId::new(), CallerId::Principal(owner()), CommandBody::AdmitPatch { - answers: None, patch, }, ), @@ -487,7 +486,6 @@ fn a_grammar_names_each_verb_once_and_has_a_schema() { fn submit_as( kernel: &mut WorldKernel, caller: CallerId, - answers: Option<crate::PatchAnswer>, patch: WorldPatch, ) -> Result<SubmitReceipt, KernelError> { let snapshot = kernel.snapshot().unwrap(); @@ -496,14 +494,14 @@ fn submit_as( &snapshot, CommandId::new(), caller.clone(), - CommandBody::AdmitPatch { answers, patch }, + CommandBody::AdmitPatch { patch }, ), &crate::AuthenticatedCaller::fixture(caller), ) } /// A bound Draft world whose revision has moved past genesis: one owner patch -/// that adds a dead-end place the elaborator can answer. +/// that adds a dead-end place. fn advanced_grammar_world() -> (tempfile::TempDir, WorldKernel, crate::EntityId) { let extra = [("hail", verb(RenderPath::Conversation, &[]))]; let (dir, kernel) = create(bound(Some(grammar_with(&extra)), "Advanced")); @@ -539,25 +537,23 @@ fn advanced_grammar_world() -> (tempfile::TempDir, WorldKernel, crate::EntityId) (dir, kernel, dead_end) } -type Door = (&'static str, CallerId, Option<crate::PatchAnswer>); +type Door = (&'static str, CallerId); /// Each door refuses an outside kind and a wrong role signature, typed, and the /// refusal leaves the revision where it was. The owner and the consumer declare -/// unanswered only in Draft; Play and the elaborator act in Active. +/// in Draft and in Active; Play acts in Active. fn refuse_at_each_door(kernel: &mut WorldKernel, doors: Vec<Door>) { - for (door, caller, answers) in doors { + for (door, caller) in doors { let revision = kernel.state.revision; let kind = submit_as( kernel, caller.clone(), - answers.clone(), patch_of(vec![declare("wave", "wave", &[])]), ); assert_eq!(rejected(kind), not_in_grammar("wave"), "{door}"); let roles = submit_as( kernel, caller, - answers, patch_of(vec![declare("hail", "hail", &[("who", person())])]), ); assert_eq!(rejected(roles), disagrees("hail"), "{door}"); @@ -570,16 +566,15 @@ fn refuse_at_each_door(kernel: &mut WorldKernel, doors: Vec<Door>) { #[test] fn every_admission_door_refuses_outside_the_grammar_after_the_revision_has_moved() { - let (_dir, mut kernel, dead_end) = advanced_grammar_world(); + let (_dir, mut kernel, _) = advanced_grammar_world(); assert_eq!(kernel.state.revision, 1); let draft_doors = vec![ - ("owner", CallerId::Principal(owner()), None), + ("owner", CallerId::Principal(owner())), ( "consumer", CallerId::System(crate::SystemCapability::Consumer { consumer: crate::ConsumerId::of_name("grammar-door"), }), - None, ), ]; refuse_at_each_door(&mut kernel, draft_doors); @@ -588,27 +583,9 @@ fn every_admission_door_refuses_outside_the_grammar_after_the_revision_has_moved kernel.state.revision > 1, "the world has moved past genesis" ); - let answer = crate::derive_boundaries(&kernel.state) - .unwrap() - .into_iter() - .find(|boundary| { - matches!(boundary, crate::CausalBoundary::UnelaboratedDestination { place, .. } - if *place == dead_end) - }) - .expect("the dead end is an unelaborated destination"); let active_doors = vec![ - ( - "play", - CallerId::System(crate::SystemCapability::Play), - None, - ), - ( - "elaborator", - CallerId::System(crate::SystemCapability::Elaborator { - jurisdiction: crate::JurisdictionKey::PlaceSubtree(dead_end), - }), - Some(crate::PatchAnswer::Boundary(answer)), - ), + ("owner in Active", CallerId::Principal(owner())), + ("play", CallerId::System(crate::SystemCapability::Play)), ]; refuse_at_each_door(&mut kernel, active_doors); // The same path admits what the grammar carries, so the refusals above are @@ -616,7 +593,6 @@ fn every_admission_door_refuses_outside_the_grammar_after_the_revision_has_moved let receipt = submit_as( &mut kernel, CallerId::System(crate::SystemCapability::Play), - None, patch_of(vec![declare("hail", "hail", &[])]), ) .unwrap(); @@ -682,7 +658,6 @@ fn an_effect_resolved_elsewhere_cannot_install_an_entry_outside_the_grammar() { &twin, CommandId::new(), &patch_of(vec![declare("probe", kind, roles)]), - None, ) .expect("the unbound twin admits any canonical kind") }; @@ -698,7 +673,6 @@ fn an_effect_resolved_elsewhere_cannot_install_an_entry_outside_the_grammar() { CommandId::new(), &CallerId::Principal(owner()), &crate::WorldEffect::PatchAdmitted { - answers: None, resolved, }, ); diff --git a/native/aetherlight/src/import_key_tests.rs b/native/aetherlight/src/import_key_tests.rs index 41800eab9..a1001c76a 100644 --- a/native/aetherlight/src/import_key_tests.rs +++ b/native/aetherlight/src/import_key_tests.rs @@ -8,8 +8,8 @@ use crate::patch::{ }; use crate::tests::{activate, auth_principal, command, creation, owner}; use crate::{ - CallerId, CommandBody, CommandId, ConsumerId, CreateWorld, EntityId, JurisdictionKey, - KernelError, NewController, PatchAnswer, SubjectDeclaration, SubjectKind, SubmitReceipt, + CallerId, CommandBody, CommandId, ConsumerId, CreateWorld, EntityId, KernelError, + NewController, SubjectDeclaration, SubjectKind, SubmitReceipt, SystemCapability, WorldKernel, WorldPatch, }; use std::collections::BTreeSet; @@ -70,7 +70,6 @@ fn patch_of(declarations: Vec<Declaration>) -> WorldPatch { fn submit_as( kernel: &mut WorldKernel, caller: CallerId, - answers: Option<PatchAnswer>, patch: WorldPatch, ) -> Result<SubmitReceipt, KernelError> { let snapshot = kernel.snapshot().unwrap(); @@ -79,7 +78,7 @@ fn submit_as( &snapshot, CommandId::new(), caller.clone(), - CommandBody::AdmitPatch { answers, patch }, + CommandBody::AdmitPatch { patch }, ), &crate::AuthenticatedCaller::fixture(caller), ) @@ -156,7 +155,6 @@ fn one_patch_cannot_declare_two_subjects_with_one_import_key() { let error = submit_as( &mut kernel, CallerId::Principal(owner()), - None, patch_of(vec![ mirror("first", beta.clone(), place), mirror("second", beta, place), @@ -167,14 +165,13 @@ fn one_patch_cannot_declare_two_subjects_with_one_import_key() { } /// The fixture world past genesis but still in Draft: the owner has added an -/// unwalked place the elaborator can later answer. +/// unwalked place. fn advanced_keyed_world() -> (tempfile::TempDir, WorldKernel, EntityId) { let (dir, mut kernel) = keyed_world(); let place = commons(&kernel); submit_as( &mut kernel, CallerId::Principal(owner()), - None, patch_of(vec![ Declaration::Entity(EntityDeclaration { handle: DraftHandle::new("dead-end"), @@ -204,19 +201,18 @@ fn advanced_keyed_world() -> (tempfile::TempDir, WorldKernel, EntityId) { } /// Each door names the held key, typed, and the refusal leaves the revision -/// where it was. The owner and the consumer declare in Draft only; Play and the -/// elaborator act in Active. +/// where it was. The owner and the consumer declare in Draft, and in Active +/// too; Play acts in Active. fn refuse_held_key_at_each_door( kernel: &mut WorldKernel, place: EntityId, - doors: Vec<(&str, CallerId, Option<PatchAnswer>)>, + doors: Vec<(&str, CallerId)>, ) { - for (door, caller, answers) in doors { + for (door, caller) in doors { let revision = kernel.state.revision; let result = submit_as( kernel, caller, - answers, patch_of(vec![mirror("copy", Some(alpha()), place)]), ); assert_eq!(rejected(result), vec![held("copy")], "{door}"); @@ -241,31 +237,17 @@ fn a_held_import_key_is_refused_at_every_door_after_the_revision_has_moved() { &mut kernel, dead_end, vec![ - ("owner", CallerId::Principal(owner()), None), - ("consumer", consumer(), None), + ("owner", CallerId::Principal(owner())), + ("consumer", consumer()), ], ); activate(&mut kernel); - let answer = crate::derive_boundaries(&kernel.state) - .unwrap() - .into_iter() - .find(|boundary| { - matches!(boundary, crate::CausalBoundary::UnelaboratedDestination { place, .. } - if *place == dead_end) - }) - .expect("the dead end is an unelaborated destination"); refuse_held_key_at_each_door( &mut kernel, dead_end, vec![ - ("play", CallerId::System(SystemCapability::Play), None), - ( - "elaborator", - CallerId::System(SystemCapability::Elaborator { - jurisdiction: JurisdictionKey::PlaceSubtree(dead_end), - }), - Some(PatchAnswer::Boundary(answer.clone())), - ), + ("owner in Active", CallerId::Principal(owner())), + ("play", CallerId::System(SystemCapability::Play)), ], ); // The same doors admit an unheld key, so the refusals are the key's; and @@ -273,10 +255,7 @@ fn a_held_import_key_is_refused_at_every_door_after_the_revision_has_moved() { let fresh = key("aetheria.ship", "Gamma"); let receipt = submit_as( &mut kernel, - CallerId::System(SystemCapability::Elaborator { - jurisdiction: JurisdictionKey::PlaceSubtree(dead_end), - }), - Some(PatchAnswer::Boundary(answer)), + CallerId::Principal(owner()), patch_of(vec![mirror("fresh", Some(fresh.clone()), dead_end)]), ) .unwrap(); @@ -284,7 +263,6 @@ fn a_held_import_key_is_refused_at_every_door_after_the_revision_has_moved() { let again = submit_as( &mut kernel, CallerId::System(SystemCapability::Play), - None, patch_of(vec![mirror("fresh-again", Some(fresh), dead_end)]), ); assert_eq!(rejected(again), vec![held("fresh-again")]); @@ -298,7 +276,6 @@ fn a_held_import_key_is_refused_in_a_later_patch() { let error = submit_as( &mut kernel, CallerId::Principal(owner()), - None, patch_of(vec![mirror("again", Some(alpha()), place)]), ); assert_eq!(rejected(error), vec![held("again")]); @@ -321,7 +298,6 @@ fn a_retired_subjects_import_key_is_never_reissued() { submit_as( &mut kernel, CallerId::Principal(owner()), - None, WorldPatch { declarations: Vec::new(), operations: vec![ComponentOp::Retire { @@ -347,7 +323,6 @@ fn a_retired_subjects_import_key_is_never_reissued() { let error = submit_as( &mut kernel, CallerId::Principal(owner()), - None, patch_of(vec![mirror("reborn", Some(alpha()), place)]), ); assert_eq!(rejected(error), vec![held("reborn")]); @@ -378,7 +353,6 @@ fn keys_that_differ_in_any_way_are_distinct_records() { submit_as( &mut kernel, CallerId::Principal(owner()), - None, patch_of(declarations), ) .expect("nine distinct keys beside the held one are admitted together"); @@ -389,7 +363,6 @@ fn keys_that_differ_in_any_way_are_distinct_records() { let again = submit_as( &mut kernel, CallerId::Principal(owner()), - None, patch_of(vec![mirror("repeat", Some(forged.clone()), place)]), ); assert_eq!(rejected(again), vec![held("repeat")], "forgery {index}"); @@ -419,7 +392,6 @@ fn a_malformed_import_key_is_refused_without_echoing_it() { let set = rejected(submit_as( &mut kernel, CallerId::Principal(owner()), - None, patch_of(vec![mirror("bad", Some(bad.clone()), place)]), )); assert_eq!(set, vec![malformed("bad")], "case {index}"); @@ -443,7 +415,6 @@ fn a_malformed_import_key_is_refused_without_echoing_it() { submit_as( &mut kernel, CallerId::Principal(owner()), - None, patch_of(declarations), ) .expect("keys of exactly 200 bytes per part are admitted"); @@ -462,7 +433,6 @@ fn the_subjects_map_refuses_a_second_subject_for_one_key_even_when_resolved_else Some(key("aetheria.ship", "Omega")), place, )]), - None, ) .expect("the key is unheld at the revision both were resolved against") }; @@ -470,7 +440,6 @@ fn the_subjects_map_refuses_a_second_subject_for_one_key_even_when_resolved_else let mut state = kernel.state.clone(); let before = state.subjects.len(); let effect = |resolved| crate::WorldEffect::PatchAdmitted { - answers: None, resolved, }; crate::apply_effect( @@ -558,7 +527,6 @@ fn a_record_key_is_one_canonical_spelling() { submit_as( kernel, CallerId::Principal(owner()), - None, patch_of(vec![mirror( handle, Some(key("aetheria.ship", record)), @@ -607,7 +575,6 @@ fn a_lore_page_path_with_spaces_is_a_record_key() { submit_as( kernel, CallerId::Principal(owner()), - None, patch_of(vec![mirror( handle, Some(key("aetheria.lore", record)), @@ -626,7 +593,6 @@ fn a_loaded_state_with_a_bad_import_key_is_refused() { submit_as( &mut kernel, CallerId::Principal(owner()), - None, patch_of(vec![mirror( "beta", Some(key("aetheria.ship", "Beta")), @@ -678,7 +644,6 @@ fn admitting_a_resolved_effect_refuses_two_subjects_with_one_key() { mirror("first", Some(key("aetheria.ship", "Beta")), place), mirror("second", Some(key("aetheria.ship", "Gamma")), place), ]), - None, ) .expect("two distinct keys resolve") }; @@ -714,7 +679,6 @@ fn a_decomposable_character_is_refused_in_nfd_at_every_position() { submit_as( kernel, CallerId::Principal(owner()), - None, patch_of(vec![mirror( handle, Some(key("aetheria.lore", &record)), diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index e8064175f..1ae7ca180 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -433,8 +433,8 @@ pub(super) fn verify_history( // Authority is re-decided here for free: `apply_committed_command` // re-runs `reduce` against the pre-commit state and requires effect // equality, then `apply_effect`, and both of those call - // `require_patch_author` and `confine_to_jurisdiction`. A forged row - // claiming an elaborator caller for a patch outside its jurisdiction + // `require_patch_author` and `confine_to_ground`. A forged row + // claiming a confined caller for a patch outside its ground // fails replay rather than being admitted by a reducer that trusts the // recorded caller. A third statement of the same rule here would be a // third owner of one decision. @@ -736,23 +736,6 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> "an attention stamp names an unknown subject or a future minute".into(), )); } - if state - .scale_intent - .jurisdictions - .keys() - .any(|root| !is_place(root)) - || state - .scale_intent - .jurisdictions - .values() - .map(|weight| u64::from(*weight)) - .sum::<u64>() - > 1000 - { - return Err(JournalError::Corrupt( - "the scale intent names a non-place root or distributes more than the whole".into(), - )); - } // The civic subgraph, in the slot the deleted `authority_scope` check // occupied: a jurisdiction names live ground under a canonical kind, an // office sits on an institution and lends something to a person who holds @@ -1057,7 +1040,6 @@ fn kernel_error(error: KernelError) -> JournalError { #[cfg(test)] mod tests { use super::*; - use crate::WorldScaleIntentRef; use crate::patch::kernel_speak_grant; use crate::tests::speak_entry; use crate::{ @@ -1112,7 +1094,6 @@ mod tests { position: None, import_key: None, }), - scale_intent: WorldScaleIntentRef::default(), grammar: None, }; let (mut kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap(); @@ -1195,7 +1176,6 @@ mod tests { position: None, import_key: None, }), - scale_intent: WorldScaleIntentRef::default(), grammar: None, }; let (mut kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap(); @@ -1209,7 +1189,6 @@ mod tests { expected_revision: snapshot.revision, caller: CallerId::Principal(owner), body: CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: vec![ Declaration::Entity(EntityDeclaration { @@ -1508,7 +1487,6 @@ mod tests { command_id, CallerId::Principal(owner()), CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: Vec::new(), operations: vec![crate::ComponentOp::Relocate { @@ -1672,7 +1650,6 @@ mod tests { position: None, import_key: None, }), - scale_intent: WorldScaleIntentRef::default(), grammar: None, }; let (kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap(); @@ -2193,7 +2170,6 @@ mod custody_tests { CommandId::new(), CallerId::Principal(owner()), CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: Vec::new(), operations: vec![ComponentOp::Transfer { @@ -2447,7 +2423,6 @@ mod custody_tests { CommandId::new(), CallerId::Principal(owner()), CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: Vec::new(), operations: vec![ @@ -2736,149 +2711,4 @@ mod custody_tests { assert!(matches!(recover(rows, None), Err(JournalError::Corrupt(_)))); } - /// Replay re-decides authority, so a stored row is not believed about who - /// authored it. An honest elaborator commit is rewritten to claim a - /// jurisdiction that does not cover its answer, and the history it belongs - /// to stops recovering. - #[test] - fn soul_a_forged_elaborator_commit_row_fails_replay() { - use crate::tests::{activate, submit_owner}; - use crate::{ - AuthenticatedCaller, CausalBoundary, Declaration, DraftHandle, EntityDeclaration, - JurisdictionKey, PatchAnswer, RouteDeclaration, SystemCapability, - }; - - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let (mut kernel, _) = WorldKernel::create( - &path, - creation(CommandId::new(), "Forged Authorship"), - &auth_principal(owner()), - ) - .unwrap(); - let seed = kernel.snapshot().unwrap(); - let commons = seed.places[0].id; - submit_owner( - &mut kernel, - &seed, - CommandBody::AdmitPatch { - answers: None, - patch: WorldPatch { - declarations: vec![ - Declaration::Entity(EntityDeclaration { - handle: DraftHandle::new("road"), - label: "The Unwalked Road".into(), - kind: EntityKind::Place, - container: Some(Ref::Existing(commons)), - }), - Declaration::Route(RouteDeclaration { - handle: DraftHandle::new("lane"), - label: "The Long Lane".into(), - from: Ref::Existing(commons), - to: Ref::Draft(DraftHandle::new("road")), - access: crate::AccessKind::Public, - cost: crate::Cost(1), - }), - ], - operations: Vec::new(), - evidence: Vec::new(), - }, - }, - ); - activate(&mut kernel); - - let boundary = crate::derive_boundaries(&kernel.state) - .unwrap() - .into_iter() - .find(|boundary| matches!(boundary, CausalBoundary::UnelaboratedDestination { .. })) - .expect("the road is a dead end"); - let CausalBoundary::UnelaboratedDestination { place: road, .. } = boundary else { - unreachable!("the boundary was matched above") - }; - let caller = CallerId::System(SystemCapability::Elaborator { - jurisdiction: JurisdictionKey::PlaceSubtree(road), - }); - let snapshot = kernel.snapshot().unwrap(); - kernel - .submit( - command( - &snapshot, - CommandId::new(), - caller.clone(), - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(boundary)), - patch: WorldPatch { - declarations: vec![Declaration::Entity(EntityDeclaration { - handle: DraftHandle::new("shed"), - label: "The Roadside Shed".into(), - kind: EntityKind::Place, - container: Some(Ref::Existing(road)), - })], - operations: Vec::new(), - evidence: Vec::new(), - }, - }, - ), - &AuthenticatedCaller::fixture(caller), - ) - .expect("the honest elaboration commits"); - - let state_row = || { - envelope( - STATE_ROW, - STATE_SCHEMA, - kernel.state.world_id.key(), - &kernel.state, - ) - .unwrap() - }; - let rows_of = |commits: Vec<crate::WorldCommit>| { - let mut rows: Vec<CultCacheEnvelope> = commits - .iter() - .map(|commit| { - envelope(COMMIT_ROW, COMMIT_SCHEMA, commit.command.id().key(), commit).unwrap() - }) - .collect(); - rows.push(state_row()); - rows - }; - - let honest: Vec<crate::WorldCommit> = - kernel.journal.commits.values().cloned().collect(); - recover(rows_of(honest.clone()), None).expect("the honest history replays"); - - // Rewrite only the recorded caller, to a jurisdiction that does not - // cover the answer the same row carries. - let mut forged_one = false; - let forged: Vec<crate::WorldCommit> = honest - .into_iter() - .map(|mut commit| { - if let crate::CommittedCommand::WorldCommand(command) = &mut commit.command - && matches!( - command.caller, - CallerId::System(SystemCapability::Elaborator { .. }) - ) - { - command.caller = CallerId::System(SystemCapability::Elaborator { - jurisdiction: JurisdictionKey::PlaceSubtree(commons), - }); - // Re-seal the row, so the chain digest cannot answer for - // the authority check. The elaborator commit is the last - // one, so no successor's `previous_commit_digest` moves. - commit.digest = commit_digest(&commit).unwrap(); - forged_one = true; - } - commit - }) - .collect(); - assert!(forged_one, "no elaborator row was found to forge"); - let error = recover(rows_of(forged), None).expect_err("a forged authorship replayed"); - let JournalError::Corrupt(detail) = &error else { - panic!("unexpected refusal: {error:?}"); - }; - assert!( - !detail.contains("commit chain is not contiguous"), - "the chain digest answered for the authority check: {detail}" - ); - } } diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index 63fcc0b8b..c8247a0cd 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -70,8 +70,7 @@ pub use grammar::{ RenderPath, }; pub use patch::{ - CommitmentKey, DraftHandle, JurisdictionKey, Mismatch, PatchAnswer, Ref, RefKind, RefName, Role, - Site, Statement, WorldPatch, + CommitmentKey, DraftHandle, Mismatch, Ref, RefKind, RefName, Role, Site, Statement, WorldPatch, }; pub(crate) use patch::{ AccessKind, Affordance, Audience, AuthoredSource, AuthorityGrant, AuthorityTarget, @@ -79,7 +78,6 @@ pub(crate) use patch::{ DependencyTarget, EntityKind, EvidenceRef, FactRecord, FactStanding, Forum, GrievanceKindName, Knowledge, KnowledgeSource, Office, OfficeName, Position, PressureMagnitude, PressureSource, Quantity, Reach, - WorldScaleIntent, WorldScaleIntentRef, }; pub use patch::ImportKey; #[cfg(test)] @@ -360,9 +358,6 @@ struct CreateWorld { owner: PrincipalId, title: String, patch: WorldPatch, - /// Authored once, here, and never mutated: `CommandBody::AdmitPatch` carries - /// no intent, so write-once is the command shape rather than a check. - scale_intent: WorldScaleIntentRef, /// The grammar the world is bound to for its whole life, or none for an /// open-catalog world. Authored here and nowhere else: genesis installs it. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -378,23 +373,6 @@ pub struct CreateWorldIntent { pub human_subject_label: String, pub narrative_persona_label: Option<String>, pub operational_agent_label: Option<String>, - /// World-wide target of goal-bearing subjects per kind. Required, and may - /// be empty: a world with no target is a deliberate choice, not a default - /// that arrives because nobody said anything. - pub targets: BTreeMap<SubjectKind, u32>, - /// The jurisdiction roots genesis declares beside the commons, because - /// `resolve_patch` only resolves roots the same patch declares. - pub jurisdictions: Vec<CreateJurisdictionIntent>, -} - -/// One jurisdiction root as ingress states it. The handle is a string here and -/// a `DraftHandle` inside the world subtree, which is the one lowering: the -/// handle constructor is not reachable from runtime ingress. -#[derive(Clone, Debug)] -pub struct CreateJurisdictionIntent { - pub handle: String, - pub label: String, - pub permille: u32, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] @@ -414,11 +392,6 @@ enum CallerId { #[serde(tag = "capability", rename_all = "snake_case")] enum SystemCapability { Clock, - /// Authors structure inside one jurisdiction. Never derived from session - /// evidence, never minted by ingress, never held by a subject. - Elaborator { - jurisdiction: JurisdictionKey, - }, /// One external consumer, authoring only the subjects this world has /// admitted as its mirrors. Minted by exactly one mailbox method, after the /// ingress has authenticated the document; never derived from session @@ -441,8 +414,6 @@ enum SystemCapability { /// derived from `controller_assignments` at decision time. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum PatchGround { - /// A place subtree. The elaborator's shape, unchanged in meaning. - Jurisdiction(JurisdictionKey), /// Every subject bound to this consumer. Consumer(ConsumerId), } @@ -619,10 +590,6 @@ pub enum CommandBody { opportunity: DecisionOpportunity, }, AdmitPatch { - /// Draft answers nothing. Active must answer a currently derived - /// boundary or a jurisdiction whose deficit is nonzero, and the commit - /// must satisfy what it answered. - answers: Option<PatchAnswer>, patch: WorldPatch, }, /// The world's only clock advance. Owner or the clock capability, and the @@ -814,8 +781,6 @@ struct WorldState { /// `ScopePreimage`: it is world truth, and it is read by no precondition, so /// a tick that only advances pressure moves no proposal's binding. now: FictionalMinutes, - /// The authored scale target, written once by genesis and never mutated. - scale_intent: WorldScaleIntent, controller_assignments: BTreeMap<DecisionScope, ControllerAssignment>, /// What an affordance *is*. World-authored, Draft-only, written by /// `admit_resolved` alone. @@ -837,9 +802,6 @@ enum WorldEffect { resolved: ResolvedPatch, }, PatchAdmitted { - /// What this commit answered, so `apply_effect` re-decides the same - /// rule `reduce` decided and then proves the answer was satisfied. - answers: Option<PatchAnswer>, resolved: ResolvedPatch, }, DraftApproved { @@ -964,11 +926,6 @@ pub struct SubjectSnapshot { /// itself. View-only, covered by no digest of its own: it is already bound /// through `components`. pub(crate) dependencies: Vec<DependencyTarget>, - /// A projection of `qualifies`, not a stored flag and not a second count: - /// whether this subject already reduces its jurisdiction's scale deficit. - /// The seed brief needs to say which subjects count; recomputing the - /// conjunction outside the kernel would be a second definition of alive. - pub qualified: bool, /// The greatest `DecisionEvent.revision` whose scope is this subject, or /// `None` if the subject never acted. Derived from `state.events` alone: /// no new state, no schema change. The recency marker `projector_knowledge` @@ -1145,10 +1102,6 @@ pub struct WorldSnapshot { /// Everyone in a world shares the clock, and no controller can read a `due` /// without it. pub now: FictionalMinutes, - /// The elaborator's surface. There is no global pressure register and no - /// commitment gazetteer. - pub boundaries: Vec<CausalBoundary>, - pub scale_deficit: Vec<ScaleDeficitRow>, pub state_digest: String, pub last_commit_digest: Option<String>, } @@ -1299,12 +1252,6 @@ pub enum KernelError { CorruptJournal(String), #[error("private reducer invariant failed: {0}")] Invariant(String), - #[error("an active patch must answer a derived boundary or a nonzero deficit")] - AnswerRequired, - #[error("this world derives no such boundary or deficit")] - AnswerNotDerived, - #[error("the admitted patch does not satisfy the boundary or deficit it answered")] - AnswerNotSatisfied, } impl KernelError { @@ -1371,7 +1318,6 @@ fn prepare_creation( ), input.id, &input.patch, - Some(&input.scale_intent), ) .map_err(KernelError::PatchRejected)?; require_ruler(&CallerId::Principal(input.owner.clone()), &resolved) @@ -1707,30 +1653,20 @@ fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result<WorldEffect, motion: clock::derive_motion(state, to), }) } - CommandBody::AdmitPatch { answers, patch } => { - // Answer before authority, because the jurisdiction check reads the - // answer and a missing one must read as `AnswerRequired` rather - // than `Unauthorized`. Resolution before confinement, because - // confinement reads draft-resolved referents and a structurally - // broken patch should return its complete mismatch set rather than - // a jurisdiction complaint about a reference that does not resolve. - require_answer( - state, - &command.caller, - answers.as_ref(), - !(patch.declarations.is_empty() && patch.evidence.is_empty()), - )?; - let confinement = require_patch_author(state, &command.caller, answers.as_ref())?; - let resolved = patch::resolve_patch(state, command.id, patch, None) + CommandBody::AdmitPatch { patch } => { + require_play_active(state, &command.caller)?; + // Resolution before confinement, because confinement reads + // draft-resolved referents and a structurally broken patch should + // return its complete mismatch set rather than a jurisdiction + // complaint about a reference that does not resolve. + let confinement = require_patch_author(state, &command.caller)?; + let resolved = patch::resolve_patch(state, command.id, patch) .map_err(KernelError::PatchRejected)?; require_ruler(&command.caller, &resolved).map_err(KernelError::PatchRejected)?; if let Some(ground) = confinement { confine_to_ground(state, &resolved, ground).map_err(KernelError::PatchRejected)?; } - Ok(WorldEffect::PatchAdmitted { - answers: answers.clone(), - resolved, - }) + Ok(WorldEffect::PatchAdmitted { resolved }) } } } @@ -1746,9 +1682,7 @@ fn require_system_capability(caller: &CallerId, body: &CommandBody) -> Result<() (SystemCapability::Clock, CommandBody::AdvanceTime { .. }) | (SystemCapability::Play, CommandBody::AdvanceTime { .. }) | ( - SystemCapability::Elaborator { .. } - | SystemCapability::Consumer { .. } - | SystemCapability::Play, + SystemCapability::Consumer { .. } | SystemCapability::Play, CommandBody::AdmitPatch { .. } ) ); @@ -1773,60 +1707,15 @@ fn require_clock_caller(state: &WorldState, caller: &CallerId) -> Result<(), Ker } } -/// Answering is what lets an Active patch declare. Draft answers nothing: -/// `SeedRequest` — the ontology's draft-phase answer — is not inhabited, so -/// genesis and draft elaboration answer nothing. In Active, a patch that only -/// changes components of existing structure is the operator's hand and answers -/// nothing; a patch that declares or admits evidence is elaboration, and -/// elaboration answers a boundary the kernel currently derives or a -/// jurisdiction whose deficit is nonzero. -fn require_answer( - state: &WorldState, - caller: &CallerId, - answers: Option<&PatchAnswer>, - declares: bool, -) -> Result<(), KernelError> { +/// The play table authors nothing in Draft: it is the Active world's hand. +fn require_play_active(state: &WorldState, caller: &CallerId) -> Result<(), KernelError> { if caller == &CallerId::System(SystemCapability::Play) && state.phase == WorldPhase::Draft { return Err(KernelError::WrongPhase { expected: WorldPhase::Active, actual: state.phase, }); } - match (state.phase, answers) { - (WorldPhase::Draft, None) => Ok(()), - (WorldPhase::Draft, Some(_)) => Err(KernelError::AnswerNotDerived), - (WorldPhase::Active, None) if declares => { - if caller == &CallerId::System(SystemCapability::Play) { - Ok(()) - } else { - Err(KernelError::AnswerRequired) - } - } - (WorldPhase::Active, None) => Ok(()), - (WorldPhase::Active, Some(PatchAnswer::Boundary(claimed))) => { - exact_boundary(state, claimed).map(|_| ()) - } - (WorldPhase::Active, Some(PatchAnswer::Deficit(jurisdiction))) => { - if jurisdiction_deficit(state, *jurisdiction)? > 0 { - Ok(()) - } else { - Err(KernelError::AnswerNotDerived) - } - } - } -} - -/// The total deficit of one jurisdiction, which is what an answer must strictly -/// reduce. -fn jurisdiction_deficit( - state: &WorldState, - jurisdiction: JurisdictionKey, -) -> Result<u64, KernelError> { - Ok(derive_scale_deficit(state)? - .into_iter() - .filter(|row| row.jurisdiction == jurisdiction) - .map(|row| u64::from(row.deficit)) - .sum()) + Ok(()) } /// A human principal joins `required_approvers`, so only the lane that builds @@ -1874,7 +1763,6 @@ impl WorldState { pressures: BTreeMap::new(), last_opportunity_at: BTreeMap::new(), now: FictionalMinutes::default(), - scale_intent: WorldScaleIntent::default(), controller_assignments: BTreeMap::new(), affordance_catalog: BTreeMap::new(), affordance_grants: BTreeMap::new(), @@ -1914,7 +1802,6 @@ impl WorldState { &state, command.id, &command.patch, - Some(&command.scale_intent), ) .map_err(KernelError::PatchRejected)?; if &expected != resolved { @@ -2188,9 +2075,6 @@ fn admit_resolved( )); } } - if let Some(intent) = &resolved.scale_intent { - state.scale_intent = intent.clone(); - } apply_operations(state, &resolved.operations, &resolved.evidence, resolves_to) } @@ -3832,7 +3716,6 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> { magnitude: *magnitude, }) .collect(), - qualified: qualifies(state, *subject_id), last_acted_at: last_acted_at.get(subject_id).copied(), }) }) @@ -3934,307 +3817,11 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> { facts, opportunities: order_opportunities(state, derive_opportunities(state)?), now: state.now, - boundaries: derive_boundaries(state)?, - scale_deficit: derive_scale_deficit(state)?, state_digest: state.state_digest.clone(), last_commit_digest: state.last_commit_digest.clone(), }) } -/// A place in the world's causal reach that the world has not yet grown into. -/// Derived, never stored, and cleared by no writer: a boundary stops being -/// derived when its predicate stops holding. -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] -#[serde(tag = "boundary", rename_all = "snake_case")] -pub enum CausalBoundary { - UnelaboratedDestination { - route: EdgeId, - place: EntityId, - scope: BoundaryDigest, - }, - MissingStructure { - subject: SubjectId, - key: CommitmentKey, - scope: BoundaryDigest, - }, - /// Declared, never derived: no relations partition exists. Answering one is - /// `AnswerNotDerived`. - PolityInCausalRange { - subject: SubjectId, - scope: BoundaryDigest, - }, - /// Declared, never derived: no population membership and no slice concept - /// exists. Answering one is `AnswerNotDerived`. - IndividuationRequired { - population: SubjectId, - scope: BoundaryDigest, - }, -} - -/// The digest of exactly the components that derive one boundary, produced by -/// the one `digest()` owner, in the `ScopeDigest` idiom. -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] -#[serde(transparent)] -pub struct BoundaryDigest(String); - -impl BoundaryDigest { - /// The digest text, for the one command-key derivation that hashes it. - pub(crate) fn text(&self) -> &str { - &self.0 - } - - /// The deficit lane's answer has no preimage of its own: its digest is the - /// session's, produced by the same `sha256:` spelling. - pub(crate) fn from_digest(value: String) -> Self { - Self(value) - } -} - -#[derive(Serialize)] -struct UnelaboratedDestinationPreimage<'a> { - world_id: WorldId, - route: &'a EdgeRecord, - place: &'a EntityRecord, - contained: BTreeSet<EntityId>, - occupants: BTreeSet<SubjectId>, - incident: BTreeSet<EdgeId>, -} - -#[derive(Serialize)] -struct MissingStructurePreimage<'a> { - world_id: WorldId, - subject: SubjectId, - key: CommitmentKey, - commitment: &'a Commitment, - counterparty_authority: BTreeSet<AuthorityGrant>, - redress: &'a BTreeMap<GrievanceKindName, Forum>, -} - -/// Beside `derive_opportunities`, and reached from `snapshot` and from -/// `reduce`'s `AdmitPatch` arm. The same shape as the opportunity derivation, -/// not the same function: the inputs and the consumers differ, and a shared -/// derivation returning a sum type would be a generic helper wearing a name. -fn derive_boundaries(state: &WorldState) -> Result<Vec<CausalBoundary>, KernelError> { - let mut boundaries = Vec::new(); - for (edge_id, record) in &state.edges { - let (from, to) = record.endpoints(); - for place in [from, to] { - let contained: BTreeSet<EntityId> = state - .entities - .iter() - .filter(|(_, entity)| entity.container == Some(place)) - .map(|(entity_id, _)| *entity_id) - .collect(); - let occupants: BTreeSet<SubjectId> = state - .positions - .iter() - .filter(|(_, position)| position.place == place) - .map(|(subject_id, _)| *subject_id) - .collect(); - let incident: BTreeSet<EdgeId> = state - .edges - .iter() - .filter(|(_, candidate)| { - let (candidate_from, candidate_to) = candidate.endpoints(); - candidate_from == place || candidate_to == place - }) - .map(|(candidate_id, _)| *candidate_id) - .collect(); - if !contained.is_empty() - || !occupants.is_empty() - || incident.len() != 1 - || !incident.contains(edge_id) - { - continue; - } - let entity = state - .entities - .get(&place) - .ok_or_else(|| KernelError::Invariant("a route names no canonical place".into()))?; - boundaries.push(CausalBoundary::UnelaboratedDestination { - route: *edge_id, - place, - scope: BoundaryDigest(digest(&UnelaboratedDestinationPreimage { - world_id: state.world_id, - route: record, - place: entity, - contained, - occupants, - incident, - })?), - }); - } - } - // A commitment the counterparty can neither command nor litigate. Both - // clauses read the civic partitions through their own predicates, so - // jurisdiction lent by an office counts and no second covering rule exists. - // A `Goal` derives nothing: a promise to oneself needs no forum. - for (subject, held) in &state.commitments { - for (key, commitment) in held { - let Some(counterparty) = commitment.counterparty else { - continue; - }; - let counterparty_authority = subject_authority(state, counterparty); - let commandable = counterparty_authority - .iter() - .any(|grant| covers(state, grant.over, Target::Subject(*subject))); - let litigable = state - .redress - .values() - .any(|forum| covers(state, forum.standing, Target::Subject(counterparty))); - if commandable || litigable { - continue; - } - boundaries.push(CausalBoundary::MissingStructure { - subject: *subject, - key: *key, - scope: BoundaryDigest(digest(&MissingStructurePreimage { - world_id: state.world_id, - subject: *subject, - key: *key, - commitment, - counterparty_authority, - redress: &state.redress, - })?), - }); - } - } - Ok(boundaries) -} - -/// The sole validator of a claimed boundary, mirroring `exact_opportunity`. -fn exact_boundary( - state: &WorldState, - claimed: &CausalBoundary, -) -> Result<CausalBoundary, KernelError> { - derive_boundaries(state)? - .into_iter() - .find(|current| current == claimed) - .ok_or(KernelError::AnswerNotDerived) -} - -/// One region's count for one subject kind. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] -pub struct ScaleDeficitRow { - pub jurisdiction: JurisdictionKey, - pub kind: SubjectKind, - pub target: u32, - pub qualified: u32, - pub deficit: u32, -} - -/// Whether a subject counts toward the world's scale target. Aliveness is -/// structural and phase-free: a controller, a non-empty grant set, and a held -/// `Goal`. A Draft world's deficit is what the seed lane has left to author; an -/// Active world's is what the elaborator has left to answer. -/// -/// There is no phase clause here because `require_answer` already owns the -/// Draft-answer refusal: it refuses every Draft answer outright, so a phase -/// clause in this predicate would protect nothing and would only pin a Draft -/// world's deficit at the authored intent forever, leaving the seed lane no -/// derived termination. -/// -/// The conjunction is written once, because retirement and grant revocation -/// make the first two clauses live later and a scattered count would then be -/// wrong in three places. "Executable" is structural, never "preconditions -/// currently hold": evaluating them per subject per snapshot would make the -/// deficit flicker as routes open and close. -fn qualifies(state: &WorldState, subject_id: SubjectId) -> bool { - let scope = DecisionScope { subject_id }; - state.controller_assignments.contains_key(&scope) - && state - .affordance_grants - .get(&scope) - .is_some_and(|granted| !granted.is_empty()) - && state.commitments.get(&subject_id).is_some_and(|held| { - held.values() - .any(|commitment| commitment.kind == CommitmentKind::Goal) - }) -} - -/// Derived in `snapshot`, never stored. `snapshot` is the recount: it already -/// re-derives everything, and a second after-every-commit step would be a -/// second owner. Only admitted subjects reduce it, so a rejected patch leaves -/// it visible, which is free — a rejection mutates nothing. -fn derive_scale_deficit(state: &WorldState) -> Result<Vec<ScaleDeficitRow>, KernelError> { - let mut counted: BTreeMap<(JurisdictionKey, SubjectKind), u32> = BTreeMap::new(); - for (subject_id, subject) in &state.subjects { - if !qualifies(state, *subject_id) { - continue; - } - match state.positions.get(subject_id) { - // A subject under nested roots counts toward both: layered - // jurisdiction applied to counting. A subject standing somewhere - // no declared root covers still counts, in `Uncovered`, so the - // deficit stays total over every qualifying subject. - Some(position) => { - let mut covered = false; - for root in state.scale_intent.jurisdictions.keys() { - if patch::covers_place(&state.entities, *root, position.place) { - covered = true; - *counted - .entry((JurisdictionKey::PlaceSubtree(*root), subject.kind)) - .or_default() += 1; - } - } - if !covered { - *counted - .entry((JurisdictionKey::Uncovered, subject.kind)) - .or_default() += 1; - } - } - // Counted, visible, and reducing no target. - None => { - *counted - .entry((JurisdictionKey::Uncovered, subject.kind)) - .or_default() += 1; - } - } - } - let mut rows: BTreeMap<(JurisdictionKey, SubjectKind), ScaleDeficitRow> = BTreeMap::new(); - for (kind, world_target) in &state.scale_intent.targets { - for (root, permille) in &state.scale_intent.jurisdictions { - let jurisdiction = JurisdictionKey::PlaceSubtree(*root); - let target = u32::try_from( - u64::from(*world_target) - .checked_mul(u64::from(*permille)) - .ok_or_else(|| KernelError::Invariant("scale target overflow".into()))? - / 1000, - ) - .map_err(|_| KernelError::Invariant("scale target overflow".into()))?; - let qualified = counted - .get(&(jurisdiction, *kind)) - .copied() - .unwrap_or_default(); - rows.insert( - (jurisdiction, *kind), - ScaleDeficitRow { - jurisdiction, - kind: *kind, - target, - qualified, - deficit: target.saturating_sub(qualified), - }, - ); - } - } - for ((jurisdiction, kind), qualified) in counted { - rows.entry((jurisdiction, kind)) - .or_insert(ScaleDeficitRow { - jurisdiction, - kind, - target: 0, - qualified, - deficit: 0, - }) - .qualified = qualified; - } - Ok(rows - .into_values() - .filter(|row| row.target > 0 || row.qualified > 0) - .collect()) -} - /// A pure re-ordering of `derive_opportunities`' output: same values, same /// length, same set. Never a filter — filtering by readiness would drag /// precondition reads into `ScopePreimage`, and a tick could then withdraw an @@ -4449,81 +4036,18 @@ fn required_approvers(state: &WorldState) -> BTreeSet<PrincipalId> { fn require_patch_author( state: &WorldState, caller: &CallerId, - answers: Option<&PatchAnswer>, ) -> Result<Option<PatchGround>, KernelError> { match caller { CallerId::Principal(principal) if principal == &state.owner => Ok(None), CallerId::System(SystemCapability::Play) => Ok(None), - CallerId::System(SystemCapability::Elaborator { jurisdiction }) => { - let answer = answers.ok_or(KernelError::Unauthorized)?; - let ground = PatchGround::Jurisdiction(*jurisdiction); - if !ground_covers(state, ground, answer) { - return Err(KernelError::Unauthorized); - } - Ok(Some(ground)) - } CallerId::System(SystemCapability::Consumer { consumer }) => { - // Authority over its own mirrors is not jurisdictional and does not - // depend on an answer. An answer, when present, must name a subject - // this consumer is bound to, so a consumer cannot claim credit for - // structure it is confined out of writing. - let ground = PatchGround::Consumer(*consumer); - if let Some(answer) = answers - && !ground_covers(state, ground, answer) - { - return Err(KernelError::Unauthorized); - } - Ok(Some(ground)) + // Authority over its own mirrors is not jurisdictional. + Ok(Some(PatchGround::Consumer(*consumer))) } _ => Err(KernelError::Unauthorized), } } -/// Does the caller's jurisdiction cover the thing the answer names? -/// -/// Two coverings, deliberately asymmetric. A boundary is covered -/// **transitively** through `covers_place`, so a parent jurisdiction's -/// elaborator may answer a boundary in a nested child. A deficit is covered by -/// **exact key equality**: a subject under nested roots counts toward both -/// roots' targets, so a parent answering a child's row would reduce two targets -/// with one subject and drain a child's queue while its own row stays red. -/// Boundaries name a thing; deficits name a row. -/// A consumer's arm is narrower on purpose: it may answer only a -/// `MissingStructure` boundary on one of its own mirrors. A deficit is -/// jurisdictional and a consumer holds no jurisdiction; a boundary about a -/// foreign subject is not its business. -fn ground_covers(state: &WorldState, held: PatchGround, answer: &PatchAnswer) -> bool { - let held = match held { - PatchGround::Jurisdiction(jurisdiction) => jurisdiction, - PatchGround::Consumer(consumer) => { - let PatchAnswer::Boundary(CausalBoundary::MissingStructure { subject, .. }) = answer - else { - return false; - }; - return bound_to_consumer(state, *subject, consumer); - } - }; - match answer { - PatchAnswer::Boundary(CausalBoundary::UnelaboratedDestination { place, .. }) => { - place_in(state, held, *place) - } - // The two never-derived variants join this clause only so the match is - // total; `exact_boundary` refuses them before authority is read. - PatchAnswer::Boundary( - CausalBoundary::MissingStructure { subject, .. } - | CausalBoundary::PolityInCausalRange { subject, .. } - | CausalBoundary::IndividuationRequired { - population: subject, - .. - }, - ) => match state.positions.get(subject) { - Some(position) => place_in(state, held, position.place), - None => held == JurisdictionKey::Uncovered, - }, - PatchAnswer::Deficit(key) => *key == held, - } -} - /// Is this committed subject one of that consumer's mirrors? The consumer's /// ground is derived here, at decision time, and never carried on the wire: a /// binding a later commit revoked shrinks the consumer's authority with no @@ -4538,12 +4062,6 @@ fn bound_to_consumer(state: &WorldState, subject: SubjectId, consumer: ConsumerI == Some(consumer) } -fn place_in(state: &WorldState, held: JurisdictionKey, place: EntityId) -> bool { - match held { - JurisdictionKey::PlaceSubtree(root) => patch::covers_place(&state.entities, root, place), - JurisdictionKey::Uncovered => false, - } -} /// The ground a patch writes on, as one map over `state ∪ patch`, so a place /// declared and built on in the same patch confines through the chain it @@ -4565,31 +4083,23 @@ fn candidate_places( entities } -/// Every place-or-subject referent a jurisdictional author writes must sit under -/// its jurisdiction. Returns the complete set, like every other check. +/// Every referent a confined author writes must sit on its ground. Returns the +/// complete set, like every other check. /// /// Placeless referents — resource kinds, catalog entries, canonical facts — /// name no ground and are not confined. A place declared with no container is a -/// new jurisdiction root and is the owner's act. There is no relevance test: a -/// patch that satisfies its answer may also declare unrelated structure inside -/// its jurisdiction, because "the minimum the boundary needs" is a semantic -/// verdict the kernel must not hold. +/// new jurisdiction root and is the owner's act. fn confine_to_ground( state: &WorldState, resolved: &ResolvedPatch, held: PatchGround, ) -> Result<(), Vec<Mismatch>> { let entities = candidate_places(state, resolved); - // A consumer names no ground, so every place, every route, and every + // A consumer names no place ground, so every place, every route, and every // place-shaped reach is refused with no extra rule: relocation, route // opening and closing, cost changes, and place-subtree grants are // unrepresentable for it because they carry a place or a route. - let inside = |place: EntityId| match held { - PatchGround::Jurisdiction(JurisdictionKey::PlaceSubtree(root)) => { - patch::covers_place(&entities, root, place) - } - PatchGround::Jurisdiction(JurisdictionKey::Uncovered) | PatchGround::Consumer(_) => false, - }; + // // Every subject's consumer binding over `state ∪ patch`, so a consumer's // first document can declare its own mirror and write it in one patch. let mut bindings: BTreeMap<SubjectId, Option<ConsumerId>> = state @@ -4600,17 +4110,6 @@ fn confine_to_ground( for declared in &resolved.subjects { bindings.insert(declared.subject_id, declared.controller.consumer()); } - let mut positions: BTreeMap<SubjectId, Option<EntityId>> = state - .positions - .iter() - .map(|(subject, position)| (*subject, Some(position.place))) - .collect(); - for declared in &resolved.subjects { - positions.insert( - declared.subject_id, - declared.position.map(|position| position.place), - ); - } let mut edges: BTreeMap<EdgeId, (EntityId, EntityId)> = state .edges .iter() @@ -4622,27 +4121,16 @@ fn confine_to_ground( let mut mismatches = Vec::new(); let confine_subject = |site: &Site, subject: SubjectId, mismatches: &mut Vec<Mismatch>| { - let admitted = match held { - PatchGround::Jurisdiction(jurisdiction) => { - match positions.get(&subject).copied().flatten() { - Some(place) => inside(place), - None => jurisdiction == JurisdictionKey::Uncovered, - } - } - // Position is unconfined for a consumer: what binds a mirror is who - // controls it, not where it stands. - PatchGround::Consumer(consumer) => { - bindings.get(&subject).copied().flatten() == Some(consumer) - } - }; + // Position is unconfined for a consumer: what binds a mirror is who + // controls it, not where it stands. + let PatchGround::Consumer(consumer) = held; + let admitted = bindings.get(&subject).copied().flatten() == Some(consumer); if !admitted { mismatches.push(Mismatch::OutsideJurisdiction { site: site.clone() }); } }; - let confine_place = |site: &Site, place: EntityId, mismatches: &mut Vec<Mismatch>| { - if !inside(place) { - mismatches.push(Mismatch::OutsideJurisdiction { site: site.clone() }); - } + let confine_place = |site: &Site, _place: EntityId, mismatches: &mut Vec<Mismatch>| { + mismatches.push(Mismatch::OutsideJurisdiction { site: site.clone() }); }; for declared in &resolved.subjects { @@ -4656,7 +4144,7 @@ fn confine_to_ground( let site = Site::Declaration(declared.handle.clone()); match declared.entity.container { Some(container) => confine_place(&site, container, &mut mismatches), - // A root is the owner's act. An elaborator elaborates inside one. + // A root is the owner's act. None => mismatches.push(Mismatch::OutsideJurisdiction { site }), } } @@ -5006,9 +4494,7 @@ fn apply_effect( (SystemCapability::Clock, WorldEffect::TimeAdvanced { .. }) | (SystemCapability::Play, WorldEffect::TimeAdvanced { .. }) | ( - SystemCapability::Elaborator { .. } - | SystemCapability::Consumer { .. } - | SystemCapability::Play, + SystemCapability::Consumer { .. } | SystemCapability::Play, WorldEffect::PatchAdmitted { .. } ) ); @@ -5022,15 +4508,15 @@ fn apply_effect( "world genesis cannot be applied as a mutable effect".into(), )); } - WorldEffect::PatchAdmitted { answers, resolved } => { - require_answer(state, caller, answers.as_ref(), !resolved.declares_nothing())?; + WorldEffect::PatchAdmitted { resolved } => { + require_play_active(state, caller)?; require_ruler(caller, resolved).map_err(|_| { KernelError::Invariant( "admitted patch rules or mints without the play authority".into(), ) })?; let confinement = - require_patch_author(state, caller, answers.as_ref()).map_err(|_| { + require_patch_author(state, caller).map_err(|_| { KernelError::Invariant( "admitted patch does not satisfy admission authority".into(), ) @@ -5042,33 +4528,8 @@ fn apply_effect( ) })?; } - // The deficit before the write, so "strictly decreased" is a - // comparison rather than a claim the effect makes. - let before = match answers { - Some(PatchAnswer::Deficit(jurisdiction)) => { - jurisdiction_deficit(state, *jurisdiction)? - } - _ => 0, - }; let resolves_to = resolution_revision(state)?; admit_resolved(state, resolved, resolves_to)?; - // What makes "a commit clears exactly the boundary it answers" - // structural rather than hoped for. "Nothing else clears one" is - // true by construction: boundaries are derived and no writer - // clears one. - match answers { - Some(PatchAnswer::Boundary(answered)) => { - if exact_boundary(state, answered).is_ok() { - return Err(KernelError::AnswerNotSatisfied); - } - } - Some(PatchAnswer::Deficit(jurisdiction)) => { - if jurisdiction_deficit(state, *jurisdiction)? >= before { - return Err(KernelError::AnswerNotSatisfied); - } - } - None => {} - } } WorldEffect::DraftApproved { principal } => { if state.phase != WorldPhase::Draft @@ -5360,7 +4821,6 @@ mod tests { }), ], }, - scale_intent: WorldScaleIntentRef::default(), grammar: None, } } @@ -5524,7 +4984,6 @@ mod tests { kernel, &before, CommandBody::AdmitPatch { - answers: None, patch: topology_patch(speak_entry(kernel)), }, ); @@ -5844,7 +5303,6 @@ mod tests { kernel, &before, CommandBody::AdmitPatch { - answers: None, patch: custody_patch(topology, speak_entry(kernel)), }, ); @@ -6296,7 +5754,6 @@ mod tests { kernel, &before, CommandBody::AdmitPatch { - answers: None, patch: civic_patch(topology, speak_entry(kernel)), }, ); @@ -6397,7 +5854,6 @@ mod tests { kernel, &before, CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { evidence: vec![EvidenceRef::new(FLOOD_EVIDENCE)], operations: Vec::new(), @@ -6579,7 +6035,6 @@ mod tests { pub(crate) fn operations(operations: Vec<ComponentOp>) -> CommandBody { CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: Vec::new(), operations, @@ -6715,7 +6170,6 @@ mod tests { &mut kernel, &active, CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: Vec::new(), operations: vec![ComponentOp::CloseRoute { @@ -7635,7 +7089,6 @@ mod tests { &mut kernel, &before, CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: vec![ Declaration::Entity(EntityDeclaration { @@ -7695,7 +7148,6 @@ mod tests { &mut kernel, &active, CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: Vec::new(), operations: vec![ComponentOp::Relocate { @@ -7726,7 +7178,6 @@ mod tests { &mut kernel, &moved, CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: Vec::new(), operations: vec![ComponentOp::CloseRoute { @@ -8500,7 +7951,6 @@ mod tests { &mut kernel, &before, CommandBody::AdmitPatch { - answers: None, patch } ), @@ -8608,9 +8058,7 @@ mod custody_tests { qty: Quantity(OPENING_BALANCE + 1), }], evidence: Vec::new(), - scale_intent: None, }, - answers: None, }; let error = apply_effect( &mut candidate, @@ -8661,7 +8109,6 @@ mod custody_tests { &mut kernel, &before, CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: vec![ Declaration::Entity(EntityDeclaration { @@ -8876,7 +8323,6 @@ mod custody_tests { &mut kernel, &draft, CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: Vec::new(), operations: vec![ComponentOp::Admit { @@ -9198,9 +8644,7 @@ mod custody_tests { channels: Vec::new(), operations, evidence: Vec::new(), - scale_intent: None, }, - answers: None, }; let transfer = |qty: u64| ResolvedOp::Transfer { from: custody.holder, @@ -9320,7 +8764,6 @@ mod custody_tests { &mut kernel, &before, CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: vec![ Declaration::Entity(EntityDeclaration { @@ -9593,7 +9036,6 @@ mod knowledge_tests { let start = draft.snapshot().unwrap(); let declare = |standing: FactStandingRef, evidence: Vec<EvidenceRef>| CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: vec![Declaration::Fact(FactDeclaration { handle: DraftHandle::new("rumour"), @@ -10543,7 +9985,6 @@ mod knowledge_tests { let before = kernel.snapshot().unwrap(); let catalog_before = kernel.state.affordance_catalog.len(); let declare = |preconditions: Vec<Precondition>| CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: vec![Declaration::Affordance(AffordanceDeclaration { handle: DraftHandle::new("herald"), @@ -11088,12 +10529,11 @@ mod soul_knowledge_tests { /// `verify_state_shape` checks the forward speech direction only: an event's /// claim is asserted by the acting subject and named by no other event. The /// reverse, that every claim is named by some event, is deliberately absent, - /// because a world may declare a claim in Draft with no event behind it. - /// That gap is not a hole: active admission refuses every declaration, so - /// `AssertClaim` is the only way a claim enters an active world and it is - /// synthesized with its event. + /// because a world may declare a claim with no event behind it, in Draft + /// or, since the owner declares in Active unanswered, in Active too. Such a + /// claim is a valid shape and its store reopens. #[test] - fn soul_an_orphan_claim_is_a_draft_shape_and_unreachable_in_active() { + fn an_orphan_claim_is_a_valid_shape_and_reopens() { let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("world.cc"); let (mut kernel, speech, active) = speech_kernel(directory.path(), "OrphanClaim"); @@ -11110,14 +10550,13 @@ mod soul_knowledge_tests { let world_id = kernel.state.world_id; let before = kernel.state.clone(); - let error = kernel + let receipt = kernel .submit( command( &active, CommandId::new(), CallerId::Principal(owner()), CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: vec![Declaration::Fact(FactDeclaration { handle: DraftHandle::new("rumour"), @@ -11134,15 +10573,13 @@ mod soul_knowledge_tests { ), &auth_principal(owner()), ) - .unwrap_err(); - assert!( - matches!(error, KernelError::AnswerRequired), - "an active world admitted an unanswered declaration: {error:?}" - ); - assert_eq!(kernel.state, before); + .expect("the owner declares a claim in Active"); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert_eq!(kernel.state.facts.len(), before.facts.len() + 1); + let facts = kernel.state.facts.clone(); drop(kernel); let replayed = WorldKernel::open(&path, world_id).expect("the orphan store is healthy"); - assert_eq!(replayed.state.facts, before.facts); + assert_eq!(replayed.state.facts, facts); } /// Replay equality across every new arm, twice, with no RNG and no clock in @@ -11337,8 +10774,8 @@ mod witness_tests { /// Nesting, because "under a place" is the whole question. A hemisphere /// holds a region and a far coast; the region holds a village and one /// unwalked hollow; subjects stand in the village, on the coast, and in the - /// hemisphere under neither. The hollow is empty so an elaborator has a - /// boundary to answer and a witness has a place that reaches nobody. + /// hemisphere under neither. The hollow is empty so a witness has a place + /// that reaches nobody. struct Nesting { hemisphere: EntityId, region: EntityId, @@ -11408,7 +10845,6 @@ mod witness_tests { &mut kernel, &before, CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: vec![ place("hemisphere", "The Lit Hemisphere", None), @@ -11814,80 +11250,6 @@ mod witness_tests { )); } - /// The place is the whole ground, and it is not a weaker confinement than - /// the recipients: everyone the fan-out selects stands under it. An - /// elaborator witnesses inside its root, and nowhere outside or above it. - #[test] - fn an_elaborator_may_witness_inside_its_root_and_not_outside_or_above() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, world, _) = nesting_kernel(directory.path(), "Jurisdiction"); - let answer = derive_boundaries(&kernel.state) - .unwrap() - .into_iter() - .find(|boundary| { - matches!(boundary, CausalBoundary::UnelaboratedDestination { place, .. } - if *place == world.hollow) - }) - .expect("the hollow is an unelaborated destination"); - let submit = |kernel: &mut WorldKernel, place: EntityId| { - let snapshot = kernel.snapshot().unwrap(); - let caller = CallerId::System(SystemCapability::Elaborator { - jurisdiction: JurisdictionKey::PlaceSubtree(world.region), - }); - kernel.submit( - command( - &snapshot, - CommandId::new(), - caller.clone(), - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(answer.clone())), - patch: WorldPatch { - // The boundary the elaborator answers: the hollow - // grows a room. The witness rides beside it, and - // only the witness is confined by its place. - declarations: vec![Declaration::Entity(EntityDeclaration { - handle: DraftHandle::new("shed"), - label: "The Hollow Shed".into(), - kind: EntityKind::Place, - container: Some(Ref::Existing(world.hollow)), - })], - operations: vec![witness(world.asteroid, place, Confidence::Believed)], - evidence: Vec::new(), - }, - }, - ), - &AuthenticatedCaller::fixture(caller), - ) - }; - let outside = |result: Result<SubmitReceipt, KernelError>| match result { - Err(KernelError::PatchRejected(set)) => set, - other => panic!("expected a confined refusal, got {other:?}"), - }; - - assert_eq!( - outside(submit(&mut kernel, world.coast)), - vec![Mismatch::OutsideJurisdiction { - site: Site::Operation(0) - }] - ); - assert_eq!( - outside(submit(&mut kernel, world.hemisphere)), - vec![Mismatch::OutsideJurisdiction { - site: Site::Operation(0) - }] - ); - let before_admit = kernel.state.revision; - let admitted = submit(&mut kernel, world.village); - assert!( - matches!(admitted, Ok(SubmitReceipt::Applied(_))), - "{admitted:?}" - ); - assert_eq!( - knows(&kernel, world.villager, world.asteroid), - seen(Confidence::Believed, before_admit + 1) - ); - } - /// A consumer names no ground, and a jurisdiction over placeless subjects /// names no place. Both refuse every witness through the same closure, with /// no rule in `confine_to_ground` naming the operation. @@ -11903,21 +11265,16 @@ mod witness_tests { operations: vec![witness(world.asteroid, world.village, Confidence::Certain)], evidence: Vec::new(), }, - None, ) .expect("the witness resolves over committed state"); - for ground in [ - PatchGround::Consumer(ConsumerId::of_name("witness.consumer")), - PatchGround::Jurisdiction(JurisdictionKey::Uncovered), - ] { - assert_eq!( - confine_to_ground(&kernel.state, &resolved, ground), - Err(vec![Mismatch::OutsideJurisdiction { - site: Site::Operation(0) - }]), - "{ground:?} admitted a witness" - ); - } + let ground = PatchGround::Consumer(ConsumerId::of_name("witness.consumer")); + assert_eq!( + confine_to_ground(&kernel.state, &resolved, ground), + Err(vec![Mismatch::OutsideJurisdiction { + site: Site::Operation(0) + }]), + "{ground:?} admitted a witness" + ); } /// The digest reads the keys of a subject's own knowledge, so a witness @@ -12438,16 +11795,6 @@ mod witness_tests { Confidence::Believed, )]), ); - // An active world admits declarations only through the elaborator lane, - // which is also the lane whose confinement the witness must satisfy. - let answer = derive_boundaries(&kernel.state) - .unwrap() - .into_iter() - .find(|boundary| { - matches!(boundary, CausalBoundary::UnelaboratedDestination { place, .. } - if *place == world.hollow) - }) - .expect("the hollow is an unelaborated destination"); let beacon = *kernel .state .affordance_catalog @@ -12458,16 +11805,13 @@ mod witness_tests { let arrival = |kernel: &mut WorldKernel, handle: &str, label: &str, position: Option<EntityId>| { let snapshot = kernel.snapshot().unwrap(); - let caller = CallerId::System(SystemCapability::Elaborator { - jurisdiction: JurisdictionKey::PlaceSubtree(world.region), - }); + let caller = CallerId::Principal(owner()); kernel.submit( command( &snapshot, CommandId::new(), caller.clone(), CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(answer.clone())), patch: WorldPatch { declarations: vec![ Declaration::Entity(EntityDeclaration { @@ -12657,7 +12001,7 @@ mod witness_tests { /// The clock, commitments, pressure, ordered attention, boundaries, and scale. #[cfg(test)] mod clock_tests { - use super::patch::{PreconditionRef, PressureSourceRef, WorldScaleIntentRef}; + use super::patch::{PreconditionRef, PressureSourceRef}; use super::tests::{ activate, affordance_named, authority_kind, auth_principal, command, creation, office, operations, opportunity_for, owner, human_principal, reject_owner, speech_world, @@ -12725,7 +12069,6 @@ mod clock_tests { kernel, &before, CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { evidence: vec![EvidenceRef::new("vault:harvest")], declarations: vec![ @@ -13629,561 +12972,6 @@ mod clock_tests { ); } - /// Verification 14, first half: a dead end is derived, answered once, and - /// then no longer derived. Nothing clears one but the predicate failing. - #[test] - fn an_unelaborated_destination_is_derived_and_answered_exactly_once() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "DeadEnd"); - let boundaries = derive_boundaries(&kernel.state).unwrap(); - let destinations: Vec<_> = boundaries - .iter() - .filter(|boundary| matches!(boundary, CausalBoundary::UnelaboratedDestination { .. })) - .collect(); - assert_eq!(destinations.len(), 1); - let answered = destinations[0].clone(); - assert!(matches!( - answered, - CausalBoundary::UnelaboratedDestination { route, place, .. } - if route == clockwork.gate && place == clockwork.dead_end - )); - - let snapshot = kernel.snapshot().unwrap(); - assert!(snapshot.boundaries.contains(&answered)); - submit_owner( - &mut kernel, - &snapshot, - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(answered.clone())), - patch: WorldPatch { - declarations: vec![Declaration::Entity(EntityDeclaration { - handle: DraftHandle::new("shed"), - label: "The Roadside Shed".into(), - kind: EntityKind::Place, - container: Some(Ref::Existing(clockwork.dead_end)), - })], - operations: Vec::new(), - evidence: Vec::new(), - }, - }, - ); - assert!( - !derive_boundaries(&kernel.state) - .unwrap() - .contains(&answered) - ); - - // Answering it again names a boundary the kernel no longer derives. - let snapshot = kernel.snapshot().unwrap(); - let error = kernel - .submit( - command( - &snapshot, - CommandId::new(), - CallerId::Principal(owner()), - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(answered)), - patch: WorldPatch { - declarations: vec![Declaration::Entity(EntityDeclaration { - handle: DraftHandle::new("byre"), - label: "The Roadside Byre".into(), - kind: EntityKind::Place, - container: Some(Ref::Existing(clockwork.dead_end)), - })], - operations: Vec::new(), - evidence: Vec::new(), - }, - }, - ), - &auth_principal(owner()), - ) - .unwrap_err(); - assert!(matches!(error, KernelError::AnswerNotDerived), "{error:?}"); - } - - /// A promise the counterparty can neither command nor litigate is a missing - /// structure, and either repair clears it. A goal never derives one. - #[test] - fn a_commitment_with_no_authority_or_redress_derives_missing_structure() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Structure"); - let missing = CausalBoundary::MissingStructure { - subject: clockwork.farmer, - key: clockwork.obligation, - scope: BoundaryDigest(String::new()), - }; - let derives = |kernel: &WorldKernel| { - derive_boundaries(&kernel.state) - .unwrap() - .into_iter() - .any(|boundary| match (&boundary, &missing) { - ( - CausalBoundary::MissingStructure { subject, key, .. }, - CausalBoundary::MissingStructure { - subject: expected_subject, - key: expected_key, - .. - }, - ) => subject == expected_subject && key == expected_key, - _ => false, - }) - }; - assert!(derives(&kernel)); - // A goal is a promise to oneself and needs no forum. - assert!(!derive_boundaries(&kernel.state).unwrap().iter().any( - |boundary| matches!(boundary, CausalBoundary::MissingStructure { key, .. } if *key == clockwork.goal) - )); - - // Jurisdiction over the promisor's ground clears it. - let snapshot = kernel.snapshot().unwrap(); - let grant = ComponentOp::GrantAuthority { - holder: Ref::Existing(clockwork.treasury), - grant: AuthorityGrantRef { - kind: AuthorityKindName("command".into()), - over: AuthorityTargetRef::PlaceSubtree(Ref::Existing(clockwork.yard)), - }, - }; - submit_owner(&mut kernel, &snapshot, operations(vec![grant.clone()])); - assert!(!derives(&kernel)); - - // Revoke it, and a forum whose standing covers the counterparty clears - // it the other way. - let snapshot = kernel.snapshot().unwrap(); - submit_owner( - &mut kernel, - &snapshot, - operations(vec![ComponentOp::RevokeAuthority { - holder: Ref::Existing(clockwork.treasury), - grant: AuthorityGrantRef { - kind: AuthorityKindName("command".into()), - over: AuthorityTargetRef::PlaceSubtree(Ref::Existing(clockwork.yard)), - }, - }]), - ); - assert!(derives(&kernel)); - let snapshot = kernel.snapshot().unwrap(); - submit_owner( - &mut kernel, - &snapshot, - operations(vec![ComponentOp::OpenForum { - grievance: GrievanceKindName("debt".into()), - forum: Ref::Existing(clockwork.reeve), - standing: AuthorityTargetRef::Subject(Ref::Existing(clockwork.treasury)), - }]), - ); - assert!(!derives(&kernel)); - } - - /// Verification 14, second half: an answer must be derived, and the commit - /// must satisfy what it answered. - #[test] - fn an_answer_must_be_derived_and_must_be_satisfied() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Answers"); - let before = kernel.state.clone(); - let declaring = |answers: Option<PatchAnswer>, handle: &str| CommandBody::AdmitPatch { - answers, - patch: WorldPatch { - declarations: vec![Declaration::Entity(EntityDeclaration { - handle: DraftHandle::new(handle), - label: "A Later Room".into(), - kind: EntityKind::Place, - container: None, - })], - operations: Vec::new(), - evidence: Vec::new(), - }, - }; - let refuse = |kernel: &mut WorldKernel, body: CommandBody| { - let snapshot = kernel.snapshot().unwrap(); - kernel - .submit( - command( - &snapshot, - CommandId::new(), - CallerId::Principal(owner()), - body, - ), - &auth_principal(owner()), - ) - .unwrap_err() - }; - - // Declaring in Active without answering. - assert!(matches!( - refuse(&mut kernel, declaring(None, "unanswered")), - KernelError::AnswerRequired - )); - // The two declared-but-never-derived variants. - for boundary in [ - CausalBoundary::PolityInCausalRange { - subject: clockwork.reeve, - scope: BoundaryDigest(String::new()), - }, - CausalBoundary::IndividuationRequired { - population: clockwork.reeve, - scope: BoundaryDigest(String::new()), - }, - ] { - assert!(matches!( - refuse( - &mut kernel, - declaring(Some(PatchAnswer::Boundary(boundary)), "underived") - ), - KernelError::AnswerNotDerived - )); - } - // A jurisdiction with no deficit. - assert!(matches!( - refuse( - &mut kernel, - declaring( - Some(PatchAnswer::Deficit(JurisdictionKey::Uncovered)), - "no-deficit" - ) - ), - KernelError::AnswerNotDerived - )); - // A derived boundary answered by a patch that leaves the predicate - // holding. - let destination = derive_boundaries(&kernel.state) - .unwrap() - .into_iter() - .find(|boundary| matches!(boundary, CausalBoundary::UnelaboratedDestination { .. })) - .expect("the dead end"); - assert!(matches!( - refuse( - &mut kernel, - declaring(Some(PatchAnswer::Boundary(destination)), "elsewhere") - ), - KernelError::AnswerNotSatisfied - )); - assert_eq!(kernel.state, before); - - // Draft answers nothing. - let directory = tempfile::tempdir().unwrap(); - let mut draft_kernel = WorldKernel::create( - directory.path().join("world.cc"), - creation(CommandId::new(), "Draft"), - &auth_principal(owner()), - ) - .expect("a created world") - .0; - assert!(matches!( - refuse( - &mut draft_kernel, - declaring( - Some(PatchAnswer::Deficit(JurisdictionKey::Uncovered)), - "in-draft" - ) - ), - KernelError::AnswerNotDerived - )); - } - - fn creation_with_intent( - id: CommandId, - title: &str, - intent: WorldScaleIntentRef, - ) -> CreateWorld { - let mut creation = creation(id, title); - creation.scale_intent = intent; - creation - } - - fn intent(root: &str, persons: u32, permille: u32) -> WorldScaleIntentRef { - WorldScaleIntentRef { - targets: BTreeMap::from([(SubjectKind::Person, persons)]), - jurisdictions: BTreeMap::from([(DraftHandle::new(root), permille)]), - } - } - - /// Verification 22, first half: only a qualified subject reduces the - /// deficit, and `Goal` carries the whole discrimination. - #[test] - fn a_subject_counts_toward_the_deficit_only_when_qualified() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = WorldKernel::create( - directory.path().join("world.cc"), - creation_with_intent( - CommandId::new(), - "Scale", - intent(super::tests::COMMONS, 3, 1000), - ), - &auth_principal(owner()), - ) - .expect("a created world") - .0; - let commons = kernel - .state - .scale_intent - .jurisdictions - .keys() - .copied() - .next() - .expect("the declared root"); - let active = activate(&mut kernel); - let counted = active - .subjects - .iter() - .find(|subject| subject.kind == SubjectKind::Person) - .expect("the fixture world has a person") - .id; - - let deficit = |kernel: &WorldKernel, jurisdiction: JurisdictionKey| { - derive_scale_deficit(&kernel.state) - .unwrap() - .into_iter() - .find(|row| row.jurisdiction == jurisdiction && row.kind == SubjectKind::Person) - }; - let row = deficit(&kernel, JurisdictionKey::PlaceSubtree(commons)) - .expect("a target of three persons"); - assert_eq!((row.target, row.qualified, row.deficit), (3, 0, 3)); - - // A controller and a grant are not enough; a `Goal` is what counts. - let snapshot = kernel.snapshot().unwrap(); - submit_owner( - &mut kernel, - &snapshot, - operations(vec![ComponentOp::CreateCommitment { - subject: Ref::Existing(counted), - counterparty: None, - kind: CommitmentKind::Goal, - due: FictionalMinutes(500), - period: None, - checks: Vec::new(), - statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), - }]), - ); - let goal = *kernel.state.commitments[&counted] - .keys() - .next() - .expect("the goal"); - let row = deficit(&kernel, JurisdictionKey::PlaceSubtree(commons)).unwrap(); - assert_eq!((row.target, row.qualified, row.deficit), (3, 1, 2)); - - // Discharging it raises the deficit again. - let snapshot = kernel.snapshot().unwrap(); - submit_owner( - &mut kernel, - &snapshot, - operations(vec![ComponentOp::DischargeCommitment { - subject: Ref::Existing(counted), - key: goal, - }]), - ); - let row = deficit(&kernel, JurisdictionKey::PlaceSubtree(commons)).unwrap(); - assert_eq!((row.target, row.qualified, row.deficit), (3, 0, 3)); - } - - /// A qualifying subject standing somewhere no declared root covers still - /// counts, in the `Uncovered` row, rather than vanishing from the deficit - /// entirely: the count is total over every qualifying subject. - #[test] - fn a_subject_placed_outside_every_root_counts_as_uncovered() { - let directory = tempfile::tempdir().unwrap(); - let mut creation = creation_with_intent( - CommandId::new(), - "Uncovered", - intent(super::tests::COMMONS, 3, 1000), - ); - creation - .patch - .declarations - .push(Declaration::Entity(EntityDeclaration { - handle: DraftHandle::new("elsewhere"), - label: "The Elsewhere".into(), - kind: EntityKind::Place, - container: None, - })); - creation - .patch - .declarations - .push(Declaration::Route(RouteDeclaration { - handle: DraftHandle::new("bridge"), - label: "The Elsewhere Bridge".into(), - from: Ref::Draft(DraftHandle::new(super::tests::COMMONS)), - to: Ref::Draft(DraftHandle::new("elsewhere")), - access: AccessKind::Public, - cost: Cost(1), - })); - let mut kernel = WorldKernel::create( - directory.path().join("world.cc"), - creation, - &auth_principal(owner()), - ) - .expect("a created world") - .0; - let active = activate(&mut kernel); - let subject_count = kernel.state.subjects.len() as u32; - assert_eq!(subject_count, 3, "the base fixture declares three subjects"); - - // Every subject qualifies, so the deficit's row counts must sum to - // the whole subject count. - let goal = |subject: SubjectId| ComponentOp::CreateCommitment { - subject: Ref::Existing(subject), - counterparty: None, - kind: CommitmentKind::Goal, - due: FictionalMinutes(500), - period: None, - checks: Vec::new(), - statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), - }; - let subject_ids: Vec<SubjectId> = - active.subjects.iter().map(|subject| subject.id).collect(); - let snapshot = kernel.snapshot().unwrap(); - submit_owner( - &mut kernel, - &snapshot, - operations(subject_ids.iter().copied().map(goal).collect()), - ); - - let moved = active - .subjects - .iter() - .find(|subject| subject.kind == SubjectKind::Person) - .expect("the fixture world has a person") - .id; - let bridge = active - .routes - .iter() - .find(|route| route.label == "The Elsewhere Bridge") - .expect("the declared route") - .id; - let snapshot = kernel.snapshot().unwrap(); - submit_owner( - &mut kernel, - &snapshot, - operations(vec![ComponentOp::Relocate { - subject: Ref::Existing(moved), - via: Ref::Existing(bridge), - }]), - ); - - let rows = derive_scale_deficit(&kernel.state).unwrap(); - let uncovered = rows - .iter() - .find(|row| { - row.jurisdiction == JurisdictionKey::Uncovered && row.kind == SubjectKind::Person - }) - .expect("the relocated subject counts as uncovered"); - assert_eq!(uncovered.qualified, 1); - - let counted_total: u32 = rows.iter().map(|row| row.qualified).sum(); - assert_eq!( - counted_total, subject_count, - "the deficit is total over every qualifying subject" - ); - } - - /// Weights distribute the target and never raise it, and a root must be a - /// declared place. - #[test] - fn scale_weights_distribute_and_never_raise() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let over_whole = WorldScaleIntentRef { - targets: BTreeMap::from([(SubjectKind::Person, 10)]), - jurisdictions: BTreeMap::from([ - (DraftHandle::new(super::tests::COMMONS), 700), - (DraftHandle::new("human"), 400), - ]), - }; - let Err(error) = WorldKernel::create( - &path, - creation_with_intent(CommandId::new(), "TooMuch", over_whole), - &auth_principal(owner()), - ) else { - panic!("a genesis intent over the whole was admitted"); - }; - let KernelError::PatchRejected(mismatches) = error else { - panic!("expected a rejected genesis patch"); - }; - assert!(mismatches.contains(&Mismatch::ScaleWeightsExceedWhole)); - // `human` is a subject handle, not a place. - assert!(mismatches.contains(&Mismatch::UnknownJurisdictionRoot { - handle: DraftHandle::new("human"), - })); - - // Half the whole distributes half the target, rounded down. - let mut kernel = WorldKernel::create( - &path, - creation_with_intent( - CommandId::new(), - "Half", - intent(super::tests::COMMONS, 5, 500), - ), - &auth_principal(owner()), - ) - .expect("a created world") - .0; - activate(&mut kernel); - let rows = derive_scale_deficit(&kernel.state).unwrap(); - let commons_target: u32 = rows - .iter() - .filter(|row| matches!(row.jurisdiction, JurisdictionKey::PlaceSubtree(_))) - .map(|row| row.target) - .sum(); - assert_eq!(commons_target, 2); - assert!(commons_target <= 5); - } - - /// A rejected patch mutates nothing, so the deficit it would have reduced - /// stays visible. - #[test] - fn a_rejected_patch_leaves_the_deficit_unchanged_and_visible() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = WorldKernel::create( - directory.path().join("world.cc"), - creation_with_intent( - CommandId::new(), - "Rejected", - intent(super::tests::COMMONS, 3, 1000), - ), - &auth_principal(owner()), - ) - .expect("a created world") - .0; - let active = activate(&mut kernel); - let before = derive_scale_deficit(&kernel.state).unwrap(); - let subjects: Vec<SubjectId> = active - .subjects - .iter() - .filter(|subject| subject.kind == SubjectKind::Person) - .map(|subject| subject.id) - .collect(); - let goal = |subject: SubjectId, due: u64| ComponentOp::CreateCommitment { - subject: Ref::Existing(subject), - counterparty: None, - kind: CommitmentKind::Goal, - due: FictionalMinutes(due), - period: None, - checks: Vec::new(), - statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), - }; - - // One of the two goals is born past due. - assert_eq!( - reject_owner( - &mut kernel, - &active, - operations(vec![goal(subjects[0], 500), goal(subjects[1], 0)]), - ), - vec![Mismatch::CommitmentDueInThePast { operation: 1 }] - ); - assert_eq!(derive_scale_deficit(&kernel.state).unwrap(), before); - - let snapshot = kernel.snapshot().unwrap(); - submit_owner( - &mut kernel, - &snapshot, - operations(vec![goal(subjects[0], 500), goal(subjects[1], 600)]), - ); - let after = derive_scale_deficit(&kernel.state).unwrap(); - let total = |rows: &[ScaleDeficitRow]| -> u32 { rows.iter().map(|row| row.deficit).sum() }; - assert_eq!(total(&after) + 2, total(&before)); - } - /// Every commitment shape check, in one complete sorted set. #[test] fn commitment_declaration_negatives() { @@ -14580,118 +13368,6 @@ mod clock_tests { } } - /// Soul falsification of the admission ruling: in Active a patch that only - /// changes components answers nothing, a patch that declares or admits - /// evidence must answer, and the answer gate closes before the resolver - /// ever runs. - #[test] - fn soul_an_active_patch_answers_only_when_it_elaborates() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Elaborate"); - - // Component-only, no answer: admitted. - let snapshot = kernel.snapshot().unwrap(); - submit_owner( - &mut kernel, - &snapshot, - operations(vec![ComponentOp::AdvancePressure { - source: PressureSourceRef::Subject(Ref::Existing(clockwork.reeve)), - target: Ref::Existing(clockwork.farmer), - by: PressureMagnitude(2), - }]), - ); - assert_eq!( - pressure( - &kernel, - clockwork.farmer, - PressureSource::Subject(clockwork.reeve) - ), - 2 - ); - - let refuse = |kernel: &mut WorldKernel, body: CommandBody| { - let snapshot = kernel.snapshot().unwrap(); - kernel - .submit( - command( - &snapshot, - CommandId::new(), - CallerId::Principal(owner()), - body, - ), - &auth_principal(owner()), - ) - .unwrap_err() - }; - - // Evidence alone is elaboration too, so it answers. - let evidence_only = CommandBody::AdmitPatch { - answers: None, - patch: WorldPatch { - declarations: Vec::new(), - operations: Vec::new(), - evidence: vec![EvidenceRef::new("soul://evidence-only")], - }, - }; - assert!(matches!( - refuse(&mut kernel, evidence_only), - KernelError::AnswerRequired - )); - - // The gate is ahead of the resolver: a declaring patch that is also - // structurally broken is refused for the missing answer, not for the - // mismatch it would otherwise return. - let broken = CommandBody::AdmitPatch { - answers: None, - patch: WorldPatch { - declarations: vec![Declaration::Entity(EntityDeclaration { - handle: DraftHandle::new("orphan"), - label: "An Orphan Room".into(), - kind: EntityKind::Place, - container: Some(Ref::Draft(DraftHandle::new("nowhere"))), - })], - operations: Vec::new(), - evidence: Vec::new(), - }, - }; - assert!( - matches!(refuse(&mut kernel, broken), KernelError::AnswerRequired), - "the resolver ran before the answer gate" - ); - - // A derived answer that the patch satisfies commits, and the boundary - // is gone afterwards. - let answered = derive_boundaries(&kernel.state) - .unwrap() - .into_iter() - .find(|boundary| matches!(boundary, CausalBoundary::UnelaboratedDestination { .. })) - .expect("the dead end"); - let snapshot = kernel.snapshot().unwrap(); - submit_owner( - &mut kernel, - &snapshot, - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(answered.clone())), - patch: WorldPatch { - declarations: vec![Declaration::Entity(EntityDeclaration { - handle: DraftHandle::new("cairn"), - label: "A Roadside Cairn".into(), - kind: EntityKind::Place, - container: Some(Ref::Existing(clockwork.dead_end)), - })], - operations: Vec::new(), - evidence: Vec::new(), - }, - }, - ); - assert!( - !derive_boundaries(&kernel.state) - .unwrap() - .contains(&answered), - "the answered boundary is still derived" - ); - } - /// Soul falsification: pressure magnitude cannot overflow or go negative, /// and zero is spelled by absence at both ends. #[test] @@ -14790,58 +13466,6 @@ mod clock_tests { assert_eq!(digests(&kernel), before, "the clock entered a scope digest"); } - /// Soul falsification: the authored scale target is written once by genesis - /// and by no Active lane. `AdmitPatch` resolves with no intent at all, so - /// there is no shape for an Active rewrite to take. - #[test] - fn soul_the_scale_intent_is_written_once_by_genesis() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = WorldKernel::create( - directory.path().join("world.cc"), - creation_with_intent( - CommandId::new(), - "WriteOnce", - intent(super::tests::COMMONS, 3, 1000), - ), - &auth_principal(owner()), - ) - .expect("a created world") - .0; - let active = activate(&mut kernel); - let authored = kernel.state.scale_intent.clone(); - assert!(!authored.jurisdictions.is_empty()); - - let subject = active - .subjects - .iter() - .find(|subject| subject.kind == SubjectKind::Person) - .expect("a person") - .id; - let body = operations(vec![ComponentOp::CreateCommitment { - subject: Ref::Existing(subject), - counterparty: None, - kind: CommitmentKind::Goal, - due: FictionalMinutes(500), - period: None, - checks: Vec::new(), - statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), - }]); - // The Active resolver is handed no intent, so the resolved patch cannot - // carry one. - let CommandBody::AdmitPatch { patch, .. } = &body else { - panic!("the operations helper builds an admitted patch"); - }; - let resolved = - patch::resolve_patch(&kernel.state, CommandId::new(), patch, None).expect("resolves"); - assert!( - resolved.scale_intent.is_none(), - "an Active patch resolved a scale intent" - ); - - submit_owner(&mut kernel, &active, body); - assert_eq!(kernel.state.scale_intent, authored); - } - // ---- PA.f26: the genesis lane obeys `require_ruler` too ------------ /// PA.f26: `prepare_creation` and `WorldState::genesis` both call @@ -14927,7 +13551,6 @@ mod clock_tests { &WorldState::empty(world_id, input.owner.clone(), title.clone(), None), input.id, &input.patch, - Some(&input.scale_intent), ) .expect("the resolver is actor-blind and accepts a Ruled fact"); let effect = WorldEffect::WorldCreated { @@ -14954,7 +13577,6 @@ mod clock_tests { &WorldState::empty(world_id, input.owner.clone(), title.clone(), None), input.id, &input.patch, - Some(&input.scale_intent), ) .expect("the resolver is actor-blind and accepts a Mint"); let effect = WorldEffect::WorldCreated { @@ -14966,30 +13588,6 @@ mod clock_tests { assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); } - /// An owner commit that adds a commitment to the first person: a real - /// Active patch with no answer, and nothing to do with lenses. - fn operations_patch(kernel: &WorldKernel) -> WorldPatch { - let subject = kernel - .state - .subjects - .iter() - .find(|(_, state)| state.kind == SubjectKind::Person) - .map(|(id, _)| *id) - .expect("a person"); - let CommandBody::AdmitPatch { patch, .. } = operations(vec![ComponentOp::CreateCommitment { - subject: Ref::Existing(subject), - counterparty: None, - kind: CommitmentKind::Goal, - due: FictionalMinutes(kernel.state.now.0 + 500), - period: None, - checks: Vec::new(), - statement: Statement::new("A promise kept with no flavor at all.").unwrap(), - }]) else { - panic!("the operations helper builds an admitted patch"); - }; - patch - } - /// Soul falsification: a discharge names one subject's own live key. #[test] fn soul_discharging_a_foreign_or_already_discharged_commitment_is_refused() { @@ -15144,55 +13742,7 @@ mod clock_tests { assert_eq!(replayed.pressures, kernel.state.pressures); } - /// Soul falsification: a `BoundaryDigest` binds the structure that derives - /// it, and nothing else. The clock is not in the preimage, so a tick leaves - /// it where it is; closing the one route out of the dead end leaves the - /// predicate holding and must still move the digest. - #[test] - fn soul_a_boundary_digest_binds_its_structure_and_not_the_clock() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Digest"); - let destination = |kernel: &WorldKernel| { - derive_boundaries(&kernel.state) - .unwrap() - .into_iter() - .find_map(|boundary| match boundary { - CausalBoundary::UnelaboratedDestination { place, scope, .. } - if place == clockwork.dead_end => - { - Some(scope) - } - _ => None, - }) - .expect("the dead end") - }; - let before = destination(&kernel); - - // The clock moves; the digest does not. - tick(&mut kernel, 10).expect("the tick commits"); - assert_eq!(destination(&kernel), before, "the clock entered a preimage"); - - // The route's own record moves; the digest must follow. - let snapshot = kernel.snapshot().unwrap(); - submit_owner( - &mut kernel, - &snapshot, - operations(vec![ComponentOp::CloseRoute { - route: Ref::Existing(clockwork.gate), - }]), - ); - assert_ne!( - destination(&kernel), - before, - "the digest ignored the route it names" - ); - } - - // ---- the elaborator capability ------------------------------------- - - fn elaborator(jurisdiction: JurisdictionKey) -> CallerId { - CallerId::System(SystemCapability::Elaborator { jurisdiction }) - } + // ---- system capabilities ------------------------------------------ fn submit_as( kernel: &mut WorldKernel, @@ -15206,14 +13756,6 @@ mod clock_tests { ) } - fn dead_end_boundary(kernel: &WorldKernel) -> CausalBoundary { - derive_boundaries(&kernel.state) - .unwrap() - .into_iter() - .find(|boundary| matches!(boundary, CausalBoundary::UnelaboratedDestination { .. })) - .expect("the fixture derives one dead end") - } - fn shed_under(container: EntityId, handle: &str) -> WorldPatch { WorldPatch { declarations: vec![Declaration::Entity(EntityDeclaration { @@ -15227,61 +13769,16 @@ mod clock_tests { } } - /// Verification 14: the mailbox port cannot express an unanswered - /// elaborator patch, so this is reachable only through the journal lane — - /// and it is refused there. - #[test] - fn elaborator_patch_without_answer_is_answer_required() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Unanswered"); - let revision = kernel.state.revision; - let error = submit_as( - &mut kernel, - elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), - CommandBody::AdmitPatch { - answers: None, - patch: shed_under(clockwork.dead_end, "shed"), - }, - ) - .unwrap_err(); - assert!(matches!(error, KernelError::AnswerRequired), "{error:?}"); - assert_eq!(kernel.state.revision, revision); - } - - /// Verification 14: a jurisdiction whose every row is zero has nothing to - /// answer, so the answer is not derived. - #[test] - fn patch_answering_a_zero_deficit_is_rejected() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "ZeroDeficit"); - let jurisdiction = JurisdictionKey::PlaceSubtree(clockwork.dead_end); - assert!( - derive_scale_deficit(&kernel.state) - .unwrap() - .iter() - .all(|row| row.deficit == 0) - ); - let error = submit_as( - &mut kernel, - elaborator(jurisdiction), - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Deficit(jurisdiction)), - patch: shed_under(clockwork.dead_end, "shed"), - }, - ) - .unwrap_err(); - assert!(matches!(error, KernelError::AnswerNotDerived), "{error:?}"); - } - /// The one admission rule at the top of `reduce` refuses four bodies before /// any of them is read, and the clock's capability is refused the fifth. #[test] fn a_system_capability_is_admitted_for_exactly_one_body() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "Capability"); - let held = elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)); + let held = CallerId::System(SystemCapability::Consumer { + consumer: ConsumerId::of_name("capability-consumer"), + }); let opportunity = opportunity_for(&active, clockwork.reeve); - let answered = dead_end_boundary(&kernel); let forbidden = [ CommandBody::ApproveDraft, CommandBody::ActivateWorld, @@ -15301,7 +13798,6 @@ mod clock_tests { &mut kernel, clock_caller(), CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(answered)), patch: shed_under(clockwork.dead_end, "shed"), }, ) @@ -15310,363 +13806,6 @@ mod clock_tests { assert_eq!(kernel.state.revision, active.revision); } - /// Seed admission is the owner's lane: an elaborator in Draft has no - /// derived boundary to answer and nothing to be authorized for. - #[test] - fn elaborator_in_draft_is_unauthorized() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = WorldKernel::create( - directory.path().join("world.cc"), - creation(CommandId::new(), "DraftLane"), - &auth_principal(owner()), - ) - .expect("a created world") - .0; - let commons = kernel.snapshot().unwrap().places[0].id; - let error = submit_as( - &mut kernel, - elaborator(JurisdictionKey::PlaceSubtree(commons)), - CommandBody::AdmitPatch { - answers: None, - patch: shed_under(commons, "shed"), - }, - ) - .unwrap_err(); - // Draft answers nothing, so the answer gate passes and authority - // refuses: an elaborator with no answer holds nothing. - assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); - } - - /// Boundaries are covered transitively, so a parent jurisdiction's - /// elaborator may answer a boundary in a nested child — and a sibling root - /// may not answer it at all. - #[test] - fn boundary_jurisdiction_is_transitive_and_exclusive() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Transitive"); - let answered = dead_end_boundary(&kernel); - let hall = kernel.state.entities[&clockwork.yard] - .container - .expect("the yard sits in the hall"); - - // The hall's elaborator does not cover the unwalked road. - let error = submit_as( - &mut kernel, - elaborator(JurisdictionKey::PlaceSubtree(hall)), - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(answered.clone())), - patch: shed_under(clockwork.dead_end, "shed"), - }, - ) - .unwrap_err(); - assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); - - // One unconfined owner patch answers that boundary and opens a second - // one strictly inside the hall, so the two coverings can be told apart - // on one world. - let snapshot = kernel.snapshot().unwrap(); - submit_owner( - &mut kernel, - &snapshot, - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(answered.clone())), - patch: WorldPatch { - declarations: vec![ - Declaration::Entity(EntityDeclaration { - handle: DraftHandle::new("shed"), - label: "The Roadside Shed".into(), - kind: EntityKind::Place, - container: Some(Ref::Existing(clockwork.dead_end)), - }), - Declaration::Entity(EntityDeclaration { - handle: DraftHandle::new("cellar"), - label: "The Yard Cellar".into(), - kind: EntityKind::Place, - container: Some(Ref::Existing(clockwork.yard)), - }), - Declaration::Route(RouteDeclaration { - handle: DraftHandle::new("hatch"), - label: "The Cellar Hatch".into(), - from: Ref::Existing(clockwork.yard), - to: Ref::Draft(DraftHandle::new("cellar")), - access: AccessKind::Public, - cost: Cost(1), - }), - ], - operations: Vec::new(), - evidence: Vec::new(), - }, - }, - ); - assert!( - !derive_boundaries(&kernel.state) - .unwrap() - .contains(&answered) - ); - - let cellar = kernel - .state - .entities - .iter() - .find(|(_, entity)| entity.label == "The Yard Cellar") - .map(|(id, _)| *id) - .expect("the declared cellar"); - let nested = dead_end_boundary(&kernel); - assert!(matches!( - nested, - CausalBoundary::UnelaboratedDestination { place, .. } if place == cellar - )); - - // The road's root does not reach into the hall. - let error = submit_as( - &mut kernel, - elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(nested.clone())), - patch: shed_under(cellar, "crock"), - }, - ) - .unwrap_err(); - assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); - - // The hall's does, transitively, through the same containment walk the - // civic lane uses. - submit_as( - &mut kernel, - elaborator(JurisdictionKey::PlaceSubtree(hall)), - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(nested.clone())), - patch: shed_under(cellar, "crock"), - }, - ) - .expect("the parent root covers a nested boundary"); - assert!(!derive_boundaries(&kernel.state).unwrap().contains(&nested)); - } - - /// A deficit is covered by exact key equality. A parent answering a child's - /// row would reduce two targets with one subject, because a subject under - /// nested roots counts toward both. - #[test] - fn parent_jurisdiction_cannot_answer_a_child_deficit_row() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = WorldKernel::create( - directory.path().join("world.cc"), - creation_with_intent( - CommandId::new(), - "Rows", - intent(super::tests::COMMONS, 3, 1000), - ), - &auth_principal(owner()), - ) - .expect("a created world") - .0; - let commons = *kernel - .state - .scale_intent - .jurisdictions - .keys() - .next() - .expect("the declared root"); - let active = activate(&mut kernel); - let inner = active.places[0].id; - let row = JurisdictionKey::PlaceSubtree(commons); - assert!( - derive_scale_deficit(&kernel.state) - .unwrap() - .iter() - .any(|candidate| candidate.jurisdiction == row && candidate.deficit > 0) - ); - let error = submit_as( - &mut kernel, - elaborator(JurisdictionKey::Uncovered), - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Deficit(row)), - patch: shed_under(inner, "shed"), - }, - ) - .unwrap_err(); - assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); - } - - /// Confinement: a valid answer does not license a write outside the - /// jurisdiction, and a place with no container is a new root, which is the - /// owner's act. - #[test] - fn an_elaborator_cannot_write_outside_its_jurisdiction() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Confined"); - let answered = dead_end_boundary(&kernel); - let held = elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)); - - let foreign = submit_as( - &mut kernel, - held.clone(), - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(answered.clone())), - patch: shed_under(clockwork.yard, "yardshed"), - }, - ) - .unwrap_err(); - assert!( - matches!(&foreign, KernelError::PatchRejected(set) - if set == &vec![Mismatch::OutsideJurisdiction { - site: Site::Declaration(DraftHandle::new("yardshed")), - }]), - "{foreign:?}" - ); - - let rootless = submit_as( - &mut kernel, - held, - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(answered.clone())), - patch: WorldPatch { - declarations: vec![Declaration::Entity(EntityDeclaration { - handle: DraftHandle::new("newroot"), - label: "A New Country".into(), - kind: EntityKind::Place, - container: None, - })], - operations: Vec::new(), - evidence: Vec::new(), - }, - }, - ) - .unwrap_err(); - assert!( - matches!(&rootless, KernelError::PatchRejected(set) - if set == &vec![Mismatch::OutsideJurisdiction { - site: Site::Declaration(DraftHandle::new("newroot")), - }]), - "{rootless:?}" - ); - - // The owner is unconfined, and the identical rootless patch commits — - // once it answers something the kernel derives. - let snapshot = kernel.snapshot().unwrap(); - submit_owner( - &mut kernel, - &snapshot, - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(answered)), - patch: WorldPatch { - declarations: vec![Declaration::Entity(EntityDeclaration { - handle: DraftHandle::new("newroot"), - label: "A New Country".into(), - kind: EntityKind::Place, - container: Some(Ref::Existing(clockwork.dead_end)), - })], - operations: Vec::new(), - evidence: Vec::new(), - }, - }, - ); - } - - /// Verification 17: seed admission and boundary elaboration reach one - /// reducer. The same structural defect returns the same complete set on - /// both lanes. - #[test] - fn seed_admission_and_boundary_elaboration_reach_one_reducer() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "OneReducer"); - let answered = dead_end_boundary(&kernel); - let dangling = |handle: &str| WorldPatch { - declarations: vec![Declaration::Entity(EntityDeclaration { - handle: DraftHandle::new(handle), - label: "The Nowhere Shed".into(), - kind: EntityKind::Place, - container: Some(Ref::Draft(DraftHandle::new("nothing"))), - })], - operations: Vec::new(), - evidence: Vec::new(), - }; - let snapshot = kernel.snapshot().unwrap(); - let owner_error = kernel - .submit( - command( - &snapshot, - CommandId::new(), - CallerId::Principal(owner()), - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(answered.clone())), - patch: dangling("shed"), - }, - ), - &auth_principal(owner()), - ) - .unwrap_err(); - let elaborator_error = submit_as( - &mut kernel, - elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(answered.clone())), - patch: dangling("shed"), - }, - ) - .unwrap_err(); - let set_of = |error: &KernelError| match error { - KernelError::PatchRejected(set) => set.clone(), - other => panic!("{other:?}"), - }; - assert_eq!(set_of(&owner_error), set_of(&elaborator_error)); - - // And both lanes commit the sound patch through the one writer. - submit_as( - &mut kernel, - elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(answered)), - patch: shed_under(clockwork.dead_end, "shed"), - }, - ) - .expect("the elaborated patch commits"); - } - - /// `reduce` decides and `apply_effect` re-decides: a hand-built effect with - /// a jurisdiction that does not cover its answer never applies. - #[test] - fn apply_effect_re_decides_elaborator_authority() { - let directory = tempfile::tempdir().unwrap(); - let (kernel, clockwork, _) = clock_kernel(directory.path(), "Redecide"); - let answered = dead_end_boundary(&kernel); - let hall = kernel.state.entities[&clockwork.yard].container.unwrap(); - let command_id = CommandId::issue(); - let resolved = patch::resolve_patch( - &kernel.state, - command_id, - &shed_under(clockwork.dead_end, "shed"), - None, - ) - .expect("the patch resolves"); - let effect = WorldEffect::PatchAdmitted { - answers: Some(PatchAnswer::Boundary(answered)), - resolved, - }; - - let mut candidate = kernel.state.clone(); - let error = apply_effect( - &mut candidate, - command_id, - &elaborator(JurisdictionKey::PlaceSubtree(hall)), - &effect, - ) - .unwrap_err(); - assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); - assert_eq!(candidate, kernel.state); - - // The honest jurisdiction applies through the same arm. - let mut candidate = kernel.state.clone(); - apply_effect( - &mut candidate, - command_id, - &elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), - &effect, - ) - .expect("the covering jurisdiction applies"); - assert_ne!(candidate, kernel.state); - } - /// The mismatch vocabulary is kernel-internal plus controller telemetry. It /// never enters a commit, and `verify_state_shape` never grows a clause for /// it because no partition holds one. @@ -15674,16 +13813,14 @@ mod clock_tests { fn mismatch_never_appears_in_a_world_commit() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Separation"); - let answered = dead_end_boundary(&kernel); submit_as( &mut kernel, - elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CallerId::Principal(owner()), CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(answered)), patch: shed_under(clockwork.dead_end, "shed"), }, ) - .expect("the elaboration commits"); + .expect("the owner's patch commits"); let bytes = rmp_serde::to_vec_named(&kernel.state).expect("state encodes"); let text = String::from_utf8_lossy(&bytes); @@ -15699,349 +13836,6 @@ mod clock_tests { // ---- Soul: the confinement predicate past its declaration lane ------ - /// Confinement is claimed for every referent a jurisdictional author - /// writes, not only for declarations. An operation naming a route with one - /// endpoint outside the jurisdiction is outside, and the site it reports is - /// the operation's. - #[test] - fn soul_an_operation_naming_a_half_outside_route_is_outside_the_jurisdiction() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "OperationLane"); - let answered = dead_end_boundary(&kernel); - let revision = kernel.state.revision; - // The Field Gate runs hall -> dead end. The dead end's elaborator holds - // one of its two ends and therefore holds neither. - let mut patch = shed_under(clockwork.dead_end, "shed"); - patch.operations = vec![ComponentOp::AlterCost { - route: Ref::Existing(clockwork.gate), - cost: Cost(2), - }]; - let error = submit_as( - &mut kernel, - elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(answered.clone())), - patch, - }, - ) - .unwrap_err(); - assert!( - matches!(&error, KernelError::PatchRejected(set) - if set == &vec![Mismatch::OutsideJurisdiction { site: Site::Operation(0) }]), - "{error:?}" - ); - assert_eq!(kernel.state.revision, revision); - - // The owner is unconfined and the identical patch commits. - let snapshot = kernel.snapshot().unwrap(); - let mut owner_patch = shed_under(clockwork.dead_end, "shed"); - owner_patch.operations = vec![ComponentOp::AlterCost { - route: Ref::Existing(clockwork.gate), - cost: Cost(2), - }]; - submit_owner( - &mut kernel, - &snapshot, - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(answered)), - patch: owner_patch, - }, - ); - } - - /// The fifth body the capability rule refuses. `ExerciseDecision` is the - /// one the existing negative omits, and it is the one a subject's lane uses. - #[test] - fn soul_an_elaborator_cannot_exercise_a_decision() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "NoExercise"); - let revision = kernel.state.revision; - let error = submit_as( - &mut kernel, - elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), - CommandBody::ExerciseDecision { - opportunity: opportunity_for(&active, clockwork.reeve), - invocation: DecisionInvocation { - affordance: clockwork.deliver, - bindings: Vec::new(), - proposed: Vec::new(), - speech: None, - display: None, - }, - }, - ) - .unwrap_err(); - assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); - assert_eq!(kernel.state.revision, revision); - } - - /// Two boundaries under two disjoint roots, opened by one owner patch. - /// Answering one leaves the other derived with its digest unmoved, so the - /// second elaborator commits afterwards at a later revision. Answering the - /// first a second time is not derived. - #[test] - fn soul_disjoint_boundaries_commit_independently_and_a_spent_answer_is_not_derived() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Disjoint"); - let road = dead_end_boundary(&kernel); - let hall = kernel.state.entities[&clockwork.yard] - .container - .expect("the yard sits in the hall"); - - // One unconfined patch answers the road and opens one dead end under - // each root: a cellar under the yard, an annex off the road. - let snapshot = kernel.snapshot().unwrap(); - submit_owner( - &mut kernel, - &snapshot, - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(road)), - patch: WorldPatch { - declarations: vec![ - Declaration::Entity(EntityDeclaration { - handle: DraftHandle::new("cellar"), - label: "The Yard Cellar".into(), - kind: EntityKind::Place, - container: Some(Ref::Existing(clockwork.yard)), - }), - Declaration::Route(RouteDeclaration { - handle: DraftHandle::new("hatch"), - label: "The Cellar Hatch".into(), - from: Ref::Existing(clockwork.yard), - to: Ref::Draft(DraftHandle::new("cellar")), - access: AccessKind::Public, - cost: Cost(1), - }), - Declaration::Entity(EntityDeclaration { - handle: DraftHandle::new("annex"), - label: "The Road Annex".into(), - kind: EntityKind::Place, - container: Some(Ref::Existing(clockwork.dead_end)), - }), - Declaration::Route(RouteDeclaration { - handle: DraftHandle::new("spur"), - label: "The Road Spur".into(), - from: Ref::Existing(clockwork.dead_end), - to: Ref::Draft(DraftHandle::new("annex")), - access: AccessKind::Public, - cost: Cost(1), - }), - ], - operations: Vec::new(), - evidence: Vec::new(), - }, - }, - ); - - let place_named = |kernel: &WorldKernel, label: &str| { - kernel - .state - .entities - .iter() - .find(|(_, entity)| entity.label == label) - .map(|(id, _)| *id) - .expect("the declared place") - }; - let cellar = place_named(&kernel, "The Yard Cellar"); - let annex = place_named(&kernel, "The Road Annex"); - let boundary_at = |kernel: &WorldKernel, place: EntityId| { - derive_boundaries(&kernel.state) - .unwrap() - .into_iter() - .find(|boundary| { - matches!(boundary, CausalBoundary::UnelaboratedDestination { place: at, .. } if *at == place) - }) - .unwrap_or_else(|| panic!("no boundary at {place:?}")) - }; - // Both are derived at the same revision, and both are read before - // either is answered. - let cellar_answer = boundary_at(&kernel, cellar); - let annex_answer = boundary_at(&kernel, annex); - - submit_as( - &mut kernel, - elaborator(JurisdictionKey::PlaceSubtree(hall)), - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(cellar_answer.clone())), - patch: shed_under(cellar, "crock"), - }, - ) - .expect("the hall's elaborator answers the cellar"); - let after_first = kernel.state.revision; - - // The other root's answer is untouched by that commit: same value, - // same digest, still derived. - assert!( - derive_boundaries(&kernel.state) - .unwrap() - .contains(&annex_answer) - ); - submit_as( - &mut kernel, - elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(annex_answer)), - patch: shed_under(annex, "barrow"), - }, - ) - .expect("the road's elaborator answers the annex"); - assert!(kernel.state.revision > after_first); - - // The spent answer is a value nothing derives any more. - let error = submit_as( - &mut kernel, - elaborator(JurisdictionKey::PlaceSubtree(hall)), - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(cellar_answer)), - patch: shed_under(cellar, "second_crock"), - }, - ) - .unwrap_err(); - assert!(matches!(error, KernelError::AnswerNotDerived), "{error:?}"); - } - - /// The third structural bound, reached through the elaborator lane: the - /// answer must be derived, every write must be inside the jurisdiction, and - /// the answer must stop being derived after the write. - #[test] - fn soul_an_elaborator_patch_that_does_not_satisfy_its_answer_is_refused() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Unsatisfied"); - let road = dead_end_boundary(&kernel); - let hall = kernel.state.entities[&clockwork.yard] - .container - .expect("the yard sits in the hall"); - - // One owner patch answers the road and opens a cellar dead end inside - // the hall, so the hall's elaborator has an answer it covers and a - // legal write that does not satisfy it. - let snapshot = kernel.snapshot().unwrap(); - submit_owner( - &mut kernel, - &snapshot, - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(road)), - patch: WorldPatch { - declarations: vec![ - Declaration::Entity(EntityDeclaration { - handle: DraftHandle::new("shed"), - label: "The Roadside Shed".into(), - kind: EntityKind::Place, - container: Some(Ref::Existing(clockwork.dead_end)), - }), - Declaration::Entity(EntityDeclaration { - handle: DraftHandle::new("cellar"), - label: "The Yard Cellar".into(), - kind: EntityKind::Place, - container: Some(Ref::Existing(clockwork.yard)), - }), - Declaration::Route(RouteDeclaration { - handle: DraftHandle::new("hatch"), - label: "The Cellar Hatch".into(), - from: Ref::Existing(clockwork.yard), - to: Ref::Draft(DraftHandle::new("cellar")), - access: AccessKind::Public, - cost: Cost(1), - }), - ], - operations: Vec::new(), - evidence: Vec::new(), - }, - }, - ); - let cellar = kernel - .state - .entities - .iter() - .find(|(_, entity)| entity.label == "The Yard Cellar") - .map(|(id, _)| *id) - .expect("the declared cellar"); - let cellar_answer = derive_boundaries(&kernel.state) - .unwrap() - .into_iter() - .find(|boundary| { - matches!(boundary, CausalBoundary::UnelaboratedDestination { place, .. } if *place == cellar) - }) - .expect("the cellar is a dead end"); - let revision = kernel.state.revision; - - // Inside the hall, so confinement passes; nowhere near the cellar, so - // the answered boundary is still derived after the write. - let error = submit_as( - &mut kernel, - elaborator(JurisdictionKey::PlaceSubtree(hall)), - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(cellar_answer.clone())), - patch: shed_under(clockwork.yard, "yardshed"), - }, - ) - .unwrap_err(); - assert!( - matches!(error, KernelError::AnswerNotSatisfied), - "{error:?}" - ); - assert_eq!(kernel.state.revision, revision); - assert!( - derive_boundaries(&kernel.state) - .unwrap() - .contains(&cellar_answer), - "a refused patch left the boundary derived" - ); - - // The same author satisfying the same answer commits. - submit_as( - &mut kernel, - elaborator(JurisdictionKey::PlaceSubtree(hall)), - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(cellar_answer.clone())), - patch: shed_under(cellar, "crock"), - }, - ) - .expect("the satisfying patch commits"); - assert!( - !derive_boundaries(&kernel.state) - .unwrap() - .contains(&cellar_answer) - ); - } - - /// Pass 6's rule survives the ungating of `EvidenceRef::new`: a canonical - /// fact still needs its receipt listed on the patch that declares it, and an - /// elaborator gets the same refusal the owner does. - #[test] - fn soul_an_elaborator_cannot_mint_a_canonical_fact_without_a_listed_receipt() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Provenance"); - let answered = dead_end_boundary(&kernel); - let revision = kernel.state.revision; - let mut patch = shed_under(clockwork.dead_end, "shed"); - patch.declarations.push(Declaration::Fact(FactDeclaration { - handle: DraftHandle::new("flood"), - label: "The Flooded Hinge".into(), - statement: Statement::new("The lower hinge flooded.").expect("a canonical statement"), - standing: FactStandingRef::Canonical { - evidence: EvidenceRef::new("vault:forged"), - }, - })); - let error = submit_as( - &mut kernel, - elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(answered)), - patch, - }, - ) - .unwrap_err(); - assert!( - matches!(&error, KernelError::PatchRejected(set) - if set.contains(&Mismatch::FactWithoutEvidence { - handle: DraftHandle::new("flood"), - })), - "{error:?}" - ); - assert_eq!(kernel.state.revision, revision); - } - // ---- Cut 3: the play authority, `Ruled` facts and `Mint` ----------- fn play_caller() -> CallerId { @@ -16081,7 +13875,6 @@ mod clock_tests { &mut kernel, play_caller(), CommandBody::AdmitPatch { - answers: None, patch: shed_under(clockwork.dead_end, "play-shed"), }, ) @@ -16089,50 +13882,32 @@ mod clock_tests { assert!(matches!(receipt, SubmitReceipt::Applied(_))); } - /// Invariant 5, second half: the elaborator gate is unchanged. + /// With no answer gate, the owner declares in Active as it does in Draft. #[test] - fn an_elaborator_declaration_in_active_without_an_answer_is_still_refused() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "ElaboratorUnanswered"); - let error = submit_as( - &mut kernel, - elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), - CommandBody::AdmitPatch { - answers: None, - patch: shed_under(clockwork.dead_end, "shed"), - }, - ) - .unwrap_err(); - assert!(matches!(error, KernelError::AnswerRequired), "{error:?}"); - } - - /// Invariant 5, second half: the owner's own gate is unchanged too. Only - /// `Play` is exempted from `AnswerRequired`. - #[test] - fn the_owner_still_cannot_declare_unanswered_in_active() { + fn the_owner_declares_in_active_without_an_answer() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "OwnerUnanswered"); let snapshot = kernel.snapshot().unwrap(); - let error = kernel + let receipt = kernel .submit( command( &snapshot, CommandId::new(), CallerId::Principal(owner()), CommandBody::AdmitPatch { - answers: None, patch: shed_under(clockwork.dead_end, "shed"), }, ), &auth_principal(owner()), ) - .unwrap_err(); - assert!(matches!(error, KernelError::AnswerRequired), "{error:?}"); + .expect("the owner declares in Active"); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(kernel.state.entities.values().any(|entity| entity.label == "The shed")); } /// Invariant 5: the play authority reaches the whole world, unconfined to - /// a ground. Writing under a place no jurisdiction covers, with no - /// answer, is exactly what an elaborator or the owner cannot do. + /// a ground. Writing under a place no jurisdiction covers is exactly what + /// a confined author cannot do. #[test] fn the_play_authority_is_unconfined() { let directory = tempfile::tempdir().unwrap(); @@ -16141,7 +13916,6 @@ mod clock_tests { &mut kernel, play_caller(), CommandBody::AdmitPatch { - answers: None, patch: shed_under(clockwork.dead_end, "unconfined-shed"), }, ) @@ -16164,7 +13938,6 @@ mod clock_tests { &mut kernel, play_caller(), CommandBody::AdmitPatch { - answers: None, patch: shed_under(commons, "shed"), }, ) @@ -16261,7 +14034,6 @@ mod clock_tests { &mut kernel, play_caller(), CommandBody::AdmitPatch { - answers: None, patch, }, ) @@ -16304,7 +14076,6 @@ mod clock_tests { &mut kernel, play_caller(), CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: Vec::new(), operations: vec![ComponentOp::Mint { @@ -16343,7 +14114,6 @@ mod clock_tests { &mut kernel, play_caller(), CommandBody::AdmitPatch { - answers: None, patch, }, ) @@ -16370,7 +14140,6 @@ mod clock_tests { &mut kernel, play_caller(), CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: Vec::new(), operations: vec![ComponentOp::Admit { @@ -16396,7 +14165,6 @@ mod clock_tests { &mut kernel, play_caller(), CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: Vec::new(), operations: vec![ComponentOp::Admit { @@ -16438,7 +14206,6 @@ mod clock_tests { CommandId::new(), CallerId::Principal(owner()), CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: vec![fact("vault:draft-uncited")], operations: Vec::new(), @@ -16464,7 +14231,6 @@ mod clock_tests { CommandId::new(), CallerId::Principal(owner()), CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: vec![fact("vault:draft-cited")], operations: Vec::new(), @@ -16477,17 +14243,11 @@ mod clock_tests { .expect("a cited canonical fact is admitted for the owner in Draft"); } - // PA.f29a: the owner in Active, with a real answer. Its own - // `clock_kernel`, so the boundary this answers is not the one the - // Play blocks above already left cleared. The cited patch also - // seats a fresh occupant at the dead end: what actually clears an - // `UnelaboratedDestination` boundary ("a commit clears exactly the - // boundary it answers"), so the citation succeeding is not - // masked by an `AnswerNotSatisfied` refusal. + // PA.f29a: the owner in Active. Its own `clock_kernel`. The cited + // patch also seats a fresh occupant at the dead end. { let directory = tempfile::tempdir().unwrap(); let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "OwnerActiveEvidence"); - let answered = dead_end_boundary(&kernel); let speak = super::tests::speak_entry(&kernel); let fact = |evidence: &str| { Declaration::Fact(FactDeclaration { @@ -16503,7 +14263,6 @@ mod clock_tests { &mut kernel, CallerId::Principal(owner()), CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(answered.clone())), patch: WorldPatch { declarations: vec![fact("vault:active-uncited")], operations: Vec::new(), @@ -16523,7 +14282,6 @@ mod clock_tests { &mut kernel, CallerId::Principal(owner()), CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(answered)), patch: WorldPatch { declarations: vec![ fact("vault:active-cited"), @@ -16544,218 +14302,17 @@ mod clock_tests { ) .expect("a cited canonical fact is admitted for the owner in Active"); } - - // PA.f29a: an answered elaborator. Its own `clock_kernel` for the - // same reason. The occupant the cited patch seats at the dead end - // is inside the elaborator's own `PlaceSubtree` jurisdiction, so - // `confine_to_ground` admits it the same as the fact. - { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = - clock_kernel(directory.path(), "ElaboratorEvidence"); - let answered = dead_end_boundary(&kernel); - let speak = super::tests::speak_entry(&kernel); - let caller = elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)); - let fact = |evidence: &str| { - Declaration::Fact(FactDeclaration { - handle: DraftHandle::new("elaborator-fact"), - label: "The Elaborator Count".into(), - statement: Statement::new("The elaborator count stands.").unwrap(), - standing: FactStandingRef::Canonical { - evidence: EvidenceRef::new(evidence), - }, - }) - }; - let error = submit_as( - &mut kernel, - caller.clone(), - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(answered.clone())), - patch: WorldPatch { - declarations: vec![fact("vault:elaborator-uncited")], - operations: Vec::new(), - evidence: Vec::new(), - }, - }, - ) - .unwrap_err(); - assert!( - matches!(&error, KernelError::PatchRejected(set) - if set.contains(&Mismatch::FactWithoutEvidence { - handle: DraftHandle::new("elaborator-fact"), - })), - "{error:?}" - ); - submit_as( - &mut kernel, - caller, - CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(answered)), - patch: WorldPatch { - declarations: vec![ - fact("vault:elaborator-cited"), - Declaration::Subject(SubjectDeclaration { - handle: DraftHandle::new("wanderer"), - label: "The Elaborator's Wanderer".into(), - kind: SubjectKind::Person, - controller: NewController::NarrativePersona, - affordances: BTreeSet::from([speak]), - position: Some(Ref::Existing(clockwork.dead_end)), - import_key: None, - }), - ], - operations: Vec::new(), - evidence: vec![EvidenceRef::new("vault:elaborator-cited")], - }, - }, - ) - .expect("a cited canonical fact is admitted for an answered elaborator"); - } - - // PA.f29a: a consumer, on its own mirror. A consumer cannot canonize - // (confine_to_ground refuses `Canonical` for consumer ground - // outright), so this exercises the same gate through `Admit` - // instead. In Draft, where `require_answer` asks nothing of anyone, - // so this is the evidence gate alone and not entangled with a - // consumer's inability to ever clear a place-shaped boundary (a - // consumer touches no place at all). - { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = WorldKernel::create( - directory.path().join("world.cc"), - creation(CommandId::new(), "ConsumerMirrorEvidence"), - &auth_principal(owner()), - ) - .expect("a created world") - .0; - let commons = *kernel - .state - .entities - .iter() - .find(|(_, record)| record.label == "The Commons") - .expect("the declared commons") - .0; - let grain = { - let snapshot = kernel.snapshot().unwrap(); - submit_owner( - &mut kernel, - &snapshot, - CommandBody::AdmitPatch { - answers: None, - patch: WorldPatch { - declarations: vec![Declaration::Entity(EntityDeclaration { - handle: DraftHandle::new("grain"), - label: "Consumer Grain".into(), - kind: EntityKind::Resource, - container: None, - })], - operations: Vec::new(), - evidence: Vec::new(), - }, - }, - ); - *kernel - .state - .entities - .iter() - .find(|(_, record)| record.label == "Consumer Grain") - .expect("the declared resource") - .0 - }; - let consumer_id = ConsumerId::of_name("clock-mirror-consumer"); - let snapshot = kernel.snapshot().unwrap(); - submit_owner( - &mut kernel, - &snapshot, - CommandBody::AdmitPatch { - answers: None, - patch: WorldPatch { - declarations: vec![Declaration::Subject(SubjectDeclaration { - handle: DraftHandle::new("mirror"), - label: "The Clockwork Mirror".into(), - kind: SubjectKind::Institution, - controller: NewController::External { - consumer: consumer_id, - }, - affordances: BTreeSet::new(), - position: Some(Ref::Existing(commons)), - import_key: None, - })], - operations: Vec::new(), - evidence: Vec::new(), - }, - }, - ); - let mirror = *kernel - .state - .subjects - .iter() - .find(|(_, subject)| subject.label == "The Clockwork Mirror") - .expect("the declared mirror") - .0; - let consumer_caller = CallerId::System(SystemCapability::Consumer { - consumer: consumer_id, - }); - - let error = submit_as( - &mut kernel, - consumer_caller.clone(), - CommandBody::AdmitPatch { - answers: None, - patch: WorldPatch { - declarations: Vec::new(), - operations: vec![ComponentOp::Admit { - holder: Ref::Existing(mirror), - resource: Ref::Existing(grain), - qty: Quantity(1), - evidence: EvidenceRef::new("vault:mirror-uncited"), - }], - evidence: Vec::new(), - }, - }, - ) - .unwrap_err(); - assert!( - matches!(&error, KernelError::PatchRejected(set) - if set.contains(&Mismatch::AdmitWithoutEvidence { operation: 0 })), - "{error:?}" - ); - - submit_as( - &mut kernel, - consumer_caller, - CommandBody::AdmitPatch { - answers: None, - patch: WorldPatch { - declarations: Vec::new(), - operations: vec![ComponentOp::Admit { - holder: Ref::Existing(mirror), - resource: Ref::Existing(grain), - qty: Quantity(1), - evidence: EvidenceRef::new("vault:mirror-cited"), - }], - evidence: vec![EvidenceRef::new("vault:mirror-cited")], - }, - }, - ) - .expect("a cited admit is admitted for a consumer on its own mirror"); - } } /// `reduce` decides and `apply_effect` re-decides: a forged - /// `PatchAdmitted` under an elaborator caller, carrying a `Mint` the - /// resolver would accept (the resolver is actor-blind) and that fully - /// satisfies confinement (the minted subject is declared inside the - /// elaborator's own jurisdiction), is still refused at apply. `Mint` - /// carries no confinement veto of its own — unlike a `Ruled` fact, - /// `confine_to_ground` has no redundant clause for it — so only - /// `require_ruler`'s re-decision can be refusing this. Follows - /// `apply_effect_re_decides_elaborator_authority`. + /// `PatchAdmitted` under the owner, carrying a `Mint` the resolver would + /// accept (the resolver is actor-blind) and that fully satisfies + /// confinement (the owner is unconfined), is still refused at apply. Only + /// `require_ruler`'s re-decision can be refusing this. #[test] fn apply_effect_re_decides_the_ruler() { let directory = tempfile::tempdir().unwrap(); let (kernel, clockwork, _) = clock_kernel(directory.path(), "RedecideRulerMint"); - let answered = dead_end_boundary(&kernel); let speak = super::tests::speak_entry(&kernel); let command_id = CommandId::issue(); let patch = WorldPatch { @@ -16783,18 +14340,15 @@ mod clock_tests { }], evidence: Vec::new(), }; - let resolved = patch::resolve_patch(&kernel.state, command_id, &patch, None) + let resolved = patch::resolve_patch(&kernel.state, command_id, &patch) .expect("the patch resolves; the resolver is actor-blind"); - let effect = WorldEffect::PatchAdmitted { - answers: Some(PatchAnswer::Boundary(answered)), - resolved, - }; + let effect = WorldEffect::PatchAdmitted { resolved }; let mut candidate = kernel.state.clone(); let error = apply_effect( &mut candidate, command_id, - &elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + &CallerId::Principal(owner()), &effect, ) .unwrap_err(); @@ -16817,15 +14371,11 @@ mod clock_tests { fn apply_effect_re_decides_the_ruler_for_the_owner_too() { let directory = tempfile::tempdir().unwrap(); let (kernel, _, _) = clock_kernel(directory.path(), "RedecideRulerOwner"); - let answered = dead_end_boundary(&kernel); let command_id = CommandId::issue(); let patch = ruled_fact_patch("rule"); - let resolved = patch::resolve_patch(&kernel.state, command_id, &patch, None) + let resolved = patch::resolve_patch(&kernel.state, command_id, &patch) .expect("the patch resolves; the resolver is actor-blind"); - let effect = WorldEffect::PatchAdmitted { - answers: Some(PatchAnswer::Boundary(answered)), - resolved, - }; + let effect = WorldEffect::PatchAdmitted { resolved }; let mut candidate = kernel.state.clone(); let error = apply_effect( @@ -16913,7 +14463,6 @@ mod clock_tests { CommandId::new(), CallerId::Principal(owner()), CommandBody::AdmitPatch { - answers: None, patch, }, ), @@ -16951,7 +14500,6 @@ mod clock_tests { &mut kernel, play_caller(), CommandBody::AdmitPatch { - answers: None, patch, }, ) @@ -16987,7 +14535,6 @@ mod clock_tests { kernel, CallerId::Principal(owner()), CommandBody::AdmitPatch { - answers: None, patch: retire_patch(subject), }, ) @@ -16997,12 +14544,10 @@ mod clock_tests { /// via the owner in Active. Shared by the retirement and grant tests that /// need a subject `mode()` already excludes. fn declare_mirror(kernel: &mut WorldKernel, clockwork: &Clockwork, name: &str) -> SubjectId { - let answered = dead_end_boundary(kernel); submit_as( kernel, CallerId::Principal(owner()), CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(answered)), patch: WorldPatch { declarations: vec![Declaration::Subject(SubjectDeclaration { handle: DraftHandle::new("mirror"), @@ -17012,9 +14557,6 @@ mod clock_tests { consumer: ConsumerId::of_name(name), }, affordances: BTreeSet::new(), - // At the dead end, so this declaration also clears - // the boundary its own answer claims: an occupied - // place is no longer unelaborated. position: Some(Ref::Existing(clockwork.dead_end)), import_key: None, })], @@ -17103,7 +14645,6 @@ mod clock_tests { &mut kernel, play_caller(), CommandBody::AdmitPatch { - answers: None, patch, }, ) @@ -17174,19 +14715,18 @@ mod clock_tests { } /// P4.3: `confine_to_ground` refuses a `Retire` for a confined author - /// unconditionally, even for a subject this same patch declares and - /// places inside the elaborator's own jurisdiction. + /// unconditionally, even for a subject this same patch declares. #[test] - fn an_elaborator_cannot_retire_inside_its_jurisdiction() { + fn a_confined_author_cannot_retire() { let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RetireElaborator"); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RetireConfined"); let speak = super::tests::speak_entry(&kernel); - let answered = dead_end_boundary(&kernel); let error = submit_as( &mut kernel, - elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CallerId::System(SystemCapability::Consumer { + consumer: ConsumerId::of_name("confined"), + }), CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(answered)), patch: WorldPatch { declarations: vec![Declaration::Subject(SubjectDeclaration { handle: DraftHandle::new("stray"), @@ -17225,7 +14765,6 @@ mod clock_tests { &mut kernel, play_caller(), CommandBody::AdmitPatch { - answers: None, patch: retire_patch(clockwork.farmer), }, ) @@ -17294,7 +14833,6 @@ mod clock_tests { &mut kernel, &before, CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: vec![ wave_affordance(), @@ -17338,7 +14876,6 @@ mod clock_tests { &mut kernel, play_caller(), CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: vec![wave_affordance()], operations: vec![ComponentOp::GrantAffordance { @@ -17375,7 +14912,6 @@ mod clock_tests { &mut kernel, play_caller(), CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: Vec::new(), operations: vec![ComponentOp::RevokeAffordance { @@ -17410,7 +14946,6 @@ mod clock_tests { &mut kernel, play_caller(), CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: Vec::new(), operations: vec![ComponentOp::RevokeAffordance { @@ -17430,7 +14965,6 @@ mod clock_tests { &mut kernel, play_caller(), CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: Vec::new(), operations: vec![ComponentOp::RevokeAffordance { @@ -17471,7 +15005,6 @@ mod clock_tests { &mut kernel, play_caller(), CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: Vec::new(), operations: vec![ComponentOp::RevokeAffordance { @@ -17499,19 +15032,18 @@ mod clock_tests { } /// P5.1: `confine_to_ground` refuses `GrantAffordance` for a confined - /// author unconditionally, even for a subject this same patch declares - /// and places inside the elaborator's own jurisdiction. + /// author unconditionally, even for a subject this same patch declares. #[test] - fn an_elaborator_cannot_grant() { + fn a_confined_author_cannot_grant() { let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "GrantElaborator"); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "GrantConfined"); let speak = super::tests::speak_entry(&kernel); - let answered = dead_end_boundary(&kernel); let error = submit_as( &mut kernel, - elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CallerId::System(SystemCapability::Consumer { + consumer: ConsumerId::of_name("confined"), + }), CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(answered)), patch: WorldPatch { declarations: vec![Declaration::Subject(SubjectDeclaration { handle: DraftHandle::new("stray"), @@ -17691,7 +15223,7 @@ mod clock_tests { fact: Ref::Draft(DraftHandle::new("news")), to: AudienceRef::Channel(Ref::Draft(DraftHandle::new("wire"))), }); - submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { answers: None, patch }) + submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { patch }) .expect("admitted"); let reeve_knows = kernel .state @@ -17719,7 +15251,7 @@ mod clock_tests { ])), controller: None, })); - submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { answers: None, patch: declare }) + submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { patch: declare }) .expect("declare"); owner_retires(&mut kernel, clockwork.reeve).expect("retire"); let wire = *kernel.state.channels.keys().next().unwrap(); @@ -17729,7 +15261,7 @@ mod clock_tests { fact: Ref::Draft(DraftHandle::new("news")), to: AudienceRef::Channel(Ref::Existing(wire)), }); - let error = submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { answers: None, patch }) + let error = submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { patch }) .unwrap_err(); assert!( matches!(&error, KernelError::PatchRejected(set) @@ -17788,7 +15320,7 @@ mod clock_tests { source: AuthoredSource::Witnessed, confidence: Confidence::Certain, }); - let error = submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { answers: None, patch }) + let error = submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { patch }) .unwrap_err(); assert!( matches!(&error, KernelError::PatchRejected(set) @@ -17809,7 +15341,7 @@ mod clock_tests { source: AuthoredSource::Witnessed, confidence: Confidence::Certain, }); - submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { answers: None, patch: declare }) + submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { patch: declare }) .expect("the reeve learns the fact"); let fact = *kernel.state.knowledge[&clockwork.reeve].keys().next().unwrap(); owner_retires(&mut kernel, clockwork.reeve).expect("retire"); @@ -17915,19 +15447,19 @@ mod clock_tests { } /// PA.f35, MuB: `RevokeAffordance` is confined exactly as every other - /// structural operation, so an elaborator cannot use it to touch a - /// subject's grants outside its jurisdiction. + /// structural operation, so a confined author cannot use it to touch a + /// subject's grants. #[test] - fn an_elaborator_cannot_revoke() { + fn a_confined_author_cannot_revoke() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf35ElabRevoke"); - let answered = dead_end_boundary(&kernel); let speak = super::tests::speak_entry(&kernel); let error = submit_as( &mut kernel, - elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CallerId::System(SystemCapability::Consumer { + consumer: ConsumerId::of_name("confined"), + }), CommandBody::AdmitPatch { - answers: Some(PatchAnswer::Boundary(answered)), patch: WorldPatch { declarations: vec![Declaration::Subject(SubjectDeclaration { handle: DraftHandle::new("stray"), @@ -18310,7 +15842,7 @@ mod clock_tests { let error = submit_as( &mut kernel, play_caller(), - CommandBody::AdmitPatch { answers: None, patch }, + CommandBody::AdmitPatch { patch }, ) .unwrap_err(); assert!( @@ -18348,7 +15880,7 @@ mod clock_tests { submit_as( &mut kernel, play_caller(), - CommandBody::AdmitPatch { answers: None, patch }, + CommandBody::AdmitPatch { patch }, ) .expect("admitted"); let mirror_knows = kernel @@ -18378,7 +15910,6 @@ mod clock_tests { &mut kernel, play_caller(), CommandBody::AdmitPatch { - answers: None, patch: WorldPatch { declarations: vec![ Declaration::Subject(SubjectDeclaration { diff --git a/native/aetherlight/src/patch.rs b/native/aetherlight/src/patch.rs index 4023addea..ba8a8b4fb 100644 --- a/native/aetherlight/src/patch.rs +++ b/native/aetherlight/src/patch.rs @@ -608,40 +608,6 @@ pub(crate) enum PreconditionRef { }, } -/// The authored scale target: how many qualified subjects of each kind the -/// world means to hold, and how that target distributes over jurisdiction -/// roots. Written once by genesis and never mutated. Not a component of any -/// referent, so not a `Declaration` and not a partition. -#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub(crate) struct WorldScaleIntent { - /// Target qualified subjects per kind, world-wide. - pub(crate) targets: BTreeMap<SubjectKind, u32>, - /// Jurisdiction roots and their share, in permille. Weights distribute the - /// target and never raise it: the sum is checked `<= 1000`. - pub(crate) jurisdictions: BTreeMap<EntityId, u32>, -} - -/// The genesis-lane twin: the intent names places the same patch declares, and -/// there is no other way to name them before they exist. -#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub(crate) struct WorldScaleIntentRef { - pub(crate) targets: BTreeMap<SubjectKind, u32>, - pub(crate) jurisdictions: BTreeMap<DraftHandle, u32>, -} - -/// One counted region of the scale deficit. `Uncovered` is the residual: a -/// subject with no jurisdiction root covering it — standing nowhere, or -/// standing somewhere outside every declared root's subtree — is counted and -/// visible while reducing no target. -#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] -#[serde(tag = "jurisdiction", content = "root", rename_all = "snake_case")] -pub enum JurisdictionKey { - PlaceSubtree(EntityId), - Uncovered, -} - /// What must already be true of committed state before an invocation is /// admitted. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] @@ -908,7 +874,7 @@ pub enum Site { pub(crate) struct EvidenceRef(String); impl EvidenceRef { - /// The elaborator's evidence receipts are built here, and `Deserialize` + /// An author's evidence receipts are built here, and `Deserialize` /// already mints one from any string, so this constructor gates nothing. /// Canonical text is checked by the resolver, in the complete mismatch set. pub(super) fn new(value: impl Into<String>) -> Self { @@ -1297,16 +1263,6 @@ pub(crate) enum ComponentOp { }, } -/// What an Active `AdmitPatch` answers. Draft answers nothing; Active must -/// answer a boundary the kernel currently derives or a jurisdiction whose -/// deficit is nonzero, and the commit must satisfy what it answered. -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(tag = "answer", rename_all = "snake_case")] -pub enum PatchAnswer { - Boundary(super::CausalBoundary), - Deficit(JurisdictionKey), -} - #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] #[serde(deny_unknown_fields)] pub struct WorldPatch { @@ -1675,13 +1631,6 @@ pub enum Mismatch { UnknownCommitment { operation: usize, }, - /// A scale-intent jurisdiction root that is not a declared place. - UnknownJurisdictionRoot { - handle: DraftHandle, - }, - /// The permille weights sum over 1000: weights distribute the target and - /// never raise it. - ScaleWeightsExceedWhole, /// A jurisdictional author wrote outside its jurisdiction. The owner is /// unconfined and never sees this. OutsideJurisdiction { @@ -1951,7 +1900,7 @@ pub(crate) enum ResolvedOp { }, /// A visible act: the actor's own sentence, seen by everyone standing in /// the actor's place. Lowered only by the kernel's speech path beside - /// `AssertClaim`, never by a patch, so no seed or elaborator can move a + /// `AssertClaim`, never by a patch, so no author can move a /// person's body from outside the person. There is no audience field: a /// display cannot go down a channel, and the room is re-derived from live /// `positions` at apply, so a forged effect cannot assert a landing the @@ -2075,10 +2024,6 @@ pub(super) struct ResolvedPatch { pub(super) channels: Vec<ResolvedChannel>, pub(super) operations: Vec<ResolvedOp>, pub(super) evidence: Vec<EvidenceRef>, - /// `Some` on the genesis lane and nowhere else: `CommandBody::AdmitPatch` - /// carries no intent, so the write-once rule is the command shape rather - /// than a check. - pub(super) scale_intent: Option<WorldScaleIntent>, } impl ResolvedPatch { @@ -3153,7 +3098,6 @@ pub(super) fn resolve_patch( state: &super::WorldState, command_id: CommandId, patch: &WorldPatch, - scale_intent: Option<&WorldScaleIntentRef>, ) -> Result<ResolvedPatch, Vec<Mismatch>> { let world_id = state.world_id; let admits_human = super::admits_human(state.revision, &state.subjects); @@ -5004,26 +4948,6 @@ pub(super) fn resolve_patch( }); } - if let Some(intent) = scale_intent { - for handle in intent.jurisdictions.keys() { - if index.get(handle) != Some(&PLACE) { - mismatches.push(Mismatch::UnknownJurisdictionRoot { - handle: handle.clone(), - }); - } - } - // Weights distribute the target and never raise it. - if intent - .jurisdictions - .values() - .map(|weight| u64::from(*weight)) - .sum::<u64>() - > 1000 - { - mismatches.push(Mismatch::ScaleWeightsExceedWhole); - } - } - if patch.declarations.is_empty() && patch.operations.is_empty() { mismatches.push(Mismatch::NoCanonicalChange); } @@ -5688,21 +5612,6 @@ pub(super) fn resolve_patch( channels: declared_channels, operations, evidence: patch.evidence.clone(), - scale_intent: scale_intent.map(|intent| WorldScaleIntent { - targets: intent.targets.clone(), - jurisdictions: intent - .jurisdictions - .iter() - .map(|(handle, weight)| { - ( - *allocated_entities - .get(handle) - .expect("a jurisdiction root resolved above"), - *weight, - ) - }) - .collect(), - }), }) } @@ -5990,7 +5899,6 @@ mod tests { fn admit(patch: WorldPatch) -> CommandBody { CommandBody::AdmitPatch { - answers: None, patch, } } @@ -6615,46 +6523,6 @@ mod tests { assert_eq!(kernel.journal.commit_count(), 1); } - /// Active admits the four operations and nothing else, so it never mints a - /// canonical ID. - #[test] - fn an_active_patch_that_declares_anything_is_rejected() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = draft_world(directory.path()); - let active = activate(&mut kernel); - let commits_before = kernel.journal.commit_count(); - let declaring = patch_of(vec![entity( - "rhythm-road", - "The Rhythm Road", - EntityKind::Place, - )]); - let bearing_evidence = WorldPatch { - declarations: Vec::new(), - operations: Vec::new(), - evidence: vec![EvidenceRef("run-115".into())], - }; - - for patch in [declaring, bearing_evidence] { - let error = kernel - .submit( - command( - &active, - CommandId::new(), - CallerId::Principal(owner()), - admit(patch), - ), - &auth_principal(owner()), - ) - .unwrap_err(); - // Declaring in Active is elaboration, and elaboration answers a - // boundary. An unanswered one is refused before resolution. - assert!(matches!(error, KernelError::AnswerRequired)); - } - assert_eq!(kernel.journal.commit_count(), commits_before); - assert_eq!(kernel.snapshot().unwrap(), active); - assert_eq!(kernel.state.entities.len(), FIXTURE_ENTITIES); - } - /// Three places whose containers form a cycle name themselves, and the /// unrelated empty label joins the same complete set. #[test] @@ -6880,8 +6748,7 @@ mod tests { let (topology, civic, before) = civic_world(&mut kernel); // `topology.walker` already exists and already stands at `yard`, so - // this delegation patch is operations-only: no declaration, no - // `AnswerRequired` elaboration boundary to clear. + // this delegation patch is operations-only: no declaration. let delegated = submit_owner( &mut kernel, &before, @@ -7151,8 +7018,8 @@ mod tests { assert_ne!(admitted, genesis_human); let command_id = CommandId::new(); - let first = resolve_patch(&kernel.state, command_id, &patch, None).unwrap(); - let second = resolve_patch(&kernel.state, command_id, &patch, None).unwrap(); + let first = resolve_patch(&kernel.state, command_id, &patch).unwrap(); + let second = resolve_patch(&kernel.state, command_id, &patch).unwrap(); assert_eq!(first, second); } @@ -7279,13 +7146,12 @@ mod tests { } /// The `PatchAdmitted` arm is not a trusting applier. A forged effect, a - /// replayed one, a non-owner caller, and the Active phase each die inside - /// `apply_effect`, without the journal's reduce-equality check running. + /// replayed one and a non-owner caller each die inside `apply_effect`, + /// without the journal's reduce-equality check running. #[test] - fn apply_effect_rejects_a_forged_stale_unauthorized_or_active_patch_effect() { + fn apply_effect_rejects_a_forged_stale_or_unauthorized_patch_effect() { let directory = tempfile::tempdir().unwrap(); - let mut kernel = draft_world(directory.path()); - let before = kernel.snapshot().unwrap(); + let kernel = draft_world(directory.path()); let patch = patch_of(vec![ entity("rhythm-road", "The Rhythm Road", EntityKind::Place), institution( @@ -7295,10 +7161,9 @@ mod tests { Some(Ref::Draft(DraftHandle::new("rhythm-road"))), ), ]); - let resolved = resolve_patch(&kernel.state, CommandId::new(), &patch, None).unwrap(); + let resolved = resolve_patch(&kernel.state, CommandId::new(), &patch).unwrap(); let honest = super::super::WorldEffect::PatchAdmitted { resolved: resolved.clone(), - answers: None, }; // Forged: the position names a place no partition holds, and the effect @@ -7314,7 +7179,6 @@ mod tests { CommandId::issue(), &CallerId::Principal(owner()), &super::super::WorldEffect::PatchAdmitted { - answers: None, resolved: forged, }, ) @@ -7350,21 +7214,6 @@ mod tests { .unwrap_err(); assert!(matches!(unauthorized, KernelError::Invariant(_))); assert_eq!(candidate, kernel.state); - - // And an unanswered declaring effect is refused in Active before any - // partition is touched. - let active = activate(&mut kernel); - assert_eq!(active.revision, before.revision + 3); - let mut candidate = kernel.state.clone(); - let unanswered = super::super::apply_effect( - &mut candidate, - CommandId::issue(), - &CallerId::Principal(owner()), - &honest, - ) - .unwrap_err(); - assert!(matches!(unanswered, KernelError::AnswerRequired)); - assert_eq!(candidate, kernel.state); } /// Soul falsification: the three pass-2 `Mismatch` variants that no landed @@ -7510,9 +7359,7 @@ mod tests { edge_id, }], evidence: Vec::new(), - scale_intent: None, }, - answers: None, }; let mut candidate = kernel.state.clone(); let error = super::super::apply_effect( From fe6819a0a8441f49914d25746c99b66e092d976c Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Thu, 19 Nov 2026 22:16:55 +0100 Subject: [PATCH 125/190] Aetherlight AL2a.6: record the agency cut A in PROVENANCE Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/PROVENANCE.md | 99 +++++++++++++++++++++++--------- 1 file changed, 73 insertions(+), 26 deletions(-) diff --git a/native/aetherlight/PROVENANCE.md b/native/aetherlight/PROVENANCE.md index b3405c47c..f796c8008 100644 --- a/native/aetherlight/PROVENANCE.md +++ b/native/aetherlight/PROVENANCE.md @@ -19,19 +19,14 @@ binary and no newline rule touches it. Line ranges are in the c43eb54 file. | c43eb54 path (under `crates/ghostlight/`) | Here | Range | Edits | | --- | --- | --- | --- | -| `src/lib.rs` | `src/lib.rs` | all | E1-E5, E10, E11 | -| `src/action.rs` | `src/action.rs` | all | E11 | +| `src/lib.rs` | `src/lib.rs` | all | E1-E5, E10-E12 | +| `src/action.rs` | `src/action.rs` | all | E11, E12 | | `src/clock.rs` | `src/clock.rs` | all | none | -| `src/journal.rs` | `src/journal.rs` | all | none | +| `src/journal.rs` | `src/journal.rs` | all | E12 | | `src/grammar.rs` | `src/grammar.rs` | all | none | -| `src/grammar/tests.rs` | `src/grammar/tests.rs` | all | none | -| `src/lens.rs` | `src/lens.rs` | all | E8, E9 | -| `src/cover.rs` | `src/cover.rs` | all | none | -| `src/import_key_tests.rs` | `src/import_key_tests.rs` | all | none | -| `src/patch.rs` | `src/patch.rs` | 1-6059 and 7906-9606 (dropped 6060-7905: the patch tool catalog, `PATCH_TOOLS`, `patch_tools()`, the `field_example` helpers, `mod catalog_tests`) | E6, E7 | -| `tests/fixtures/base_world.cc` | same | all | none | -| `tests/fixtures/base_world.digests` | same | all | none | -| `tests/fixtures/base_world.id` | same | all | none | +| `src/grammar/tests.rs` | `src/grammar/tests.rs` | all | E12 | +| `src/import_key_tests.rs` | `src/import_key_tests.rs` | all | E12 | +| `src/patch.rs` | `src/patch.rs` | 1-6059 and 7906-9606 (dropped 6060-7905: the patch tool catalog, `PATCH_TOOLS`, `patch_tools()`, the `field_example` helpers, `mod catalog_tests`) | E6, E7, E12 | | `Cargo.lock` | `Cargo.lock` | all | pruned by cargo to the dependencies below | `Cargo.toml` is new: package `aetherlight`, its own `[workspace]`, no features, @@ -76,11 +71,15 @@ unicode-normalization, unicode-properties, uuid; dev tempfile. `clock_tests::committed_requires_the_named_kind`, `soul_knowledge_tests::a_telling_by_a_speaker_outside_its_audience_does_not_apply`. +- E12. Cut AL2a deletes the model-guidance lanes; see the section below. It + supersedes E4's `cover` import, E8 and E9 (`lens.rs` is gone), and `lib.rs`, + `patch.rs`, `journal.rs`, `action.rs`, `grammar/tests.rs` and + `import_key_tests.rs` lose the symbols and tests listed there. + Not renamed: the `ghostlight.*` schema ids and namespaces in the code -(`STATE_SCHEMA`, `COMMIT_SCHEMA`, journal schema rows, `ghostlight.speech`, -`ghostlight.cover.v1`). They enter derived ids and digests; the golden replay -`grammar::tests::existing_world_reopens_with_unchanged_digests` proves them -unchanged. AL3 owns the format rename. +(`STATE_SCHEMA`, `COMMIT_SCHEMA`, journal schema rows, `ghostlight.speech`). They enter derived ids and digests. No test pins them +since AL2a removed the golden replay (see below); AL4 adds Aetherlight's own +golden. AL3 owns the format rename. ## Left behind @@ -119,23 +118,71 @@ By hand, against this file: read the upstream diff for the taken files, apply it here, and record it in this file with its upstream commit and the files it touched. A fix that lands in a left-behind file is not pulled. -## Leave-set vocabulary still compiled (AL2a's triage list) +## Cut AL2a: the model-guidance lanes -`#![allow(dead_code)]` hides about 248 dead-code warnings, among them vocabulary -that only the left-behind lanes used. AL2a decides each as delete, keep or rename. -Several enter derived ids or digests, so a removal is a format change (AL3), not -a cleanup. +Authority: cut `aetherlight-cut-agency-a` r1 of campaign `aetheria-release`; +rulings `aetherlight-narrative-state-owner` and `dialogue-is-world-action`. +Deleted, with their c43eb54 homes: -- Consumer lane: `ConsumerId`, `consumer_id`, `consumer_caller`, - `bound_to_consumer`, `CONSUMER_ID_NAMESPACE`, `VerifiedPrincipalEvidence`. +- Lens (`src/lens.rs`, 361 lines): `Lens`, `LensWeights`; the genesis input, + `WorldState`, snapshot and creation field `lens_weights`; + `CommandBody::SetLensWeights`; `WorldEffect::LensWeightsReplaced`; + `Mismatch::LensWeightsNeverDraw`; the draw-rule check in `verify_state_shape`. +- Cover and agency graph (`src/cover.rs`, 1105 lines): `Cover`, `Cell`, + `CoverBudget`, `derive_cover`, `AgencyGraph`; `WorldKernel::agency_graph` and + `fn agency_graph` (`lib.rs`); `CommandId::for_cell`, `for_cell_constituent`. +- Persona material (`lib.rs`, `patch.rs`): `PersonaMaterial`, `PersonaReadRef`, + `ComponentOp::SetPersonaMaterial` and `ResolvedOp::SetPersonaMaterial` with + resolution, apply and confinement arms, `WorldState.persona_material`, the + subject snapshot's `material`, `WorldPatch::sets_persona_of_existing_subject`. + The op set goes from 34 to 33. +- Brief: the `brief` string in `CreateWorld`, `CreateWorldIntent`, `WorldState`, + `WorldEffect::WorldCreated`, the snapshot and the shape checks. +- Elaborator lane: `SystemCapability::Elaborator`, `PatchAnswer`, + `CausalBoundary`, `BoundaryDigest` and `derive_boundaries`, `exact_boundary`, + `require_answer` (the `AnswerRequired` gate), `jurisdiction_deficit`, + `ground_covers`, `place_in`, `PatchGround::Jurisdiction`; `WorldScaleIntent`, + `WorldScaleIntentRef`, `JurisdictionKey`, `ScaleDeficitRow`, `qualifies`, + `derive_scale_deficit`, the subject snapshot's `qualified`, the snapshot's + `boundaries` and `scale_deficit`, `CreateWorld.scale_intent`, + `CreateWorldIntent.targets` and `jurisdictions`, `CreateJurisdictionIntent`, + `WorldState.scale_intent`; `CommandBody::AdmitPatch.answers` and + `WorldEffect::PatchAdmitted.answers`; `KernelError::AnswerRequired`, + `AnswerNotDerived`, `AnswerNotSatisfied`; `Mismatch::UnknownJurisdictionRoot` + and `ScaleWeightsExceedWhole`. `resolve_patch` loses its intent parameter. +- The golden replay `grammar::tests::existing_world_reopens_with_unchanged_digests` + and `tests/fixtures/base_world.*`: removing state fields changed the state + shape, so Ghostlight's recorded world no longer decodes. AL4 adds + Aetherlight's own golden. + +Behaviour that changed with the gate: with `require_answer` gone, the owner and +`Play` declare in Active with no answer, and a confined author's only remaining +check is `confine_to_ground`, which now serves the consumer ground alone. +`require_play_active` keeps the one rule `require_answer` also held: `Play` +authors nothing in Draft. + +Kept untouched for AL2b: controllers and `ControllerMode`, consumers +(`ConsumerId`, `SystemCapability::Consumer`, `PatchGround::Consumer`, +`bound_to_consumer`), opportunities, scope digests, attention order, the draft +phase and approvals, `ExerciseDecision`, `DeclineDecision`, +`VerifiedPrincipalEvidence`. + +## Leave-set vocabulary still compiled (AL2b's and AL4's triage list) + +`#![allow(dead_code)]` still hides the dead code of a crate with no entry point. +What the cut deletes is gone; what remains is part B's: + +- Consumer lane: `ConsumerId`, `CONSUMER_ID_NAMESPACE`, `bound_to_consumer`, + `PatchGround::Consumer` and the consumer arm of `confine_to_ground`, + `VerifiedPrincipalEvidence`. - Controller lane: `verified_controller`, `resolve_controller`, `controller_mode`, `controller_receipt`, `controller_decline_receipt`, `controller_key`. -- Elaborator lane: `Elaborator`, `GrantElaborator`, `RetireElaborator`, - `ElaboratorEvidence`, `ElaboratorUnanswered`, `elaborator_error`, - `UnelaboratedDestination` and its preimage, and the tests that name them. +- Tick-driver readers `WorldKernel::opportunities` and `clock_advances`, and + `CreateWorldIntent` (no consumer after the mailbox left). - Mailbox and vault comments (`WorldMailbox`, `vault:` evidence strings). -Reproduce the full list with `RUSTFLAGS=--force-warn dead_code cargo build`. +Reproduce the list with `RUSTFLAGS=--force-warn dead_code cargo test --no-run`: +under test configuration the items nothing exercises show up. ## Obligations this cut hands to AL4 From fff6f9e7edb5cda1d43822b4b5e71bc4548b6f25 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Thu, 19 Nov 2026 22:40:14 +0100 Subject: [PATCH 126/190] Aetherlight AL2a fix 1: declaring in Active is Play's act; bump schema ids; pin the confinement re-decisions require_play_active refuses any non-Play declaration or evidence in an Active world, restoring the typed-command path as the only door; the owner-declares test becomes the_owner_cannot_declare_in_active and the kept-lane tests that used the owner to declare use Play. STATE_SCHEMA and COMMIT_SCHEMA go to v7 and a v6 row is refused. New tests pin apply_effect's confinement and declare-in-Active re-decisions, and confine_to_ground's unconditional retire/grant/revoke arm is probed directly on a hand-built resolved patch (the resolver refuses those on a mirror first, so no submit can isolate it). Stale elaboration-lane comments in patch.rs reworded. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/grammar/tests.rs | 3 +- native/aetherlight/src/import_key_tests.rs | 7 +- native/aetherlight/src/journal.rs | 5 +- native/aetherlight/src/lib.rs | 418 +++++++++------------ native/aetherlight/src/patch.rs | 9 +- 5 files changed, 190 insertions(+), 252 deletions(-) diff --git a/native/aetherlight/src/grammar/tests.rs b/native/aetherlight/src/grammar/tests.rs index ec9115e82..7dca39f73 100644 --- a/native/aetherlight/src/grammar/tests.rs +++ b/native/aetherlight/src/grammar/tests.rs @@ -541,7 +541,7 @@ type Door = (&'static str, CallerId); /// Each door refuses an outside kind and a wrong role signature, typed, and the /// refusal leaves the revision where it was. The owner and the consumer declare -/// in Draft and in Active; Play acts in Active. +/// in Draft only; Play declares in Active. fn refuse_at_each_door(kernel: &mut WorldKernel, doors: Vec<Door>) { for (door, caller) in doors { let revision = kernel.state.revision; @@ -584,7 +584,6 @@ fn every_admission_door_refuses_outside_the_grammar_after_the_revision_has_moved "the world has moved past genesis" ); let active_doors = vec![ - ("owner in Active", CallerId::Principal(owner())), ("play", CallerId::System(crate::SystemCapability::Play)), ]; refuse_at_each_door(&mut kernel, active_doors); diff --git a/native/aetherlight/src/import_key_tests.rs b/native/aetherlight/src/import_key_tests.rs index a1001c76a..5976d5d54 100644 --- a/native/aetherlight/src/import_key_tests.rs +++ b/native/aetherlight/src/import_key_tests.rs @@ -201,8 +201,8 @@ fn advanced_keyed_world() -> (tempfile::TempDir, WorldKernel, EntityId) { } /// Each door names the held key, typed, and the refusal leaves the revision -/// where it was. The owner and the consumer declare in Draft, and in Active -/// too; Play acts in Active. +/// where it was. The owner and the consumer declare in Draft only; Play +/// declares in Active. fn refuse_held_key_at_each_door( kernel: &mut WorldKernel, place: EntityId, @@ -246,7 +246,6 @@ fn a_held_import_key_is_refused_at_every_door_after_the_revision_has_moved() { &mut kernel, dead_end, vec![ - ("owner in Active", CallerId::Principal(owner())), ("play", CallerId::System(SystemCapability::Play)), ], ); @@ -255,7 +254,7 @@ fn a_held_import_key_is_refused_at_every_door_after_the_revision_has_moved() { let fresh = key("aetheria.ship", "Gamma"); let receipt = submit_as( &mut kernel, - CallerId::Principal(owner()), + CallerId::System(SystemCapability::Play), patch_of(vec![mirror("fresh", Some(fresh.clone()), dead_end)]), ) .unwrap(); diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index 1ae7ca180..ae0588651 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -1284,12 +1284,15 @@ mod tests { } /// A store written under an older schema is refused at open: both - /// `consumer.v4` strings. No migration, no dual read. + /// `consumer.v4` strings and the pre-cut `consumer.v6` ones. No migration, + /// no dual read. #[test] fn a_store_written_under_an_older_schema_is_refused() { for (row_type, schema) in [ (STATE_ROW, "ghostlight.world_state.consumer.v4"), (COMMIT_ROW, "ghostlight.world_commit.consumer.v4"), + (STATE_ROW, "ghostlight.world_state.consumer.v6"), + (COMMIT_ROW, "ghostlight.world_commit.consumer.v6"), ] { let row = CultCacheEnvelope { key: "state".into(), diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index c8247a0cd..76246e783 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -145,8 +145,8 @@ impl VerifiedPrincipalEvidence { } } -pub const STATE_SCHEMA: &str = "ghostlight.world_state.consumer.v6"; -pub(crate) const COMMIT_SCHEMA: &str = "ghostlight.world_commit.consumer.v6"; +pub const STATE_SCHEMA: &str = "ghostlight.world_state.consumer.v7"; +pub(crate) const COMMIT_SCHEMA: &str = "ghostlight.world_commit.consumer.v7"; /// Compatibility tag derived from [`STATE_SCHEMA`]: the trailing /// `<family>-<version>` pair (e.g. `foundation-v1`). Callers that publish a @@ -1654,7 +1654,11 @@ fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result<WorldEffect, }) } CommandBody::AdmitPatch { patch } => { - require_play_active(state, &command.caller)?; + require_play_active( + state, + &command.caller, + !(patch.declarations.is_empty() && patch.evidence.is_empty()), + )?; // Resolution before confinement, because confinement reads // draft-resolved referents and a structurally broken patch should // return its complete mismatch set rather than a jurisdiction @@ -1707,14 +1711,26 @@ fn require_clock_caller(state: &WorldState, caller: &CallerId) -> Result<(), Ker } } -/// The play table authors nothing in Draft: it is the Active world's hand. -fn require_play_active(state: &WorldState, caller: &CallerId) -> Result<(), KernelError> { - if caller == &CallerId::System(SystemCapability::Play) && state.phase == WorldPhase::Draft { +/// The play table authors nothing in Draft, and in Active declaring (new +/// structure, or evidence) is the play table's act alone: the host reports +/// events as typed commands and scripts propose, so no second door opens +/// beside that path. A patch that only changes components of existing +/// structure is any admitted author's. +fn require_play_active( + state: &WorldState, + caller: &CallerId, + declares: bool, +) -> Result<(), KernelError> { + let play = caller == &CallerId::System(SystemCapability::Play); + if play && state.phase == WorldPhase::Draft { return Err(KernelError::WrongPhase { expected: WorldPhase::Active, actual: state.phase, }); } + if declares && !play && state.phase == WorldPhase::Active { + return Err(KernelError::Unauthorized); + } Ok(()) } @@ -4509,7 +4525,7 @@ fn apply_effect( )); } WorldEffect::PatchAdmitted { resolved } => { - require_play_active(state, caller)?; + require_play_active(state, caller, !resolved.declares_nothing())?; require_ruler(caller, resolved).map_err(|_| { KernelError::Invariant( "admitted patch rules or mints without the play authority".into(), @@ -10530,7 +10546,7 @@ mod soul_knowledge_tests { /// claim is asserted by the acting subject and named by no other event. The /// reverse, that every claim is named by some event, is deliberately absent, /// because a world may declare a claim with no event behind it, in Draft - /// or, since the owner declares in Active unanswered, in Active too. Such a + /// or, by the play table, in Active. Such a /// claim is a valid shape and its store reopens. #[test] fn an_orphan_claim_is_a_valid_shape_and_reopens() { @@ -10555,7 +10571,7 @@ mod soul_knowledge_tests { command( &active, CommandId::new(), - CallerId::Principal(owner()), + CallerId::System(SystemCapability::Play), CommandBody::AdmitPatch { patch: WorldPatch { declarations: vec![Declaration::Fact(FactDeclaration { @@ -10571,9 +10587,9 @@ mod soul_knowledge_tests { }, }, ), - &auth_principal(owner()), + &AuthenticatedCaller::fixture(CallerId::System(SystemCapability::Play)), ) - .expect("the owner declares a claim in Active"); + .expect("the play table declares a claim in Active"); assert!(matches!(receipt, SubmitReceipt::Applied(_))); assert_eq!(kernel.state.facts.len(), before.facts.len() + 1); let facts = kernel.state.facts.clone(); @@ -11805,7 +11821,7 @@ mod witness_tests { let arrival = |kernel: &mut WorldKernel, handle: &str, label: &str, position: Option<EntityId>| { let snapshot = kernel.snapshot().unwrap(); - let caller = CallerId::Principal(owner()); + let caller = CallerId::System(SystemCapability::Play); kernel.submit( command( &snapshot, @@ -13815,12 +13831,12 @@ mod clock_tests { let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Separation"); submit_as( &mut kernel, - CallerId::Principal(owner()), + play_caller(), CommandBody::AdmitPatch { patch: shed_under(clockwork.dead_end, "shed"), }, ) - .expect("the owner's patch commits"); + .expect("the play table's patch commits"); let bytes = rmp_serde::to_vec_named(&kernel.state).expect("state encodes"); let text = String::from_utf8_lossy(&bytes); @@ -13882,27 +13898,37 @@ mod clock_tests { assert!(matches!(receipt, SubmitReceipt::Applied(_))); } - /// With no answer gate, the owner declares in Active as it does in Draft. + /// Declaring in Active is the play table's act alone: the owner is refused + /// for new structure and for evidence, and an operations-only owner patch + /// is still admitted (the other tests here do it). #[test] - fn the_owner_declares_in_active_without_an_answer() { + fn the_owner_cannot_declare_in_active() { let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "OwnerUnanswered"); - let snapshot = kernel.snapshot().unwrap(); - let receipt = kernel - .submit( - command( - &snapshot, - CommandId::new(), - CallerId::Principal(owner()), - CommandBody::AdmitPatch { - patch: shed_under(clockwork.dead_end, "shed"), - }, - ), - &auth_principal(owner()), + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "OwnerDeclares"); + let revision = kernel.state.revision; + let evidence_only = WorldPatch { + declarations: Vec::new(), + operations: Vec::new(), + evidence: vec![EvidenceRef::new("vault:loose")], + }; + for patch in [shed_under(clockwork.dead_end, "shed"), evidence_only] { + let error = submit_as( + &mut kernel, + CallerId::Principal(owner()), + CommandBody::AdmitPatch { patch }, ) - .expect("the owner declares in Active"); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); - assert!(kernel.state.entities.values().any(|entity| entity.label == "The shed")); + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + } + assert_eq!(kernel.state.revision, revision); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + patch: shed_under(clockwork.dead_end, "shed"), + }, + ) + .expect("the play table declares the same patch"); } /// Invariant 5: the play authority reaches the whole world, unconfined to @@ -14242,66 +14268,6 @@ mod clock_tests { ) .expect("a cited canonical fact is admitted for the owner in Draft"); } - - // PA.f29a: the owner in Active. Its own `clock_kernel`. The cited - // patch also seats a fresh occupant at the dead end. - { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "OwnerActiveEvidence"); - let speak = super::tests::speak_entry(&kernel); - let fact = |evidence: &str| { - Declaration::Fact(FactDeclaration { - handle: DraftHandle::new("active-fact"), - label: "The Active Count".into(), - statement: Statement::new("The active count stands.").unwrap(), - standing: FactStandingRef::Canonical { - evidence: EvidenceRef::new(evidence), - }, - }) - }; - let error = submit_as( - &mut kernel, - CallerId::Principal(owner()), - CommandBody::AdmitPatch { - patch: WorldPatch { - declarations: vec![fact("vault:active-uncited")], - operations: Vec::new(), - evidence: Vec::new(), - }, - }, - ) - .unwrap_err(); - assert!( - matches!(&error, KernelError::PatchRejected(set) - if set.contains(&Mismatch::FactWithoutEvidence { - handle: DraftHandle::new("active-fact"), - })), - "{error:?}" - ); - submit_as( - &mut kernel, - CallerId::Principal(owner()), - CommandBody::AdmitPatch { - patch: WorldPatch { - declarations: vec![ - fact("vault:active-cited"), - Declaration::Subject(SubjectDeclaration { - handle: DraftHandle::new("wanderer"), - label: "The Owner's Wanderer".into(), - kind: SubjectKind::Person, - controller: NewController::NarrativePersona, - affordances: BTreeSet::from([speak]), - position: Some(Ref::Existing(clockwork.dead_end)), - import_key: None, - }), - ], - operations: Vec::new(), - evidence: vec![EvidenceRef::new("vault:active-cited")], - }, - }, - ) - .expect("a cited canonical fact is admitted for the owner in Active"); - } } /// `reduce` decides and `apply_effect` re-decides: a forged @@ -14313,29 +14279,13 @@ mod clock_tests { fn apply_effect_re_decides_the_ruler() { let directory = tempfile::tempdir().unwrap(); let (kernel, clockwork, _) = clock_kernel(directory.path(), "RedecideRulerMint"); - let speak = super::tests::speak_entry(&kernel); + let grain = resource_named(&kernel, "Winter Grain"); let command_id = CommandId::issue(); let patch = WorldPatch { - declarations: vec![ - Declaration::Entity(EntityDeclaration { - handle: DraftHandle::new("loot"), - label: "Roadside Loot".into(), - kind: EntityKind::Resource, - container: None, - }), - Declaration::Subject(SubjectDeclaration { - handle: DraftHandle::new("finder"), - label: "The Roadside Finder".into(), - kind: SubjectKind::Person, - controller: NewController::NarrativePersona, - affordances: BTreeSet::from([speak]), - position: Some(Ref::Existing(clockwork.dead_end)), - import_key: None, - }), - ], + declarations: Vec::new(), operations: vec![ComponentOp::Mint { - holder: Ref::Draft(DraftHandle::new("finder")), - resource: Ref::Draft(DraftHandle::new("loot")), + holder: Ref::Existing(clockwork.reeve), + resource: Ref::Existing(grain), qty: Quantity(4), }], evidence: Vec::new(), @@ -14361,6 +14311,71 @@ mod clock_tests { assert_ne!(candidate, kernel.state); } + /// `apply_effect` re-decides confinement: a forged `PatchAdmitted` under a + /// consumer, carrying an operations-only route cost change the resolver + /// accepts and no consumer ground covers, is refused at apply. + #[test] + fn apply_effect_re_decides_confinement() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, clockwork, _) = clock_kernel(directory.path(), "RedecideGround"); + let command_id = CommandId::issue(); + let patch = WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::AlterCost { + route: Ref::Existing(clockwork.gate), + cost: Cost(2), + }], + evidence: Vec::new(), + }; + let resolved = patch::resolve_patch(&kernel.state, command_id, &patch) + .expect("the patch resolves; the resolver is actor-blind"); + let effect = WorldEffect::PatchAdmitted { resolved }; + let consumer = CallerId::System(SystemCapability::Consumer { + consumer: ConsumerId::of_name("redecide-ground"), + }); + let mut candidate = kernel.state.clone(); + let error = apply_effect(&mut candidate, command_id, &consumer, &effect).unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + assert_eq!(candidate, kernel.state); + + let mut candidate = kernel.state.clone(); + apply_effect(&mut candidate, command_id, &CallerId::Principal(owner()), &effect) + .expect("the unconfined owner applies the same effect"); + assert_ne!(candidate, kernel.state); + } + + /// `apply_effect` re-decides that declaring in Active is the play table's + /// act: a forged `PatchAdmitted` that declares, under the owner, is refused + /// at apply, and the play table applies it through the same arm. + #[test] + fn apply_effect_re_decides_that_declaring_in_active_is_plays() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, clockwork, _) = clock_kernel(directory.path(), "RedecideDeclares"); + let command_id = CommandId::issue(); + let resolved = patch::resolve_patch( + &kernel.state, + command_id, + &shed_under(clockwork.dead_end, "shed"), + ) + .expect("the patch resolves; the resolver is actor-blind"); + let effect = WorldEffect::PatchAdmitted { resolved }; + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + command_id, + &CallerId::Principal(owner()), + &effect, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + assert_eq!(candidate, kernel.state); + + let mut candidate = kernel.state.clone(); + apply_effect(&mut candidate, command_id, &play_caller(), &effect) + .expect("the play table applies it"); + assert_ne!(candidate, kernel.state); + } + /// PA.f27a: the owner is a `CallerId::Principal` like any other, and /// `apply_effect`'s re-decision of `require_ruler` carries no exemption /// for that variant. A forged `PatchAdmitted` under the owner, carrying @@ -14370,7 +14385,12 @@ mod clock_tests { #[test] fn apply_effect_re_decides_the_ruler_for_the_owner_too() { let directory = tempfile::tempdir().unwrap(); - let (kernel, _, _) = clock_kernel(directory.path(), "RedecideRulerOwner"); + let (kernel, _) = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "RedecideRulerOwner"), + &auth_principal(owner()), + ) + .unwrap(); let command_id = CommandId::issue(); let patch = ruled_fact_patch("rule"); let resolved = patch::resolve_patch(&kernel.state, command_id, &patch) @@ -14541,12 +14561,12 @@ mod clock_tests { } /// Declares a mirror bound to a consumer this test invents, at the yard, - /// via the owner in Active. Shared by the retirement and grant tests that + /// via the play table in Active. Shared by the retirement and grant tests that /// need a subject `mode()` already excludes. fn declare_mirror(kernel: &mut WorldKernel, clockwork: &Clockwork, name: &str) -> SubjectId { submit_as( kernel, - CallerId::Principal(owner()), + play_caller(), CommandBody::AdmitPatch { patch: WorldPatch { declarations: vec![Declaration::Subject(SubjectDeclaration { @@ -14565,7 +14585,7 @@ mod clock_tests { }, }, ) - .expect("the owner declares a mirror in Active"); + .expect("the play table declares a mirror in Active"); kernel .snapshot() .unwrap() @@ -14700,6 +14720,48 @@ mod clock_tests { ); } + /// `confine_to_ground` refuses `Retire`, `GrantAffordance` and + /// `RevokeAffordance` for a confined author unconditionally, even over a + /// subject bound to that author's own ground. The resolver refuses these + /// on a mirror before confinement runs, so the arm is probed directly on + /// a hand-built resolved patch: only the unconditional arm can refuse it. + #[test] + fn a_confined_author_cannot_retire_grant_or_revoke_its_own_mirror() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "ConfinedOwn"); + let mirror = declare_mirror(&mut kernel, &clockwork, "confined-own"); + let ground = PatchGround::Consumer(ConsumerId::of_name("confined-own")); + for operation in [ + ResolvedOp::Retire { subject: mirror }, + ResolvedOp::GrantAffordance { + subject: mirror, + affordance: clockwork.threaten, + }, + ResolvedOp::RevokeAffordance { + subject: mirror, + affordance: clockwork.threaten, + }, + ] { + let resolved = ResolvedPatch { + subjects: Vec::new(), + entities: Vec::new(), + routes: Vec::new(), + affordances: Vec::new(), + facts: Vec::new(), + channels: Vec::new(), + operations: vec![operation.clone()], + evidence: Vec::new(), + }; + assert_eq!( + confine_to_ground(&kernel.state, &resolved, ground), + Err(vec![Mismatch::OutsideJurisdiction { + site: Site::Operation(0) + }]), + "{operation:?}" + ); + } + } + /// P4.3: a mirror is owned by another world; this one cannot retire it. #[test] fn a_mirror_cannot_be_retired() { @@ -14714,46 +14776,6 @@ mod clock_tests { ); } - /// P4.3: `confine_to_ground` refuses a `Retire` for a confined author - /// unconditionally, even for a subject this same patch declares. - #[test] - fn a_confined_author_cannot_retire() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RetireConfined"); - let speak = super::tests::speak_entry(&kernel); - let error = submit_as( - &mut kernel, - CallerId::System(SystemCapability::Consumer { - consumer: ConsumerId::of_name("confined"), - }), - CommandBody::AdmitPatch { - patch: WorldPatch { - declarations: vec![Declaration::Subject(SubjectDeclaration { - handle: DraftHandle::new("stray"), - label: "The Roadside Stray".into(), - kind: SubjectKind::Person, - controller: NewController::NarrativePersona, - affordances: BTreeSet::from([speak]), - position: Some(Ref::Existing(clockwork.dead_end)), - import_key: None, - })], - operations: vec![ComponentOp::Retire { - subject: Ref::Draft(DraftHandle::new("stray")), - }], - evidence: Vec::new(), - }, - }, - ) - .unwrap_err(); - assert!( - matches!(&error, KernelError::PatchRejected(set) - if set.contains(&Mismatch::OutsideJurisdiction { - site: Site::Operation(0) - })), - "{error:?}" - ); - } - /// P4.3: the owner and the play authority are the two callers a /// `Retire` admits. #[test] @@ -15031,47 +15053,6 @@ mod clock_tests { assert_eq!(ControllerAssignment::Retired.expected_caller(), None); } - /// P5.1: `confine_to_ground` refuses `GrantAffordance` for a confined - /// author unconditionally, even for a subject this same patch declares. - #[test] - fn a_confined_author_cannot_grant() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "GrantConfined"); - let speak = super::tests::speak_entry(&kernel); - let error = submit_as( - &mut kernel, - CallerId::System(SystemCapability::Consumer { - consumer: ConsumerId::of_name("confined"), - }), - CommandBody::AdmitPatch { - patch: WorldPatch { - declarations: vec![Declaration::Subject(SubjectDeclaration { - handle: DraftHandle::new("stray"), - label: "The Roadside Stray".into(), - kind: SubjectKind::Person, - controller: NewController::NarrativePersona, - affordances: BTreeSet::from([speak]), - position: Some(Ref::Existing(clockwork.dead_end)), - import_key: None, - })], - operations: vec![ComponentOp::GrantAffordance { - subject: Ref::Draft(DraftHandle::new("stray")), - affordance: Ref::Existing(clockwork.threaten), - }], - evidence: Vec::new(), - }, - }, - ) - .unwrap_err(); - assert!( - matches!(&error, KernelError::PatchRejected(set) - if set.contains(&Mismatch::OutsideJurisdiction { - site: Site::Operation(0) - })), - "{error:?}" - ); - } - // ---- Retirement fix batch (PA.f31-PA.f35) ------------------------------ fn human_subject(snapshot: &WorldSnapshot) -> SubjectId { @@ -15446,49 +15427,6 @@ mod clock_tests { assert_eq!(error, vec![Mismatch::UnplacedSubject { operation: 1 }]); } - /// PA.f35, MuB: `RevokeAffordance` is confined exactly as every other - /// structural operation, so a confined author cannot use it to touch a - /// subject's grants. - #[test] - fn a_confined_author_cannot_revoke() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf35ElabRevoke"); - let speak = super::tests::speak_entry(&kernel); - let error = submit_as( - &mut kernel, - CallerId::System(SystemCapability::Consumer { - consumer: ConsumerId::of_name("confined"), - }), - CommandBody::AdmitPatch { - patch: WorldPatch { - declarations: vec![Declaration::Subject(SubjectDeclaration { - handle: DraftHandle::new("stray"), - label: "The Roadside Stray".into(), - kind: SubjectKind::Person, - controller: NewController::NarrativePersona, - affordances: BTreeSet::from([ - speak.clone(), - Ref::Existing(clockwork.threaten), - ]), - position: Some(Ref::Existing(clockwork.dead_end)), - import_key: None, - })], - operations: vec![ComponentOp::RevokeAffordance { - subject: Ref::Draft(DraftHandle::new("stray")), - affordance: Ref::Existing(clockwork.threaten), - }], - evidence: Vec::new(), - }, - }, - ) - .unwrap_err(); - assert!( - matches!(&error, KernelError::PatchRejected(set) - if set.contains(&Mismatch::OutsideJurisdiction { site: Site::Operation(0) })), - "{error:?}" - ); - } - /// PA.f35, MuC: `retired` on a subject snapshot row is read from /// `ControllerAssignment::Retired` specifically, not from /// `mode().is_none()` — a mirror's mode is also `None`, and a mirror must diff --git a/native/aetherlight/src/patch.rs b/native/aetherlight/src/patch.rs index ba8a8b4fb..b8161ccc8 100644 --- a/native/aetherlight/src/patch.rs +++ b/native/aetherlight/src/patch.rs @@ -1274,9 +1274,8 @@ pub struct WorldPatch { /// The one byte bound on a `WorldPatch` frame from any external source, and /// the three item bounds on a `WorldPatch` as a value. One owner, two /// consumers: the consumer ingress decodes against them through -/// `decode_patch`, and the elaboration lane checks its own assembled draft -/// against the same three item caps through `check_patch_caps`, before -/// submission. +/// `decode_patch`, and `check_patch_caps` applies the same three item caps to +/// an assembled value before submission. pub(crate) const MAX_PATCH_BYTES: usize = 256 * 1024; pub(crate) const MAX_PATCH_DECLARATIONS: usize = 64; pub(crate) const MAX_PATCH_OPERATIONS: usize = 128; @@ -1338,8 +1337,8 @@ pub(crate) fn check_patch_caps(patch: &WorldPatch) -> Result<(), PatchDecodeErro /// One named structural check that a patch failed. A rejection carries the /// complete set, never the first failure. It never enters `WorldState`, /// `WorldEffect`, `CommandEnvelope`, or `WorldCommit`; the serde derives exist -/// for exactly one reader, the elaboration checkpoint, which is -/// controller-owned telemetry under its own row type and its own schema. +/// for telemetry readers outside the kernel, under their own row type and +/// schema. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] #[serde(tag = "mismatch", rename_all = "snake_case")] pub enum Mismatch { From bf92a054f63e8b99326407ba99fd410f356ba26c Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Thu, 19 Nov 2026 22:40:15 +0100 Subject: [PATCH 127/190] Aetherlight AL2a fix 2: PROVENANCE routing note, schema bump and the completed residue list Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/PROVENANCE.md | 45 +++++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 13 deletions(-) diff --git a/native/aetherlight/PROVENANCE.md b/native/aetherlight/PROVENANCE.md index f796c8008..83dd10878 100644 --- a/native/aetherlight/PROVENANCE.md +++ b/native/aetherlight/PROVENANCE.md @@ -12,8 +12,8 @@ Every file below was copied as a raw git blob (`git show`), never `git archive`. The blobs are LF, as upstream. A Windows checkout with `core.autocrlf` turns the `.rs` files and the two text fixtures into CRLF; rustc, the fixture readers (`lines()`, `trim()`) and the golden test absorb that, so no `.gitattributes` is -kept (a first commit had one; its stated reason did not hold). `base_world.cc` is -binary and no newline rule touches it. Line ranges are in the c43eb54 file. +kept (a first commit had one; its stated reason did not hold). The recorded-world +fixture (removed in AL2a) was binary and no newline rule touched it. Line ranges are in the c43eb54 file. ## Taken @@ -77,9 +77,13 @@ unicode-normalization, unicode-properties, uuid; dev tempfile. `import_key_tests.rs` lose the symbols and tests listed there. Not renamed: the `ghostlight.*` schema ids and namespaces in the code -(`STATE_SCHEMA`, `COMMIT_SCHEMA`, journal schema rows, `ghostlight.speech`). They enter derived ids and digests. No test pins them -since AL2a removed the golden replay (see below); AL4 adds Aetherlight's own -golden. AL3 owns the format rename. +(`STATE_SCHEMA`, `COMMIT_SCHEMA`, journal schema rows, `ghostlight.speech`). They +enter derived ids and digests. No test pins their digests since AL2a removed the +golden replay (see below); AL3/AL5 add Aetherlight's own once ids are derived +(follow-up `aetherlight-golden-replay-dialogue`). AL2a bumped `STATE_SCHEMA` and +`COMMIT_SCHEMA` from `consumer.v6` to `consumer.v7` because the state shape lost +fields, so a pre-cut store is refused at the schema gate (tested with v6 rows). +AL3 owns the format rename. ## Left behind @@ -109,7 +113,7 @@ binding, preconditions, audience, band selection and lowering (`action.rs`); `cultcache-rs` is pinned at Ghostlight's rev `85f7024a35ea42cf9f0a0199a064526427150191`, the rev that wrote -`tests/fixtures/base_world.cc`, not Aetheria's C# CultLib pin. The fork +Ghostlight's recorded-world fixture (removed in AL2a), not Aetheria's C# CultLib pin. The fork reproduces Ghostlight first; AL3 removes cultcache-rs. ## Pulling a later Ghostlight fix @@ -151,15 +155,20 @@ Deleted, with their c43eb54 homes: `AnswerNotDerived`, `AnswerNotSatisfied`; `Mismatch::UnknownJurisdictionRoot` and `ScaleWeightsExceedWhole`. `resolve_patch` loses its intent parameter. - The golden replay `grammar::tests::existing_world_reopens_with_unchanged_digests` - and `tests/fixtures/base_world.*`: removing state fields changed the state + and the recorded-world fixtures under `tests/fixtures`: removing state fields changed the state shape, so Ghostlight's recorded world no longer decodes. AL4 adds Aetherlight's own golden. -Behaviour that changed with the gate: with `require_answer` gone, the owner and -`Play` declare in Active with no answer, and a confined author's only remaining -check is `confine_to_ground`, which now serves the consumer ground alone. -`require_play_active` keeps the one rule `require_answer` also held: `Play` -authors nothing in Draft. +Behaviour with the gate gone: `require_play_active` keeps the one rule +`require_answer` also held (`Play` authors nothing in Draft) and states the other +as a plain rule: in Active, declaring (new structure or evidence) is `Play`'s act +alone, and the owner is refused. A confined author's only remaining check is +`confine_to_ground`, which now serves the consumer ground alone. + +AL4's ABI must route the host through typed commands (the sim reports events, +scripts propose), never through owner declarations in Active: under +`aetherlight-narrative-state-owner` an owner declaring in Active would be a second +door beside that path. Kept untouched for AL2b: controllers and `ControllerMode`, consumers (`ConsumerId`, `SystemCapability::Consumer`, `PatchGround::Consumer`, @@ -179,9 +188,19 @@ What the cut deletes is gone; what remains is part B's: `controller_receipt`, `controller_decline_receipt`, `controller_key`. - Tick-driver readers `WorldKernel::opportunities` and `clock_advances`, and `CreateWorldIntent` (no consumer after the mailbox left). +- Authenticated-caller vocabulary: `AuthenticatedCaller::fixture`, + `verified_principal`, `verified_controller`, `verified_system`, and + `requires_owner_restart`; id helpers `text` and `nil_for_test`; `as_str`, + `digest` (scope preimage); `commits_for_test`; grammar `verbs`. AL4's ABI + decides which of these it needs. +- Patch ingress: `decode_patch`, `check_patch_caps`, `PatchDecodeError` and + `MAX_PATCH_BYTES`, `MAX_PATCH_DECLARATIONS`, `MAX_PATCH_OPERATIONS`, + `MAX_PATCH_EVIDENCE`; the consumer ingress and elaboration lane read them, and + nothing here does. AL2b deletes them with the consumer lane unless AL4's ABI + decodes patches itself. - Mailbox and vault comments (`WorldMailbox`, `vault:` evidence strings). -Reproduce the list with `RUSTFLAGS=--force-warn dead_code cargo test --no-run`: +Reproduce the list with `RUSTFLAGS=--force-warn dead_code cargo test --lib --no-run`: under test configuration the items nothing exercises show up. ## Obligations this cut hands to AL4 From cfad9819cf9a341838c63051ea021cb36b78ef60 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Thu, 19 Nov 2026 23:52:07 +0100 Subject: [PATCH 128/190] Aetherlight AL2b-1: Act { actor, invocation } replaces opportunity-based exercise Deletes DecisionOpportunity, ScopeDigest, attention order, last_opportunity_at, decline, the operator log, controller receipts and the three opportunity errors. Adds CommandBody::Act and WorldEffect::Acted, admitted for System(Play) in Active only; require_granted takes the actor. DecisionEvent carries actor, not scope and controller_id. State and commit schema ids move to v8. Tests whose subject was a deleted lane are deleted; kept-lane tests are rewritten onto one helper submitting Act as System(Play), and write-locality tests compare scope_components. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/action.rs | 295 ++-- native/aetherlight/src/journal.rs | 70 +- native/aetherlight/src/lib.rs | 2441 +++++------------------------ 3 files changed, 508 insertions(+), 2298 deletions(-) diff --git a/native/aetherlight/src/action.rs b/native/aetherlight/src/action.rs index 031579623..9b5c1a303 100644 --- a/native/aetherlight/src/action.rs +++ b/native/aetherlight/src/action.rs @@ -1,8 +1,8 @@ //! The invocation pipeline: catalog lookup, role binding, precondition //! evaluation, effect-ceiling checking, band selection, and lowering. //! -//! One entry point, [`exercise`], reached from `reduce`'s `ExerciseDecision` arm -//! and from `apply_effect`'s `DecisionExercised` arm, so a forged effect is +//! One entry point, [`exercise`], reached from `reduce`'s `Act` arm +//! and from `apply_effect`'s `Acted` arm, so a forged effect is //! re-derived by the same function that produced the honest one. Nothing else //! draws a band, and the draw goes through the one `digest()` owner. @@ -12,7 +12,7 @@ use super::patch::{ }; use super::{ AffordanceId, AuthorityGrant, AuthorityTarget, CommandId, DecisionEvent, DecisionInvocation, - DecisionOpportunity, EdgeId, EntityId, EventId, FictionalMinutes, GrantedAffordance, + EdgeId, EntityId, EventId, FictionalMinutes, GrantedAffordance, KernelError, Magnitude, SubjectId, Target, WorldId, WorldState, digest, }; use serde::Serialize; @@ -116,7 +116,7 @@ pub enum ActionMismatch { /// The band draw's whole preimage. Five fields, none of them from the /// invocation's payload: the proposer varies the attempt and cannot vary the /// draw. `affordance` is the id carried by the kernel-verified grant, so the -/// draw cannot be steered by an affordance the scope does not hold. +/// draw cannot be steered by an affordance the actor does not hold. #[derive(Serialize)] struct BandPreimage { world_id: WorldId, @@ -136,12 +136,11 @@ struct BandPreimage { pub(super) fn exercise( state: &WorldState, command_id: CommandId, - current: &DecisionOpportunity, + actor: SubjectId, granted: &GrantedAffordance<'_>, invocation: &DecisionInvocation, ) -> Result<DecisionEvent, KernelError> { let entry = granted.entry; - let actor = current.scope.subject_id; let mut rejections = Vec::new(); let components = super::scope_components(state, actor); @@ -242,8 +241,7 @@ pub(super) fn exercise( Ok(DecisionEvent { id: EventId::for_command(command_id), revision, - scope: current.scope, - controller_id: current.controller_id, + actor, affordance: granted.id, speech, display, @@ -631,11 +629,9 @@ fn authority_target_of(target: Target) -> Option<AuthorityTarget> { /// `within`. Cost 0 — already standing there — succeeds; `Present` is the strict /// form. An unplaced actor reaches nothing. /// -/// This reads routes the scope digest does not cover, which is deliberate: the -/// alternative binds a proposal to a transitively large slice of world topology -/// and rejects it whenever anything near the actor commits. Admission runs at -/// commit against live state instead, so a route that closed while the proposal -/// was in flight makes this fail rather than letting a stale path commit. +/// Admission runs at commit against live state, so a route that closed while +/// the proposal was in flight makes this fail rather than letting a stale path +/// commit. fn reachable( state: &WorldState, actor: SubjectId, @@ -1019,12 +1015,12 @@ mod tests { }; use crate::tests::{ ADMIT_KIND, COMMAND_KIND, Civic, LEVY_KIND, OPENING_BALANCE, SEIZURE_GRIEVANCE, Topology, - WARDEN_OFFICE, activate, affordance_named, auth_principal, authority_kind, civic_world, - command, custody_world, grant_to, grievance, office, operations, opportunity_for, - over_place, over_subject, human_principal, reject_owner, submit_owner, + WARDEN_OFFICE, act, act_command, activate, affordance_named, authority_kind, civic_world, + command, custody_world, grant_to, grievance, office, operations, over_place, + over_subject, play_caller, reject_owner, submit_owner, }; use crate::{ - AffordanceKindName, AuthenticatedCaller, AuthoredSource, CallerId, CommandBody, Confidence, + AffordanceKindName, AuthenticatedCaller, AuthoredSource, CommandBody, Confidence, Declaration, EffectSlot, EntityKind, ProposedEffect, RoleBinding, Statement, SubmitReceipt, WorldEffect, WorldKernel, WorldPatch, WorldSnapshot, apply_effect, }; @@ -1066,11 +1062,11 @@ mod tests { fn draw_once( state: &WorldState, command_id: CommandId, - opportunity: &DecisionOpportunity, + actor: SubjectId, invocation: &DecisionInvocation, ) -> Result<DecisionEvent, KernelError> { - let granted = crate::require_granted(state, opportunity, invocation.affordance)?; - exercise(state, command_id, opportunity, &granted, invocation) + let granted = crate::require_granted(state, actor, invocation.affordance)?; + exercise(state, command_id, actor, &granted, invocation) } fn binding(role: &str, target: Target) -> RoleBinding { @@ -1105,19 +1101,14 @@ mod tests { self.carry_of(qty, place, self.tithe) } - fn clerk_opportunity(&self) -> DecisionOpportunity { - opportunity_for(&self.active, self.clerk) - } - fn try_exercise( &self, invocation: &DecisionInvocation, ) -> Result<DecisionEvent, KernelError> { - let opportunity = self.clerk_opportunity(); draw_once( &self.kernel.state, CommandId::issue(), - &opportunity, + self.clerk, invocation, ) } @@ -1130,22 +1121,7 @@ mod tests { } fn commit(&mut self, invocation: DecisionInvocation) -> SubmitReceipt { - let opportunity = self.clerk_opportunity(); - let caller = CallerId::Controller(opportunity.controller_id); - self.kernel - .submit( - command( - &self.active, - CommandId::new(), - caller.clone(), - CommandBody::ExerciseDecision { - opportunity, - invocation, - }, - ), - &AuthenticatedCaller::fixture(caller), - ) - .expect("the invocation commits") + act(&mut self.kernel, self.clerk, invocation).expect("the invocation commits") } fn held(&self, holder: SubjectId) -> u64 { @@ -1443,10 +1419,9 @@ mod tests { let directory = tempfile::tempdir().unwrap(); let bench = bench(directory.path(), "Bands"); // Three equally weighted bands, so the draw alone decides. - let opportunity = bench.clerk_opportunity(); let invocation = bench.variant(&bench.carry(1, bench.yard), "carry_chance"); let draw = |command_id: CommandId, invocation: &DecisionInvocation| { - draw_once(&bench.kernel.state, command_id, &opportunity, invocation) + draw_once(&bench.kernel.state, command_id, bench.clerk, invocation) .expect("the invocation is admissible") .band }; @@ -1567,11 +1542,10 @@ mod tests { // The draw is a pure function of the pre-commit revision and the // command id, so the command id that reaches a band is findable // before the envelope is built rather than hunted by retrying. - let opportunity = bench.clerk_opportunity(); let command_id = (0..256) .map(|_| CommandId::issue()) .find(|candidate| { - draw_once(&bench.kernel.state, *candidate, &opportunity, &split) + draw_once(&bench.kernel.state, *candidate, bench.clerk, &split) .expect("the invocation is admissible") .band == wanted @@ -1580,22 +1554,14 @@ mod tests { let before_clerk = bench.held(bench.clerk); let before_keeper = bench.held(bench.keeper); - let caller = CallerId::Controller(opportunity.controller_id); - let receipt = bench - .kernel - .submit( - command( - &bench.active, - command_id, - caller.clone(), - CommandBody::ExerciseDecision { - opportunity, - invocation: split.clone(), - }, - ), - &AuthenticatedCaller::fixture(caller), - ) - .expect("the invocation commits"); + let receipt = act_command( + &mut bench.kernel, + command_id, + play_caller(), + bench.clerk, + split.clone(), + ) + .expect("the invocation commits"); assert!(matches!(receipt, SubmitReceipt::Applied(_))); bench.refresh(); let event = bench @@ -1681,11 +1647,10 @@ mod tests { fn a_forged_band_or_forged_effect_does_not_apply() { let directory = tempfile::tempdir().unwrap(); let bench = bench(directory.path(), "ForgedAction"); - let opportunity = bench.clerk_opportunity(); let command_id = CommandId::issue(); let invocation = bench.carry(2, bench.yard); - let honest = draw_once(&bench.kernel.state, command_id, &opportunity, &invocation).unwrap(); - let caller = CallerId::Controller(opportunity.controller_id); + let honest = draw_once(&bench.kernel.state, command_id, bench.clerk, &invocation).unwrap(); + let caller = play_caller(); for forged in [ DecisionEvent { @@ -1707,25 +1672,43 @@ mod tests { &mut candidate, command_id, &caller, - &WorldEffect::DecisionExercised { - opportunity: opportunity.clone(), + &WorldEffect::Acted { invocation: invocation.clone(), event: forged, }, ) .unwrap_err(); - assert!(matches!(error, KernelError::Invariant(_))); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); assert_eq!(candidate, bench.kernel.state); } + // An event naming another actor does not apply either: the actor is + // read from the event, so a swapped actor is re-derived for the swap. + let mut candidate = bench.kernel.state.clone(); + assert!( + apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::Acted { + invocation: invocation.clone(), + event: DecisionEvent { + actor: bench.keeper, + ..honest.clone() + }, + }, + ) + .is_err() + ); + assert_eq!(candidate, bench.kernel.state); + // The honest event still applies through the same arm. let mut candidate = bench.kernel.state.clone(); apply_effect( &mut candidate, command_id, &caller, - &WorldEffect::DecisionExercised { - opportunity, + &WorldEffect::Acted { invocation: invocation.clone(), event: honest, }, @@ -1748,26 +1731,18 @@ mod tests { .expect("the human subject") .id; let holdings = kernel.state.holdings.clone(); - let receipt = kernel - .submit( - command( - &active, - CommandId::new(), - CallerId::Principal(human_principal()), - CommandBody::ExerciseDecision { - opportunity: opportunity_for(&active, human), - invocation: DecisionInvocation { - affordance: speak, - bindings: Vec::new(), - proposed: Vec::new(), - speech: Some(Statement::new("I open the door.").unwrap()), - display: None, - }, - }, - ), - &auth_principal(human_principal()), - ) - .expect("the Speak entry commits"); + let receipt = act( + &mut kernel, + human, + DecisionInvocation { + affordance: speak, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("I open the door.").unwrap()), + display: None, + }, + ) + .expect("the Speak entry commits"); assert!(matches!(receipt, SubmitReceipt::Applied(_))); let event = kernel.state.events.last().unwrap(); assert_eq!(event.band, 0); @@ -1899,7 +1874,7 @@ mod tests { draw_once( &self.kernel.state, CommandId::issue(), - &opportunity_for(&self.active, actor), + actor, invocation, ) } @@ -1916,23 +1891,7 @@ mod tests { } fn commit_as(&mut self, actor: SubjectId, invocation: DecisionInvocation) -> SubmitReceipt { - let opportunity = opportunity_for(&self.active, actor); - let caller = CallerId::Controller(opportunity.controller_id); - let receipt = self - .kernel - .submit( - command( - &self.active, - CommandId::new(), - caller.clone(), - CommandBody::ExerciseDecision { - opportunity, - invocation, - }, - ), - &AuthenticatedCaller::fixture(caller), - ) - .expect("the invocation commits"); + let receipt = act(&mut self.kernel, actor, invocation).expect("the invocation commits"); self.refresh(); receipt } @@ -2029,9 +1988,7 @@ mod tests { assert!(bench.kernel.state.authority.get(&reeve).is_none()); assert!(bench.try_as(reeve, &bench.levy(farmer, 1)).is_ok()); - // A proposal bound before the vacate rebinds rather than rejecting. - let bound = opportunity_for(&bench.active, reeve); - let caller = CallerId::Controller(bound.controller_id); + // The vacated office lends nothing: the act is refused at admission. let invocation = bench.levy(farmer, 1); bench.admit(vec![ComponentOp::VacateOffice { institution: PatchRef::Existing(bench.civic.treasury), @@ -2039,29 +1996,8 @@ mod tests { }]); let holdings = bench.kernel.state.holdings.clone(); - let error = bench - .kernel - .submit( - command( - &bench.active, - CommandId::new(), - caller.clone(), - CommandBody::ExerciseDecision { - opportunity: bound.clone(), - invocation, - }, - ), - &AuthenticatedCaller::fixture(caller), - ) - .unwrap_err(); - let KernelError::ScopeChanged { - scope, expected, .. - } = error - else { - panic!("a vacated office is a rebind, not a rejection"); - }; - assert_eq!(scope, bound.scope); - assert_eq!(expected, bound.scope_digest); + let error = act(&mut bench.kernel, reeve, invocation).unwrap_err(); + assert!(matches!(error, KernelError::ActionRejected(_)), "{error:?}"); assert_eq!(bench.kernel.state.holdings, holdings); assert_eq!( bench.rejected_as(reeve, &bench.levy(farmer, 1)), @@ -2416,32 +2352,23 @@ mod tests { // The treasury commands the hall, and the passage has both endpoints // under it. The draw decides whether the interdiction lands. - let opportunity = opportunity_for(&bench.active, treasury); let closing = (0..256) .map(|_| CommandId::issue()) .find(|candidate| { - draw_once(&bench.kernel.state, *candidate, &opportunity, &sanction) + draw_once(&bench.kernel.state, *candidate, treasury, &sanction) .expect("the invocation is admissible") .band == 0 }) .expect("a two-band entry reaches its first band over 256 command ids"); - let caller = CallerId::Controller(opportunity.controller_id); - let receipt = bench - .kernel - .submit( - command( - &bench.active, - closing, - caller.clone(), - CommandBody::ExerciseDecision { - opportunity, - invocation: sanction, - }, - ), - &AuthenticatedCaller::fixture(caller), - ) - .expect("the sanction commits"); + let receipt = act_command( + &mut bench.kernel, + closing, + play_caller(), + treasury, + sanction, + ) + .expect("the sanction commits"); assert!(matches!(receipt, SubmitReceipt::Applied(_))); bench.refresh(); assert!(!bench.kernel.state.edges[&passage].is_open()); @@ -2479,20 +2406,7 @@ mod tests { actor: SubjectId, invocation: DecisionInvocation, ) -> Result<SubmitReceipt, KernelError> { - let opportunity = opportunity_for(&bench.active, actor); - let caller = CallerId::Controller(opportunity.controller_id); - bench.kernel.submit( - command( - &bench.active, - CommandId::new(), - caller.clone(), - CommandBody::ExerciseDecision { - opportunity, - invocation, - }, - ), - &AuthenticatedCaller::fixture(caller), - ) + act(&mut bench.kernel, actor, invocation) } /// `DelegationNotMonotone` is not a fixture-only verdict: the real `submit` @@ -2562,11 +2476,11 @@ mod tests { assert_eq!(admitted.positions[&walker].place, bench.civic.chamber); } - /// The rebind requirement at the layer the operator sees it: a grant change - /// on the *granter* invalidates the delegate's bound opportunity, and the - /// refusal is `ScopeChanged`, not `ActionRejected`. + /// A grant change on the *granter* reaches the delegate: once the + /// treasury's levy ground is revoked, the reeve's act is refused at + /// admission, and nothing commits. #[test] - fn soul_a_granter_revocation_rebinds_the_delegate() { + fn soul_a_granter_revocation_refuses_the_delegates_act() { let directory = tempfile::tempdir().unwrap(); let mut bench = civics(directory.path(), "SoulRebind"); let reeve = bench.civic.reeve; @@ -2574,37 +2488,19 @@ mod tests { let treasury = bench.civic.treasury; let hall = bench.civic.hall; - // Bound before the revocation, submitted after it. - let bound = bench.active.clone(); - let opportunity = opportunity_for(&bound, reeve); - let caller = CallerId::Controller(opportunity.controller_id); + assert!(bench.try_as(reeve, &bench.levy(farmer, 1)).is_ok()); let invocation = bench.levy(farmer, 1); bench.admit(vec![ComponentOp::RevokeAuthority { holder: PatchRef::Existing(treasury), grant: crate::tests::grant_of(LEVY_KIND, over_place(hall)), }]); - // The envelope carries the current revision, so only the stale scope - // digest can refuse it. - assert_ne!(bound.revision, bench.active.revision); - let error = bench - .kernel - .submit( - command( - &bench.active, - CommandId::new(), - caller.clone(), - CommandBody::ExerciseDecision { - opportunity, - invocation, - }, - ), - &AuthenticatedCaller::fixture(caller), - ) - .unwrap_err(); + let events = bench.kernel.state.events.len(); + let error = act(&mut bench.kernel, reeve, invocation).unwrap_err(); assert!( - matches!(error, KernelError::ScopeChanged { .. }), - "a revoked lend is a rebind, not a rejection: {error:?}" + matches!(error, KernelError::ActionRejected(_)), + "a revoked lend is a rejection: {error:?}" ); + assert_eq!(bench.kernel.state.events.len(), events); } /// Structural overlap alone does not see a `Subject` grant sitting inside @@ -2689,14 +2585,13 @@ mod tests { appoint, ] { let before = bench.kernel.state.clone(); - let opportunity = opportunity_for(&bench.active, treasury); - let caller = CallerId::Controller(opportunity.controller_id); + let caller = play_caller(); let envelope = command( &bench.active, CommandId::new(), caller.clone(), - CommandBody::ExerciseDecision { - opportunity, + CommandBody::Act { + actor: treasury, invocation, }, ); @@ -2709,8 +2604,8 @@ mod tests { .expect("the act commits"); assert!(matches!(receipt, SubmitReceipt::Applied(_))); bench.refresh(); - let WorldEffect::DecisionExercised { event, .. } = first else { - panic!("an exercised decision"); + let WorldEffect::Acted { event, .. } = first else { + panic!("an acted effect"); }; assert_eq!( bench.kernel.state.events.last().expect("a committed event"), diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index ae0588651..033855ad8 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -727,15 +727,6 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> )); } } - if state - .last_opportunity_at - .iter() - .any(|(subject_id, stamp)| !state.subjects.contains_key(subject_id) || *stamp > state.now) - { - return Err(JournalError::Corrupt( - "an attention stamp names an unknown subject or a future minute".into(), - )); - } // The civic subgraph, in the slot the deleted `authority_scope` check // occupied: a jurisdiction names live ground under a canonical kind, an // office sits on an institution and lends something to a person who holds @@ -899,10 +890,11 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> let mut claimed = BTreeSet::new(); let mut previous_event_revision = 0; for event in &state.events { - state - .controller_assignments - .get(&event.scope) - .ok_or_else(|| JournalError::Corrupt("event references an unknown scope".into()))?; + if !state.subjects.contains_key(&event.actor) { + return Err(JournalError::Corrupt( + "event references an unknown actor".into(), + )); + } let entry = state .affordance_catalog .get(&event.affordance) @@ -915,7 +907,7 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> && state.facts.get(&fact).is_some_and(|record| { record.standing == super::FactStanding::Claimed { - by: event.scope.subject_id, + by: event.actor, } }) }) @@ -926,15 +918,14 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> || event.revision == 0 || event.revision > state.revision || event.revision <= previous_event_revision - // Present-tense controller identity and present-tense affordance - // grants are not judged here: retiring a subject or revoking a - // verb it once used must not corrupt the history of that use. - // Authority at commit time is judged once, by `reduce`, and after - // that by replay (`verify_history` re-runs `reduce` for every - // commit) and by the digest chain. This shape check only holds - // time-invariant facts: the event's scope resolves to a live - // assignment (checked above) and its affordance is a catalog - // entry (checked above). + // Present-tense affordance grants are not judged here: retiring a + // subject or revoking a verb it once used must not corrupt the + // history of that use. Authority at commit time is judged once, by + // `reduce`, and after that by replay (`verify_history` re-runs + // `reduce` for every commit) and by the digest chain. This shape + // check only holds time-invariant facts: the event's actor is a + // subject (checked above) and its affordance is a catalog entry + // (checked above). || event.band >= entry.outcome_bands.len() // Speech rides only a speech-carrying entry; such an entry always // addresses someone, by words or by a visible act; a display may @@ -951,7 +942,7 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> || !display_is_canonical { return Err(JournalError::Corrupt( - "decision event is noncanonical or violates controller scope".into(), + "decision event is noncanonical".into(), )); } previous_event_revision = event.revision; @@ -1534,7 +1525,7 @@ mod tests { fn soul_a_forged_band_or_effect_in_the_journal_dies_at_replay() { use crate::tests::{ activate, admit_custody, admit_topology, affordance_named, auth_principal, command, - opportunity_for, owner, + owner, play_caller, }; use crate::{ AuthenticatedCaller, DecisionInvocation, Magnitude, ProposedEffect, Quantity, @@ -1555,8 +1546,7 @@ mod tests { let custody = admit_custody(&mut kernel, &topology); let active = activate(&mut kernel); let entry = affordance_named(&active, kind); - let opportunity = opportunity_for(&active, custody.holder); - let caller = CallerId::Controller(opportunity.controller_id); + let caller = play_caller(); let command_id = CommandId::new(); let role = |name: &str, target| RoleBinding { role: crate::Role(name.into()), @@ -1568,8 +1558,8 @@ mod tests { &active, command_id, caller.clone(), - CommandBody::ExerciseDecision { - opportunity, + CommandBody::Act { + actor: custody.holder, invocation: DecisionInvocation { affordance: entry, bindings: vec![ @@ -1597,8 +1587,8 @@ mod tests { let mut forged_head = kernel.state.clone(); let mut forged_commits = kernel.journal.commits.clone(); let forged = forged_commits.get_mut(&command_id).unwrap(); - let WorldEffect::DecisionExercised { event, .. } = &mut forged.effect else { - panic!("expected an exercised decision effect"); + let WorldEffect::Acted { event, .. } = &mut forged.effect else { + panic!("expected an acted effect"); }; mutate(event); let forged_event = event.clone(); @@ -1824,7 +1814,7 @@ mod tests { /// the same envelope is already applied. #[test] fn restart_replay_after_a_levy_is_exact() { - use crate::tests::{affordance_named, civic_world, command, opportunity_for, owner}; + use crate::tests::{affordance_named, civic_world, command, owner, play_caller}; use crate::{ DecisionInvocation, Magnitude, ProposedEffect, Quantity, Role, RoleBinding, SubmitReceipt, Target, @@ -1839,14 +1829,13 @@ mod tests { ) .unwrap(); let (_, civic, active) = civic_world(&mut kernel); - let opportunity = opportunity_for(&active, civic.treasury); - let caller = CallerId::Controller(opportunity.controller_id); + let caller = play_caller(); let envelope = command( &active, CommandId::new(), caller.clone(), - CommandBody::ExerciseDecision { - opportunity, + CommandBody::Act { + actor: civic.treasury, invocation: DecisionInvocation { affordance: affordance_named(&active, "levy"), bindings: vec![ @@ -2207,7 +2196,7 @@ mod custody_tests { /// seed does not reproduce fails effect equality on the way back in. #[test] fn restart_replay_after_an_action_is_exact() { - use crate::tests::affordance_named; + use crate::tests::{affordance_named, play_caller}; use crate::{AuthenticatedCaller, Magnitude, ProposedEffect, RoleBinding, Target}; let directory = tempfile::tempdir().unwrap(); @@ -2223,8 +2212,7 @@ mod custody_tests { let custody = admit_custody(&mut kernel, &topology); let active = crate::tests::activate(&mut kernel); let carry = affordance_named(&active, "carry"); - let opportunity = crate::tests::opportunity_for(&active, custody.holder); - let caller = CallerId::Controller(opportunity.controller_id); + let caller = play_caller(); let role = |name: &str, target| RoleBinding { role: crate::Role(name.into()), @@ -2234,8 +2222,8 @@ mod custody_tests { &active, CommandId::new(), caller.clone(), - CommandBody::ExerciseDecision { - opportunity: opportunity.clone(), + CommandBody::Act { + actor: custody.holder, invocation: crate::DecisionInvocation { affordance: carry, bindings: vec![ diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index 76246e783..763c18804 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -145,8 +145,8 @@ impl VerifiedPrincipalEvidence { } } -pub const STATE_SCHEMA: &str = "ghostlight.world_state.consumer.v7"; -pub(crate) const COMMIT_SCHEMA: &str = "ghostlight.world_commit.consumer.v7"; +pub const STATE_SCHEMA: &str = "ghostlight.world_state.consumer.v8"; +pub(crate) const COMMIT_SCHEMA: &str = "ghostlight.world_commit.consumer.v8"; /// Compatibility tag derived from [`STATE_SCHEMA`]: the trailing /// `<family>-<version>` pair (e.g. `foundation-v1`). Callers that publish a @@ -456,55 +456,6 @@ pub struct DecisionScope { pub subject_id: SubjectId, } -/// The digest of exactly the components a proposal's verification reads: the -/// scope's controller assignment, its affordance grants, its subject's Position, -/// and the routes incident to that place. Built through the one `digest()` -/// helper over ordered containers, so it is a pure function of committed state. -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] -#[serde(transparent)] -pub struct ScopeDigest(String); - -impl ScopeDigest { - fn as_str(&self) -> &str { - &self.0 - } - - #[cfg(test)] - pub(crate) fn fixture(value: &str) -> Self { - Self(value.into()) - } -} - -#[derive(Serialize)] -struct ScopePreimage<'a> { - world_id: WorldId, - subject_id: SubjectId, - controller: &'a ControllerAssignment, - /// The granted entries *and their definitions*: preconditions and ceilings - /// are what admission reads, so a change to a granted entry must change the - /// digest. - affordances: BTreeMap<AffordanceId, &'a Affordance>, - components: &'a ScopeComponents, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -pub struct DecisionOpportunity { - pub world_id: WorldId, - pub(crate) revision: u64, - pub(crate) scope_digest: ScopeDigest, - pub scope: DecisionScope, - pub(crate) controller_id: ControllerId, - pub controller_mode: ControllerMode, - pub affordance_ids: Vec<AffordanceId>, -} - -impl DecisionOpportunity { - pub(crate) fn digest(&self) -> Result<String, KernelError> { - digest(self) - } -} - /// The referent a role is bound to. Canonical IDs only: an invocation happens /// in Active, where no declaration exists, so a draft reference is /// unrepresentable here and the action lane runs no draft resolution. @@ -582,13 +533,12 @@ pub struct PrincipalCommandIntent { pub enum CommandBody { ApproveDraft, ActivateWorld, - ExerciseDecision { - opportunity: DecisionOpportunity, + /// One subject's act. Play's alone: the actor's grants decide whether the + /// affordance is its to use. + Act { + actor: SubjectId, invocation: DecisionInvocation, }, - DeclineDecision { - opportunity: DecisionOpportunity, - }, AdmitPatch { patch: WorldPatch, }, @@ -696,8 +646,7 @@ impl ControllerAssignment { pub(crate) struct DecisionEvent { pub(crate) id: EventId, pub(crate) revision: u64, - pub(crate) scope: DecisionScope, - pub(crate) controller_id: ControllerId, + pub(crate) actor: SubjectId, /// The entry exercised. The invocation itself lives on the effect: the /// invocation is what the caller said, the event is what the world recorded. pub(crate) affordance: AffordanceId, @@ -772,10 +721,6 @@ struct WorldState { /// Pressure *on* each subject, keyed target-major then source. Never empty /// for a present key; no stored zero magnitude. pressures: BTreeMap<SubjectId, BTreeMap<PressureSource, PressureMagnitude>>, - /// When each subject was last given a decision opportunity it consumed. - /// Absence means never. The debt term of the attention order and nothing - /// else. - last_opportunity_at: BTreeMap<SubjectId, FictionalMinutes>, /// Minutes since genesis. The world's only clock, advanced by exactly one /// command body and read by no wall clock. It enters `state_digest` and no /// `ScopePreimage`: it is world truth, and it is read by no precondition, so @@ -808,17 +753,13 @@ enum WorldEffect { principal: PrincipalId, }, WorldActivated, - DecisionExercised { - opportunity: DecisionOpportunity, + Acted { /// The command's own input, kept beside the event rather than inside it: /// the invocation is what the caller said, the event is what the world /// recorded, and only the first carries text. invocation: DecisionInvocation, event: DecisionEvent, }, - DecisionDeclined { - opportunity: DecisionOpportunity, - }, /// The first effect that mutates state for subjects other than one scope. /// Its gate is the clock capability or the owner, and `apply_effect` /// re-derives the whole motion, so a forged fulfilment, magnitude, row, or @@ -1094,11 +1035,6 @@ pub struct WorldSnapshot { /// currently perceives: no subject-facing surface reads this field, which /// exists for the play table's own `table_view` alone. pub(crate) facts: Vec<FactSnapshot>, - /// Already ordered by pressure, then attention debt, then id: one owner, so - /// an operator interface, the mesh projection, and any future driver read - /// the same order and - /// none computes its own. - pub opportunities: Vec<DecisionOpportunity>, /// Everyone in a world shares the clock, and no controller can read a `due` /// without it. pub now: FictionalMinutes, @@ -1106,33 +1042,6 @@ pub struct WorldSnapshot { pub last_commit_digest: Option<String>, } -/// One committed act as the human operator's story feed reads it. It is the -/// operator surface, not a perception surface: no subject-facing lane receives -/// it, and `SelectedDecision` never sees an event log at all. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct OperatorEvent { - pub revision: u64, - pub speaker: SubjectId, - pub speaker_label: String, - pub speech: Option<Statement>, - pub display: Option<Statement>, - /// The affordance kind the act exercised. - pub verb: String, - /// How the world's grammar renders that verb; none in a world with no - /// grammar. - pub render_path: Option<RenderPath>, - /// What the act bound each of the verb's roles to, in the invocation's - /// order. - pub roles: Vec<BoundRole>, -} - -/// One role an act bound, with the label of what it was bound to. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct BoundRole { - pub role: String, - pub target: String, -} - #[derive(Clone, Debug, PartialEq, Eq)] pub struct CommitReceipt { pub command_id: CommandId, @@ -1216,17 +1125,7 @@ pub enum KernelError { DraftAlreadyApproved, #[error("draft is missing required approvals: {0:?}")] MissingApprovals(Vec<PrincipalId>), - #[error("this world derives no such decision opportunity")] - OpportunityMismatch, - #[error("decision scope changed since the proposal was bound")] - ScopeChanged { - scope: DecisionScope, - expected: ScopeDigest, - actual: ScopeDigest, - }, - #[error("caller does not control this decision scope")] - ControllerMismatch, - #[error("decision affordance is not granted by the opportunity")] + #[error("decision affordance is not granted to the actor")] AffordanceDenied, #[error("expected revision {expected}, current revision {actual}")] RevisionMismatch { expected: u64, actual: u64 }, @@ -1404,49 +1303,6 @@ impl WorldKernel { snapshot(&self.state) } - /// The human operator's story feed. Separate from `snapshot` so that no - /// controller lane can reach an unscoped event log: a `WorldSnapshot` field - /// no consumer may read in full would be a loaded gun with a comment on it. - fn operator_log(&self) -> Result<Vec<OperatorEvent>, KernelError> { - self.journal.ensure_healthy()?; - // An event records what the world did; the invocation, which names the - // bound roles, lives on the commit that produced it. - let invocations: BTreeMap<EventId, &DecisionInvocation> = self - .journal - .commits() - .filter_map(|commit| match &commit.effect { - WorldEffect::DecisionExercised { - invocation, event, .. - } => Some((event.id, invocation)), - _ => None, - }) - .collect(); - operator_log(&self.state, &invocations) - } - - /// The tick driver's opportunity list, in the same order a snapshot - /// carries it. Separate from `snapshot`: only the tick driver reads it. - fn opportunities(&self) -> Result<Vec<DecisionOpportunity>, KernelError> { - self.journal.ensure_healthy()?; - Ok(order_opportunities( - &self.state, - derive_opportunities(&self.state)?, - )) - } - - /// How many clock advances the world has committed: the next tick's - /// ordinal, held by the world and read from its journal. Separate from - /// `snapshot` for the reason `opportunities` is: only the tick driver - /// reads it. - fn clock_advances(&self) -> Result<u64, KernelError> { - self.journal.ensure_healthy()?; - Ok(self - .journal - .commits() - .filter(|commit| matches!(commit.effect, WorldEffect::TimeAdvanced { .. })) - .count() as u64) - } - fn submit( &mut self, command: CommandEnvelope, @@ -1514,57 +1370,6 @@ impl WorldKernel { self.journal.commit_for(command_id) } - fn controller_receipt( - &self, - command_id: CommandId, - opportunity: &DecisionOpportunity, - invocation: &DecisionInvocation, - ) -> Result<Option<CommitReceipt>, KernelError> { - self.journal.ensure_healthy()?; - let Some(commit) = self.committed_command(command_id) else { - return Ok(None); - }; - let CommittedCommand::WorldCommand(CommandEnvelope { - body: - CommandBody::ExerciseDecision { - opportunity: committed_opportunity, - invocation: committed_invocation, - }, - .. - }) = &commit.command - else { - return Err(KernelError::CommandIdConflict); - }; - if committed_opportunity != opportunity || committed_invocation != invocation { - return Err(KernelError::CommandIdConflict); - } - Ok(Some(CommitReceipt::from(commit))) - } - - fn controller_decline_receipt( - &self, - command_id: CommandId, - opportunity: &DecisionOpportunity, - ) -> Result<Option<CommitReceipt>, KernelError> { - self.journal.ensure_healthy()?; - let Some(commit) = self.committed_command(command_id) else { - return Ok(None); - }; - let CommittedCommand::WorldCommand(CommandEnvelope { - body: - CommandBody::DeclineDecision { - opportunity: committed_opportunity, - }, - .. - }) = &commit.command - else { - return Err(KernelError::CommandIdConflict); - }; - if committed_opportunity != opportunity { - return Err(KernelError::CommandIdConflict); - } - Ok(Some(CommitReceipt::from(commit))) - } } fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result<WorldEffect, KernelError> { @@ -1600,41 +1405,18 @@ fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result<WorldEffect, } Ok(WorldEffect::WorldActivated) } - CommandBody::ExerciseDecision { - opportunity, - invocation, - } => { + CommandBody::Act { actor, invocation } => { require_phase(state, WorldPhase::Active)?; - let current = exact_opportunity(state, opportunity)?; - let assignment = state - .controller_assignments - .get(¤t.scope) - .ok_or(KernelError::OpportunityMismatch)?; - if assignment.expected_caller().as_ref() != Some(&command.caller) { - return Err(KernelError::ControllerMismatch); + if command.caller != CallerId::System(SystemCapability::Play) { + return Err(KernelError::Unauthorized); } - let granted = require_granted(state, ¤t, invocation.affordance)?; - let event = action::exercise(state, command.id, ¤t, &granted, invocation)?; - Ok(WorldEffect::DecisionExercised { - opportunity: current, + let granted = require_granted(state, *actor, invocation.affordance)?; + let event = action::exercise(state, command.id, *actor, &granted, invocation)?; + Ok(WorldEffect::Acted { invocation: invocation.clone(), event, }) } - CommandBody::DeclineDecision { opportunity } => { - require_phase(state, WorldPhase::Active)?; - let current = exact_opportunity(state, opportunity)?; - let assignment = state - .controller_assignments - .get(¤t.scope) - .ok_or(KernelError::OpportunityMismatch)?; - if assignment.expected_caller().as_ref() != Some(&command.caller) { - return Err(KernelError::ControllerMismatch); - } - Ok(WorldEffect::DecisionDeclined { - opportunity: current, - }) - } CommandBody::AdvanceTime { minutes } => { // There is no time in Draft: a world under construction has no due // dates to cross. @@ -1689,6 +1471,7 @@ fn require_system_capability(caller: &CallerId, body: &CommandBody) -> Result<() SystemCapability::Consumer { .. } | SystemCapability::Play, CommandBody::AdmitPatch { .. } ) + | (SystemCapability::Play, CommandBody::Act { .. }) ); if admitted { Ok(()) @@ -1777,7 +1560,6 @@ impl WorldState { redress: BTreeMap::new(), commitments: BTreeMap::new(), pressures: BTreeMap::new(), - last_opportunity_at: BTreeMap::new(), now: FictionalMinutes::default(), controller_assignments: BTreeMap::new(), affordance_catalog: BTreeMap::new(), @@ -3515,69 +3297,6 @@ fn scope_components(state: &WorldState, subject_id: SubjectId) -> ScopeComponent } } -/// The human operator's story feed, derived from the causal record. The events -/// log is not a perception surface: `knowledge` is the sole answer to what a -/// subject may act on and what its projection may contain. -fn operator_log( - state: &WorldState, - invocations: &BTreeMap<EventId, &DecisionInvocation>, -) -> Result<Vec<OperatorEvent>, KernelError> { - state - .events - .iter() - .map(|event| { - let speaker = state - .subjects - .get(&event.scope.subject_id) - .ok_or_else(|| KernelError::Invariant("event names no live subject".into()))?; - let invocation = invocations.get(&event.id).ok_or_else(|| { - KernelError::Invariant("event has no committed invocation".into()) - })?; - let entry = state - .affordance_catalog - .get(&event.affordance) - .ok_or_else(|| KernelError::Invariant("event names no catalog entry".into()))?; - let roles = invocation - .bindings - .iter() - .map(|binding| { - let label = match binding.target { - Target::Subject(id) => state.subjects.get(&id).map(|s| s.label.clone()), - Target::Entity(id) => state.entities.get(&id).map(|e| e.label.clone()), - Target::Edge(id) => state.edges.contains_key(&id).then(|| "edge".to_owned()), - }; - label - .map(|target| BoundRole { - role: binding.role.0.clone(), - target, - }) - .ok_or_else(|| KernelError::Invariant("event binds no live referent".into())) - }) - .collect::<Result<Vec<_>, _>>()?; - Ok(OperatorEvent { - revision: event.revision, - speaker: event.scope.subject_id, - speaker_label: speaker.label.clone(), - speech: event - .speech - .and_then(|fact| state.facts.get(&fact)) - .map(|record| record.statement.clone()), - display: event - .display - .and_then(|fact| state.facts.get(&fact)) - .map(|record| record.statement.clone()), - verb: entry.kind.0.clone(), - render_path: state - .grammar - .as_ref() - .and_then(|grammar| grammar.verb(&entry.kind.0)) - .map(|verb| verb.render_path), - roles, - }) - }) - .collect() -} - fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> { // One pass over the causal record so each subject's own knowledge map can be // stamped with the revision that minted each claim it holds. @@ -3600,7 +3319,7 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> { .events .iter() .fold(BTreeMap::new(), |mut acc, event| { - let entry = acc.entry(event.scope.subject_id).or_insert(event.revision); + let entry = acc.entry(event.actor).or_insert(event.revision); if event.revision > *entry { *entry = event.revision; } @@ -3831,124 +3550,13 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> { routes, channels, facts, - opportunities: order_opportunities(state, derive_opportunities(state)?), now: state.now, state_digest: state.state_digest.clone(), last_commit_digest: state.last_commit_digest.clone(), }) } -/// A pure re-ordering of `derive_opportunities`' output: same values, same -/// length, same set. Never a filter — filtering by readiness would drag -/// precondition reads into `ScopePreimage`, and a tick could then withdraw an -/// opportunity a controller is mid-inference on, which `exact_opportunity` -/// would report as `OpportunityMismatch` rather than the honest `ScopeChanged`. -/// -/// A subject never attended sorts ahead of every subject that has, and a -/// subject with no pressure still climbs one tick at a time, so the order -/// starves nobody. `SubjectId` is the final tiebreak, so the order is total and -/// identical on every machine. -fn order_opportunities( - state: &WorldState, - mut opportunities: Vec<DecisionOpportunity>, -) -> Vec<DecisionOpportunity> { - opportunities.sort_by_key(|opportunity| { - let subject_id = opportunity.scope.subject_id; - ( - std::cmp::Reverse(pressure_total(state, subject_id)), - std::cmp::Reverse(attention_debt(state, subject_id)), - subject_id, - ) - }); - opportunities -} - -fn pressure_total(state: &WorldState, subject_id: SubjectId) -> u64 { - state - .pressures - .get(&subject_id) - .into_iter() - .flat_map(BTreeMap::values) - .fold(0u64, |total, magnitude| { - total.saturating_add(u64::from(magnitude.0)) - }) -} - -/// Minutes since this subject last consumed an opportunity. Absence is -/// `u64::MAX`: never attended outranks every subject that has. -fn attention_debt(state: &WorldState, subject_id: SubjectId) -> u64 { - state - .last_opportunity_at - .get(&subject_id) - .map_or(u64::MAX, |stamp| state.now.since(*stamp)) -} - -fn derive_opportunities(state: &WorldState) -> Result<Vec<DecisionOpportunity>, KernelError> { - if state.phase != WorldPhase::Active { - return Ok(Vec::new()); - } - state - .controller_assignments - .iter() - // World truth, not a scheduling preference: a mirror has no turn, so it - // never mints an opportunity and never trips the empty-grant invariant. - .filter(|(_, controller)| controller.mode().is_some()) - .map(|(scope, controller)| { - let (Some(controller_id), Some(controller_mode)) = (controller.id(), controller.mode()) - else { - return Err(KernelError::Invariant( - "decision scope has no controller turn".into(), - )); - }; - let affordance_ids: Vec<_> = state - .affordance_grants - .get(scope) - .into_iter() - .flatten() - .copied() - .collect(); - if affordance_ids.is_empty() { - return Err(KernelError::Invariant( - "active decision scope has no affordances".into(), - )); - } - Ok(DecisionOpportunity { - world_id: state.world_id, - revision: state.revision, - scope_digest: scope_digest(state, *scope)?, - scope: *scope, - controller_id, - controller_mode, - affordance_ids, - }) - }) - .collect() -} - -/// The entries one scope is granted, paired with their definitions. A grant -/// naming no catalog entry is a corrupt kernel rather than a rejection: one -/// owner writes both partitions in one commit. -fn granted_entries( - state: &WorldState, - scope: DecisionScope, -) -> Result<BTreeMap<AffordanceId, &Affordance>, KernelError> { - state - .affordance_grants - .get(&scope) - .into_iter() - .flatten() - .map(|affordance_id| { - state - .affordance_catalog - .get(affordance_id) - .map(|entry| (*affordance_id, entry)) - .ok_or_else(|| KernelError::Invariant("granted affordance has no entry".into())) - }) - .collect() -} - -/// One affordance the kernel has already gated: the opportunity offers this -/// entry, the scope holds it, and `entry` is its catalog definition. It is the +/// One affordance the kernel has already gated: the actor holds this entry, and `entry` is its catalog definition. It is the /// only way to name an affordance to `action::exercise`, so a caller cannot /// reach the invocation pipeline without passing the grant check first. pub(crate) struct GrantedAffordance<'a> { @@ -3956,81 +3564,32 @@ pub(crate) struct GrantedAffordance<'a> { pub(crate) entry: &'a Affordance, } -/// The membership half of the affordance check, shared by `reduce` and -/// `apply_effect`: the opportunity offers the entry and the scope holds it. It -/// returns the entry rather than a unit, so the gate and the lookup are one act. +/// The grant check, shared by `reduce` and `apply_effect`: the actor's own +/// entry set holds the affordance and the catalog defines it. It returns the +/// entry rather than a unit, so the gate and the lookup are one act, and it is +/// the only constructor of `GrantedAffordance`. Retire removes a subject's +/// grants, so a retired actor holds nothing. fn require_granted<'a>( state: &'a WorldState, - current: &DecisionOpportunity, + actor: SubjectId, affordance: AffordanceId, ) -> Result<GrantedAffordance<'a>, KernelError> { - if current.affordance_ids.contains(&affordance) - && state - .affordance_grants - .get(¤t.scope) - .is_some_and(|granted| granted.contains(&affordance)) - { - let entry = state - .affordance_catalog - .get(&affordance) - .ok_or_else(|| KernelError::Invariant("granted affordance has no entry".into()))?; - Ok(GrantedAffordance { - id: affordance, - entry, - }) - } else { - Err(KernelError::AffordanceDenied) - } -} - -/// The sole producer of a `ScopeDigest`. The components it reads come from -/// `scope_components`, which the snapshot reads too. -fn scope_digest(state: &WorldState, scope: DecisionScope) -> Result<ScopeDigest, KernelError> { - let controller = state - .controller_assignments + let scope = DecisionScope { subject_id: actor }; + if !state + .affordance_grants .get(&scope) - .ok_or_else(|| KernelError::Invariant("decision scope has no controller".into()))?; - let affordances = granted_entries(state, scope)?; - let components = scope_components(state, scope.subject_id); - digest(&ScopePreimage { - world_id: state.world_id, - subject_id: scope.subject_id, - controller, - affordances, - components: &components, + .is_some_and(|granted| granted.contains(&affordance)) + { + return Err(KernelError::AffordanceDenied); + } + let entry = state + .affordance_catalog + .get(&affordance) + .ok_or_else(|| KernelError::Invariant("granted affordance has no entry".into()))?; + Ok(GrantedAffordance { + id: affordance, + entry, }) - .map(ScopeDigest) -} - -/// Binding, which is one of the two checks a committed invocation passes. -/// Binding is scope-digest equality: has what the proposal was made against -/// moved? Admission — preconditions, effect ceilings, and the band draw, all in -/// `action::exercise` — is the other, and it runs at commit against the same -/// revision the digest was verified at. A component that admission reads but -/// binding does not is therefore fail-closed by re-check at commit rather than -/// by rejecting the proposal when it changes. -fn exact_opportunity( - state: &WorldState, - claimed: &DecisionOpportunity, -) -> Result<DecisionOpportunity, KernelError> { - if claimed.world_id != state.world_id { - return Err(KernelError::OpportunityMismatch); - } - let current = derive_opportunities(state)? - .into_iter() - .find(|current| current.scope == claimed.scope) - .ok_or(KernelError::OpportunityMismatch)?; - if claimed.revision > state.revision { - return Err(KernelError::OpportunityMismatch); - } - if current.scope_digest != claimed.scope_digest { - return Err(KernelError::ScopeChanged { - scope: claimed.scope, - expected: claimed.scope_digest.clone(), - actual: current.scope_digest, - }); - } - Ok(current) } fn required_approvers(state: &WorldState) -> BTreeSet<PrincipalId> { @@ -4513,6 +4072,7 @@ fn apply_effect( SystemCapability::Consumer { .. } | SystemCapability::Play, WorldEffect::PatchAdmitted { .. } ) + | (SystemCapability::Play, WorldEffect::Acted { .. }) ); if !admitted { return Err(KernelError::Unauthorized); @@ -4569,33 +4129,23 @@ fn apply_effect( } state.phase = WorldPhase::Active; } - WorldEffect::DecisionExercised { - opportunity, - invocation, - event, - } => { - let current = exact_opportunity(state, opportunity)?; - let assignment = state - .controller_assignments - .get(¤t.scope) - .ok_or_else(|| { - KernelError::Invariant("decision scope lost its controller".into()) - })?; + WorldEffect::Acted { invocation, event } => { if state.phase != WorldPhase::Active - || assignment.expected_caller().as_ref() != Some(caller) + || caller != &CallerId::System(SystemCapability::Play) { return Err(KernelError::Invariant( - "decision effect does not match exact opportunity authority".into(), + "acted effect does not match Play's authority".into(), )); } - let granted = require_granted(state, ¤t, invocation.affordance)?; + let granted = require_granted(state, event.actor, invocation.affordance)?; // The whole event is re-derived by the function that produced the // honest one, so a forged band, operation, magnitude, minted claim, // or utterance is one comparison rather than a clause apiece. - let derived = action::exercise(state, command_id, ¤t, &granted, invocation)?; + let derived = + action::exercise(state, command_id, event.actor, &granted, invocation)?; if derived != *event { return Err(KernelError::Invariant( - "decision effect does not derive from its opportunity".into(), + "acted effect does not derive from the actor's grants".into(), )); } state.events.push(event.clone()); @@ -4605,30 +4155,6 @@ fn apply_effect( // now; read it back rather than computing it a second time. apply_operations(state, &event.effects, &[], event.revision)?; } - state - .last_opportunity_at - .insert(current.scope.subject_id, state.now); - } - WorldEffect::DecisionDeclined { opportunity } => { - let current = exact_opportunity(state, opportunity)?; - let assignment = state - .controller_assignments - .get(¤t.scope) - .ok_or_else(|| { - KernelError::Invariant("decision scope lost its controller".into()) - })?; - if state.phase != WorldPhase::Active - || assignment.expected_caller().as_ref() != Some(caller) - { - return Err(KernelError::Invariant( - "decline effect does not match exact opportunity authority".into(), - )); - } - // A decline consumed the turn: a controller that keeps declining - // must not keep the head of the queue. - state - .last_opportunity_at - .insert(current.scope.subject_id, state.now); } WorldEffect::TimeAdvanced { minutes, @@ -6059,30 +5585,31 @@ mod tests { } } - pub(crate) fn opportunity_for( - snapshot: &WorldSnapshot, - subject_id: SubjectId, - ) -> DecisionOpportunity { - snapshot - .opportunities + /// The first entry the subject holds, in id order. + pub(crate) fn first_grant(snapshot: &WorldSnapshot, subject_id: SubjectId) -> AffordanceId { + *snapshot + .subjects .iter() - .find(|value| value.scope.subject_id == subject_id) - .expect("the subject has an opportunity") - .clone() + .find(|subject| subject.id == subject_id) + .expect("the subject exists") + .affordances + .first() + .expect("the subject holds an affordance") } - fn opportunity(snapshot: &WorldSnapshot, mode: ControllerMode) -> DecisionOpportunity { - snapshot - .opportunities + /// The first subject whose controller has this mode. + fn subject_by_mode(state: &WorldState, mode: ControllerMode) -> SubjectId { + state + .controller_assignments .iter() - .find(|value| value.controller_mode == mode) - .unwrap() - .clone() + .find(|(_, assignment)| assignment.mode() == Some(mode)) + .map(|(scope, _)| scope.subject_id) + .expect("a subject has this controller mode") } - fn speak(opportunity: &DecisionOpportunity, text: &str) -> DecisionInvocation { + pub(crate) fn speak(affordance: AffordanceId, text: &str) -> DecisionInvocation { DecisionInvocation { - affordance: opportunity.affordance_ids[0], + affordance, bindings: Vec::new(), proposed: Vec::new(), speech: Some(Statement::new(text).unwrap()), @@ -6090,238 +5617,50 @@ mod tests { } } - #[test] - fn external_opportunities_reject_nested_authority_claims() { - let opportunity = DecisionOpportunity { - world_id: WorldId::issue(), - revision: 4, - scope_digest: ScopeDigest::fixture("sha256:fixture"), - scope: DecisionScope { - subject_id: SubjectId::issue(), - }, - controller_id: ControllerId::issue(), - controller_mode: ControllerMode::NarrativePersona, - affordance_ids: vec![AffordanceId::issue()], - }; - let mut nested = serde_json::to_value(&opportunity).unwrap(); - nested["scope"]["caller"] = serde_json::json!("legacy-owner"); - assert!(serde_json::from_value::<DecisionOpportunity>(nested).is_err()); - - let mut outer = serde_json::to_value(&opportunity).unwrap(); - outer["callerId"] = serde_json::json!("legacy-controller"); - assert!(serde_json::from_value::<DecisionOpportunity>(outer).is_err()); + /// The one door for an act in tests: Play submits `Act` for the actor. + pub(crate) fn act_as( + kernel: &mut WorldKernel, + caller: CallerId, + actor: SubjectId, + invocation: DecisionInvocation, + ) -> Result<SubmitReceipt, KernelError> { + act_command(kernel, CommandId::new(), caller, actor, invocation) } - /// A commit elsewhere in the world does not discard a bound proposal: the - /// binding is the scope digest, and this scope did not change. - #[test] - fn an_unchanged_scope_commits_at_a_later_revision() { - let dir = tempfile::tempdir().unwrap(); - let (mut kernel, _) = WorldKernel::create( - dir.path().join("world.cc"), - creation(CommandId::new(), "Unchanged"), - &auth_principal(owner()), + pub(crate) fn act_command( + kernel: &mut WorldKernel, + command_id: CommandId, + caller: CallerId, + actor: SubjectId, + invocation: DecisionInvocation, + ) -> Result<SubmitReceipt, KernelError> { + let snapshot = kernel.snapshot().unwrap(); + kernel.submit( + command( + &snapshot, + command_id, + caller.clone(), + CommandBody::Act { actor, invocation }, + ), + &AuthenticatedCaller::fixture(caller), ) - .unwrap(); - let topology = admit_topology(&mut kernel); - let active = activate(&mut kernel); - let bound = opportunity_for(&active, topology.walker); - - let persona = opportunity(&active, ControllerMode::NarrativePersona); - let persona_caller = CallerId::Controller(persona.controller_id); - kernel - .submit( - command( - &active, - CommandId::new(), - persona_caller.clone(), - CommandBody::ExerciseDecision { - invocation: speak(&persona, "The yard is quiet."), - opportunity: persona, - }, - ), - &AuthenticatedCaller::fixture(persona_caller), - ) - .unwrap(); - let later = kernel.snapshot().unwrap(); - assert_eq!(later.revision, active.revision + 1); - - let walker_caller = CallerId::Controller(bound.controller_id); - let receipt = kernel - .submit( - command( - &later, - CommandId::new(), - walker_caller.clone(), - CommandBody::ExerciseDecision { - invocation: speak(&bound, "I take the ramp."), - opportunity: bound.clone(), - }, - ), - &AuthenticatedCaller::fixture(walker_caller), - ) - .unwrap(); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); - let after = kernel.state.events.clone(); - assert_eq!(after.len(), 2); - assert_eq!(after[1].revision, bound.revision + 2); } - /// Closing a route incident to the subject's place changes exactly what the - /// proposal's verification reads, so the bound proposal dies at the digest. - #[test] - fn a_changed_scope_is_rejected_with_scope_changed() { - let dir = tempfile::tempdir().unwrap(); - let (mut kernel, _) = WorldKernel::create( - dir.path().join("world.cc"), - creation(CommandId::new(), "Changed"), - &auth_principal(owner()), - ) - .unwrap(); - let topology = admit_topology(&mut kernel); - let active = activate(&mut kernel); - let bound = opportunity_for(&active, topology.walker); - - submit_owner( - &mut kernel, - &active, - CommandBody::AdmitPatch { - patch: WorldPatch { - declarations: Vec::new(), - operations: vec![ComponentOp::CloseRoute { - route: Ref::Existing(topology.ramp), - }], - evidence: Vec::new(), - }, - }, - ); - let closed = kernel.snapshot().unwrap(); - let walker_caller = CallerId::Controller(bound.controller_id); - let error = kernel - .submit( - command( - &closed, - CommandId::new(), - walker_caller.clone(), - CommandBody::ExerciseDecision { - invocation: speak(&bound, "I take the ramp."), - opportunity: bound.clone(), - }, - ), - &AuthenticatedCaller::fixture(walker_caller), - ) - .unwrap_err(); - let KernelError::ScopeChanged { - scope, - expected, - actual, - } = error - else { - panic!("expected a changed scope"); - }; - assert_eq!(scope, bound.scope); - assert_eq!(expected, bound.scope_digest); - assert_ne!(expected, actual); - assert_eq!(kernel.snapshot().unwrap(), closed); + pub(crate) fn play_caller() -> CallerId { + CallerId::System(SystemCapability::Play) } - /// The digest covers the scope's controller, its grants, its Position, and - /// its incident routes, and nothing else in the world. - #[test] - fn scope_digest_reads_exactly_its_components() { - let dir = tempfile::tempdir().unwrap(); - let (mut kernel, _) = WorldKernel::create( - dir.path().join("world.cc"), - creation(CommandId::new(), "Components"), - &auth_principal(owner()), + pub(crate) fn act( + kernel: &mut WorldKernel, + actor: SubjectId, + invocation: DecisionInvocation, + ) -> Result<SubmitReceipt, KernelError> { + act_as( + kernel, + CallerId::System(SystemCapability::Play), + actor, + invocation, ) - .unwrap(); - let topology = admit_topology(&mut kernel); - activate(&mut kernel); - let scope = DecisionScope { - subject_id: topology.walker, - }; - let base = scope_digest(&kernel.state, scope).unwrap(); - - let mut changed_controller = kernel.state.clone(); - let assignment = changed_controller - .controller_assignments - .get_mut(&scope) - .unwrap(); - *assignment = ControllerAssignment::NarrativePersona { - controller_id: assignment.id().expect("the fixture scope has a controller"), - }; - assert_ne!(scope_digest(&changed_controller, scope).unwrap(), base); - - let mut changed_grants = kernel.state.clone(); - let extra = AffordanceId::issue(); - changed_grants - .affordance_catalog - .insert(extra, patch::kernel_speak_entry()); - changed_grants - .affordance_grants - .entry(scope) - .or_default() - .insert(extra); - assert_ne!(scope_digest(&changed_grants, scope).unwrap(), base); - - // The digest reads the granted entries' definitions, not only their - // ids: admission reads preconditions and ceilings, so altering an entry - // must move the digest. - let mut changed_entry = kernel.state.clone(); - let granted = *kernel.state.affordance_grants[&scope].first().unwrap(); - changed_entry - .affordance_catalog - .get_mut(&granted) - .unwrap() - .carries_speech = false; - assert_ne!(scope_digest(&changed_entry, scope).unwrap(), base); - - let mut changed_position = kernel.state.clone(); - changed_position.positions.insert( - topology.walker, - Position { - place: topology.road, - }, - ); - assert_ne!(scope_digest(&changed_position, scope).unwrap(), base); - - let mut changed_route = kernel.state.clone(); - changed_route - .edges - .get_mut(&topology.ramp) - .unwrap() - .set_cost(Cost(99)); - assert_ne!(scope_digest(&changed_route, scope).unwrap(), base); - - // The span joins road and gate, so it is incident to neither the walker's - // place nor its scope; an unrelated subject's decision is invisible too. - let mut unrelated_route = kernel.state.clone(); - unrelated_route - .edges - .get_mut(&topology.span) - .unwrap() - .set_cost(Cost(99)); - assert_eq!(scope_digest(&unrelated_route, scope).unwrap(), base); - - let active = kernel.snapshot().unwrap(); - let persona = opportunity(&active, ControllerMode::NarrativePersona); - let persona_caller = CallerId::Controller(persona.controller_id); - kernel - .submit( - command( - &active, - CommandId::new(), - persona_caller.clone(), - CommandBody::ExerciseDecision { - invocation: speak(&persona, "Unrelated."), - opportunity: persona, - }, - ), - &AuthenticatedCaller::fixture(persona_caller), - ) - .unwrap(); - assert_eq!(scope_digest(&kernel.state, scope).unwrap(), base); } #[test] @@ -6337,27 +5676,16 @@ mod tests { let genesis = kernel.snapshot().unwrap(); assert_eq!(genesis.title, "Delvehold"); assert_eq!(genesis.phase, WorldPhase::Draft); - assert!(genesis.opportunities.is_empty()); - let active = activate(&mut kernel); assert_eq!(active.phase, WorldPhase::Active); - assert_eq!(active.opportunities.len(), 3); - let human_opportunity = opportunity(&active, ControllerMode::Human); - kernel - .submit( - command( - &active, - CommandId::new(), - CallerId::Principal(human_principal()), - CommandBody::ExerciseDecision { - invocation: speak(&human_opportunity, "I open the door."), - opportunity: human_opportunity, - }, - ), - &auth_principal(human_principal()), - ) - .unwrap(); + let human = subject_by_mode(&kernel.state, ControllerMode::Human); + act( + &mut kernel, + human, + speak(first_grant(&active, human), "I open the door."), + ) + .unwrap(); let after_human = kernel.snapshot().unwrap(); assert_eq!(kernel.state.events.len(), 1); assert_eq!( @@ -6365,30 +5693,15 @@ mod tests { Some("I open the door.") ); - let persona_opportunity = opportunity(&after_human, ControllerMode::NarrativePersona); - let persona_caller = CallerId::Controller(persona_opportunity.controller_id); - kernel - .submit( - command( - &after_human, - CommandId::new(), - persona_caller.clone(), - CommandBody::ExerciseDecision { - invocation: speak(&persona_opportunity, "Then mind the hinge."), - opportunity: persona_opportunity, - }, - ), - &AuthenticatedCaller::fixture(persona_caller), - ) - .unwrap(); - let after_persona = kernel.snapshot().unwrap(); + let persona = subject_by_mode(&kernel.state, ControllerMode::NarrativePersona); + act( + &mut kernel, + persona, + speak(first_grant(&after_human, persona), "Then mind the hinge."), + ) + .unwrap(); assert_eq!(kernel.state.events.len(), 2); - assert!( - after_persona - .opportunities - .iter() - .all(|value| value.revision == after_persona.revision) - ); + assert_eq!(kernel.state.events[1].actor, persona); } #[test] @@ -6458,132 +5771,17 @@ mod tests { let approved = kernel.snapshot().unwrap(); submit_owner(&mut kernel, &approved, CommandBody::ActivateWorld); let active = kernel.snapshot().unwrap(); - let persona = opportunity(&active, ControllerMode::NarrativePersona); + let persona = subject_by_mode(&kernel.state, ControllerMode::NarrativePersona); let commits_before_forgery = kernel.journal.commit_count(); - assert!(matches!( - kernel.submit( - command( - &active, - CommandId::new(), - CallerId::Principal(human_principal()), - CommandBody::ExerciseDecision { - invocation: speak(&persona, "Puppet"), - opportunity: persona, - }, - ), - &auth_principal(human_principal()) - ), - Err(KernelError::ControllerMismatch) - )); - assert_eq!(kernel.journal.commit_count(), commits_before_forgery); - assert_eq!(kernel.snapshot().unwrap(), active); - } - - #[test] - fn a_tampered_or_unknown_opportunity_never_commits() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("world.cc"); - let (mut kernel, _) = WorldKernel::create( - &path, - creation(CommandId::new(), "Exact"), - &auth_principal(owner()), + let error = act_as( + &mut kernel, + CallerId::Principal(human_principal()), + persona, + speak(first_grant(&active, persona), "Puppet"), ) - .unwrap(); - let active = activate(&mut kernel); - let original = opportunity(&active, ControllerMode::Human); - // An entry only the operational subject is granted: the human's scope - // does not hold it, which is what denial means now that an affordance id - // names a catalog entry rather than one subject's copy of one. - let denied_invocation = DecisionInvocation { - affordance: affordance_named(&active, "convene"), - bindings: Vec::new(), - proposed: Vec::new(), - speech: Some(Statement::new("No grant").unwrap()), - display: None, - }; - assert!(matches!( - kernel.submit( - command( - &active, - CommandId::new(), - CallerId::Principal(human_principal()), - CommandBody::ExerciseDecision { - invocation: denied_invocation, - opportunity: original.clone(), - }, - ), - &auth_principal(human_principal()) - ), - Err(KernelError::AffordanceDenied) - )); - // A claimed affordance the world did not grant carries no authority: the - // kernel exercises the opportunity it derives, never the one submitted. - let forged_affordance = AffordanceId::issue(); - let mut tampered = original.clone(); - tampered.affordance_ids.push(forged_affordance); - assert!(matches!( - kernel.submit( - command( - &active, - CommandId::new(), - CallerId::Principal(human_principal()), - CommandBody::ExerciseDecision { - invocation: DecisionInvocation { - affordance: forged_affordance, - bindings: Vec::new(), - proposed: Vec::new(), - speech: Some(Statement::new("Forged").unwrap()), - display: None, - }, - opportunity: tampered, - }, - ), - &auth_principal(human_principal()) - ), - Err(KernelError::AffordanceDenied) - )); - assert_eq!(kernel.snapshot().unwrap(), active); - - let mut forged_scope = original.clone(); - forged_scope.scope_digest = ScopeDigest::fixture("sha256:not-this-scope"); - assert!(matches!( - kernel.submit( - command( - &active, - CommandId::new(), - CallerId::Principal(human_principal()), - CommandBody::ExerciseDecision { - invocation: speak(&original, "No"), - opportunity: forged_scope, - }, - ), - &auth_principal(human_principal()) - ), - Err(KernelError::ScopeChanged { .. }) - )); - assert_eq!(kernel.snapshot().unwrap(), active); - - let unknown_scope = DecisionOpportunity { - scope: DecisionScope { - subject_id: SubjectId::issue(), - }, - ..original.clone() - }; - assert!(matches!( - kernel.submit( - command( - &active, - CommandId::new(), - CallerId::Principal(human_principal()), - CommandBody::ExerciseDecision { - invocation: speak(&original, "No"), - opportunity: unknown_scope, - }, - ), - &auth_principal(human_principal()) - ), - Err(KernelError::OpportunityMismatch) - )); + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + assert_eq!(kernel.journal.commit_count(), commits_before_forgery); assert_eq!(kernel.snapshot().unwrap(), active); } @@ -6595,15 +5793,15 @@ mod tests { let (mut kernel, creation_receipt) = WorldKernel::create(&path, creation.clone(), &auth_principal(owner())).unwrap(); let active = activate(&mut kernel); - let decision = opportunity(&active, ControllerMode::OperationalAgent); - let caller = CallerId::Controller(decision.controller_id); + let operator = subject_by_mode(&kernel.state, ControllerMode::OperationalAgent); + let caller = play_caller(); let command = command( &active, CommandId::new(), caller.clone(), - CommandBody::ExerciseDecision { - invocation: speak(&decision, "The vote carries."), - opportunity: decision, + CommandBody::Act { + actor: operator, + invocation: speak(first_grant(&active, operator), "The vote carries."), }, ); let applied = kernel @@ -6633,152 +5831,6 @@ mod tests { assert_eq!(reopened.snapshot().unwrap(), accepted); } - #[test] - fn controller_receipt_is_bound_to_the_exact_opportunity_and_invocation() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("world.cc"); - let (mut kernel, _) = WorldKernel::create( - &path, - creation(CommandId::new(), "Receipt Scope"), - &auth_principal(owner()), - ) - .unwrap(); - let active = activate(&mut kernel); - let decision = opportunity(&active, ControllerMode::OperationalAgent); - let other = opportunity(&active, ControllerMode::NarrativePersona); - let command_id = CommandId::new(); - let caller = CallerId::Controller(decision.controller_id); - let invocation = speak(&decision, "The record is exact."); - kernel - .submit( - command( - &active, - command_id, - caller.clone(), - CommandBody::ExerciseDecision { - invocation: invocation.clone(), - opportunity: decision.clone(), - }, - ), - &AuthenticatedCaller::fixture(caller), - ) - .unwrap(); - - let receipt = kernel - .controller_receipt(command_id, &decision, &invocation) - .unwrap() - .expect("committed controller command has a receipt"); - assert_eq!(receipt.command_id, command_id); - assert!( - kernel - .controller_receipt(CommandId::new(), &decision, &invocation) - .unwrap() - .is_none() - ); - assert!(matches!( - kernel.controller_receipt(command_id, &other, &invocation), - Err(KernelError::CommandIdConflict) - )); - let altered_invocation = speak(&decision, "A different proposal."); - assert!(matches!( - kernel.controller_receipt(command_id, &decision, &altered_invocation), - Err(KernelError::CommandIdConflict) - )); - } - - #[test] - fn controller_decline_consumes_only_its_exact_opportunity() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("world.cc"); - let (mut kernel, _) = WorldKernel::create( - &path, - creation(CommandId::new(), "Decline Scope"), - &auth_principal(owner()), - ) - .unwrap(); - let active = activate(&mut kernel); - let decision = opportunity(&active, ControllerMode::OperationalAgent); - let other = opportunity(&active, ControllerMode::NarrativePersona); - let caller = CallerId::Controller(decision.controller_id); - - assert!(matches!( - kernel.submit( - command( - &active, - CommandId::new(), - CallerId::Controller(other.controller_id), - CommandBody::DeclineDecision { - opportunity: decision.clone(), - }, - ), - &AuthenticatedCaller::fixture(CallerId::Controller(other.controller_id)), - ), - Err(KernelError::ControllerMismatch) - )); - assert_eq!(kernel.snapshot().unwrap(), active); - - let command_id = CommandId::new(); - let decline = command( - &active, - command_id, - caller.clone(), - CommandBody::DeclineDecision { - opportunity: decision.clone(), - }, - ); - let SubmitReceipt::Applied(receipt) = kernel - .submit( - decline.clone(), - &AuthenticatedCaller::fixture(caller.clone()), - ) - .unwrap() - else { - panic!("exact decline was not applied") - }; - let after = kernel.snapshot().unwrap(); - assert_eq!(after.revision, active.revision + 1); - assert!(kernel.state.events.is_empty()); - let refreshed = opportunity(&after, ControllerMode::OperationalAgent); - assert_ne!(refreshed, decision); - assert_eq!( - kernel - .controller_decline_receipt(command_id, &decision) - .unwrap(), - Some(receipt.clone()) - ); - assert!(matches!( - kernel.controller_decline_receipt(command_id, &other), - Err(KernelError::CommandIdConflict) - )); - assert!(matches!( - kernel.controller_receipt( - command_id, - &decision, - &speak(&decision, "A decline is not speech."), - ), - Err(KernelError::CommandIdConflict) - )); - assert_eq!( - kernel - .submit(decline, &AuthenticatedCaller::fixture(caller.clone())) - .unwrap(), - SubmitReceipt::AlreadyApplied(receipt.clone()) - ); - assert_eq!(kernel.snapshot().unwrap(), after); - drop(kernel); - let reopened = WorldKernel::open(&path, after.world_id).unwrap(); - assert_eq!(reopened.snapshot().unwrap(), after); - assert_eq!( - reopened - .controller_decline_receipt( - command_id, - &opportunity(&active, ControllerMode::OperationalAgent), - ) - .unwrap(), - Some(receipt) - ); - } - #[test] fn duplicate_and_stale_commands_do_not_commit() { let dir = tempfile::tempdir().unwrap(); @@ -7082,7 +6134,7 @@ mod tests { /// and every component outside the scope. Each step below is a real commit /// that moves the world, not a hand-edited state. #[test] - fn soul_scope_digest_excludes_revision_phase_and_everything_outside_the_scope() { + fn soul_scope_components_exclude_revision_phase_and_everything_outside_the_scope() { let dir = tempfile::tempdir().unwrap(); let (mut kernel, _) = WorldKernel::create( dir.path().join("world.cc"), @@ -7094,7 +6146,7 @@ mod tests { let scope = DecisionScope { subject_id: topology.walker, }; - let base = scope_digest(&kernel.state, scope).unwrap(); + let base = scope_components(&kernel.state, scope.subject_id); let start_revision = kernel.state.revision; // A new place elsewhere, a route that touches neither the walker's @@ -7137,12 +6189,12 @@ mod tests { }, ); assert_ne!(kernel.state.revision, start_revision); - assert_eq!(scope_digest(&kernel.state, scope).unwrap(), base); + assert_eq!(scope_components(&kernel.state, scope.subject_id), base); // Activation changes the phase, the approvals, and the revision. let active = activate(&mut kernel); assert_eq!(active.phase, WorldPhase::Active); - assert_eq!(scope_digest(&kernel.state, scope).unwrap(), base); + assert_eq!(scope_components(&kernel.state, scope.subject_id), base); // Another subject's Position moving is not this scope's business. let annexway = *kernel @@ -7186,7 +6238,7 @@ mod tests { .unwrap() }) ); - assert_eq!(scope_digest(&kernel.state, scope).unwrap(), base); + assert_eq!(scope_components(&kernel.state, scope.subject_id), base); // A route incident to the walker's own place is inside the scope. let moved = kernel.snapshot().unwrap(); @@ -7203,55 +6255,7 @@ mod tests { }, }, ); - assert_ne!(scope_digest(&kernel.state, scope).unwrap(), base); - } - - /// Soul falsification: a claimed opportunity whose `affordance_ids` name - /// grants this scope does not hold cannot widen authority. The kernel reads - /// the derived list, so the forged one is ignored and the invocation is - /// denied on the real grants. - #[test] - fn soul_a_forged_affordance_list_cannot_widen_authority() { - let dir = tempfile::tempdir().unwrap(); - let (mut kernel, _) = WorldKernel::create( - dir.path().join("world.cc"), - creation(CommandId::new(), "Affordances"), - &auth_principal(owner()), - ) - .unwrap(); - let active = activate(&mut kernel); - let persona = opportunity(&active, ControllerMode::NarrativePersona); - let operator = opportunity(&active, ControllerMode::OperationalAgent); - - // The persona claims the operator's entry and lists it as its own. - let convened = affordance_named(&active, "convene"); - assert!(operator.affordance_ids.contains(&convened)); - assert!(!persona.affordance_ids.contains(&convened)); - let mut forged = persona.clone(); - forged.affordance_ids = vec![convened, persona.affordance_ids[0]]; - let caller = CallerId::Controller(persona.controller_id); - let error = kernel - .submit( - command( - &active, - CommandId::new(), - caller.clone(), - CommandBody::ExerciseDecision { - opportunity: forged, - invocation: DecisionInvocation { - affordance: convened, - bindings: Vec::new(), - proposed: Vec::new(), - speech: Some(Statement::new("Not my grant.").unwrap()), - display: None, - }, - }, - ), - &AuthenticatedCaller::fixture(caller), - ) - .unwrap_err(); - assert!(matches!(error, KernelError::AffordanceDenied)); - assert_eq!(kernel.snapshot().unwrap(), active); + assert_ne!(scope_components(&kernel.state, scope.subject_id), base); } /// Soul: an `AffordanceId` now names a catalog entry, not a subject's copy @@ -7260,7 +6264,7 @@ mod tests { /// same `convene` id commits for the scope that holds it and is denied for /// one that does not. #[test] - fn soul_a_shared_catalog_id_is_gated_by_the_scope_grant() { + fn act_needs_the_actors_grant() { let dir = tempfile::tempdir().unwrap(); let (mut kernel, _) = WorldKernel::create( dir.path().join("world.cc"), @@ -7280,12 +6284,6 @@ mod tests { .iter() .all(|subject| subject.affordances.contains(&speak)) ); - assert!( - active - .opportunities - .iter() - .all(|opportunity| opportunity.affordance_ids.contains(&speak)) - ); let holders: Vec<SubjectId> = active .subjects .iter() @@ -7294,57 +6292,44 @@ mod tests { .collect(); assert_eq!(holders.len(), 1); - let invoke = |kernel: &mut WorldKernel, snapshot: &WorldSnapshot, subject: SubjectId| { - let opportunity = opportunity_for(snapshot, subject); - let caller = CallerId::Controller(opportunity.controller_id); - kernel.submit( - command( - snapshot, - CommandId::new(), - caller.clone(), - CommandBody::ExerciseDecision { - opportunity, - invocation: DecisionInvocation { - affordance: convened, - bindings: Vec::new(), - proposed: Vec::new(), - speech: Some(Statement::new("The council convenes.").unwrap()), - display: None, - }, - }, - ), - &AuthenticatedCaller::fixture(caller), + let invoke = |kernel: &mut WorldKernel, subject: SubjectId| { + act( + kernel, + subject, + DecisionInvocation { + affordance: convened, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("The council convenes.").unwrap()), + display: None, + }, ) }; // The grantee's scope commits with that id. assert!(matches!( - invoke(&mut kernel, &active, holders[0]).unwrap(), + invoke(&mut kernel, holders[0]).unwrap(), SubmitReceipt::Applied(_) )); // A scope that does not hold the entry is denied the very same id, and // nothing commits. let after = kernel.snapshot().unwrap(); - // A controller-driven scope, so the denial is the grant check rather - // than the human lane's caller check reached first. let stranger = after .subjects .iter() - .find(|subject| { - !subject.affordances.contains(&convened) && subject.human_controller.is_none() - }) - .expect("a controller-driven subject without the grant") + .find(|subject| !subject.affordances.contains(&convened)) + .expect("a subject without the grant") .id; assert!(matches!( - invoke(&mut kernel, &after, stranger).unwrap_err(), + invoke(&mut kernel, stranger).unwrap_err(), KernelError::AffordanceDenied )); assert_eq!(kernel.snapshot().unwrap(), after); } #[test] - fn a_stale_grant_rejects_but_a_distant_route_reaches_admission_instead() { + fn a_distant_route_closing_leaves_the_actors_scope_alone_and_its_act_commits() { let dir = tempfile::tempdir().unwrap(); let (mut kernel, _) = WorldKernel::create( dir.path().join("world.cc"), @@ -7354,28 +6339,12 @@ mod tests { .unwrap(); let topology = admit_topology(&mut kernel); let active = activate(&mut kernel); - let bound = opportunity_for(&active, topology.walker); let speak = affordance_named(&active, "speak"); - // Binding is scope-digest equality, and the digest reads the granted - // entries' definitions: altering one moves the digest, so a proposal - // bound before that change no longer binds. - let mut altered = kernel.state.clone(); - altered - .affordance_catalog - .get_mut(&speak) - .expect("the Speak entry") - .carries_speech = false; - assert_ne!( - scope_digest(&altered, bound.scope).unwrap(), - scope_digest(&kernel.state, bound.scope).unwrap() - ); - - // A route the actor does not stand beside is outside the digest, so - // closing it leaves the binding intact. That is deliberate: admission - // re-reads the live graph at commit, so nothing commits on stale - // topology and a proposal is not invalidated by distant traffic. - let before_digest = scope_digest(&kernel.state, bound.scope).unwrap(); + // A route the actor does not stand beside is outside its scope. + // Admission re-reads the live graph at commit, so nothing commits on + // stale topology. + let before_components = scope_components(&kernel.state, topology.walker); let before = kernel.snapshot().unwrap(); submit_owner( &mut kernel, @@ -7385,32 +6354,23 @@ mod tests { }]), ); assert_eq!( - scope_digest(&kernel.state, bound.scope).unwrap(), - before_digest, - "a route outside the actor's incident set does not rebind the proposal" + scope_components(&kernel.state, topology.walker), + before_components, + "a route outside the actor's incident set is not in its scope" ); - let snapshot = kernel.snapshot().unwrap(); - let receipt = kernel - .submit( - command( - &snapshot, - CommandId::new(), - CallerId::Controller(bound.controller_id), - CommandBody::ExerciseDecision { - opportunity: bound.clone(), - invocation: DecisionInvocation { - affordance: speak, - bindings: Vec::new(), - proposed: Vec::new(), - speech: Some(Statement::new("Still here.").unwrap()), - display: None, - }, - }, - ), - &AuthenticatedCaller::fixture(CallerId::Controller(bound.controller_id)), - ) - .expect("a distant route closing does not rebind this proposal"); + let receipt = act( + &mut kernel, + topology.walker, + DecisionInvocation { + affordance: speak, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("Still here.").unwrap()), + display: None, + }, + ) + .expect("a distant route closing does not stop this act"); assert!(matches!(receipt, SubmitReceipt::Applied(_))); } @@ -7423,25 +6383,15 @@ mod tests { let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "Two"); let (_, civic, active) = civic_world(&mut kernel); - let treasury = opportunity_for(&active, civic.treasury); - let reeve = opportunity_for(&active, civic.reeve); - assert_ne!(treasury.controller_id, reeve.controller_id); - assert_eq!( + let controller_of = |subject_id: SubjectId| { active - .opportunities + .subjects .iter() - .filter(|value| value.scope.subject_id == civic.treasury) - .count(), - 1 - ); - assert_eq!( - active - .opportunities - .iter() - .filter(|value| value.scope.subject_id == civic.reeve) - .count(), - 1 - ); + .find(|subject| subject.id == subject_id) + .unwrap() + .controller_id + }; + assert_ne!(controller_of(civic.treasury), controller_of(civic.reeve)); // Both are authorized over the hall — one directly, one by delegation — // and neither appears in the other's components. @@ -7482,16 +6432,15 @@ mod tests { let edges = kernel.state.edges.clone(); let entities = kernel.state.entities.clone(); - let opportunity = opportunity_for(&active, civic.treasury); - let caller = CallerId::Controller(opportunity.controller_id); + let caller = play_caller(); let receipt = kernel .submit( command( &active, CommandId::new(), caller.clone(), - CommandBody::ExerciseDecision { - opportunity, + CommandBody::Act { + actor: civic.treasury, invocation: DecisionInvocation { affordance: affordance_named(&active, "levy"), bindings: vec![ @@ -7780,13 +6729,12 @@ mod tests { /// The digest reads what the actor is authorized over and nothing about the /// world the actor reaches. #[test] - fn scope_digest_reads_authority_and_delegation_but_not_occupancy() { + fn scope_components_read_authority_and_delegation_but_not_occupancy() { let directory = tempfile::tempdir().unwrap(); let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "Digest"); let (topology, civic, _) = civic_world(&mut kernel); - let scope = |subject_id| DecisionScope { subject_id }; let digest_of = |kernel: &WorldKernel, subject_id| { - scope_digest(&kernel.state, scope(subject_id)).unwrap() + scope_components(&kernel.state, subject_id) }; let admit = |kernel: &mut WorldKernel, ops: Vec<ComponentOp>| { let before = kernel.snapshot().unwrap(); @@ -8022,9 +6970,9 @@ mod tests { #[cfg(test)] mod custody_tests { use super::tests::{ - OPENING_BALANCE, TITHE_RECEIPT, activate, admit_custody, admit_topology, auth_principal, - command, creation, custody_world, operations, opportunity_for, owner, reject_owner, - speak_entry, submit_owner, + OPENING_BALANCE, TITHE_RECEIPT, act, activate, admit_custody, admit_topology, + auth_principal, creation, custody_world, first_grant, operations, owner, reject_owner, + speak, speak_entry, submit_owner, }; use super::*; @@ -8485,7 +7433,7 @@ mod custody_tests { /// The digest reads the acting subject's own holdings and dependencies, and /// only its own: a counterparty's churn does not move it. #[test] - fn scope_digest_reads_holdings_and_dependencies() { + fn scope_components_read_holdings_and_dependencies() { let directory = tempfile::tempdir().unwrap(); let mut kernel = custody_kernel(directory.path(), "ScopeCustody"); let topology = admit_topology(&mut kernel); @@ -8494,15 +7442,15 @@ mod custody_tests { let scope = DecisionScope { subject_id: custody.holder, }; - let base = scope_digest(&kernel.state, scope).unwrap(); + let base = scope_components(&kernel.state, scope.subject_id); let mut spent = kernel.state.clone(); set_held(&mut spent, custody.holder, custody.tithe, 1); - assert_ne!(scope_digest(&spent, scope).unwrap(), base); + assert_ne!(scope_components(&spent, scope.subject_id), base); let mut gained = kernel.state.clone(); set_held(&mut gained, custody.holder, custody.ingot, 1); - assert_ne!(scope_digest(&gained, scope).unwrap(), base); + assert_ne!(scope_components(&gained, scope.subject_id), base); let mut bound = kernel.state.clone(); bound @@ -8510,7 +7458,7 @@ mod custody_tests { .entry(custody.holder) .or_default() .insert(DependencyTarget::Resource(custody.tithe)); - assert_ne!(scope_digest(&bound, scope).unwrap(), base); + assert_ne!(scope_components(&bound, scope.subject_id), base); let mut elsewhere = kernel.state.clone(); set_held(&mut elsewhere, custody.counterparty, custody.tithe, 9); @@ -8519,56 +7467,7 @@ mod custody_tests { .entry(custody.counterparty) .or_default() .insert(DependencyTarget::Resource(custody.ingot)); - assert_eq!(scope_digest(&elsewhere, scope).unwrap(), base); - } - - /// A proposal bound while its subject held seven must not commit after - /// someone took six. Custody churn rejects more bound proposals than route - /// churn did; that is the binding working. - #[test] - fn a_spend_bound_to_a_stale_balance_is_rejected() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = custody_kernel(directory.path(), "Stale"); - let (_, custody, active) = custody_world(&mut kernel); - let bound = opportunity_for(&active, custody.holder); - - submit_owner( - &mut kernel, - &active, - operations(vec![ComponentOp::Transfer { - from: Ref::Existing(custody.holder), - to: Ref::Existing(custody.counterparty), - resource: Ref::Existing(custody.tithe), - qty: Quantity(6), - }]), - ); - - let moved = kernel.snapshot().unwrap(); - let commits = kernel.journal.commit_count(); - let error = kernel - .submit( - command( - &moved, - CommandId::new(), - CallerId::Controller(bound.controller_id), - CommandBody::ExerciseDecision { - opportunity: bound.clone(), - invocation: DecisionInvocation { - affordance: bound.affordance_ids[0], - bindings: Vec::new(), - proposed: Vec::new(), - speech: Some(Statement::new("The tithe is short.").unwrap()), - display: None, - }, - }, - ), - &AuthenticatedCaller::fixture(CallerId::Controller(bound.controller_id)), - ) - .unwrap_err(); - - assert!(matches!(error, KernelError::ScopeChanged { .. })); - assert_eq!(kernel.journal.commit_count(), commits); - assert_eq!(kernel.snapshot().unwrap(), moved); + assert_eq!(scope_components(&elsewhere, scope.subject_id), base); } /// Soul, proof 4: the ledger equation stated as arithmetic over the @@ -8814,16 +7713,15 @@ mod custody_tests { assert_eq!(kernel.snapshot().unwrap(), before); } - /// Soul, scope: a transfer changes the *receiver's* components too, so the - /// counterparty's in-flight proposal is refused with `ScopeChanged` while an - /// unrelated subject's bound proposal still commits at the later revision. + /// Soul, scope: a transfer changes the *receiver's* components too, and + /// no unrelated subject's, whose act still commits at the later revision. #[test] fn soul_an_incoming_transfer_changes_only_the_counterpartys_scope() { let directory = tempfile::tempdir().unwrap(); let mut kernel = custody_kernel(directory.path(), "IncomingScope"); let (topology, custody, active) = custody_world(&mut kernel); - let receiver = opportunity_for(&active, custody.counterparty); - let bystander = opportunity_for(&active, topology.walker); + let receiver_before = scope_components(&kernel.state, custody.counterparty); + let bystander_before = scope_components(&kernel.state, topology.walker); submit_owner( &mut kernel, @@ -8837,44 +7735,23 @@ mod custody_tests { ); let moved = kernel.snapshot().unwrap(); - let exercise = |opportunity: &DecisionOpportunity| CommandBody::ExerciseDecision { - opportunity: opportunity.clone(), - invocation: DecisionInvocation { - affordance: opportunity.affordance_ids[0], - bindings: Vec::new(), - proposed: Vec::new(), - speech: Some(Statement::new("Counted before the tithe arrived.").unwrap()), - display: None, - }, - }; - - let error = kernel - .submit( - command( - &moved, - CommandId::new(), - CallerId::Controller(receiver.controller_id), - exercise(&receiver), - ), - &AuthenticatedCaller::fixture(CallerId::Controller(receiver.controller_id)), - ) - .unwrap_err(); - assert!( - matches!(error, KernelError::ScopeChanged { .. }), - "the receiver's holdings moved under its bound proposal: {error:?}" + assert_ne!( + scope_components(&kernel.state, custody.counterparty), + receiver_before, + "the receiver's holdings moved" + ); + assert_eq!( + scope_components(&kernel.state, topology.walker), + bystander_before, + "an unrelated subject's scope is untouched by the transfer" ); - let receipt = kernel - .submit( - command( - &moved, - CommandId::new(), - CallerId::Controller(bystander.controller_id), - exercise(&bystander), - ), - &AuthenticatedCaller::fixture(CallerId::Controller(bystander.controller_id)), - ) - .expect("an unrelated subject's bound proposal is untouched by the transfer"); + let receipt = act( + &mut kernel, + topology.walker, + speak(first_grant(&moved, topology.walker), "Unmoved."), + ) + .expect("an unrelated subject acts at the later revision"); assert!(matches!(receipt, SubmitReceipt::Applied(_))); } } @@ -8886,9 +7763,9 @@ mod custody_tests { mod knowledge_tests { use super::patch::{RefName, Site}; use super::tests::{ - affordance_named, + act, play_caller, affordance_named, FLOOD_EVIDENCE, FLOOD_STATEMENT, Speech, auth_principal, command, creation, operations, - opportunity_for, owner, reject_owner, speech_world, spoken, submit_owner, + owner, reject_owner, speech_world, spoken, submit_owner, }; use super::*; use std::path::Path; @@ -8907,24 +7784,10 @@ mod knowledge_tests { fn utter( kernel: &mut WorldKernel, - snapshot: &WorldSnapshot, actor: SubjectId, invocation: DecisionInvocation, ) -> Result<SubmitReceipt, KernelError> { - let opportunity = opportunity_for(snapshot, actor); - let caller = CallerId::Controller(opportunity.controller_id); - kernel.submit( - command( - snapshot, - CommandId::new(), - caller.clone(), - CommandBody::ExerciseDecision { - opportunity, - invocation, - }, - ), - &AuthenticatedCaller::fixture(caller), - ) + act(kernel, actor, invocation) } fn say(affordance: AffordanceId, bindings: Vec<RoleBinding>, text: &str) -> DecisionInvocation { @@ -9119,11 +7982,8 @@ mod knowledge_tests { #[test] fn evidenced_knowledge_of_a_claim_is_rejected() { let directory = tempfile::tempdir().unwrap(); - let (mut kernel, speech, active) = speech_kernel(directory.path(), "Evidenced"); - utter( - &mut kernel, - &active, - speech.speaker, + let (mut kernel, speech, _) = speech_kernel(directory.path(), "Evidenced"); + utter(&mut kernel, speech.speaker, say( speech.proclaim, vec![binding("channel", Target::Entity(speech.horn))], @@ -9173,10 +8033,7 @@ mod knowledge_tests { fn speak_fans_out_to_the_audience_and_not_beyond() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, speech, active) = speech_kernel(directory.path(), "FanOut"); - utter( - &mut kernel, - &active, - speech.speaker, + utter(&mut kernel, speech.speaker, say( speech.whisper, vec![binding("target", Target::Subject(speech.listener))], @@ -9218,11 +8075,8 @@ mod knowledge_tests { #[test] fn co_location_reach_is_the_exact_place_and_a_channel_place_is_the_subtree() { let directory = tempfile::tempdir().unwrap(); - let (mut kernel, speech, active) = speech_kernel(directory.path(), "Reach"); - utter( - &mut kernel, - &active, - speech.speaker, + let (mut kernel, speech, _) = speech_kernel(directory.path(), "Reach"); + utter(&mut kernel, speech.speaker, say( speech.proclaim, vec![binding("channel", Target::Entity(speech.horn))], @@ -9236,11 +8090,7 @@ mod knowledge_tests { assert_eq!(knows(&kernel, speech.stranger, broadcast), None); // The same speaker's voice reaches only the hall. - let active = kernel.snapshot().unwrap(); - utter( - &mut kernel, - &active, - speech.speaker, + utter(&mut kernel, speech.speaker, say( speech.whisper, vec![binding("target", Target::Subject(speech.listener))], @@ -9262,11 +8112,7 @@ mod knowledge_tests { via: Ref::Existing(speech.stair), }]), ); - let active = kernel.snapshot().unwrap(); - utter( - &mut kernel, - &active, - speech.speaker, + utter(&mut kernel, speech.speaker, say( speech.whisper, vec![binding("target", Target::Subject(speech.bystander))], @@ -9283,12 +8129,9 @@ mod knowledge_tests { #[test] fn speaking_into_an_empty_room_commits_the_claim_and_lands_nothing() { let directory = tempfile::tempdir().unwrap(); - let (mut kernel, speech, active) = speech_kernel(directory.path(), "EmptyRoom"); + let (mut kernel, speech, _) = speech_kernel(directory.path(), "EmptyRoom"); let knowledge_before = kernel.state.knowledge.clone(); - utter( - &mut kernel, - &active, - speech.bystander, + utter(&mut kernel, speech.bystander, say( speech.whisper, vec![binding("target", Target::Subject(speech.bystander))], @@ -9339,10 +8182,7 @@ mod knowledge_tests { fn a_display_is_seen_by_the_room_and_by_no_one_else() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, speech, active) = speech_kernel(directory.path(), "Display"); - utter( - &mut kernel, - &active, - speech.speaker, + utter(&mut kernel, speech.speaker, show( speech.proclaim, vec![binding("channel", Target::Entity(speech.horn))], @@ -9374,7 +8214,7 @@ mod knowledge_tests { assert_eq!(knows(&kernel, blind, seen), None); } // One act minted both claims, so the listener's snapshot stamps both - // rows with the one revision, and the operator's feed carries both. + // rows with the one revision. let snapshot = kernel.snapshot().unwrap(); let listener = snapshot .subjects @@ -9388,9 +8228,6 @@ mod knowledge_tests { .map(|row| row.minted_at) .collect(); assert_eq!(stamps, BTreeSet::from([Some(event.revision)])); - let log = kernel.operator_log().unwrap(); - assert_eq!(log.last().unwrap().speech.as_ref().unwrap().as_str(), "The horn carries."); - assert_eq!(log.last().unwrap().display.as_ref().unwrap().as_str(), "I fold my arms."); } /// A silent turn: the kernel `speak` entry invoked with no utterance and a @@ -9402,10 +8239,7 @@ mod knowledge_tests { let directory = tempfile::tempdir().unwrap(); let (mut kernel, speech, active) = speech_kernel(directory.path(), "Silent"); let speak = affordance_named(&active, "speak"); - utter( - &mut kernel, - &active, - speech.speaker, + utter(&mut kernel, speech.speaker, show(speak, Vec::new(), None, "I nod toward the stair."), ) .expect("a silent act commits"); @@ -9418,12 +8252,8 @@ mod knowledge_tests { ); assert_eq!(claimed(&kernel), 1); - let active = kernel.snapshot().unwrap(); let knowledge_before = kernel.state.knowledge.clone(); - utter( - &mut kernel, - &active, - speech.bystander, + utter(&mut kernel, speech.bystander, show(speak, Vec::new(), None, "I sit on the step."), ) .expect("a display into an empty room commits"); @@ -9444,7 +8274,7 @@ mod knowledge_tests { let mut padded = show(speak, Vec::new(), None, "placeholder"); padded.display = Some(serde_json::from_str::<Statement>("\" \"").unwrap()); assert_eq!( - rejected(utter(&mut kernel, &active, speech.speaker, padded)), + rejected(utter(&mut kernel, speech.speaker, padded)), vec![ActionMismatch::EmptyDisplay] ); let mute = DecisionInvocation { @@ -9455,14 +8285,11 @@ mod knowledge_tests { display: None, }; assert_eq!( - rejected(utter(&mut kernel, &active, speech.speaker, mute)), + rejected(utter(&mut kernel, speech.speaker, mute)), vec![ActionMismatch::SpeechRequired] ); assert_eq!( - rejected(utter( - &mut kernel, - &active, - speech.stranger, + rejected(utter(&mut kernel, speech.stranger, show(speak, Vec::new(), None, "I shrug."), )), vec![ActionMismatch::NoAudience { precondition: 0 }] @@ -9487,18 +8314,11 @@ mod knowledge_tests { .0; let (speech, active) = speech_world(&mut kernel); let speak = affordance_named(&active, "speak"); - utter( - &mut kernel, - &active, - speech.speaker, + utter(&mut kernel, speech.speaker, show(speak, Vec::new(), Some("One."), "I raise one finger."), ) .expect("the act commits"); - let active = kernel.snapshot().unwrap(); - utter( - &mut kernel, - &active, - speech.listener, + utter(&mut kernel, speech.listener, show(speak, Vec::new(), None, "I look away."), ) .expect("the silent act commits"); @@ -9545,8 +8365,7 @@ mod knowledge_tests { "The horn still carries.", ) }; - let active = kernel.snapshot().unwrap(); - utter(&mut kernel, &active, speech.speaker, proclaim()) + utter(&mut kernel, speech.speaker, proclaim()) .expect("the controller may speak on its own channel"); let active = kernel.snapshot().unwrap(); @@ -9558,9 +8377,8 @@ mod knowledge_tests { controller: None, }]), ); - let active = kernel.snapshot().unwrap(); assert_eq!( - rejected(utter(&mut kernel, &active, speech.speaker, proclaim())), + rejected(utter(&mut kernel, speech.speaker, proclaim())), vec![ActionMismatch::NoAudience { precondition: 0 }] ); } @@ -9580,7 +8398,7 @@ mod knowledge_tests { ) }; assert_eq!( - rejected(utter(&mut kernel, &active, speech.speaker, whisper())), + rejected(utter(&mut kernel, speech.speaker, whisper())), vec![ActionMismatch::CannotReach { precondition: 0 }] ); @@ -9592,8 +8410,7 @@ mod knowledge_tests { via: Ref::Existing(speech.stair), }]), ); - let active = kernel.snapshot().unwrap(); - utter(&mut kernel, &active, speech.speaker, whisper()) + utter(&mut kernel, speech.speaker, whisper()) .expect("the addressed subject is now in the room"); let claim = minted_claim(&kernel); assert!(knows(&kernel, speech.bystander, claim).is_some()); @@ -9620,7 +8437,7 @@ mod knowledge_tests { display: None, }; assert_eq!( - rejected(utter(&mut kernel, &active, speech.listener, recant())), + rejected(utter(&mut kernel, speech.listener, recant())), vec![ActionMismatch::FactUnknown { precondition: 0 }] ); @@ -9636,7 +8453,7 @@ mod knowledge_tests { ); let active = kernel.snapshot().unwrap(); assert_eq!( - rejected(utter(&mut kernel, &active, speech.listener, recant())), + rejected(utter(&mut kernel, speech.listener, recant())), vec![ActionMismatch::FactUnknown { precondition: 0 }], "Believed falls short of Certain" ); @@ -9650,8 +8467,7 @@ mod knowledge_tests { AuthoredSource::Witnessed, )]), ); - let active = kernel.snapshot().unwrap(); - utter(&mut kernel, &active, speech.listener, recant()) + utter(&mut kernel, speech.listener, recant()) .expect("certainty admits the recant"); // Absence is the one shape of knowing nothing: no empty inner map. assert!(!kernel.state.knowledge.contains_key(&speech.listener)); @@ -9753,8 +8569,7 @@ mod knowledge_tests { let (mut kernel, speech, active) = speech_kernel(directory.path(), "Allocation"); let world_id = kernel.state.world_id; let command_id = CommandId::new(); - let opportunity = opportunity_for(&active, speech.speaker); - let caller = CallerId::Controller(opportunity.controller_id); + let caller = play_caller(); let entities_before = kernel.state.entities.len(); kernel .submit( @@ -9762,8 +8577,8 @@ mod knowledge_tests { &active, command_id, caller.clone(), - CommandBody::ExerciseDecision { - opportunity, + CommandBody::Act { + actor: speech.speaker, invocation: say( speech.whisper, vec![binding("target", Target::Subject(speech.listener))], @@ -9810,11 +8625,8 @@ mod knowledge_tests { ) .expect("a created world") .0; - let (speech, active) = speech_world(&mut kernel); - utter( - &mut kernel, - &active, - speech.speaker, + let (speech, _) = speech_world(&mut kernel); + utter(&mut kernel, speech.speaker, say( speech.proclaim, vec![binding("channel", Target::Entity(speech.horn))], @@ -9822,11 +8634,7 @@ mod knowledge_tests { ), ) .expect("the first proclamation commits"); - let active = kernel.snapshot().unwrap(); - utter( - &mut kernel, - &active, - speech.listener, + utter(&mut kernel, speech.listener, say( speech.whisper, vec![binding("target", Target::Subject(speech.speaker))], @@ -9863,20 +8671,19 @@ mod knowledge_tests { #[test] fn a_forged_claim_or_forged_recipient_does_not_apply() { let directory = tempfile::tempdir().unwrap(); - let (mut kernel, speech, active) = speech_kernel(directory.path(), "Forgery"); + let (kernel, speech, _) = speech_kernel(directory.path(), "Forgery"); let command_id = CommandId::new(); - let opportunity = opportunity_for(&active, speech.speaker); - let caller = CallerId::Controller(opportunity.controller_id); + let caller = play_caller(); let invocation = say( speech.proclaim, vec![binding("channel", Target::Entity(speech.horn))], "Honest.", ); - let granted = require_granted(&kernel.state, &opportunity, invocation.affordance).unwrap(); + let granted = require_granted(&kernel.state, speech.speaker, invocation.affordance).unwrap(); let honest = action::exercise( &kernel.state, command_id, - &opportunity, + speech.speaker, &granted, &invocation, ) @@ -9903,8 +8710,7 @@ mod knowledge_tests { &mut candidate, command_id, &caller, - &WorldEffect::DecisionExercised { - opportunity: opportunity.clone(), + &WorldEffect::Acted { invocation: invocation.clone(), event: forged, }, @@ -9927,8 +8733,7 @@ mod knowledge_tests { &mut candidate, command_id, &caller, - &WorldEffect::DecisionExercised { - opportunity, + &WorldEffect::Acted { invocation, event: honest, }, @@ -9942,23 +8747,14 @@ mod knowledge_tests { #[test] fn a_telling_moves_only_the_listeners_scope() { let directory = tempfile::tempdir().unwrap(); - let (mut kernel, speech, active) = speech_kernel(directory.path(), "ScopeMove"); + let (mut kernel, speech, _) = speech_kernel(directory.path(), "ScopeMove"); let digest = |kernel: &WorldKernel, subject: SubjectId| { - scope_digest( - &kernel.state, - DecisionScope { - subject_id: subject, - }, - ) - .unwrap() + scope_components(&kernel.state, subject) }; let listener_before = digest(&kernel, speech.listener); let bystander_before = digest(&kernel, speech.bystander); - utter( - &mut kernel, - &active, - speech.speaker, + utter(&mut kernel, speech.speaker, say( speech.whisper, vec![binding("target", Target::Subject(speech.listener))], @@ -10053,11 +8849,8 @@ mod knowledge_tests { let run = |name: &str, text: &str| { let room = directory.path().join(name); std::fs::create_dir_all(&room).unwrap(); - let (mut kernel, speech, active) = speech_kernel(&room, name); - let receipt = utter( - &mut kernel, - &active, - speech.speaker, + let (mut kernel, speech, _) = speech_kernel(&room, name); + let receipt = utter(&mut kernel, speech.speaker, say( speech.whisper, vec![binding("target", Target::Subject(speech.listener))], @@ -10097,8 +8890,8 @@ mod knowledge_tests { #[cfg(test)] mod soul_knowledge_tests { use super::tests::{ - FLOOD_STATEMENT, Speech, affordance_named, auth_principal, command, creation, operations, - opportunity_for, owner, speech_world, submit_owner, + act, play_caller, FLOOD_STATEMENT, Speech, affordance_named, auth_principal, command, creation, operations, + owner, speech_world, submit_owner, }; use super::*; use std::path::Path; @@ -10134,24 +8927,10 @@ mod soul_knowledge_tests { fn utter( kernel: &mut WorldKernel, - snapshot: &WorldSnapshot, actor: SubjectId, invocation: DecisionInvocation, ) -> Result<SubmitReceipt, KernelError> { - let opportunity = opportunity_for(snapshot, actor); - let caller = CallerId::Controller(opportunity.controller_id); - kernel.submit( - command( - snapshot, - CommandId::new(), - caller.clone(), - CommandBody::ExerciseDecision { - opportunity, - invocation, - }, - ), - &AuthenticatedCaller::fixture(caller), - ) + act(kernel, actor, invocation) } fn knows(kernel: &WorldKernel, subject: SubjectId, fact: EntityId) -> Option<Knowledge> { @@ -10163,8 +8942,8 @@ mod soul_knowledge_tests { .copied() } - fn digest_of(kernel: &WorldKernel, subject_id: SubjectId) -> ScopeDigest { - scope_digest(&kernel.state, DecisionScope { subject_id }).unwrap() + fn digest_of(kernel: &WorldKernel, subject_id: SubjectId) -> ScopeComponents { + scope_components(&kernel.state, subject_id) } fn minted_claim(kernel: &WorldKernel) -> EntityId { @@ -10205,10 +8984,7 @@ mod soul_knowledge_tests { // The controller may still speak from outside its own reach — the horn // belongs to the temple — and the listener, who stands inside the // reach, hears it. - utter( - &mut kernel, - &active, - speech.speaker, + utter(&mut kernel, speech.speaker, say( speech.proclaim, vec![binding("channel", Target::Entity(speech.horn))], @@ -10233,11 +9009,7 @@ mod soul_knowledge_tests { assert_eq!(knows(&kernel, speech.speaker, controllers_claim), None); // Now the listener speaks on the same channel. - let active = kernel.snapshot().unwrap(); - utter( - &mut kernel, - &active, - speech.listener, + utter(&mut kernel, speech.listener, say( speech.proclaim, vec![binding("channel", Target::Entity(speech.horn))], @@ -10308,7 +9080,7 @@ mod soul_knowledge_tests { ]; for (actor, invocation, expected) in cases { - let error = utter(&mut kernel, &active, actor, invocation).unwrap_err(); + let error = utter(&mut kernel, actor, invocation).unwrap_err(); let KernelError::ActionRejected(mismatches) = error else { panic!("expected an action rejection, got {error:?}"); }; @@ -10320,26 +9092,25 @@ mod soul_knowledge_tests { } /// Fan-out is the sole way knowledge enters another subject from speech, and - /// it is not carried by the effect. A forged `DecisionExercised` that widens + /// it is not carried by the effect. A forged `Acted` that widens /// the audience, appends a second telling, or tells a foreign fact is refused /// by `apply_effect` itself, so replay is never the first reader to notice. #[test] fn soul_a_forged_wider_audience_does_not_apply() { let directory = tempfile::tempdir().unwrap(); - let (kernel, speech, active) = speech_kernel(directory.path(), "WiderAudience"); + let (kernel, speech, _) = speech_kernel(directory.path(), "WiderAudience"); let command_id = CommandId::new(); - let opportunity = opportunity_for(&active, speech.speaker); - let caller = CallerId::Controller(opportunity.controller_id); + let caller = play_caller(); let invocation = say( speech.whisper, vec![binding("target", Target::Subject(speech.listener))], "Only the hall.", ); - let granted = require_granted(&kernel.state, &opportunity, invocation.affordance).unwrap(); + let granted = require_granted(&kernel.state, speech.speaker, invocation.affordance).unwrap(); let honest = action::exercise( &kernel.state, command_id, - &opportunity, + speech.speaker, &granted, &invocation, ) @@ -10382,8 +9153,7 @@ mod soul_knowledge_tests { &mut candidate, command_id, &caller, - &WorldEffect::DecisionExercised { - opportunity: opportunity.clone(), + &WorldEffect::Acted { invocation: invocation.clone(), event: forged, }, @@ -10448,17 +9218,14 @@ mod soul_knowledge_tests { speech.bystander, speech.stranger, ]; - let before: Vec<ScopeDigest> = everyone + let before: Vec<ScopeComponents> = everyone .iter() .map(|subject| digest_of(&kernel, *subject)) .collect(); let facts_before = kernel.state.facts.len(); // The bystander stands alone in the yard. - utter( - &mut kernel, - &active, - speech.bystander, + utter(&mut kernel, speech.bystander, say(speak, Vec::new(), "Nobody is here."), ) .expect("speaking into an empty room commits"); @@ -10607,11 +9374,8 @@ mod soul_knowledge_tests { let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("world.cc"); let (world_id, expected) = { - let (mut kernel, speech, active) = speech_kernel(directory.path(), "ReplayArms"); - utter( - &mut kernel, - &active, - speech.speaker, + let (mut kernel, speech, _) = speech_kernel(directory.path(), "ReplayArms"); + utter(&mut kernel, speech.speaker, say( speech.proclaim, vec![binding("channel", Target::Entity(speech.horn))], @@ -10684,10 +9448,7 @@ mod soul_knowledge_tests { let (mut kernel, speech, active) = speech_kernel(directory.path(), "OneHome"); let speak = affordance_named(&active, "speak"); let text = "A statement that appears nowhere else."; - utter( - &mut kernel, - &active, - speech.speaker, + utter(&mut kernel, speech.speaker, say(speak, Vec::new(), text), ) .expect("the kernel speak commits"); @@ -10729,51 +9490,6 @@ mod soul_knowledge_tests { FLOOD_STATEMENT ); } - - /// `operator_log` is unscoped by construction: it renders every committed - /// act's utterance regardless of who holds knowledge of it. That is correct - /// for the human operator's story feed and is exactly why it must never - /// become reachable from a controller lane. `ControllerRunner` no longer - /// owns a `WorldMailbox`; it owns a `ControllerPort`, which forwards - /// exactly the five requests a controller lane makes and has no - /// `operator_log` method at all. The separation is a type boundary now: - /// `WorldMailbox::operator_log` stays `pub(crate)` for the operator/story - /// feed owner, but nothing inside `controllers.rs` can name it. - #[test] - fn soul_the_operator_log_is_unscoped_and_must_stay_owner_only() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, speech, active) = speech_kernel(directory.path(), "OperatorLog"); - let text = "Nobody in this room but me."; - utter( - &mut kernel, - &active, - speech.bystander, - say(affordance_named(&active, "speak"), Vec::new(), text), - ) - .expect("speaking alone in the yard commits"); - - // Nobody holds it. - assert!(kernel.state.knowledge.is_empty()); - // The operator reads it anyway, with the speaker resolved by label. - let log = kernel.operator_log().unwrap(); - assert_eq!( - log, - vec![OperatorEvent { - revision: kernel.state.revision, - speaker: speech.bystander, - speaker_label: "The Yard Bystander".into(), - speech: Some(Statement::new(text).unwrap()), - display: None, - verb: "speak".into(), - render_path: None, - roles: Vec::new(), - }] - ); - // And no subject snapshot carries it. - for subject in kernel.snapshot().unwrap().subjects { - assert!(subject.knowledge.is_empty()); - } - } } /// One witnessed event over a place subtree: who it reaches, who it leaves @@ -10782,7 +9498,7 @@ mod soul_knowledge_tests { mod witness_tests { use super::patch::Site; use super::tests::{ - activate, auth_principal, command, creation, operations, opportunity_for, owner, + play_caller, activate, auth_principal, command, creation, operations, owner, reject_owner, submit_owner, }; use super::*; @@ -11293,10 +10009,10 @@ mod witness_tests { ); } - /// The digest reads the keys of a subject's own knowledge, so a witness - /// moves exactly the digests of the subjects that learned something. + /// The components carry the keys of a subject's own knowledge, so a witness + /// moves exactly the components of the subjects that learned something. #[test] - fn a_witness_moves_every_recipients_scope_digest_and_nobody_elses() { + fn a_witness_moves_every_recipients_scope_components_and_nobody_elses() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, world, active) = nesting_kernel(directory.path(), "Digest"); submit_owner( @@ -11310,7 +10026,7 @@ mod witness_tests { }]), ); let digest = |kernel: &WorldKernel, subject_id: SubjectId| { - scope_digest(&kernel.state, DecisionScope { subject_id }).unwrap() + scope_components(&kernel.state, subject_id) }; let learner = digest(&kernel, world.villager); let holder = digest(&kernel, world.neighbour); @@ -11331,107 +10047,6 @@ mod witness_tests { assert_eq!(digest(&kernel, world.coaster), outsider); } - /// A witness is the loudest producer of a moved scope: every subject that - /// learned something loses its in-flight binding, and every subject that - /// already knew keeps it. What the learner sees carries no speaker. - #[test] - fn a_witness_between_a_bound_opportunity_and_its_exercise_is_a_scope_change() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, world, active) = nesting_kernel(directory.path(), "Interruption"); - submit_owner( - &mut kernel, - &active, - operations(vec![ComponentOp::AcquireKnowledge { - subject: Ref::Existing(world.neighbour), - fact: Ref::Existing(world.asteroid), - source: AuthoredSource::Witnessed, - confidence: Confidence::Doubted, - }]), - ); - let bound = kernel.snapshot().unwrap(); - let learner = opportunity_for(&bound, world.villager); - let holder = opportunity_for(&bound, world.neighbour); - submit_owner( - &mut kernel, - &bound, - operations(vec![witness( - world.asteroid, - world.region, - Confidence::Certain, - )]), - ); - - let exercise = |kernel: &mut WorldKernel, opportunity: &DecisionOpportunity| { - let snapshot = kernel.snapshot().unwrap(); - let speak = *opportunity - .affordance_ids - .iter() - .find(|id| { - snapshot - .affordances - .iter() - .any(|entry| entry.id == **id && entry.entry.carries_speech) - }) - .expect("the scope holds a speech-carrying entry"); - let caller = CallerId::Controller(opportunity.controller_id); - kernel.submit( - command( - &snapshot, - CommandId::new(), - caller.clone(), - CommandBody::ExerciseDecision { - invocation: DecisionInvocation { - affordance: speak, - bindings: Vec::new(), - proposed: Vec::new(), - speech: Some(Statement::new("The sky moved.").unwrap()), - display: None, - }, - opportunity: opportunity.clone(), - }, - ), - &AuthenticatedCaller::fixture(caller), - ) - }; - let error = exercise(&mut kernel, &learner).unwrap_err(); - let KernelError::ScopeChanged { - scope, - expected, - actual, - } = error - else { - panic!("expected a changed scope, got {error:?}"); - }; - assert_eq!(scope, learner.scope); - assert_eq!(expected, learner.scope_digest); - assert_ne!(expected, actual); - - // The subject that already held the fact learned nothing, so its - // binding survives the same witness. - let kept = exercise(&mut kernel, &holder); - assert!(matches!(kept, Ok(SubmitReceipt::Applied(_))), "{kept:?}"); - - // What the learner now holds names no speaker: it knows the thing, not - // the telling. - let entry = knows(&kernel, world.villager, world.asteroid).expect("the learner holds it"); - assert_eq!(entry.source, KnowledgeSource::Witnessed); - let snapshot = kernel.snapshot().unwrap(); - let held = snapshot - .subjects - .iter() - .find(|subject| subject.id == world.villager) - .expect("the learner is snapshotted") - .knowledge - .iter() - .find(|row| row.fact == world.asteroid) - .expect("the learner's snapshot carries the fact"); - assert_eq!(held.source, KnowledgeSource::Witnessed); - assert!( - held.minted_at.is_none(), - "a witnessed row named a speech act" - ); - } - /// The slot names a fact and a place, never a subject, so an exercised /// witness lands the subtree with no teller anywhere in it. A slot whose /// place position binds a subject is refused before it is ever declared. @@ -11439,9 +10054,12 @@ mod witness_tests { fn a_witness_affordance_lowers_with_no_speaker() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, world, active) = nesting_kernel(directory.path(), "Affordance"); - let opportunity = opportunity_for(&active, world.villager); - let beacon = *opportunity - .affordance_ids + let beacon = *active + .subjects + .iter() + .find(|subject| subject.id == world.villager) + .expect("the villager exists") + .affordances .iter() .find(|id| { active @@ -11450,14 +10068,15 @@ mod witness_tests { .any(|entry| entry.id == **id && entry.entry.kind.0 == "beacon") }) .expect("the villager holds the beacon entry"); - let caller = CallerId::Controller(opportunity.controller_id); + let caller = play_caller(); kernel .submit( command( &active, CommandId::new(), caller.clone(), - CommandBody::ExerciseDecision { + CommandBody::Act { + actor: world.villager, invocation: DecisionInvocation { affordance: beacon, bindings: vec![ @@ -11477,7 +10096,6 @@ mod witness_tests { speech: None, display: None, }, - opportunity: opportunity.clone(), }, ), &AuthenticatedCaller::fixture(caller), @@ -12019,8 +10637,8 @@ mod witness_tests { mod clock_tests { use super::patch::{PreconditionRef, PressureSourceRef}; use super::tests::{ - activate, affordance_named, authority_kind, auth_principal, command, creation, office, - operations, opportunity_for, owner, human_principal, reject_owner, speech_world, + act, play_caller, activate, affordance_named, authority_kind, auth_principal, command, creation, office, + operations, owner, human_principal, reject_owner, speech_world, submit_owner, }; use super::*; @@ -12320,29 +10938,19 @@ mod clock_tests { affordance: AffordanceId, bindings: Vec<RoleBinding>, ) -> Result<SubmitReceipt, KernelError> { - let snapshot = kernel.snapshot().unwrap(); - let opportunity = opportunity_for(&snapshot, actor); - let caller = CallerId::Controller(opportunity.controller_id); - kernel.submit( - command( - &snapshot, - CommandId::new(), - caller.clone(), - CommandBody::ExerciseDecision { - opportunity, - invocation: DecisionInvocation { - affordance, - bindings, - proposed: vec![ProposedEffect { - slot: 0, - magnitude: Magnitude::None, - }], - speech: None, - display: None, - }, - }, - ), - &AuthenticatedCaller::fixture(caller), + act( + kernel, + actor, + DecisionInvocation { + affordance, + bindings, + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + speech: None, + display: None, + }, ) } @@ -12372,10 +10980,10 @@ mod clock_tests { .due } - /// Verification 12, both halves: a defaulted commitment advances pressure on - /// its subject, and that subject still derives exactly one opportunity. + /// Verification 12: a defaulted commitment advances pressure on + /// its subject, and the pressure grows with the next tick. #[test] - fn a_defaulted_commitment_advances_pressure_and_the_subject_derives_an_opportunity() { + fn a_defaulted_commitment_advances_pressure_one_step_per_tick() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Default"); let sourced = PressureSource::Commitment { @@ -12390,15 +10998,6 @@ mod clock_tests { 1, "only the past-due obligation pressed the farmer" ); - let snapshot = kernel.snapshot().unwrap(); - assert_eq!( - snapshot - .opportunities - .iter() - .filter(|opportunity| opportunity.scope.subject_id == clockwork.farmer) - .count(), - 1 - ); tick(&mut kernel, 1).expect("the second tick commits"); assert_eq!(pressure(&kernel, clockwork.farmer, sourced), 2); @@ -12562,22 +11161,6 @@ mod clock_tests { .expect("the threat commits"); assert_eq!(kernel.state.now, now); - let snapshot = kernel.snapshot().unwrap(); - let opportunity = opportunity_for(&snapshot, clockwork.farmer); - let caller = CallerId::Controller(opportunity.controller_id); - kernel - .submit( - command( - &snapshot, - CommandId::new(), - caller.clone(), - CommandBody::DeclineDecision { opportunity }, - ), - &AuthenticatedCaller::fixture(caller), - ) - .expect("the decline commits"); - assert_eq!(kernel.state.now, now); - let snapshot = kernel.snapshot().unwrap(); submit_owner( &mut kernel, @@ -12596,16 +11179,12 @@ mod clock_tests { let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Capability"); let before = kernel.state.clone(); let snapshot = kernel.snapshot().unwrap(); - let opportunity = opportunity_for(&snapshot, clockwork.reeve); for body in [ CommandBody::ApproveDraft, CommandBody::ActivateWorld, - CommandBody::DeclineDecision { - opportunity: opportunity.clone(), - }, - CommandBody::ExerciseDecision { - opportunity, + CommandBody::Act { + actor: clockwork.reeve, invocation: DecisionInvocation { affordance: clockwork.threaten, bindings: vec![binding("target", Target::Subject(clockwork.farmer))], @@ -12676,7 +11255,7 @@ mod clock_tests { for caller in [ CallerId::Principal(human_principal()), - CallerId::Controller(active.opportunities[0].controller_id), + CallerId::Controller(ControllerId::issue()), ] { let error = kernel .submit( @@ -12729,7 +11308,7 @@ mod clock_tests { #[test] fn a_forged_motion_does_not_apply() { let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Forged"); + let (kernel, clockwork, _) = clock_kernel(directory.path(), "Forged"); let to = FictionalMinutes(120); let honest = clock::derive_motion(&kernel.state, to); assert!(!honest.fulfilled.is_empty() || !honest.pressed.is_empty()); @@ -12868,126 +11447,6 @@ mod clock_tests { )); } - /// The order is total, deterministic, and never a filter. - #[test] - fn the_attention_order_is_total_and_deterministic() { - let directory = tempfile::tempdir().unwrap(); - let (kernel, clockwork, active) = clock_kernel(directory.path(), "Order"); - let derived = derive_opportunities(&kernel.state).unwrap(); - - let with = |pressures: BTreeMap<SubjectId, u32>, - stamps: BTreeMap<SubjectId, u64>| - -> Vec<SubjectId> { - let mut state = kernel.state.clone(); - state.now = FictionalMinutes(1_000); - state.pressures = pressures - .into_iter() - .map(|(subject, magnitude)| { - ( - subject, - BTreeMap::from([( - PressureSource::Subject(subject), - PressureMagnitude(magnitude), - )]), - ) - }) - .collect(); - state.last_opportunity_at = stamps - .into_iter() - .map(|(subject, stamp)| (subject, FictionalMinutes(stamp))) - .collect(); - order_opportunities(&state, derived.clone()) - .into_iter() - .map(|opportunity| opportunity.scope.subject_id) - .collect() - }; - - // Pressure dominates. - let ordered = with( - BTreeMap::from([(clockwork.farmer, 5), (clockwork.reeve, 3)]), - BTreeMap::new(), - ); - assert_eq!(ordered[0], clockwork.farmer); - assert_eq!(ordered[1], clockwork.reeve); - - // Equal pressure orders by debt, and a subject never attended outranks - // every subject that has. - let stamped: BTreeMap<SubjectId, u64> = active - .subjects - .iter() - .map(|subject| (subject.id, 900)) - .collect(); - let mut earlier = stamped.clone(); - earlier.insert(clockwork.treasury, 100); - let ordered = with(BTreeMap::new(), earlier); - assert_eq!(ordered[0], clockwork.treasury); - - // Never a filter: the same length and the same set, whatever the terms. - for pressures in [ - BTreeMap::new(), - BTreeMap::from([(clockwork.reeve, 1)]), - BTreeMap::from([(clockwork.farmer, 9), (clockwork.treasury, 9)]), - ] { - let ordered = with(pressures, stamped.clone()); - assert_eq!(ordered.len(), derived.len()); - assert_eq!( - ordered.iter().copied().collect::<BTreeSet<_>>(), - derived - .iter() - .map(|opportunity| opportunity.scope.subject_id) - .collect::<BTreeSet<_>>() - ); - } - } - - /// The debt term rotates: with no pressure anywhere, every subject reaches - /// the head within one pass, and standing pressure holds the head until it - /// is resolved. - #[test] - fn every_subject_reaches_the_head_within_bounded_ticks() { - let directory = tempfile::tempdir().unwrap(); - let (kernel, clockwork, _) = clock_kernel(directory.path(), "Rotation"); - let derived = derive_opportunities(&kernel.state).unwrap(); - let count = derived.len(); - - let mut state = kernel.state.clone(); - let mut seen = BTreeSet::new(); - for step in 0..count { - state.now = FictionalMinutes(u64::try_from(step).unwrap() + 1); - let head = order_opportunities(&state, derived.clone())[0] - .scope - .subject_id; - seen.insert(head); - state.last_opportunity_at.insert(head, state.now); - } - assert_eq!(seen.len(), count, "every subject reached the head"); - - // Standing pressure holds the head; the others still rotate among - // themselves once it is resolved. - state.pressures.insert( - clockwork.farmer, - BTreeMap::from([( - PressureSource::Subject(clockwork.reeve), - PressureMagnitude(4), - )]), - ); - for step in 0..count { - state.now = FictionalMinutes(1_000 + u64::try_from(step).unwrap()); - let head = order_opportunities(&state, derived.clone())[0] - .scope - .subject_id; - assert_eq!(head, clockwork.farmer); - state.last_opportunity_at.insert(head, state.now); - } - state.pressures.remove(&clockwork.farmer); - assert_ne!( - order_opportunities(&state, derived.clone())[0] - .scope - .subject_id, - clockwork.farmer - ); - } - /// Every commitment shape check, in one complete sorted set. #[test] fn commitment_declaration_negatives() { @@ -13117,9 +11576,8 @@ mod clock_tests { ); } - /// `Committed` reads the actor's own commitments, and a discharge mid-flight - /// rejects the promisor's bound proposal while the counterparty's own - /// invocation fails at admission. + /// `Committed` reads the actor's own commitments: the farmer promised the + /// treasury and the reeve did not. #[test] fn committed_reads_the_actors_own_commitments() { let directory = tempfile::tempdir().unwrap(); @@ -13153,51 +11611,6 @@ mod clock_tests { kernel.state.commitments[&clockwork.farmer].len(), before + 1 ); - - // A proposal bound before a discharge is rejected as a scope change for - // the promisor: `Committed` reads commitments, so the digest binds them. - let snapshot = kernel.snapshot().unwrap(); - let stale = opportunity_for(&snapshot, clockwork.farmer); - submit_owner( - &mut kernel, - &snapshot, - operations(vec![ComponentOp::DischargeCommitment { - subject: Ref::Existing(clockwork.farmer), - key: clockwork.obligation, - }]), - ); - let caller = CallerId::Controller(stale.controller_id); - let after = kernel.snapshot().unwrap(); - let error = kernel - .submit( - command( - &after, - CommandId::new(), - caller.clone(), - CommandBody::ExerciseDecision { - opportunity: stale, - invocation: DecisionInvocation { - affordance: clockwork.deliver, - bindings: vec![binding( - "creditor", - Target::Subject(clockwork.treasury), - )], - proposed: vec![ProposedEffect { - slot: 0, - magnitude: Magnitude::None, - }], - speech: None, - display: None, - }, - }, - ), - &AuthenticatedCaller::fixture(caller), - ) - .unwrap_err(); - assert!( - matches!(error, KernelError::ScopeChanged { .. }), - "{error:?}" - ); } /// `Committed` is a conjunction: the actor holds a commitment to this very @@ -13273,17 +11686,18 @@ mod clock_tests { .expect("an obligation to the same counterparty passes"); } - /// A tick that only advances pressure moves nobody's scope digest; a tick + /// A tick that only advances pressure moves nobody's scope components; a tick /// that fulfils a routine moves exactly that subject's. #[test] - fn a_pressure_tick_moves_no_scope_digest_and_a_routine_tick_moves_one() { + fn a_pressure_tick_moves_no_scope_components_and_a_routine_tick_moves_one() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Digests"); - let digests = |kernel: &WorldKernel| -> BTreeMap<SubjectId, ScopeDigest> { - derive_opportunities(&kernel.state) - .unwrap() - .into_iter() - .map(|opportunity| (opportunity.scope.subject_id, opportunity.scope_digest)) + let digests = |kernel: &WorldKernel| -> BTreeMap<SubjectId, ScopeComponents> { + kernel + .state + .subjects + .keys() + .map(|subject_id| (*subject_id, scope_components(&kernel.state, *subject_id))) .collect() }; @@ -13330,60 +11744,6 @@ mod clock_tests { } } - /// Soul falsification: the attention order is total on `SubjectId` when - /// pressure and debt tie, and it is the same order for every input - /// permutation. `sort_by_key` is stable, so an order that leaned on its - /// input's order would pass a single-vector test and drift with map - /// iteration. - #[test] - fn soul_the_attention_order_is_id_total_under_every_input_permutation() { - let directory = tempfile::tempdir().unwrap(); - let (kernel, clockwork, _) = clock_kernel(directory.path(), "Ties"); - let mut state = kernel.state.clone(); - state.now = FictionalMinutes(5_000); - // Equal pressure and an equal stamp on every subject: only the id can - // decide. - for subject_id in state.subjects.keys().copied().collect::<Vec<_>>() { - state.pressures.insert( - subject_id, - BTreeMap::from([( - PressureSource::Subject(clockwork.reeve), - PressureMagnitude(7), - )]), - ); - state - .last_opportunity_at - .insert(subject_id, FictionalMinutes(400)); - } - let derived = derive_opportunities(&state).unwrap(); - assert!( - derived.len() >= 3, - "the fixture ties at least three subjects" - ); - let expected: Vec<SubjectId> = order_opportunities(&state, derived.clone()) - .into_iter() - .map(|opportunity| opportunity.scope.subject_id) - .collect(); - let mut ascending = expected.clone(); - ascending.sort_unstable(); - assert_eq!(expected, ascending, "an equal-key tie is broken by id"); - - // Every rotation and the full reversal produce the same order. - for shift in 0..derived.len() { - let mut permuted = derived.clone(); - permuted.rotate_left(shift); - let mut reversed = permuted.clone(); - reversed.reverse(); - for candidate in [permuted, reversed] { - let ordered: Vec<SubjectId> = order_opportunities(&state, candidate) - .into_iter() - .map(|opportunity| opportunity.scope.subject_id) - .collect(); - assert_eq!(ordered, expected, "the order read its input's order"); - } - } - } - /// Soul falsification: pressure magnitude cannot overflow or go negative, /// and zero is spelled by absence at both ends. #[test] @@ -13432,14 +11792,6 @@ mod clock_tests { "an emptied target keeps no empty inner map" ); - // `pressure_total` and `attention_debt` are derived, never stored. - assert_eq!(pressure_total(&kernel.state, clockwork.farmer), 0); - assert_eq!( - attention_debt(&kernel.state, clockwork.treasury), - u64::MAX, - "a subject never attended carries the whole debt" - ); - // Resolving an absent row changes nothing and is refused. let snapshot = kernel.snapshot().unwrap(); let mismatches = reject_owner( @@ -13459,17 +11811,18 @@ mod clock_tests { ); } - /// Soul falsification: `now` is in no scope preimage. A tick with nothing - /// due moves the clock and not one subject's digest. + /// Soul falsification: `now` is in no scope. A tick with nothing due moves + /// the clock and not one subject's components. #[test] - fn soul_a_clock_only_tick_moves_no_scope_digest() { + fn soul_a_clock_only_tick_moves_no_scope_components() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, _, _) = clock_kernel(directory.path(), "ClockOnly"); - let digests = |kernel: &WorldKernel| -> BTreeMap<SubjectId, ScopeDigest> { - derive_opportunities(&kernel.state) - .unwrap() - .into_iter() - .map(|opportunity| (opportunity.scope.subject_id, opportunity.scope_digest)) + let digests = |kernel: &WorldKernel| -> BTreeMap<SubjectId, ScopeComponents> { + kernel + .state + .subjects + .keys() + .map(|subject_id| (*subject_id, scope_components(&kernel.state, *subject_id))) .collect() }; let before = digests(&kernel); @@ -13479,7 +11832,7 @@ mod clock_tests { tick(&mut kernel, 10).expect("the tick commits"); assert_eq!(kernel.state.now, FictionalMinutes(before_now.0 + 10)); assert!(kernel.state.pressures.is_empty()); - assert_eq!(digests(&kernel), before, "the clock entered a scope digest"); + assert_eq!(digests(&kernel), before, "the clock entered a scope"); } // ---- PA.f26: the genesis lane obeys `require_ruler` too ------------ @@ -13794,12 +12147,21 @@ mod clock_tests { let held = CallerId::System(SystemCapability::Consumer { consumer: ConsumerId::of_name("capability-consumer"), }); - let opportunity = opportunity_for(&active, clockwork.reeve); let forbidden = [ CommandBody::ApproveDraft, CommandBody::ActivateWorld, - CommandBody::DeclineDecision { - opportunity: opportunity.clone(), + CommandBody::Act { + actor: clockwork.reeve, + invocation: DecisionInvocation { + affordance: clockwork.threaten, + bindings: vec![binding("target", Target::Subject(clockwork.farmer))], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + speech: None, + display: None, + }, }, CommandBody::AdvanceTime { minutes: minutes(60), @@ -13854,10 +12216,6 @@ mod clock_tests { // ---- Cut 3: the play authority, `Ruled` facts and `Mint` ----------- - fn play_caller() -> CallerId { - CallerId::System(SystemCapability::Play) - } - fn ruled_fact_patch(handle: &str) -> WorldPatch { WorldPatch { declarations: vec![Declaration::Fact(FactDeclaration { @@ -13997,31 +12355,14 @@ mod clock_tests { assert!(kernel.state.now > active.now); } - /// P3.6: the play authority may not approve, activate, exercise, or - /// decline. `require_system_capability`, at the top of `reduce`, refuses - /// all four before any body-specific arm is read. + /// P3.6: the play authority may not approve or activate. + /// `require_system_capability`, at the top of `reduce`, refuses both + /// before any body-specific arm is read. #[test] - fn the_play_authority_cannot_approve_activate_exercise_or_decline() { + fn the_play_authority_cannot_approve_or_activate() { let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "PlayForbidden"); - let opportunity = opportunity_for(&active, clockwork.reeve); - let forbidden = [ - CommandBody::ApproveDraft, - CommandBody::ActivateWorld, - CommandBody::ExerciseDecision { - opportunity: opportunity.clone(), - invocation: DecisionInvocation { - affordance: clockwork.deliver, - bindings: Vec::new(), - proposed: Vec::new(), - speech: None, - display: None, - }, - }, - CommandBody::DeclineDecision { - opportunity: opportunity.clone(), - }, - ]; + let (mut kernel, _, _) = clock_kernel(directory.path(), "PlayForbidden"); + let forbidden = [CommandBody::ApproveDraft, CommandBody::ActivateWorld]; for body in &forbidden { let error = submit_as(&mut kernel, play_caller(), body.clone()).unwrap_err(); assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); @@ -14596,55 +12937,53 @@ mod clock_tests { .id } - /// P4.1, replay half: reopening the journal reproduces a retirement — - /// no opportunity and `retired` both survive the round trip. + /// P4.1, replay half: reopening the journal reproduces a retirement — no + /// grants and `retired` both survive the round trip. #[test] - fn a_retired_subject_holds_no_opportunity_across_a_replay() { + fn a_retired_subject_holds_no_grants_across_a_replay() { let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("world.cc"); let (world_id, reeve) = { let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "RetireReplay"); assert!( - active - .opportunities + !active + .subjects .iter() - .any(|opportunity| opportunity.scope.subject_id == clockwork.reeve), - "the reeve holds an opportunity before retirement" + .find(|subject| subject.id == clockwork.reeve) + .unwrap() + .affordances + .is_empty(), + "the reeve holds grants before retirement" ); owner_retires(&mut kernel, clockwork.reeve).expect("the owner retires the reeve"); (kernel.state.world_id, clockwork.reeve) }; let replayed = WorldKernel::open(&path, world_id).expect("the store replays"); let snapshot = replayed.snapshot().unwrap(); - assert!( - !snapshot - .opportunities - .iter() - .any(|opportunity| opportunity.scope.subject_id == reeve), - "a replayed retired subject holds no opportunity" - ); let subject = snapshot .subjects .iter() .find(|subject| subject.id == reeve) .expect("the retired subject's own row"); assert!(subject.retired); + assert!(subject.affordances.is_empty(), "a retired subject holds no grants"); } - /// P4.1: a retired subject's last opportunity is stale, not honoured. + /// P4.1: Play's `Act` for a retired subject is denied, because `Retire` + /// removed its grants. #[test] fn a_retired_subject_cannot_act() { let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "RetireCannotAct"); - let opportunity = opportunity_for(&active, clockwork.reeve); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RetireCannotAct"); owner_retires(&mut kernel, clockwork.reeve).expect("the owner retires the reeve"); - let error = submit_as( + let error = exercise( &mut kernel, - CallerId::Controller(opportunity.controller_id), - CommandBody::DeclineDecision { opportunity }, + clockwork.reeve, + clockwork.threaten, + vec![binding("target", Target::Subject(clockwork.farmer))], ) .unwrap_err(); - assert!(matches!(error, KernelError::OpportunityMismatch), "{error:?}"); + assert!(matches!(error, KernelError::AffordanceDenied), "{error:?}"); } /// P4.1: no position, so a witness at the retired subject's former place @@ -14885,15 +13224,11 @@ mod clock_tests { assert_eq!(player.affordances.len(), 2); } - /// P5.1, and the scope digest half of Q10's design: a grant and a revoke - /// in Active both move the scope digest, so a stale opportunity is - /// `ScopeChanged` rather than silently honoured. + /// P5.1: Play grants and revokes a verb in Active. #[test] fn the_play_authority_grants_and_revokes_in_active() { let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, active) = - clock_kernel(directory.path(), "PlayGrantRevoke"); - let stale = opportunity_for(&active, clockwork.reeve); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PlayGrantRevoke"); submit_as( &mut kernel, play_caller(), @@ -14920,15 +13255,6 @@ mod clock_tests { .len(), 4 ); - let error = submit_as( - &mut kernel, - CallerId::Controller(stale.controller_id), - CommandBody::DeclineDecision { - opportunity: stale.clone(), - }, - ) - .unwrap_err(); - assert!(matches!(error, KernelError::ScopeChanged { .. }), "{error:?}"); submit_as( &mut kernel, @@ -14955,7 +13281,7 @@ mod clock_tests { assert!(!reeve.affordances.contains(&clockwork.threaten)); } - /// P5.2: `derive_opportunities` requires at least one grant; a revoke + /// P5.2: the never-mute rule requires at least one grant; a revoke /// that would leave the reeve mute is refused before it ever reaches /// that invariant. #[test] @@ -15266,8 +13592,6 @@ mod clock_tests { .0; let (speech, _) = speech_world(&mut kernel); owner_retires(&mut kernel, speech.listener).expect("the owner retires the listener"); - let snapshot = kernel.snapshot().unwrap(); - let opportunity = opportunity_for(&snapshot, speech.speaker); let invocation = DecisionInvocation { affordance: speech.whisper, bindings: vec![binding("target", Target::Subject(speech.listener))], @@ -15277,8 +13601,11 @@ mod clock_tests { }; let error = submit_as( &mut kernel, - CallerId::Controller(opportunity.controller_id), - CommandBody::ExerciseDecision { invocation, opportunity }, + play_caller(), + CommandBody::Act { + actor: speech.speaker, + invocation, + }, ) .unwrap_err(); assert!( @@ -15913,7 +14240,6 @@ mod clock_tests { let wire = *kernel.state.channels.keys().next().expect("the declared channel"); let snapshot = kernel.snapshot().unwrap(); let hail = affordance_named(&snapshot, "hail"); - let opportunity = opportunity_for(&snapshot, clockwork.farmer); let invocation = DecisionInvocation { affordance: hail, bindings: vec![ @@ -15926,21 +14252,22 @@ mod clock_tests { }; submit_as( &mut kernel, - CallerId::Controller(opportunity.controller_id), - CommandBody::ExerciseDecision { + play_caller(), + CommandBody::Act { + actor: clockwork.farmer, invocation: invocation.clone(), - opportunity: opportunity.clone(), }, ) .expect("the live outcast is reachable through the channel"); owner_retires(&mut kernel, outcast).expect("retire the outcast"); - let snapshot = kernel.snapshot().unwrap(); - let opportunity = opportunity_for(&snapshot, clockwork.farmer); let error = submit_as( &mut kernel, - CallerId::Controller(opportunity.controller_id), - CommandBody::ExerciseDecision { invocation, opportunity }, + play_caller(), + CommandBody::Act { + actor: clockwork.farmer, + invocation, + }, ) .unwrap_err(); assert!( From d512a6706afb1c406450cd316c8faa1acf786f5f Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Thu, 19 Nov 2026 23:21:38 +0100 Subject: [PATCH 129/190] Aetherlight AL2b-1: Act door tests (only Play, Draft refusal, acted chain) Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/journal.rs | 39 +++++++++++++++++ native/aetherlight/src/lib.rs | 72 +++++++++++++++++++++++++++++-- 2 files changed, 108 insertions(+), 3 deletions(-) diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index 033855ad8..aa2e95b37 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -2324,6 +2324,45 @@ mod custody_tests { ); } + /// A chain holding `Acted` commits recovers and verifies on reopen, and an + /// event whose actor is no subject is corrupt at the shape check. + #[test] + fn an_acted_chain_reopens_and_a_foreign_actor_is_corrupt() { + use crate::tests::{ + act, activate, auth_principal, creation, first_grant, owner, speak, + }; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "ActedChain"), + &auth_principal(owner()), + ) + .unwrap(); + let active = activate(&mut kernel); + let actor = *active.subjects.first().map(|subject| &subject.id).unwrap(); + act( + &mut kernel, + actor, + speak(first_grant(&active, actor), "The chain holds."), + ) + .unwrap(); + let accepted = kernel.snapshot().unwrap(); + let world_id = accepted.world_id; + drop(kernel); + let reopened = WorldKernel::open(&path, world_id).expect("the acted chain recovers"); + assert_eq!(reopened.snapshot().unwrap(), accepted); + verify_state_shape(&reopened.state).expect("an honest event passes the shape check"); + + let mut forged = reopened.state.clone(); + forged.events[0].actor = crate::SubjectId::issue(); + assert!( + matches!(verify_state_shape(&forged), Err(JournalError::Corrupt(_))), + "an event naming no subject passed the shape check" + ); + } + /// Absence is zero and one slot holds one pair, so a stored zero, an empty /// holder, and a holding on something that is not a resource are each /// corrupt at replay. diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index 763c18804..2587627b1 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -10637,9 +10637,9 @@ mod witness_tests { mod clock_tests { use super::patch::{PreconditionRef, PressureSourceRef}; use super::tests::{ - act, play_caller, activate, affordance_named, authority_kind, auth_principal, command, creation, office, - operations, owner, human_principal, reject_owner, speech_world, - submit_owner, + act, act_as, activate, affordance_named, auth_principal, authority_kind, command, creation, + human_principal, office, operations, owner, play_caller, reject_owner, speak, + speech_world, submit_owner, }; use super::*; use std::path::Path; @@ -12355,6 +12355,72 @@ mod clock_tests { assert!(kernel.state.now > active.now); } + /// Act is Play's alone: the owner, the clock, a controller and a + /// non-owner principal are refused and commit nothing; Play applies. + #[test] + fn only_play_may_act() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "OnlyPlayActs"); + let invocation = DecisionInvocation { + affordance: clockwork.threaten, + bindings: vec![binding("target", Target::Subject(clockwork.farmer))], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + speech: None, + display: None, + }; + let before = kernel.state.clone(); + for caller in [ + CallerId::Principal(owner()), + CallerId::Principal(human_principal()), + clock_caller(), + CallerId::Controller(ControllerId::issue()), + ] { + let error = + act_as(&mut kernel, caller.clone(), clockwork.reeve, invocation.clone()) + .unwrap_err(); + assert!( + matches!(error, KernelError::Unauthorized), + "{caller:?}: {error:?}" + ); + } + assert_eq!(kernel.state, before, "a refused act commits nothing"); + let receipt = act(&mut kernel, clockwork.reeve, invocation).expect("Play acts"); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert_eq!(kernel.state.events.len(), before.events.len() + 1); + assert_eq!(kernel.state.events.last().unwrap().actor, clockwork.reeve); + } + + /// There is no acting before activation. + #[test] + fn act_in_draft_is_wrong_phase() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, _) = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "ActInDraft"), + &auth_principal(owner()), + ) + .unwrap(); + let error = act( + &mut kernel, + SubjectId::issue(), + speak(AffordanceId::issue(), "Too soon."), + ) + .unwrap_err(); + assert!( + matches!( + error, + KernelError::WrongPhase { + expected: WorldPhase::Active, + actual: WorldPhase::Draft, + } + ), + "{error:?}" + ); + } + /// P3.6: the play authority may not approve or activate. /// `require_system_capability`, at the top of `reduce`, refuses both /// before any body-specific arm is read. From d48f1d7aa7ed544d44301809c6b0b651fffcaeaa Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Thu, 19 Nov 2026 23:24:50 +0100 Subject: [PATCH 130/190] Aetherlight AL2b-1: comments, seal doc-test, PROVENANCE section, dead readers Restates comments that named deleted symbols as a reason, swaps the seal doc-test that named ScopeDigest for DecisionEvent, deletes WorldJournal::commits and FictionalMinutes::since (dead with the operator log and attention order), and writes the AL2b-1 PROVENANCE section with the residue list for AL2b-2. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/PROVENANCE.md | 60 +++++++++++++++++++++---- native/aetherlight/src/action.rs | 11 +++-- native/aetherlight/src/clock.rs | 7 --- native/aetherlight/src/journal.rs | 7 +-- native/aetherlight/src/lib.rs | 75 +++++++++++++------------------ native/aetherlight/src/patch.rs | 21 ++++----- 6 files changed, 98 insertions(+), 83 deletions(-) diff --git a/native/aetherlight/PROVENANCE.md b/native/aetherlight/PROVENANCE.md index 83dd10878..7ad559f15 100644 --- a/native/aetherlight/PROVENANCE.md +++ b/native/aetherlight/PROVENANCE.md @@ -172,9 +172,9 @@ door beside that path. Kept untouched for AL2b: controllers and `ControllerMode`, consumers (`ConsumerId`, `SystemCapability::Consumer`, `PatchGround::Consumer`, -`bound_to_consumer`), opportunities, scope digests, attention order, the draft -phase and approvals, `ExerciseDecision`, `DeclineDecision`, -`VerifiedPrincipalEvidence`. +`bound_to_consumer`), the draft phase and approvals, `VerifiedPrincipalEvidence`. +(Opportunities, scope digests, the attention order, `ExerciseDecision` and +`DeclineDecision` went in AL2b-1, below.) ## Leave-set vocabulary still compiled (AL2b's and AL4's triage list) @@ -185,13 +185,12 @@ What the cut deletes is gone; what remains is part B's: `PatchGround::Consumer` and the consumer arm of `confine_to_ground`, `VerifiedPrincipalEvidence`. - Controller lane: `verified_controller`, `resolve_controller`, `controller_mode`, - `controller_receipt`, `controller_decline_receipt`, `controller_key`. -- Tick-driver readers `WorldKernel::opportunities` and `clock_advances`, and - `CreateWorldIntent` (no consumer after the mailbox left). + `controller_key`. +- `CreateWorldIntent` (no consumer after the mailbox left). - Authenticated-caller vocabulary: `AuthenticatedCaller::fixture`, `verified_principal`, `verified_controller`, `verified_system`, and - `requires_owner_restart`; id helpers `text` and `nil_for_test`; `as_str`, - `digest` (scope preimage); `commits_for_test`; grammar `verbs`. AL4's ABI + `requires_owner_restart`; id helpers `text` and `nil_for_test`; + `commits_for_test`; grammar `verbs`. AL4's ABI decides which of these it needs. - Patch ingress: `decode_patch`, `check_patch_caps`, `PatchDecodeError` and `MAX_PATCH_BYTES`, `MAX_PATCH_DECLARATIONS`, `MAX_PATCH_OPERATIONS`, @@ -203,6 +202,51 @@ What the cut deletes is gone; what remains is part B's: Reproduce the list with `RUSTFLAGS=--force-warn dead_code cargo test --lib --no-run`: under test configuration the items nothing exercises show up. +## Cut AL2b-1: Play's Act replaces opportunity-based exercise + +Base `bf92a054f`. An act is one command, `Act { actor, invocation }`, admitted for +`System(Play)` in Active only, and one effect, `Acted { invocation, event }`. +`require_granted(state, actor, affordance)` is the only constructor of +`GrantedAffordance`: the actor's `affordance_grants` entry holds the affordance +and the catalog defines it, otherwise `AffordanceDenied`. `Retire` removes a +subject's grants, so a retired actor is refused by that check alone. +`action::exercise` takes the actor in place of an opportunity; its pipeline is +unchanged and the band draw keeps `command_id` as its only per-command term. +`DecisionEvent` carries `actor`, not `scope` and `controller_id`. `STATE_SCHEMA` +and `COMMIT_SCHEMA` moved to `consumer.v8`. + +Deleted, with their `bf92a054f` locations in `lib.rs`: + +- `ScopeDigest`, `ScopePreimage`, `DecisionOpportunity` (459-506) and + `scope_digest`, `exact_opportunity`, `derive_opportunities`, + `order_opportunities`, `pressure_total`, `attention_debt`, `granted_entries` + (3841-4034). `WorldSnapshot.opportunities`, `WorldState.last_opportunity_at` and + the attention-stamp shape check in `journal.rs` (730-738). +- `CommandBody::ExerciseDecision` and `DeclineDecision`, `WorldEffect:: + DecisionExercised` and `DecisionDeclined`, their `reduce` and `apply_effect` + arms, and `KernelError::OpportunityMismatch`, `ScopeChanged`, + `ControllerMismatch`. +- The operator log: `operator_log`, `OperatorEvent`, `BoundRole` (3518-3579, + 1109-1134), and the kernel readers `opportunities`, `clock_advances`, + `controller_receipt`, `controller_decline_receipt`. +- `WorldJournal::commits` and `FictionalMinutes::since`, dead once the readers + above went. + +Kept: the whole dialogue lane (`carries_speech`, `Communicate`, `Display`, the +kernel Speak entry, the grammar, `preconditions_hold`). `DecisionScope` stays the +grant key and `ControllerAssignment` stays; the owner's `AdmitPatch` and +`AdvanceTime` doors and `SystemCapability::Clock` stay. + +AL2b-2 still owns, under `aetherlight-play-only-after-genesis`: the owner's and +`Clock`'s post-genesis doors (`AdmitPatch` and `AdvanceTime`), `CallerId::Controller` +and the controller assignment, the consumer lane and ground, the draft phase and +approvals, `VerifiedPrincipalEvidence`, the never-mute rule +(`WouldLeaveSubjectMute`) and the `verify_state_shape` clause requiring a grant per +controlled scope. + +`last_acted_at` and `minted_at` in `snapshot` still read `state.events` (by +`event.actor`). AL3 needs keyed rows instead of a scan; that is the AL3 cut's. + ## Obligations this cut hands to AL4 - A cross-crate proof that forged opportunities and ids are refused, equivalent to diff --git a/native/aetherlight/src/action.rs b/native/aetherlight/src/action.rs index 9b5c1a303..2dcc50c75 100644 --- a/native/aetherlight/src/action.rs +++ b/native/aetherlight/src/action.rs @@ -73,8 +73,8 @@ pub enum ActionMismatch { EmptyDisplay, /// The acting subject's effective authority covers no such target under /// this kind. A target that walked out of the jurisdiction while the - /// proposal was in flight arrives here, not as a rebind: what the actor is - /// authorized over is in the digest, the world it reaches is not. + /// proposal was in flight arrives here: what the actor is authorized over + /// is in its scope, the world it reaches is not. NotAuthorized { precondition: usize, }, @@ -92,7 +92,7 @@ pub enum ActionMismatch { }, /// The actor does not hold the bound fact at the required confidence. A /// re-appraisal that lowered its own confidence while the proposal was in - /// flight arrives here rather than as a rebind: confidence is admission-only. + /// flight arrives here: confidence is admission-only. FactUnknown { precondition: usize, }, @@ -1976,9 +1976,8 @@ mod tests { assert!(bench.try_as(treasury, &bench.levy(farmer, 1)).is_ok()); } - /// An office lends jurisdiction its holder does not own, vacating takes it - /// back, and a proposal bound before the vacate rebinds rather than - /// rejecting: revocation mid-flight is a `ScopeChanged`. + /// An office lends jurisdiction its holder does not own, and vacating takes + /// it back: the act is refused at admission. #[test] fn office_delegation_grants_and_vacating_revokes() { let directory = tempfile::tempdir().unwrap(); diff --git a/native/aetherlight/src/clock.rs b/native/aetherlight/src/clock.rs index a02c21560..a1ba08f94 100644 --- a/native/aetherlight/src/clock.rs +++ b/native/aetherlight/src/clock.rs @@ -24,13 +24,6 @@ impl FictionalMinutes { pub(crate) fn checked_add(self, span: TickMinutes) -> Option<Self> { self.0.checked_add(u64::from(span.0)).map(Self) } - - /// Minutes elapsed since an earlier reading. Saturating because the caller - /// is the attention order, which reads a stamp `verify_state_shape` already - /// holds to `<= now`. - pub(crate) fn since(self, earlier: Self) -> u64 { - self.0.saturating_sub(earlier.0) - } } /// The span one `AdvanceTime` names. Constructor-checked `1..=MAX_ROUTE_COST` diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index aa2e95b37..9ec961c2e 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -181,11 +181,6 @@ impl WorldJournal { self.commits.get(&command_id) } - /// Every commit the journal holds, in no particular order. - pub(super) fn commits(&self) -> impl Iterator<Item = &WorldCommit> { - self.commits.values() - } - #[cfg(test)] pub(super) fn commit_count(&self) -> usize { self.commits.len() @@ -667,7 +662,7 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> )); } } - // Commitments, pressures, attention stamps, and the authored scale target. + // Commitments, pressures, and the authored scale target. // Absence is the only spelling of nothing at every level, so a store // satisfying these clauses carries no empty inner map, no zero magnitude, // and no dangling row — with no scan for any of them. diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index 2587627b1..2b3850cb9 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -47,7 +47,7 @@ //! ``` //! //! ```compile_fail -//! let _ = aetherlight::ScopeDigest::fixture("x"); +//! use aetherlight::DecisionEvent; //! ``` // The kernel has no entry point until AL4 adds the ABI, so most of it is unreachable @@ -346,7 +346,7 @@ pub(crate) enum NewController { NarrativePersona, OperationalAgent, /// Declared as a mirror of state this world does not own. Mints no - /// controller, no mode, and no opportunity. + /// controller, no mode, and no grants. External { consumer: ConsumerId, }, @@ -581,7 +581,7 @@ enum ControllerAssignment { /// A subject `Retire` ended for good. Not a second partition: /// `controller_assignments` stays the sole answer to who may call, and /// this is one of its values. It has no controller id, no mode, and no - /// caller, so it mints no opportunity and is never an audience. + /// caller, so it holds no grants and is never an audience. Retired, } @@ -705,26 +705,23 @@ struct WorldState { /// between two sources of one permission. authority: BTreeMap<SubjectId, BTreeSet<AuthorityGrant>>, /// The offices each institution constitutes, and who sits in them. An - /// incumbent never exercises its institution's opportunity: - /// `controller_assignments` stays the sole answer to who may call, and an - /// office answers the different question of what its incumbent has - /// jurisdiction over. + /// incumbent never acts as its institution: an office answers what its + /// incumbent has jurisdiction over, not who the actor is. selection: BTreeMap<SubjectId, BTreeMap<OfficeName, Office>>, /// Where each kind of grievance goes, and who may bring it. Keyed by - /// neither a subject nor a referent, so it enters no scope digest and is - /// admission-only state. + /// neither a subject nor a referent, so it enters no scope components and + /// is admission-only state. redress: BTreeMap<GrievanceKindName, Forum>, /// What each subject has promised. Never empty for a present key. commitments: BTreeMap<SubjectId, BTreeMap<CommitmentKey, Commitment>>, /// Lived meaning per subject. Read by projection and by nothing that - /// decides, so it enters `state_digest` and no `ScopePreimage`. + /// decides, so it enters `state_digest` and no scope. /// Pressure *on* each subject, keyed target-major then source. Never empty /// for a present key; no stored zero magnitude. pressures: BTreeMap<SubjectId, BTreeMap<PressureSource, PressureMagnitude>>, /// Minutes since genesis. The world's only clock, advanced by exactly one /// command body and read by no wall clock. It enters `state_digest` and no - /// `ScopePreimage`: it is world truth, and it is read by no precondition, so - /// a tick that only advances pressure moves no proposal's binding. + /// scope: it is world truth, and it is read by no precondition. now: FictionalMinutes, controller_assignments: BTreeMap<DecisionScope, ControllerAssignment>, /// What an affordance *is*. World-authored, Draft-only, written by @@ -827,12 +824,12 @@ pub struct SubjectSnapshot { pub human_controller: Option<PrincipalId>, pub affordances: BTreeSet<AffordanceId>, pub(crate) position: Option<EntityId>, - /// Set for a subject `Retire` ended: no opportunity, no position, no + /// Set for a subject `Retire` ended: no grants, no position, no /// audience, its history kept. The agent's view and the surface read this /// rather than inferring retirement from an absent position, which a /// merely unplaced live subject also has. pub retired: bool, - /// Exactly what the scope digest binds for this subject, carried whole + /// Exactly what a verification reads for this subject, carried whole /// rather than lowered into projections that then have to be diffed back /// together: its own position, incident routes, holdings, dependencies, /// grants, delegated offices, known fact keys, controlled channels, and @@ -864,10 +861,9 @@ pub struct SubjectSnapshot { /// This subject's own dependencies, lowered from `components.dependencies` /// (private to this module) so the play table's omniscient view can print /// what a `release` may name without reaching into `ScopeComponents` - /// itself. View-only, covered by no digest of its own: it is already bound - /// through `components`. + /// itself. View-only: it is already carried by `components`. pub(crate) dependencies: Vec<DependencyTarget>, - /// The greatest `DecisionEvent.revision` whose scope is this subject, or + /// The greatest `DecisionEvent.revision` whose actor is this subject, or /// `None` if the subject never acted. Derived from `state.events` alone: /// no new state, no schema change. The recency marker `projector_knowledge` /// stamps onto each knowledge row is `acquired_at > last_acted_at`. @@ -1754,9 +1750,7 @@ fn admit_resolved( )); } // Controller-shaped, both ways: a mirror receives no affordance, and - // every other controller must receive one. That is what makes the - // mirror's exclusion from opportunity derivation consistent rather than - // merely enforced. + // every other controller must receive one. if matches!( subject.controller, ControllerAssignment::ExternallyControlled { .. } @@ -3100,25 +3094,20 @@ fn overlapping_holder(state: &WorldState) -> Option<SubjectId> { } /// Exactly the components a subject's verification reads. One owner, consumed by -/// the scope digest and by the snapshot, so the two cannot drift. `routes` is +/// `action::exercise` and by the snapshot, so the two cannot drift. `routes` is /// every edge whose `from` or `to` is the subject's place: an inbound route /// decides who can arrive, and reading too little is a correctness hole while /// reading too much only costs an extra rejection. `holdings` and `dependencies` /// are the acting subject's own; a counterparty's holdings do not enter, because -/// a transfer changes both subjects' components and so changes both digests. +/// a transfer changes both subjects' components. /// It also holds what the actor *is* authorized over, and nothing about the /// world the actor reaches: the target's position, the target's container /// chain, the forum's state, and any subordinate's components stay out. A -/// realm-wide authority whose preimage held its jurisdiction's occupancy would -/// conflict with every commit in the realm, which is whole-world binding -/// restored by the front door. A target that walks out of a jurisdiction -/// mid-flight therefore fails at `Authorized` rather than rebinding, while a -/// revoked grant is a `ScopeChanged`. +/// target that walks out of a jurisdiction mid-flight fails at `Authorized` +/// at commit, and a revoked grant fails the same way. /// /// `Deserialize` is here so the narrative lane can persist a subject's own -/// components as the "before" an interruption is measured against. No field -/// changes with it, so `ScopePreimage`'s serialization — and therefore every -/// scope digest — is byte-identical. +/// components as the "before" an interruption is measured against. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(deny_unknown_fields)] pub struct ScopeComponents { @@ -3131,9 +3120,9 @@ pub struct ScopeComponents { /// What each held office lends: for every office whose incumbent is this /// subject, the institution's live grants whose kind that office delegates. /// The institution's authority is copied in through the office link, so one - /// scope digest covers the grant, the office, and the institution's - /// jurisdiction, and only delegated kinds enter — an institution's `judge` - /// jurisdiction never churns a `levy`-only incumbent's proposals. + /// scope covers the grant, the office, and the institution's jurisdiction, + /// and only delegated kinds enter — an institution's `judge` jurisdiction + /// never reaches a `levy`-only incumbent. delegated: BTreeMap<SubjectId, BTreeMap<OfficeName, BTreeSet<AuthorityGrant>>>, /// The keys of this subject's own knowledge. Keys, not payloads: a statement /// is immutable, so it cannot change without the key changing, and @@ -3143,13 +3132,11 @@ pub struct ScopeComponents { knows: BTreeSet<EntityId>, /// The channels this subject controls, with their records. Membership of a /// channel it merely hears never enters: a 1,000-member channel would churn - /// a thousand digests per membership change, which is whole-world binding by - /// the front door. + /// a thousand scopes per membership change. controls: BTreeMap<EntityId, ChannelRecord>, /// This subject's own commitments. `Precondition::Committed` reads them, so - /// the digest must bind them. Pressure, the clock, and the attention stamp - /// stay out: no precondition reads any of the three, so a tick that only - /// advances pressure invalidates no in-flight proposal. + /// they are in scope. Pressure and the clock stay out: no precondition reads + /// either. commitments: BTreeMap<CommitmentKey, Commitment>, } @@ -8742,8 +8729,8 @@ mod knowledge_tests { assert!(candidate.knowledge.contains_key(&speech.listener)); } - /// The scope table: a telling rebinds its listener and leaves a bystander - /// alone, and a reach change moves only the controller's digest. + /// The scope table: a telling moves its listener's scope and leaves a bystander + /// alone, and a reach change moves only the controller's scope. #[test] fn a_telling_moves_only_the_listeners_scope() { let directory = tempfile::tempdir().unwrap(); @@ -9237,7 +9224,7 @@ mod soul_knowledge_tests { assert_eq!( digest_of(&kernel, *subject), digest, - "an utterance nobody heard moved a scope digest" + "an utterance nobody heard moved a scope" ); } } @@ -10632,7 +10619,7 @@ mod witness_tests { } } -/// The clock, commitments, pressure, ordered attention, boundaries, and scale. +/// The clock, commitments, pressure, boundaries, and scale. #[cfg(test)] mod clock_tests { use super::patch::{PreconditionRef, PressureSourceRef}; @@ -11737,9 +11724,9 @@ mod clock_tests { let after = digests(&kernel); for (subject, digest) in &before { if *subject == clockwork.reeve { - assert_ne!(after[subject], *digest, "the fulfilling subject rebinds"); + assert_ne!(after[subject], *digest, "the fulfilling subject's scope moved"); } else { - assert_eq!(after[subject], *digest, "everyone else still commits"); + assert_eq!(after[subject], *digest, "everyone else's scope is untouched"); } } } diff --git a/native/aetherlight/src/patch.rs b/native/aetherlight/src/patch.rs index b8161ccc8..e84d5d334 100644 --- a/native/aetherlight/src/patch.rs +++ b/native/aetherlight/src/patch.rs @@ -114,8 +114,7 @@ pub(crate) struct OfficeName(pub(crate) String); /// A seat inside one institution. It carries no term and no selection method: /// there is no clock, so nothing can expire, and a field nothing reads is a /// decoration the next pass has to delete. `delegated` is the field that earns -/// its keep — `scope_components` reads it, `Authorized` resolves through it, and -/// the scope digest binds it. +/// its keep — `scope_components` reads it and `Authorized` resolves through it. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(deny_unknown_fields)] pub(crate) struct Office { @@ -348,7 +347,7 @@ pub(crate) enum ReachRef { pub(crate) struct ChannelRecord { pub(crate) reach: Reach, /// Who may speak on it besides those inside its reach, and whose scope - /// digest binds it. The horn belongs to the temple, not to whoever happens + /// components carry it. The horn belongs to the temple, not to whoever happens /// to be within earshot of it. pub(crate) controller: Option<SubjectId>, } @@ -495,9 +494,8 @@ pub(crate) struct Commitment { #[serde(transparent)] pub(crate) struct PressureMagnitude(pub(crate) u32); -/// Target-major, because every reader is: the attention order reads pressure -/// *on* a subject and the typed view shows pressure on self. Source-major has no -/// reader. +/// Target-major, because every reader is: the typed view shows pressure on +/// self. Source-major has no reader. #[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] #[serde(tag = "from", content = "of", rename_all = "snake_case")] pub(crate) enum PressureSource { @@ -1242,8 +1240,8 @@ pub(crate) enum ComponentOp { source: PressureSourceRef, target: Ref<SubjectId>, }, - /// Ends a subject's turn for good: no opportunity, no position, no - /// audience, its history kept. Only the owner and `Play` may write it. + /// Ends a subject for good: no grants, no position, no audience, its + /// history kept. Only the owner and `Play` may write it. Retire { subject: Ref<SubjectId>, }, @@ -1256,7 +1254,7 @@ pub(crate) enum ComponentOp { affordance: Ref<AffordanceId>, }, /// Revokes a grant. Refused if it would leave a controlled subject with - /// none: `derive_opportunities` requires at least one. + /// none: a controlled subject is never left mute. RevokeAffordance { subject: Ref<SubjectId>, affordance: Ref<AffordanceId>, @@ -1666,8 +1664,7 @@ pub enum Mismatch { operation: usize, }, /// A `RevokeAffordance` that would leave a controlled subject with no - /// affordance at all. `derive_opportunities` requires at least one; a - /// subject is never left mute. + /// affordance at all: a subject is never left mute. WouldLeaveSubjectMute { operation: usize, }, @@ -3228,7 +3225,7 @@ pub(super) fn resolve_patch( } } if let Declaration::Subject(subject) = declaration { - // Both ways. A mirror receives no opportunity, so it may hold no + // Both ways. A mirror receives no controller, so it may hold no // affordance; every other controller must hold one. if matches!(subject.controller, NewController::External { .. }) != subject.affordances.is_empty() From a02942f11589f16597f2ceb52d87c1c964e89da0 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Thu, 19 Nov 2026 23:35:15 +0100 Subject: [PATCH 131/190] Aetherlight AL2b-1: kill the two survivors (Acted commit-time gate, event revision order) Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/journal.rs | 13 +++++++++ native/aetherlight/src/lib.rs | 45 +++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index 9ec961c2e..d680b57f8 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -2343,6 +2343,12 @@ mod custody_tests { speak(first_grant(&active, actor), "The chain holds."), ) .unwrap(); + act( + &mut kernel, + actor, + speak(first_grant(&active, actor), "And again."), + ) + .unwrap(); let accepted = kernel.snapshot().unwrap(); let world_id = accepted.world_id; drop(kernel); @@ -2356,6 +2362,13 @@ mod custody_tests { matches!(verify_state_shape(&forged), Err(JournalError::Corrupt(_))), "an event naming no subject passed the shape check" ); + + let mut reordered = reopened.state.clone(); + reordered.events.swap(0, 1); + assert!( + matches!(verify_state_shape(&reordered), Err(JournalError::Corrupt(_))), + "events out of revision order passed the shape check" + ); } /// Absence is zero and one slot holds one pair, so a stored zero, an empty diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index 2b3850cb9..7fab23d87 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -12380,6 +12380,51 @@ mod clock_tests { assert_eq!(kernel.state.events.last().unwrap().actor, clockwork.reeve); } + /// The commit-time re-decision of an `Acted` effect is Play's, in Active: + /// the same honest effect is refused for the owner and in Draft. + #[test] + fn an_acted_effect_applies_only_for_play_in_active() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, clockwork, _) = clock_kernel(directory.path(), "ActedGate"); + let invocation = DecisionInvocation { + affordance: clockwork.threaten, + bindings: vec![binding("target", Target::Subject(clockwork.farmer))], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + speech: None, + display: None, + }; + let command_id = CommandId::new(); + let granted = + require_granted(&kernel.state, clockwork.reeve, invocation.affordance).unwrap(); + let event = + action::exercise(&kernel.state, command_id, clockwork.reeve, &granted, &invocation) + .unwrap(); + let effect = WorldEffect::Acted { invocation, event }; + + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + command_id, + &CallerId::Principal(owner()), + &effect, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + assert_eq!(candidate, kernel.state); + + let mut draft = kernel.state.clone(); + draft.phase = WorldPhase::Draft; + let error = apply_effect(&mut draft, command_id, &play_caller(), &effect).unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + + let mut honest = kernel.state.clone(); + apply_effect(&mut honest, command_id, &play_caller(), &effect).unwrap(); + assert_eq!(honest.events.len(), kernel.state.events.len() + 1); + } + /// There is no acting before activation. #[test] fn act_in_draft_is_wrong_phase() { From f51275c61d122563646ff3c1db1aa695ce4eea63 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Thu, 19 Nov 2026 23:52:05 +0100 Subject: [PATCH 132/190] Aetherlight AL2b-1: pin v8 schema ids, silent foreign actor, discharge-then-act Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/journal.rs | 117 ++++++++++++++++++++++++++++++ native/aetherlight/src/lib.rs | 35 +++++++++ 2 files changed, 152 insertions(+) diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index d680b57f8..ea042566c 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -2371,6 +2371,123 @@ mod custody_tests { ); } + /// Stores written at the previous schema ids (v7) are refused outright, + /// state row and commit row each on their own: reverting either constant + /// to v7 would let its half of the store in. + #[test] + fn v7_state_and_commit_rows_are_refused() { + use crate::tests::{act, activate, auth_principal, creation, first_grant, owner, speak}; + + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, _) = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "SchemaV7"), + &auth_principal(owner()), + ) + .unwrap(); + let active = activate(&mut kernel); + let actor = active.subjects[0].id; + act(&mut kernel, actor, speak(first_grant(&active, actor), "Counted.")).unwrap(); + let commits: Vec<WorldCommit> = kernel.journal.commits.values().cloned().collect(); + let commit_rows = |schema: &str| -> Vec<CultCacheEnvelope> { + commits + .iter() + .map(|commit| envelope(COMMIT_ROW, schema, commit.command.id().key(), commit).unwrap()) + .collect() + }; + let state_row = |schema: &str| { + envelope(STATE_ROW, schema, kernel.state.world_id.key(), &kernel.state).unwrap() + }; + assert_eq!(STATE_SCHEMA, "ghostlight.world_state.consumer.v8"); + assert_eq!(COMMIT_SCHEMA, "ghostlight.world_commit.consumer.v8"); + recover( + [commit_rows(COMMIT_SCHEMA), vec![state_row(STATE_SCHEMA)]].concat(), + None, + ) + .expect("the current schema ids recover"); + + for (what, rows) in [ + ( + "v7 state row", + [ + commit_rows(COMMIT_SCHEMA), + vec![state_row("ghostlight.world_state.consumer.v7")], + ] + .concat(), + ), + ( + "v7 commit rows", + [ + commit_rows("ghostlight.world_commit.consumer.v7"), + vec![state_row(STATE_SCHEMA)], + ] + .concat(), + ), + ] { + let error = recover(rows, None).unwrap_err(); + let JournalError::Corrupt(message) = error else { + panic!("{what}: expected a corrupt store, got {error:?}"); + }; + assert!(message.contains("wrong schema"), "{what}: {message}"); + } + } + + /// The event shape check holds for a silent act too: a non-speech event + /// whose actor is no subject is corrupt, with no minted claim to catch it. + #[test] + fn a_non_speech_event_with_a_foreign_actor_is_corrupt() { + use crate::tests::{ + act, activate, admit_custody, admit_topology, affordance_named, auth_principal, + creation, owner, + }; + use crate::{DecisionInvocation, Magnitude, ProposedEffect, Quantity, Role, RoleBinding, Target}; + + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, _) = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "SilentForgery"), + &auth_principal(owner()), + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + let active = activate(&mut kernel); + let role = |name: &str, target| RoleBinding { + role: Role(name.into()), + target, + }; + act( + &mut kernel, + custody.holder, + DecisionInvocation { + affordance: affordance_named(&active, "carry"), + bindings: vec![ + role("from", Target::Subject(custody.holder)), + role("recipient", Target::Subject(custody.counterparty)), + role("place", Target::Entity(topology.yard)), + role("resource", Target::Entity(custody.tithe)), + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(1)), + }], + speech: None, + display: None, + }, + ) + .unwrap(); + let event = kernel.state.events.last().unwrap(); + assert!(event.speech.is_none() && event.display.is_none()); + verify_state_shape(&kernel.state).expect("the honest silent event passes"); + + let mut forged = kernel.state.clone(); + forged.events.last_mut().unwrap().actor = crate::SubjectId::issue(); + assert!( + matches!(verify_state_shape(&forged), Err(JournalError::Corrupt(_))), + "a silent event naming no subject passed the shape check" + ); + } + /// Absence is zero and one slot holds one pair, so a stored zero, an empty /// holder, and a holding on something that is not a resource are each /// corrupt at replay. diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index 7fab23d87..ea1593b10 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -11600,6 +11600,41 @@ mod clock_tests { ); } + /// `Committed` reads the actor's commitments at Act time: once the + /// obligation to the treasury is discharged, the promisor's act that needs + /// it is refused and nothing commits. + #[test] + fn a_discharged_commitment_refuses_the_act_that_needs_it() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "DischargeThenAct"); + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.obligation, + }]), + ); + let events = kernel.state.events.len(); + let error = exercise( + &mut kernel, + clockwork.farmer, + clockwork.deliver, + vec![binding("creditor", Target::Subject(clockwork.treasury))], + ) + .unwrap_err(); + assert!( + matches!( + error, + KernelError::ActionRejected(ref mismatches) + if *mismatches == vec![ActionMismatch::NotCommitted { precondition: 0 }] + ), + "{error:?}" + ); + assert_eq!(kernel.state.events.len(), events); + } + /// `Committed` is a conjunction: the actor holds a commitment to this very /// counterparty and of this very kind. The farmer owes the treasury an /// obligation and nobody else, so naming the reeve fails the counterparty From be556e8a869a62c69b97100ea67c0357d92b710e Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 00:22:36 +0100 Subject: [PATCH 133/190] Aetherlight AL2b-2a: after genesis only Play writes; worlds are born Active CallerId is { Principal, Play }; one require_play gate at the top of reduce and apply_effect replaces the capability table, the owner's post-genesis doors and the Clock capability. The consumer lane (ConsumerId, PatchGround, mirrors, confine_to_ground, operation_ground), the draft phase and approvals, VerifiedPrincipalEvidence, the dead intents and the never-mute and Retire-side refusals are deleted. GrantsOutsideControl becomes GrantsToRetired; a grant row exists iff the subject holds a verb. require_ruler is genesis-only (forbid_rulings_at_genesis). Schema consumer.v9. Tests of deleted lanes are deleted, the rest go through submit_play. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/action.rs | 20 +- native/aetherlight/src/grammar/tests.rs | 35 +- native/aetherlight/src/import_key_tests.rs | 126 +- native/aetherlight/src/journal.rs | 326 +-- native/aetherlight/src/lib.rs | 2664 +++----------------- native/aetherlight/src/patch.rs | 265 +- 6 files changed, 694 insertions(+), 2742 deletions(-) diff --git a/native/aetherlight/src/action.rs b/native/aetherlight/src/action.rs index 2dcc50c75..885d65f42 100644 --- a/native/aetherlight/src/action.rs +++ b/native/aetherlight/src/action.rs @@ -251,8 +251,8 @@ pub(super) fn exercise( } /// The synthetic handle every minted claim allocates under. It is synthesized -/// only in Active and declarations are Draft-only, so no world-declared handle -/// can collide with it. +/// in an act, which declares nothing, so no world-declared handle can collide +/// with it. const SPEECH_HANDLE: &str = "ghostlight.speech"; /// The speech index, passed as `derive_id`'s discriminator. It is `0` for every @@ -1015,9 +1015,9 @@ mod tests { }; use crate::tests::{ ADMIT_KIND, COMMAND_KIND, Civic, LEVY_KIND, OPENING_BALANCE, SEIZURE_GRIEVANCE, Topology, - WARDEN_OFFICE, act, act_command, activate, affordance_named, authority_kind, civic_world, + WARDEN_OFFICE, act, act_command, affordance_named, authority_kind, civic_world, command, custody_world, grant_to, grievance, office, operations, over_place, - over_subject, play_caller, reject_owner, submit_owner, + over_subject, play_caller, reject_play, submit_play, }; use crate::{ AffordanceKindName, AuthenticatedCaller, AuthoredSource, CommandBody, Confidence, @@ -1230,7 +1230,7 @@ mod tests { // restores the two-hop cost: the check reads the live graph rather than // anything the proposal was bound against. let before = bench.kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut bench.kernel, &before, operations(vec![ComponentOp::OpenRoute { @@ -1241,7 +1241,7 @@ mod tests { assert!(bench.try_exercise(&near).is_ok()); let before = bench.kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut bench.kernel, &before, operations(vec![ComponentOp::CloseRoute { @@ -1721,7 +1721,7 @@ mod tests { fn the_kernel_speak_entry_commits_its_utterance_and_no_operation() { let directory = tempfile::tempdir().unwrap(); let mut kernel = custody_kernel(directory.path(), "SpeakEntry"); - let _topology = activate(&mut kernel); + let _topology = kernel.snapshot().unwrap(); let active = kernel.snapshot().unwrap(); let speak = affordance_named(&active, "speak"); let human = active @@ -1898,14 +1898,14 @@ mod tests { fn admit(&mut self, ops: Vec<ComponentOp>) { let before = self.kernel.snapshot().unwrap(); - let receipt = submit_owner(&mut self.kernel, &before, operations(ops)); + let receipt = submit_play(&mut self.kernel, &before, operations(ops)); assert!(matches!(receipt, SubmitReceipt::Applied(_))); self.refresh(); } fn refuse(&mut self, ops: Vec<ComponentOp>) -> Vec<crate::Mismatch> { let before = self.kernel.snapshot().unwrap(); - reject_owner(&mut self.kernel, &before, operations(ops)) + reject_play(&mut self.kernel, &before, operations(ops)) } } @@ -2024,7 +2024,7 @@ mod tests { let mut draft = custody_kernel(draft_directory.path(), "ReservedRole"); let before = draft.snapshot().unwrap(); let handle = DraftHandle::new("thief"); - let rejected = reject_owner( + let rejected = reject_play( &mut draft, &before, CommandBody::AdmitPatch { diff --git a/native/aetherlight/src/grammar/tests.rs b/native/aetherlight/src/grammar/tests.rs index 7dca39f73..9c31ff39d 100644 --- a/native/aetherlight/src/grammar/tests.rs +++ b/native/aetherlight/src/grammar/tests.rs @@ -102,12 +102,12 @@ fn admit(kernel: &mut WorldKernel, patch: WorldPatch) -> Result<SubmitReceipt, K command( &snapshot, CommandId::new(), - CallerId::Principal(owner()), + CallerId::Play, CommandBody::AdmitPatch { patch, }, ), - &auth_principal(owner()), + &crate::AuthenticatedCaller::verified_play(), ) } @@ -500,7 +500,7 @@ fn submit_as( ) } -/// A bound Draft world whose revision has moved past genesis: one owner patch +/// A bound world whose revision has moved past genesis: one Play patch /// that adds a dead-end place. fn advanced_grammar_world() -> (tempfile::TempDir, WorldKernel, crate::EntityId) { let extra = [("hail", verb(RenderPath::Conversation, &[]))]; @@ -540,8 +540,7 @@ fn advanced_grammar_world() -> (tempfile::TempDir, WorldKernel, crate::EntityId) type Door = (&'static str, CallerId); /// Each door refuses an outside kind and a wrong role signature, typed, and the -/// refusal leaves the revision where it was. The owner and the consumer declare -/// in Draft only; Play declares in Active. +/// refusal leaves the revision where it was. fn refuse_at_each_door(kernel: &mut WorldKernel, doors: Vec<Door>) { for (door, caller) in doors { let revision = kernel.state.revision; @@ -565,33 +564,15 @@ fn refuse_at_each_door(kernel: &mut WorldKernel, doors: Vec<Door>) { } #[test] -fn every_admission_door_refuses_outside_the_grammar_after_the_revision_has_moved() { +fn play_refuses_outside_the_grammar_after_the_revision_has_moved() { let (_dir, mut kernel, _) = advanced_grammar_world(); assert_eq!(kernel.state.revision, 1); - let draft_doors = vec![ - ("owner", CallerId::Principal(owner())), - ( - "consumer", - CallerId::System(crate::SystemCapability::Consumer { - consumer: crate::ConsumerId::of_name("grammar-door"), - }), - ), - ]; - refuse_at_each_door(&mut kernel, draft_doors); - crate::tests::activate(&mut kernel); - assert!( - kernel.state.revision > 1, - "the world has moved past genesis" - ); - let active_doors = vec![ - ("play", CallerId::System(crate::SystemCapability::Play)), - ]; - refuse_at_each_door(&mut kernel, active_doors); + refuse_at_each_door(&mut kernel, vec![("play", CallerId::Play)]); // The same path admits what the grammar carries, so the refusals above are // the grammar's and not a closed door. let receipt = submit_as( &mut kernel, - CallerId::System(crate::SystemCapability::Play), + CallerId::Play, patch_of(vec![declare("hail", "hail", &[])]), ) .unwrap(); @@ -670,7 +651,7 @@ fn an_effect_resolved_elsewhere_cannot_install_an_entry_outside_the_grammar() { let result = crate::apply_effect( &mut state, CommandId::new(), - &CallerId::Principal(owner()), + &CallerId::Play, &crate::WorldEffect::PatchAdmitted { resolved, }, diff --git a/native/aetherlight/src/import_key_tests.rs b/native/aetherlight/src/import_key_tests.rs index 5976d5d54..65eb5700c 100644 --- a/native/aetherlight/src/import_key_tests.rs +++ b/native/aetherlight/src/import_key_tests.rs @@ -6,11 +6,11 @@ use crate::patch::{ AccessKind, ComponentOp, Cost, Declaration, DraftHandle, EntityDeclaration, EntityKind, ImportKey, Mismatch, Ref, RouteDeclaration, }; -use crate::tests::{activate, auth_principal, command, creation, owner}; +use crate::tests::{auth_principal, command, creation, owner}; use crate::{ - CallerId, CommandBody, CommandId, ConsumerId, CreateWorld, EntityId, KernelError, + CallerId, CommandBody, CommandId, CreateWorld, EntityId, KernelError, NewController, SubjectDeclaration, SubjectKind, SubmitReceipt, - SystemCapability, WorldKernel, WorldPatch, + WorldKernel, WorldPatch, }; use std::collections::BTreeSet; @@ -88,16 +88,14 @@ fn commons(kernel: &WorldKernel) -> EntityId { *kernel.state.entities.keys().next().unwrap() } -/// A mirror subject: the one shape every door may declare, since it needs no -/// catalog grant. -fn mirror(handle: &str, import_key: Option<ImportKey>, place: EntityId) -> Declaration { +/// A keyed subject that holds no verbs: legal, since a subject may be declared +/// with none, and the lightest declaration an import can make. +fn keyed(handle: &str, import_key: Option<ImportKey>, place: EntityId) -> Declaration { Declaration::Subject(SubjectDeclaration { handle: DraftHandle::new(handle), label: format!("The {handle}"), kind: SubjectKind::Person, - controller: NewController::External { - consumer: ConsumerId::of_name("import-key"), - }, + controller: NewController::OperationalAgent, affordances: BTreeSet::new(), position: Some(Ref::Existing(place)), import_key, @@ -154,24 +152,23 @@ fn one_patch_cannot_declare_two_subjects_with_one_import_key() { let beta = Some(key("aetheria.ship", "Beta")); let error = submit_as( &mut kernel, - CallerId::Principal(owner()), + CallerId::Play, patch_of(vec![ - mirror("first", beta.clone(), place), - mirror("second", beta, place), + keyed("first", beta.clone(), place), + keyed("second", beta, place), ]), ); assert_eq!(rejected(error), vec![duplicate("second")]); assert_eq!(kernel.state.revision, revision, "a refusal moved the world"); } -/// The fixture world past genesis but still in Draft: the owner has added an -/// unwalked place. +/// The fixture world past genesis: Play has added an unwalked place. fn advanced_keyed_world() -> (tempfile::TempDir, WorldKernel, EntityId) { let (dir, mut kernel) = keyed_world(); let place = commons(&kernel); submit_as( &mut kernel, - CallerId::Principal(owner()), + CallerId::Play, patch_of(vec![ Declaration::Entity(EntityDeclaration { handle: DraftHandle::new("dead-end"), @@ -201,8 +198,7 @@ fn advanced_keyed_world() -> (tempfile::TempDir, WorldKernel, EntityId) { } /// Each door names the held key, typed, and the refusal leaves the revision -/// where it was. The owner and the consumer declare in Draft only; Play -/// declares in Active. +/// where it was. fn refuse_held_key_at_each_door( kernel: &mut WorldKernel, place: EntityId, @@ -213,7 +209,7 @@ fn refuse_held_key_at_each_door( let result = submit_as( kernel, caller, - patch_of(vec![mirror("copy", Some(alpha()), place)]), + patch_of(vec![keyed("copy", Some(alpha()), place)]), ); assert_eq!(rejected(result), vec![held("copy")], "{door}"); assert_eq!( @@ -223,12 +219,6 @@ fn refuse_held_key_at_each_door( } } -fn consumer() -> CallerId { - CallerId::System(SystemCapability::Consumer { - consumer: ConsumerId::of_name("import-key"), - }) -} - #[test] fn a_held_import_key_is_refused_at_every_door_after_the_revision_has_moved() { let (_dir, mut kernel, dead_end) = advanced_keyed_world(); @@ -236,33 +226,22 @@ fn a_held_import_key_is_refused_at_every_door_after_the_revision_has_moved() { refuse_held_key_at_each_door( &mut kernel, dead_end, - vec![ - ("owner", CallerId::Principal(owner())), - ("consumer", consumer()), - ], - ); - activate(&mut kernel); - refuse_held_key_at_each_door( - &mut kernel, - dead_end, - vec![ - ("play", CallerId::System(SystemCapability::Play)), - ], + vec![("play", CallerId::Play)], ); // The same doors admit an unheld key, so the refusals are the key's; and // what a door admitted is held against every later door. let fresh = key("aetheria.ship", "Gamma"); let receipt = submit_as( &mut kernel, - CallerId::System(SystemCapability::Play), - patch_of(vec![mirror("fresh", Some(fresh.clone()), dead_end)]), + CallerId::Play, + patch_of(vec![keyed("fresh", Some(fresh.clone()), dead_end)]), ) .unwrap(); assert!(matches!(receipt, SubmitReceipt::Applied(_))); let again = submit_as( &mut kernel, - CallerId::System(SystemCapability::Play), - patch_of(vec![mirror("fresh-again", Some(fresh), dead_end)]), + CallerId::Play, + patch_of(vec![keyed("fresh-again", Some(fresh), dead_end)]), ); assert_eq!(rejected(again), vec![held("fresh-again")]); } @@ -274,8 +253,8 @@ fn a_held_import_key_is_refused_in_a_later_patch() { let revision = kernel.state.revision; let error = submit_as( &mut kernel, - CallerId::Principal(owner()), - patch_of(vec![mirror("again", Some(alpha()), place)]), + CallerId::Play, + patch_of(vec![keyed("again", Some(alpha()), place)]), ); assert_eq!(rejected(error), vec![held("again")]); assert_eq!(kernel.state.revision, revision); @@ -296,7 +275,7 @@ fn a_retired_subjects_import_key_is_never_reissued() { .id; submit_as( &mut kernel, - CallerId::Principal(owner()), + CallerId::Play, WorldPatch { declarations: Vec::new(), operations: vec![ComponentOp::Retire { @@ -321,8 +300,8 @@ fn a_retired_subjects_import_key_is_never_reissued() { ); let error = submit_as( &mut kernel, - CallerId::Principal(owner()), - patch_of(vec![mirror("reborn", Some(alpha()), place)]), + CallerId::Play, + patch_of(vec![keyed("reborn", Some(alpha()), place)]), ); assert_eq!(rejected(error), vec![held("reborn")]); } @@ -347,11 +326,11 @@ fn keys_that_differ_in_any_way_are_distinct_records() { let declarations = forgeries .iter() .enumerate() - .map(|(index, forged)| mirror(&format!("forged-{index}"), Some(forged.clone()), place)) + .map(|(index, forged)| keyed(&format!("forged-{index}"), Some(forged.clone()), place)) .collect(); submit_as( &mut kernel, - CallerId::Principal(owner()), + CallerId::Play, patch_of(declarations), ) .expect("nine distinct keys beside the held one are admitted together"); @@ -361,8 +340,8 @@ fn keys_that_differ_in_any_way_are_distinct_records() { for (index, forged) in forgeries.iter().enumerate() { let again = submit_as( &mut kernel, - CallerId::Principal(owner()), - patch_of(vec![mirror("repeat", Some(forged.clone()), place)]), + CallerId::Play, + patch_of(vec![keyed("repeat", Some(forged.clone()), place)]), ); assert_eq!(rejected(again), vec![held("repeat")], "forgery {index}"); } @@ -390,8 +369,8 @@ fn a_malformed_import_key_is_refused_without_echoing_it() { for (index, bad) in cases.iter().enumerate() { let set = rejected(submit_as( &mut kernel, - CallerId::Principal(owner()), - patch_of(vec![mirror("bad", Some(bad.clone()), place)]), + CallerId::Play, + patch_of(vec![keyed("bad", Some(bad.clone()), place)]), )); assert_eq!(set, vec![malformed("bad")], "case {index}"); let spelled = format!("{set:?}"); @@ -409,11 +388,11 @@ fn a_malformed_import_key_is_refused_without_echoing_it() { let declarations = at_limit .iter() .enumerate() - .map(|(index, limit)| mirror(&format!("edge-{index}"), Some(limit.clone()), place)) + .map(|(index, limit)| keyed(&format!("edge-{index}"), Some(limit.clone()), place)) .collect(); submit_as( &mut kernel, - CallerId::Principal(owner()), + CallerId::Play, patch_of(declarations), ) .expect("keys of exactly 200 bytes per part are admitted"); @@ -427,7 +406,7 @@ fn the_subjects_map_refuses_a_second_subject_for_one_key_even_when_resolved_else crate::patch::resolve_patch( &kernel.state, CommandId::new(), - &patch_of(vec![mirror( + &patch_of(vec![keyed( handle, Some(key("aetheria.ship", "Omega")), place, @@ -444,7 +423,7 @@ fn the_subjects_map_refuses_a_second_subject_for_one_key_even_when_resolved_else crate::apply_effect( &mut state, CommandId::new(), - &CallerId::Principal(owner()), + &CallerId::Play, &effect(first), ) .unwrap(); @@ -452,7 +431,7 @@ fn the_subjects_map_refuses_a_second_subject_for_one_key_even_when_resolved_else let result = crate::apply_effect( &mut state, CommandId::new(), - &CallerId::Principal(owner()), + &CallerId::Play, &effect(second), ); assert!( @@ -525,8 +504,8 @@ fn a_record_key_is_one_canonical_spelling() { let submit = |kernel: &mut WorldKernel, handle: &str, record: &str| { submit_as( kernel, - CallerId::Principal(owner()), - patch_of(vec![mirror( + CallerId::Play, + patch_of(vec![keyed( handle, Some(key("aetheria.ship", record)), place, @@ -573,8 +552,8 @@ fn a_lore_page_path_with_spaces_is_a_record_key() { let declare = |kernel: &mut WorldKernel, handle: &str| { submit_as( kernel, - CallerId::Principal(owner()), - patch_of(vec![mirror( + CallerId::Play, + patch_of(vec![keyed( handle, Some(key("aetheria.lore", record)), place, @@ -591,8 +570,8 @@ fn a_loaded_state_with_a_bad_import_key_is_refused() { let place = commons(&kernel); submit_as( &mut kernel, - CallerId::Principal(owner()), - patch_of(vec![mirror( + CallerId::Play, + patch_of(vec![keyed( "beta", Some(key("aetheria.ship", "Beta")), place, @@ -640,8 +619,8 @@ fn admitting_a_resolved_effect_refuses_two_subjects_with_one_key() { &kernel.state, CommandId::new(), &patch_of(vec![ - mirror("first", Some(key("aetheria.ship", "Beta")), place), - mirror("second", Some(key("aetheria.ship", "Gamma")), place), + keyed("first", Some(key("aetheria.ship", "Beta")), place), + keyed("second", Some(key("aetheria.ship", "Gamma")), place), ]), ) .expect("two distinct keys resolve") @@ -677,8 +656,8 @@ fn a_decomposable_character_is_refused_in_nfd_at_every_position() { let submit = |kernel: &mut WorldKernel, handle: &str, record: String| { submit_as( kernel, - CallerId::Principal(owner()), - patch_of(vec![mirror( + CallerId::Play, + patch_of(vec![keyed( handle, Some(key("aetheria.lore", &record)), place, @@ -711,3 +690,18 @@ fn a_decomposable_character_is_refused_in_nfd_at_every_position() { "the genesis key and one NFC key per position are held, no NFD key" ); } + +#[test] +fn the_owner_door_is_closed_to_a_keyed_declaration() { + let (_dir, mut kernel) = keyed_world(); + let place = commons(&kernel); + let revision = kernel.state.revision; + let error = submit_as( + &mut kernel, + CallerId::Principal(owner()), + patch_of(vec![keyed("fresh", Some(key("aetheria.ship", "Gamma")), place)]), + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + assert_eq!(kernel.state.revision, revision); +} diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index ea042566c..41c293e80 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -428,10 +428,9 @@ pub(super) fn verify_history( // Authority is re-decided here for free: `apply_committed_command` // re-runs `reduce` against the pre-commit state and requires effect // equality, then `apply_effect`, and both of those call - // `require_patch_author` and `confine_to_ground`. A forged row - // claiming a confined caller for a patch outside its ground - // fails replay rather than being admitted by a reducer that trusts the - // recorded caller. A third statement of the same rule here would be a + // `require_play`. A forged row recording the owner as the caller of + // a post-genesis command fails replay rather than being admitted by a + // reducer that trusts the recorded caller. A third statement of the same rule here would be a // third owner of one decision. apply_committed_command(&mut replay, commit)?; // Two chain checks one state cannot make: the clock never runs @@ -494,7 +493,6 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> super::validate_principal(&state.owner).map_err(kernel_error)?; if state.subjects.is_empty() || state.controller_assignments.len() != state.subjects.len() - || state.affordance_grants.is_empty() { return Err(JournalError::Corrupt( "world ontology is empty or has split subject/controller ownership".into(), @@ -815,7 +813,7 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> .get(&scope) .ok_or_else(|| JournalError::Corrupt("decision subject has no controller".into()))?; super::validate_assignment(assignment).map_err(kernel_error)?; - // A mirror has no controller id, so it joins no uniqueness set. + // A retired subject has no controller id, so it joins no uniqueness set. if let Some(controller_id) = assignment.id() && !controller_ids.insert(controller_id) { @@ -833,31 +831,21 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> "controller assignment references an unknown subject".into(), )); } + // A grant row is a verb list: non-empty, for a live subject, catalog + // entries only. A subject holding no verb holds no row. for (scope, granted) in &state.affordance_grants { if !state.controller_assignments.contains_key(scope) + || super::is_retired(state, scope.subject_id) || granted.is_empty() || granted .iter() .any(|affordance_id| !state.affordance_catalog.contains_key(affordance_id)) { return Err(JournalError::Corrupt( - "affordance grant is empty, unscoped, or names no catalog entry".into(), + "affordance grant is empty, unscoped, retired, or names no catalog entry".into(), )); } } - // Both ways, the pairing `admit_resolved` decided: a mirror holds no grant, - // and every controller-bearing scope holds one. - if state - .controller_assignments - .iter() - .any(|(scope, assignment)| { - state.affordance_grants.contains_key(scope) != assignment.mode().is_some() - }) - { - return Err(JournalError::Corrupt( - "controller assignment and affordance grant do not pair".into(), - )); - } // Every stored entry still passes the declaration validator, so a forged // catalog row cannot install an entry the resolver would have refused. for entry in state.affordance_catalog.values() { @@ -867,20 +855,6 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> )); } } - // Approval shape holds only in Draft. Once the world is Active, the - // approvals that admitted it are frozen history: they are judged once by - // `reduce`'s `ActivateWorld` arm and after that by replay, not re-judged - // here against the present-day controller roster. Retiring the human - // (PA.f32) or adding a later human-controlled subject must not make a - // past activation retroactively corrupt. - if state.phase == super::WorldPhase::Draft { - let required = super::required_approvers(state); - if !state.draft_approvals.is_subset(&required) { - return Err(JournalError::Corrupt( - "draft approvals do not match canonical controller ownership".into(), - )); - } - } let mut event_ids = BTreeSet::new(); let mut claimed = BTreeSet::new(); let mut previous_event_revision = 0; @@ -1091,10 +1065,12 @@ mod tests { id: command_id, world_id: snapshot.world_id, expected_revision: snapshot.revision, - caller: CallerId::Principal(owner), - body: CommandBody::ApproveDraft, + caller: CallerId::Play, + body: CommandBody::AdvanceTime { + minutes: crate::TickMinutes::new(1).unwrap(), + }, }, - &authenticated, + &AuthenticatedCaller::verified_play(), ) .unwrap(); @@ -1104,7 +1080,9 @@ mod tests { let CommittedCommand::WorldCommand(command) = &mut command_forged.command else { panic!("expected a world command"); }; - command.body = CommandBody::ActivateWorld; + command.body = CommandBody::AdvanceTime { + minutes: crate::TickMinutes::new(2).unwrap(), + }; command_forged.digest = commit_digest(command_forged).unwrap(); command_forged_head.last_commit_digest = Some(command_forged.digest.clone()); @@ -1131,7 +1109,10 @@ mod tests { let mut effect_forged_head = kernel.state.clone(); let mut effect_forged_commits = kernel.journal.commits.clone(); let effect_forged = effect_forged_commits.get_mut(&command_id).unwrap(); - effect_forged.effect = WorldEffect::WorldActivated; + let WorldEffect::TimeAdvanced { to, .. } = &mut effect_forged.effect else { + panic!("expected a time effect"); + }; + *to = crate::FictionalMinutes(99); effect_forged.digest = commit_digest(effect_forged).unwrap(); effect_forged_head.last_commit_digest = Some(effect_forged.digest.clone()); @@ -1173,7 +1154,7 @@ mod tests { id: command_id, world_id: snapshot.world_id, expected_revision: snapshot.revision, - caller: CallerId::Principal(owner), + caller: CallerId::Play, body: CommandBody::AdmitPatch { patch: WorldPatch { declarations: vec![ @@ -1198,7 +1179,7 @@ mod tests { }, }, }, - &authenticated, + &AuthenticatedCaller::verified_play(), ) .unwrap(); @@ -1270,8 +1251,8 @@ mod tests { } /// A store written under an older schema is refused at open: both - /// `consumer.v4` strings and the pre-cut `consumer.v6` ones. No migration, - /// no dual read. + /// `consumer.v4` strings and the pre-cut `consumer.v6` and `consumer.v8` + /// ones. No migration, no dual read. #[test] fn a_store_written_under_an_older_schema_is_refused() { for (row_type, schema) in [ @@ -1279,6 +1260,8 @@ mod tests { (COMMIT_ROW, "ghostlight.world_commit.consumer.v4"), (STATE_ROW, "ghostlight.world_state.consumer.v6"), (COMMIT_ROW, "ghostlight.world_commit.consumer.v6"), + (STATE_ROW, "ghostlight.world_state.consumer.v8"), + (COMMIT_ROW, "ghostlight.world_commit.consumer.v8"), ] { let row = CultCacheEnvelope { key: "state".into(), @@ -1298,10 +1281,10 @@ mod tests { } } - /// A world whose history includes an owner's clock advance, reopened from - /// its own store rows. + /// A world whose history includes a patch and a clock advance, both Play's, + /// reopened from its own store rows. fn clock_history() -> (tempfile::TempDir, WorldKernel) { - use crate::tests::{activate, auth_principal, creation, owner, submit_owner}; + use crate::tests::{auth_principal, creation, owner, submit_play}; use crate::TickMinutes; let directory = tempfile::tempdir().unwrap(); @@ -1311,8 +1294,27 @@ mod tests { &auth_principal(owner()), ) .unwrap(); - let snapshot = activate(&mut kernel); - submit_owner( + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + patch: crate::WorldPatch { + declarations: vec![crate::patch::Declaration::Entity( + crate::patch::EntityDeclaration { + handle: crate::patch::DraftHandle::new("annex"), + label: "The Annex".into(), + kind: crate::patch::EntityKind::Place, + container: None, + }, + )], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + let snapshot = kernel.snapshot().unwrap(); + submit_play( &mut kernel, &snapshot, CommandBody::AdvanceTime { @@ -1333,10 +1335,10 @@ mod tests { rows } - /// Replay re-derives the owner's clock advance: the honest history reopens - /// to the same state digest and reading, and the store on disk does too. + /// Replay re-derives Play's patch and clock advance: the honest history + /// reopens to the same state digest and reading, and the store on disk does too. #[test] - fn a_history_with_an_owner_clock_advance_replays_exactly() { + fn a_history_with_a_patch_and_a_clock_advance_replays_exactly() { let (directory, kernel) = clock_history(); let honest: Vec<WorldCommit> = kernel.journal.commits.values().cloned().collect(); let (_, replayed, commits) = @@ -1356,46 +1358,57 @@ mod tests { /// A stored command is not believed about who made it. The forgery re-seals /// the commit around its rewrite and the head's last commit digest names the /// re-sealed commit, so no digest can answer for the check; the control, the - /// same re-sealing around the honest caller, replays. + /// same re-sealing around the honest caller, replays. Both Play's doors are + /// forged: a patch row and a clock row recorded as the owner's. #[test] - fn a_clock_advance_forged_to_another_caller_fails_replay() { - use crate::tests::human_principal; + fn a_commit_forged_to_the_owner_fails_replay() { + use crate::tests::owner; let (_directory, kernel) = clock_history(); let honest: Vec<WorldCommit> = kernel.journal.commits.values().cloned().collect(); - let forge = |rewrite: &dyn Fn(&mut WorldCommit)| -> (WorldState, Vec<WorldCommit>) { - let mut head = kernel.state.clone(); + // Re-seals the rewritten commit and every later one around it, so the + // chain of previous-commit digests agrees and only the caller check is + // left to refuse the history. + let forge = |is_row: &dyn Fn(&WorldEffect) -> bool, + rewrite: &dyn Fn(&mut WorldCommit)| + -> (WorldState, Vec<WorldCommit>) { let mut forged: Vec<WorldCommit> = honest.clone(); - let clock_row = forged - .iter_mut() - .filter(|commit| matches!(commit.effect, WorldEffect::TimeAdvanced { .. })) - .collect::<Vec<_>>(); - let [commit] = <[&mut WorldCommit; 1]>::try_from(clock_row) - .expect("the history holds exactly one clock row"); - assert_eq!( - commit.resulting_revision, head.revision, - "the clock row is the head commit" - ); - rewrite(commit); - commit.digest = commit_digest(commit).unwrap(); - head.last_commit_digest = Some(commit.digest.clone()); + forged.sort_by_key(|commit| commit.resulting_revision); + let rows: Vec<usize> = (0..forged.len()) + .filter(|index| is_row(&forged[*index].effect)) + .collect(); + let [at] = <[usize; 1]>::try_from(rows) + .expect("the history holds exactly one such row"); + rewrite(&mut forged[at]); + for index in at..forged.len() { + if index > at { + forged[index].previous_commit_digest = Some(forged[index - 1].digest.clone()); + } + forged[index].digest = commit_digest(&forged[index]).unwrap(); + } + let mut head = kernel.state.clone(); + head.last_commit_digest = forged.last().map(|commit| commit.digest.clone()); (head, forged) }; + let patch_row = |effect: &WorldEffect| matches!(effect, WorldEffect::PatchAdmitted { .. }); + let clock_row = |effect: &WorldEffect| matches!(effect, WorldEffect::TimeAdvanced { .. }); - let (head, control) = forge(&|_| {}); - recover(rows_of(&head, &control), None).expect("a consistent re-sealed store replays"); + for is_row in [&patch_row as &dyn Fn(&WorldEffect) -> bool, &clock_row] { + let (head, control) = forge(is_row, &|_| {}); + recover(rows_of(&head, &control), None) + .expect("a consistent re-sealed store replays"); - let (head, forged) = forge(&|commit| { - if let CommittedCommand::WorldCommand(command) = &mut commit.command { - command.caller = CallerId::Principal(human_principal()); - } - }); - let error = recover(rows_of(&head, &forged), None) - .expect_err("a clock advance forged to a non-owner replayed"); - let JournalError::Corrupt(detail) = error else { - panic!("unexpected refusal: {error:?}"); - }; - assert!(detail.contains("Unauthorized") || detail.contains("does not own"), "{detail}"); + let (head, forged) = forge(is_row, &|commit| { + if let CommittedCommand::WorldCommand(command) = &mut commit.command { + command.caller = CallerId::Principal(owner()); + } + }); + let error = recover(rows_of(&head, &forged), None) + .expect_err("a commit forged to the owner replayed"); + let JournalError::Corrupt(_) = error else { + panic!("unexpected refusal: {error:?}"); + }; + } } /// The tick is re-derived at replay by the same function that produced it, @@ -1403,9 +1416,9 @@ mod tests { /// its command. The clock chain refuses a rewritten reading the same way. #[test] fn a_forged_motion_does_not_replay() { - use crate::tests::{activate, auth_principal, command, owner}; + use crate::tests::{auth_principal, command, owner}; use crate::{ - AuthenticatedCaller, CallerId, CommandBody, FictionalMinutes, SystemCapability, + AuthenticatedCaller, CallerId, CommandBody, FictionalMinutes, TickMinutes, }; @@ -1418,9 +1431,9 @@ mod tests { &authenticated, ) .unwrap(); - let active = activate(&mut kernel); + let active = kernel.snapshot().unwrap(); let command_id = CommandId::new(); - let caller = CallerId::System(SystemCapability::Clock); + let caller = CallerId::Play; kernel .submit( command( @@ -1455,7 +1468,7 @@ mod tests { /// to move a different subject no longer reduces from its command. #[test] fn a_forged_relocate_effect_does_not_apply() { - use crate::tests::{activate, admit_topology, auth_principal, command, owner}; + use crate::tests::{admit_topology, auth_principal, command, owner}; let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("world.cc"); @@ -1467,14 +1480,14 @@ mod tests { ) .unwrap(); let topology = admit_topology(&mut kernel); - let active = activate(&mut kernel); + let active = kernel.snapshot().unwrap(); let command_id = CommandId::new(); kernel .submit( command( &active, command_id, - CallerId::Principal(owner()), + CallerId::Play, CommandBody::AdmitPatch { patch: WorldPatch { declarations: Vec::new(), @@ -1486,7 +1499,7 @@ mod tests { }, }, ), - &authenticated, + &AuthenticatedCaller::verified_play(), ) .unwrap(); @@ -1519,7 +1532,7 @@ mod tests { #[test] fn soul_a_forged_band_or_effect_in_the_journal_dies_at_replay() { use crate::tests::{ - activate, admit_custody, admit_topology, affordance_named, auth_principal, command, + admit_custody, admit_topology, affordance_named, auth_principal, command, owner, play_caller, }; use crate::{ @@ -1539,7 +1552,7 @@ mod tests { .unwrap(); let topology = admit_topology(&mut kernel); let custody = admit_custody(&mut kernel, &topology); - let active = activate(&mut kernel); + let active = kernel.snapshot().unwrap(); let entry = affordance_named(&active, kind); let caller = play_caller(); let command_id = CommandId::new(); @@ -2048,8 +2061,8 @@ mod tests { #[test] fn a_relocation_never_corrupts_a_civic_store() { use crate::tests::{ - LEVY_KIND, auth_principal, civic_world, operations, over_subject, owner, reject_owner, - submit_owner, + LEVY_KIND, auth_principal, civic_world, operations, over_subject, owner, reject_play, + submit_play, }; use crate::{ComponentOp, Mismatch, SubmitReceipt}; @@ -2066,7 +2079,7 @@ mod tests { let admit = |kernel: &mut WorldKernel, ops: Vec<ComponentOp>| { let before = kernel.snapshot().unwrap(); assert!(matches!( - submit_owner(kernel, &before, operations(ops)), + submit_play(kernel, &before, operations(ops)), SubmitReceipt::Applied(_) )); verify_state_shape(&kernel.state).expect("the committed store keeps its shape"); @@ -2097,7 +2110,7 @@ mod tests { assert!(place_covers(&kernel)); let before = kernel.snapshot().unwrap(); assert_eq!( - reject_owner(&mut kernel, &before, operations(name_farmer())), + reject_play(&mut kernel, &before, operations(name_farmer())), vec![Mismatch::OverlappingJurisdiction { operation: 0 }] ); @@ -2150,12 +2163,12 @@ mod custody_tests { .unwrap(); let topology = admit_topology(&mut kernel); let custody = admit_custody(&mut kernel, &topology); - let active = crate::tests::activate(&mut kernel); + let active = kernel.snapshot().unwrap(); let envelope = command( &active, CommandId::new(), - CallerId::Principal(owner()), + CallerId::Play, CommandBody::AdmitPatch { patch: WorldPatch { declarations: Vec::new(), @@ -2170,7 +2183,7 @@ mod custody_tests { }, ); let SubmitReceipt::Applied(receipt) = - kernel.submit(envelope.clone(), &authenticated).unwrap() + kernel.submit(envelope.clone(), &crate::AuthenticatedCaller::verified_play()).unwrap() else { panic!("expected an applied transfer"); }; @@ -2181,7 +2194,7 @@ mod custody_tests { let mut reopened = WorldKernel::open(&path, world_id).unwrap(); assert_eq!(reopened.snapshot().unwrap(), accepted); assert_eq!( - reopened.submit(envelope, &authenticated).unwrap(), + reopened.submit(envelope, &crate::AuthenticatedCaller::verified_play()).unwrap(), SubmitReceipt::AlreadyApplied(receipt) ); } @@ -2205,7 +2218,7 @@ mod custody_tests { .unwrap(); let topology = admit_topology(&mut kernel); let custody = admit_custody(&mut kernel, &topology); - let active = crate::tests::activate(&mut kernel); + let active = kernel.snapshot().unwrap(); let carry = affordance_named(&active, "carry"); let caller = play_caller(); @@ -2289,34 +2302,57 @@ mod custody_tests { ); } - /// PA.f39, M9: the Draft-only approval shape clause is defence in depth, - /// so it is pinned directly on `verify_state_shape` rather than only - /// through a full submit path. A fresh Draft world's approvals pass; a - /// forged principal outside `required_approvers` does not. + /// A grant row is a verb list for a live subject: each clause of the shape + /// check is pinned on `verify_state_shape` directly, one forged state per + /// clause, so deleting any one of them fails a case. #[test] - fn draft_approvals_outside_required_approvers_is_corrupt() { + fn a_malformed_grant_row_is_corrupt() { use crate::tests::{auth_principal, creation, owner}; + use crate::{AffordanceId, ControllerAssignment, DecisionScope, SubjectId}; let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("world.cc"); let (kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), "PAf39ApprovalShape"), + creation(CommandId::new(), "GrantRows"), &auth_principal(owner()), ) .unwrap(); - assert_eq!(kernel.state.phase, crate::WorldPhase::Draft); - verify_state_shape(&kernel.state) - .expect("a fresh Draft world has a canonical approval shape"); + verify_state_shape(&kernel.state).expect("a fresh world has canonical grant rows"); + let held = *kernel.state.affordance_grants.keys().next().unwrap(); - let mut forged = kernel.state.clone(); - forged - .draft_approvals - .insert(crate::PrincipalId::new("interloper@example.test")); - assert!( - matches!(verify_state_shape(&forged), Err(JournalError::Corrupt(_))), - "an approval outside the required set passed the shape check" - ); + let corrupt = |name: &str, forge: &dyn Fn(&mut WorldState)| { + let mut forged = kernel.state.clone(); + forge(&mut forged); + assert!( + matches!(verify_state_shape(&forged), Err(JournalError::Corrupt(_))), + "{name} passed the shape check" + ); + }; + corrupt("a grant row for a retired subject", &|state| { + state + .controller_assignments + .insert(held, ControllerAssignment::Retired); + }); + corrupt("an empty grant row", &|state| { + state.affordance_grants.get_mut(&held).unwrap().clear(); + }); + corrupt("a grant row for no subject", &|state| { + let verbs = state.affordance_grants[&held].clone(); + state.affordance_grants.insert( + DecisionScope { + subject_id: SubjectId::issue(), + }, + verbs, + ); + }); + corrupt("a grant row naming an uncataloged verb", &|state| { + state + .affordance_grants + .get_mut(&held) + .unwrap() + .insert(AffordanceId::issue()); + }); } /// A chain holding `Acted` commits recovers and verifies on reopen, and an @@ -2324,7 +2360,7 @@ mod custody_tests { #[test] fn an_acted_chain_reopens_and_a_foreign_actor_is_corrupt() { use crate::tests::{ - act, activate, auth_principal, creation, first_grant, owner, speak, + act, auth_principal, creation, first_grant, owner, speak, }; let directory = tempfile::tempdir().unwrap(); @@ -2335,7 +2371,7 @@ mod custody_tests { &auth_principal(owner()), ) .unwrap(); - let active = activate(&mut kernel); + let active = kernel.snapshot().unwrap(); let actor = *active.subjects.first().map(|subject| &subject.id).unwrap(); act( &mut kernel, @@ -2371,21 +2407,21 @@ mod custody_tests { ); } - /// Stores written at the previous schema ids (v7) are refused outright, + /// Stores written at the previous schema ids (v8) are refused outright, /// state row and commit row each on their own: reverting either constant - /// to v7 would let its half of the store in. + /// to v8 would let its half of the store in. #[test] - fn v7_state_and_commit_rows_are_refused() { - use crate::tests::{act, activate, auth_principal, creation, first_grant, owner, speak}; + fn v8_state_and_commit_rows_are_refused() { + use crate::tests::{act, auth_principal, creation, first_grant, owner, speak}; let directory = tempfile::tempdir().unwrap(); let (mut kernel, _) = WorldKernel::create( directory.path().join("world.cc"), - creation(CommandId::new(), "SchemaV7"), + creation(CommandId::new(), "SchemaV8"), &auth_principal(owner()), ) .unwrap(); - let active = activate(&mut kernel); + let active = kernel.snapshot().unwrap(); let actor = active.subjects[0].id; act(&mut kernel, actor, speak(first_grant(&active, actor), "Counted.")).unwrap(); let commits: Vec<WorldCommit> = kernel.journal.commits.values().cloned().collect(); @@ -2398,8 +2434,8 @@ mod custody_tests { let state_row = |schema: &str| { envelope(STATE_ROW, schema, kernel.state.world_id.key(), &kernel.state).unwrap() }; - assert_eq!(STATE_SCHEMA, "ghostlight.world_state.consumer.v8"); - assert_eq!(COMMIT_SCHEMA, "ghostlight.world_commit.consumer.v8"); + assert_eq!(STATE_SCHEMA, "ghostlight.world_state.consumer.v9"); + assert_eq!(COMMIT_SCHEMA, "ghostlight.world_commit.consumer.v9"); recover( [commit_rows(COMMIT_SCHEMA), vec![state_row(STATE_SCHEMA)]].concat(), None, @@ -2408,17 +2444,17 @@ mod custody_tests { for (what, rows) in [ ( - "v7 state row", + "v8 state row", [ commit_rows(COMMIT_SCHEMA), - vec![state_row("ghostlight.world_state.consumer.v7")], + vec![state_row("ghostlight.world_state.consumer.v8")], ] .concat(), ), ( - "v7 commit rows", + "v8 commit rows", [ - commit_rows("ghostlight.world_commit.consumer.v7"), + commit_rows("ghostlight.world_commit.consumer.v8"), vec![state_row(STATE_SCHEMA)], ] .concat(), @@ -2437,7 +2473,7 @@ mod custody_tests { #[test] fn a_non_speech_event_with_a_foreign_actor_is_corrupt() { use crate::tests::{ - act, activate, admit_custody, admit_topology, affordance_named, auth_principal, + act, admit_custody, admit_topology, affordance_named, auth_principal, creation, owner, }; use crate::{DecisionInvocation, Magnitude, ProposedEffect, Quantity, Role, RoleBinding, Target}; @@ -2451,7 +2487,7 @@ mod custody_tests { .unwrap(); let topology = admit_topology(&mut kernel); let custody = admit_custody(&mut kernel, &topology); - let active = activate(&mut kernel); + let active = kernel.snapshot().unwrap(); let role = |name: &str, target| RoleBinding { role: Role(name.into()), target, @@ -2507,7 +2543,6 @@ mod custody_tests { .unwrap(); let topology = admit_topology(&mut kernel); let custody = admit_custody(&mut kernel, &topology); - crate::tests::activate(&mut kernel); verify_state_shape(&kernel.state).expect("the admitted world has a canonical shape"); let mut zero = kernel.state.clone(); @@ -2571,12 +2606,12 @@ mod custody_tests { // `Admit` and its evidence are Draft-only, so the opening balance is // already on the log before activation. let custody = admit_custody(&mut kernel, &topology); - let active = crate::tests::activate(&mut kernel); + let active = kernel.snapshot().unwrap(); let envelope = command( &active, CommandId::new(), - CallerId::Principal(owner()), + CallerId::Play, CommandBody::AdmitPatch { patch: WorldPatch { declarations: Vec::new(), @@ -2612,7 +2647,7 @@ mod custody_tests { }, ); let SubmitReceipt::Applied(receipt) = - kernel.submit(envelope.clone(), &authenticated).unwrap() + kernel.submit(envelope.clone(), &crate::AuthenticatedCaller::verified_play()).unwrap() else { panic!("expected an applied custody patch"); }; @@ -2629,7 +2664,7 @@ mod custody_tests { assert_eq!(reopened.state.dependencies, dependencies); assert_eq!(reopened.state.state_digest, digest); assert_eq!( - reopened.submit(envelope, &authenticated).unwrap(), + reopened.submit(envelope, &crate::AuthenticatedCaller::verified_play()).unwrap(), SubmitReceipt::AlreadyApplied(receipt) ); } @@ -2650,7 +2685,6 @@ mod custody_tests { .unwrap(); let topology = admit_topology(&mut kernel); let custody = admit_custody(&mut kernel, &topology); - crate::tests::activate(&mut kernel); verify_state_shape(&kernel.state).expect("the admitted world has a canonical shape"); // A place is not a resource, so a resource dependency naming one dangles. @@ -2690,10 +2724,10 @@ mod custody_tests { /// A world with one routine, one past-due goal, and a commit chain that /// reaches them: the fixture the two clock-forgery checks below need. fn ticking_world(path: &std::path::Path) -> (WorldKernel, super::super::SubjectId, CommandId) { - use crate::tests::{activate, auth_principal, command, operations, owner}; + use crate::tests::{auth_principal, command, operations, owner}; use crate::{ AuthenticatedCaller, CallerId, CommandBody, CommitmentKind, ComponentOp, - FictionalMinutes, Ref, SystemCapability, TickMinutes, + FictionalMinutes, Ref, TickMinutes, }; let authenticated = auth_principal(owner()); @@ -2703,7 +2737,7 @@ mod custody_tests { &authenticated, ) .unwrap(); - let active = activate(&mut kernel); + let active = kernel.snapshot().unwrap(); let subject = active.subjects.first().expect("a seeded subject").id; let snapshot = kernel.snapshot().unwrap(); kernel @@ -2711,7 +2745,7 @@ mod custody_tests { command( &snapshot, CommandId::new(), - CallerId::Principal(owner()), + CallerId::Play, operations(vec![ ComponentOp::CreateCommitment { subject: Ref::Existing(subject), @@ -2733,12 +2767,12 @@ mod custody_tests { }, ]), ), - &authenticated, + &AuthenticatedCaller::verified_play(), ) .unwrap(); let tick_id = CommandId::new(); - let caller = CallerId::System(SystemCapability::Clock); + let caller = CallerId::Play; let snapshot = kernel.snapshot().unwrap(); kernel .submit( diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index ea1593b10..53b265fb0 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -103,50 +103,8 @@ use std::path::Path; use thiserror::Error; use uuid::Uuid; -/// Proof that the consumer verified a live principal, and the moment that -/// proof stops being worth anything. -/// -/// The consumer verifies; this library carries the proof. `valid_until` is the -/// consumer's own session expiry, not a fresh clock read at construction. -/// Nothing in this crate enforces it yet: Ghostlight's mailbox refused evidence -/// presented after it, and the mailbox is not part of the fork, so the ABI that -/// AL4 adds must carry that check. -/// -/// Keeping this type here, rather than taking the consumer's own session type, -/// is what keeps the consumer's principal format out of the kernel. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct VerifiedPrincipalEvidence { - account_subject_hash: String, - valid_until: DateTime<Utc>, -} - -impl VerifiedPrincipalEvidence { - pub fn new(account_subject_hash: impl Into<String>, valid_until: DateTime<Utc>) -> Self { - Self { - account_subject_hash: account_subject_hash.into(), - valid_until, - } - } - - pub fn account_subject_hash(&self) -> &str { - &self.account_subject_hash - } - - pub fn valid_until(&self) -> DateTime<Utc> { - self.valid_until - } - - #[cfg(test)] - pub(crate) fn fixture( - account_subject_hash: impl Into<String>, - valid_until: DateTime<Utc>, - ) -> Self { - Self::new(account_subject_hash, valid_until) - } -} - -pub const STATE_SCHEMA: &str = "ghostlight.world_state.consumer.v8"; -pub(crate) const COMMIT_SCHEMA: &str = "ghostlight.world_commit.consumer.v8"; +pub const STATE_SCHEMA: &str = "ghostlight.world_state.consumer.v9"; +pub(crate) const COMMIT_SCHEMA: &str = "ghostlight.world_commit.consumer.v9"; /// Compatibility tag derived from [`STATE_SCHEMA`]: the trailing /// `<family>-<version>` pair (e.g. `foundation-v1`). Callers that publish a @@ -291,13 +249,6 @@ impl PrincipalId { } } -#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum WorldPhase { - Draft, - Active, -} - #[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] #[serde(rename_all = "snake_case")] pub enum SubjectKind { @@ -314,29 +265,6 @@ pub enum ControllerMode { OperationalAgent, } -/// A configured external consumer. Opaque inside the kernel: derived from the -/// consumer's configured name at the ingress registry and never spelled back -/// out, so no consumer name can reach a match arm. -#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[serde(transparent)] -pub(crate) struct ConsumerId(Uuid); - -/// The one namespace a configured consumer name lowers through. -const CONSUMER_ID_NAMESPACE: &str = "ghostlight.consumer.id.v0"; - -impl ConsumerId { - /// The one lowering from a configured name, through `CommandId::derived`'s - /// recipe over its own namespace. Called only by the ingress registry. - pub(crate) fn of_name(name: &str) -> Self { - Self(CommandId::derived(CONSUMER_ID_NAMESPACE, &[name]).0) - } - - /// Canonical text, for the command-key derivation that hashes it. - pub(crate) fn text(self) -> String { - self.0.to_string() - } -} - #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type", rename_all = "snake_case")] pub(crate) enum NewController { @@ -345,11 +273,6 @@ pub(crate) enum NewController { }, NarrativePersona, OperationalAgent, - /// Declared as a mirror of state this world does not own. Mints no - /// controller, no mode, and no grants. - External { - consumer: ConsumerId, - }, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] @@ -364,60 +287,16 @@ struct CreateWorld { grammar: Option<GrammarBinding>, } -/// Unattributed creation intent. World ingress derives ownership, controller -/// identity, handles, kinds, and affordances from verified principal evidence. -#[derive(Clone, Debug)] -pub struct CreateWorldIntent { - pub id: CommandId, - pub title: String, - pub human_subject_label: String, - pub narrative_persona_label: Option<String>, - pub operational_agent_label: Option<String>, -} - +/// Who wrote a command. The owner principal authors genesis and nothing after +/// it; after genesis `Play` is the only caller any command body admits. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type", content = "id", rename_all = "snake_case")] enum CallerId { Principal(PrincipalId), - Controller(ControllerId), - /// An internal capability. Never derived from session evidence, never - /// minted by ingress, and admitted for exactly one command body. - System(SystemCapability), -} - -/// Internally tagged, because a data-carrying variant cannot join a bare-string -/// encoding without silently changing every commit that already carries -/// `Clock`. The tag is part of the commit digest, so the schema bumps with it. -#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(tag = "capability", rename_all = "snake_case")] -enum SystemCapability { - Clock, - /// One external consumer, authoring only the subjects this world has - /// admitted as its mirrors. Minted by exactly one mailbox method, after the - /// ingress has authenticated the document; never derived from session - /// evidence. - Consumer { - consumer: ConsumerId, - }, - /// The play table. Admitted for unanswered, unconfined Active patches, the - /// only author of `Ruled` facts and `Mint`, and for the clock. Minted only - /// by `PlayPort`. + /// The play table, minted only by `PlayPort`. Play, } -/// What a confined patch author may write. `None` from `require_patch_author` -/// still means unconfined: the owner. -/// -/// Deliberately not `AuthorityTarget`. That is in-world grant vocabulary read -/// by `covers` and `targets_overlap`; this names a caller's write scope, and -/// its consumer arm names a caller rather than a subject — the subject set is -/// derived from `controller_assignments` at decision time. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum PatchGround { - /// Every subject bound to this consumer. - Consumer(ConsumerId), -} - #[derive(Clone, Debug)] struct AuthenticatedCaller { caller: CallerId, @@ -430,17 +309,10 @@ impl AuthenticatedCaller { } } - fn verified_controller(controller: ControllerId) -> Self { + /// Visible only inside the `world` subtree. Runtime ingress cannot reach it. + fn verified_play() -> Self { Self { - caller: CallerId::Controller(controller), - } - } - - /// Visible only inside the `world` subtree and called only by - /// `WorldMailbox::submit_clock`. Runtime ingress cannot reach it. - fn verified_system(capability: SystemCapability) -> Self { - Self { - caller: CallerId::System(capability), + caller: CallerId::Play, } } @@ -518,32 +390,20 @@ struct CommandEnvelope { body: CommandBody, } -/// Unattributed human command intent. The mailbox derives the caller from -/// live app-session evidence before the reducer sees an envelope. -#[derive(Clone, Debug)] -pub struct PrincipalCommandIntent { - pub id: CommandId, - pub world_id: WorldId, - pub expected_revision: u64, - pub body: CommandBody, -} - #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type", rename_all = "snake_case")] pub enum CommandBody { - ApproveDraft, - ActivateWorld, /// One subject's act. Play's alone: the actor's grants decide whether the /// affordance is its to use. Act { actor: SubjectId, invocation: DecisionInvocation, }, + /// A patch to the world. Play's alone. AdmitPatch { patch: WorldPatch, }, - /// The world's only clock advance. Owner or the clock capability, and the - /// clock capability may do nothing else. + /// The world's only clock advance. Play's alone. AdvanceTime { minutes: TickMinutes, }, @@ -572,16 +432,8 @@ enum ControllerAssignment { OperationalAgent { controller_id: ControllerId, }, - /// A mirror of state this world does not own. It has no controller id and - /// no mode, because the kernel will not keep a fictional one so an accessor - /// can stay infallible. - ExternallyControlled { - consumer: ConsumerId, - }, - /// A subject `Retire` ended for good. Not a second partition: - /// `controller_assignments` stays the sole answer to who may call, and - /// this is one of its values. It has no controller id, no mode, and no - /// caller, so it holds no grants and is never an audience. + /// A subject `Retire` ended for good. It has no controller id and no mode, + /// so it holds no grants and is never an audience. Retired, } @@ -591,7 +443,7 @@ impl ControllerAssignment { Self::Human { controller_id, .. } | Self::NarrativePersona { controller_id } | Self::OperationalAgent { controller_id } => Some(*controller_id), - Self::ExternallyControlled { .. } | Self::Retired => None, + Self::Retired => None, } } @@ -600,43 +452,15 @@ impl ControllerAssignment { Self::Human { .. } => Some(ControllerMode::Human), Self::NarrativePersona { .. } => Some(ControllerMode::NarrativePersona), Self::OperationalAgent { .. } => Some(ControllerMode::OperationalAgent), - Self::ExternallyControlled { .. } | Self::Retired => None, - } - } - - /// `None` for a retired subject: no caller may ever act for it again. A - /// mirror still returns `Some`, the one caller that could ever act for - /// its scope; the controller lane cannot mint it either, but that caller - /// exists and is comparable. - fn expected_caller(&self) -> Option<CallerId> { - match self { - Self::Human { principal, .. } => Some(CallerId::Principal(principal.clone())), - Self::NarrativePersona { controller_id } | Self::OperationalAgent { controller_id } => { - Some(CallerId::Controller(*controller_id)) - } - Self::ExternallyControlled { consumer } => Some(CallerId::System( - SystemCapability::Consumer { consumer: *consumer }, - )), Self::Retired => None, } } - fn consumer(&self) -> Option<ConsumerId> { - match self { - Self::ExternallyControlled { consumer } => Some(*consumer), - Self::Human { .. } - | Self::NarrativePersona { .. } - | Self::OperationalAgent { .. } - | Self::Retired => None, - } - } - fn human_principal(&self) -> Option<&PrincipalId> { match self { Self::Human { principal, .. } => Some(principal), Self::NarrativePersona { .. } | Self::OperationalAgent { .. } - | Self::ExternallyControlled { .. } | Self::Retired => None, } } @@ -669,7 +493,6 @@ struct WorldState { schema: String, world_id: WorldId, revision: u64, - phase: WorldPhase, owner: PrincipalId, title: String, /// Bound by genesis and never written again; absent from a world with no @@ -677,7 +500,6 @@ struct WorldState { /// grammars existed. #[serde(default, skip_serializing_if = "Option::is_none")] grammar: Option<GrammarBinding>, - draft_approvals: BTreeSet<PrincipalId>, subjects: BTreeMap<SubjectId, SubjectState>, entities: BTreeMap<EntityId, EntityRecord>, edges: BTreeMap<EdgeId, EdgeRecord>, @@ -724,10 +546,11 @@ struct WorldState { /// scope: it is world truth, and it is read by no precondition. now: FictionalMinutes, controller_assignments: BTreeMap<DecisionScope, ControllerAssignment>, - /// What an affordance *is*. World-authored, Draft-only, written by - /// `admit_resolved` alone. + /// What an affordance *is*. World-authored and written by `admit_resolved` + /// alone. affordance_catalog: BTreeMap<AffordanceId, Affordance>, - /// Who may exercise which entry. A grant carries no payload, so a duplicate + /// Who may exercise which entry: a row exists if and only if the subject + /// holds at least one verb. A grant carries no payload, so a duplicate /// grant is unrepresentable rather than checked. affordance_grants: BTreeMap<DecisionScope, BTreeSet<AffordanceId>>, events: Vec<DecisionEvent>, @@ -746,10 +569,6 @@ enum WorldEffect { PatchAdmitted { resolved: ResolvedPatch, }, - DraftApproved { - principal: PrincipalId, - }, - WorldActivated, Acted { /// The command's own input, kept beside the event rather than inside it: /// the invocation is what the caller said, the event is what the world @@ -758,7 +577,7 @@ enum WorldEffect { event: DecisionEvent, }, /// The first effect that mutates state for subjects other than one scope. - /// Its gate is the clock capability or the owner, and `apply_effect` + /// Play's alone, and `apply_effect` /// re-derives the whole motion, so a forged fulfilment, magnitude, row, or /// target is one comparison rather than a clause apiece. TimeAdvanced { @@ -817,8 +636,8 @@ pub struct SubjectSnapshot { pub kind: SubjectKind, /// The Aetheria record this subject was imported from, if it was. pub import_key: Option<ImportKey>, - /// Absent for an externally controlled mirror, which has no controller and - /// no turn. Every reader fails closed on `None`; none gets a default. + /// Absent for a retired subject, which has no controller and no turn. + /// Every reader fails closed on `None`; none gets a default. pub(crate) controller_id: Option<ControllerId>, pub controller_mode: Option<ControllerMode>, pub human_controller: Option<PrincipalId>, @@ -1012,13 +831,10 @@ pub(crate) struct FactSnapshot { pub struct WorldSnapshot { pub world_id: WorldId, pub revision: u64, - pub phase: WorldPhase, pub owner: PrincipalId, pub title: String, /// The bound grammar's identity; none for a world with an open catalog. pub grammar: Option<GrammarIdentity>, - pub draft_approvals: BTreeSet<PrincipalId>, - pub required_approvers: BTreeSet<PrincipalId>, pub subjects: Vec<SubjectSnapshot>, pub affordances: Vec<AffordanceSnapshot>, pub places: Vec<PlaceSnapshot>, @@ -1098,7 +914,7 @@ pub enum KernelError { InvalidCommandId, #[error("world title must not be empty")] EmptyTitle, - #[error("world owner or human controller principal must be canonical and nonempty")] + #[error("world owner principal must be canonical and nonempty")] EmptyPrincipal, #[error("patch rejected: {0:?}")] PatchRejected(Vec<Mismatch>), @@ -1110,17 +926,6 @@ pub enum KernelError { AuthenticationMismatch, #[error("caller does not own this world")] Unauthorized, - #[error("command requires phase {expected:?}, current phase is {actual:?}")] - WrongPhase { - expected: WorldPhase, - actual: WorldPhase, - }, - #[error("caller is not a required draft approver")] - NotDraftApprover, - #[error("caller has already approved this draft")] - DraftAlreadyApproved, - #[error("draft is missing required approvals: {0:?}")] - MissingApprovals(Vec<PrincipalId>), #[error("decision affordance is not granted to the actor")] AffordanceDenied, #[error("expected revision {expected}, current revision {actual}")] @@ -1215,8 +1020,7 @@ fn prepare_creation( &input.patch, ) .map_err(KernelError::PatchRejected)?; - require_ruler(&CallerId::Principal(input.owner.clone()), &resolved) - .map_err(KernelError::PatchRejected)?; + forbid_rulings_at_genesis(&resolved).map_err(KernelError::PatchRejected)?; Ok(PreparedCreation { world_id, owner: input.owner.clone(), @@ -1369,43 +1173,12 @@ impl WorldKernel { } fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result<WorldEffect, KernelError> { - // The one admission rule for internal capabilities, stated here and again - // at the top of `apply_effect`: `reduce` decides and `apply_effect` - // re-decides, which is how every gate in this file is written. - require_system_capability(&command.caller, &command.body)?; + // The one admission rule, stated here and again at the top of + // `apply_effect`: `reduce` decides and `apply_effect` re-decides, which is + // how every gate in this file is written. + require_play(&command.caller)?; match &command.body { - CommandBody::ApproveDraft => { - require_phase(state, WorldPhase::Draft)?; - let CallerId::Principal(principal) = &command.caller else { - return Err(KernelError::NotDraftApprover); - }; - if !required_approvers(state).contains(principal) { - return Err(KernelError::NotDraftApprover); - } - if state.draft_approvals.contains(principal) { - return Err(KernelError::DraftAlreadyApproved); - } - Ok(WorldEffect::DraftApproved { - principal: principal.clone(), - }) - } - CommandBody::ActivateWorld => { - require_owner(state, &command.caller)?; - require_phase(state, WorldPhase::Draft)?; - let missing: Vec<_> = required_approvers(state) - .difference(&state.draft_approvals) - .cloned() - .collect(); - if !missing.is_empty() { - return Err(KernelError::MissingApprovals(missing)); - } - Ok(WorldEffect::WorldActivated) - } CommandBody::Act { actor, invocation } => { - require_phase(state, WorldPhase::Active)?; - if command.caller != CallerId::System(SystemCapability::Play) { - return Err(KernelError::Unauthorized); - } let granted = require_granted(state, *actor, invocation.affordance)?; let event = action::exercise(state, command.id, *actor, &granted, invocation)?; Ok(WorldEffect::Acted { @@ -1414,10 +1187,6 @@ fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result<WorldEffect, }) } CommandBody::AdvanceTime { minutes } => { - // There is no time in Draft: a world under construction has no due - // dates to cross. - require_phase(state, WorldPhase::Active)?; - require_clock_caller(state, &command.caller)?; let to = state .now .checked_add(*minutes) @@ -1432,90 +1201,25 @@ fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result<WorldEffect, }) } CommandBody::AdmitPatch { patch } => { - require_play_active( - state, - &command.caller, - !(patch.declarations.is_empty() && patch.evidence.is_empty()), - )?; - // Resolution before confinement, because confinement reads - // draft-resolved referents and a structurally broken patch should - // return its complete mismatch set rather than a jurisdiction - // complaint about a reference that does not resolve. - let confinement = require_patch_author(state, &command.caller)?; let resolved = patch::resolve_patch(state, command.id, patch) .map_err(KernelError::PatchRejected)?; - require_ruler(&command.caller, &resolved).map_err(KernelError::PatchRejected)?; - if let Some(ground) = confinement { - confine_to_ground(state, &resolved, ground).map_err(KernelError::PatchRejected)?; - } Ok(WorldEffect::PatchAdmitted { resolved }) } } } -/// A system capability is admitted for exactly one command body and nothing -/// else. Stated once here, reached by `reduce` and by `apply_effect`. -fn require_system_capability(caller: &CallerId, body: &CommandBody) -> Result<(), KernelError> { - let CallerId::System(capability) = caller else { - return Ok(()); - }; - let admitted = matches!( - (capability, body), - (SystemCapability::Clock, CommandBody::AdvanceTime { .. }) - | (SystemCapability::Play, CommandBody::AdvanceTime { .. }) - | ( - SystemCapability::Consumer { .. } | SystemCapability::Play, - CommandBody::AdmitPatch { .. } - ) - | (SystemCapability::Play, CommandBody::Act { .. }) - ); - if admitted { - Ok(()) - } else { - Err(KernelError::Unauthorized) +/// The one admission rule: after genesis Play is the only caller any command +/// body admits. Stated once here, reached by `reduce` and by `apply_effect`. +fn require_play(caller: &CallerId) -> Result<(), KernelError> { + match caller { + CallerId::Play => Ok(()), + CallerId::Principal(_) => Err(KernelError::Unauthorized), } } -/// The owner may tick from an interface; the tick task may tick with no -/// session. Nothing -/// else may tick. -fn require_clock_caller(state: &WorldState, caller: &CallerId) -> Result<(), KernelError> { - if matches!( - caller, - CallerId::System(SystemCapability::Clock) | CallerId::System(SystemCapability::Play) - ) { - Ok(()) - } else { - require_owner(state, caller) - } -} - -/// The play table authors nothing in Draft, and in Active declaring (new -/// structure, or evidence) is the play table's act alone: the host reports -/// events as typed commands and scripts propose, so no second door opens -/// beside that path. A patch that only changes components of existing -/// structure is any admitted author's. -fn require_play_active( - state: &WorldState, - caller: &CallerId, - declares: bool, -) -> Result<(), KernelError> { - let play = caller == &CallerId::System(SystemCapability::Play); - if play && state.phase == WorldPhase::Draft { - return Err(KernelError::WrongPhase { - expected: WorldPhase::Active, - actual: state.phase, - }); - } - if declares && !play && state.phase == WorldPhase::Active { - return Err(KernelError::Unauthorized); - } - Ok(()) -} - -/// A human principal joins `required_approvers`, so only the lane that builds -/// revision 0 from nothing may bind one. The predicate reads state, never the -/// caller. It takes the two fields it inspects rather than a whole +/// The genesis predicate: the world is being built from nothing, so the one +/// lane that builds revision 0 may bind a human controller. It reads state, +/// never the caller. It takes the two fields it inspects rather than a whole /// `WorldState` so the genesis lane, which resolves declarations before any /// `WorldState` exists, can call the same owner instead of hand-copying the /// literal it would otherwise always evaluate to. @@ -1537,11 +1241,9 @@ impl WorldState { schema: STATE_SCHEMA.into(), world_id, revision: 0, - phase: WorldPhase::Draft, owner, title, grammar, - draft_approvals: BTreeSet::new(), subjects: BTreeMap::new(), entities: BTreeMap::new(), edges: BTreeMap::new(), @@ -1603,10 +1305,8 @@ impl WorldState { "genesis effect does not derive from its creation command".into(), )); } - require_ruler(&CallerId::Principal(command.owner.clone()), resolved).map_err(|_| { - KernelError::Invariant( - "genesis effect rules or mints without the play authority".into(), - ) + forbid_rulings_at_genesis(resolved).map_err(|_| { + KernelError::Invariant("genesis effect rules or mints without the play authority".into()) })?; // Genesis resolves to revision 0 itself: `state.revision` never // advances past 0 for the creating commit (`resulting_revision: 0`), @@ -1749,17 +1449,6 @@ fn admit_resolved( "only world genesis may bind a human controller".into(), )); } - // Controller-shaped, both ways: a mirror receives no affordance, and - // every other controller must receive one. - if matches!( - subject.controller, - ControllerAssignment::ExternallyControlled { .. } - ) != subject.affordances.is_empty() - { - return Err(KernelError::Invariant( - "admitted subject's controller and affordance grant do not pair".into(), - )); - } if let Some(position) = subject.position && state .entities @@ -2731,21 +2420,6 @@ fn apply_operation( "retire operation names an already retired subject".into(), )); } - ControllerAssignment::ExternallyControlled { .. } => { - return Err(KernelError::Invariant( - "retire operation names a mirror this world does not own".into(), - )); - } - // A human's Draft approval cannot be removed by removing the - // human: re-decided here beside the resolver's - // `RetiresAnApprover`, since resolution is speculative and - // this is the actual commit. Active retires the human freely; - // its approval is frozen history by then, judged by replay. - ControllerAssignment::Human { .. } if state.phase == WorldPhase::Draft => { - return Err(KernelError::Invariant( - "retire operation would remove a Draft approver".into(), - )); - } ControllerAssignment::Human { .. } | ControllerAssignment::NarrativePersona { .. } | ControllerAssignment::OperationalAgent { .. } => {} @@ -2762,29 +2436,36 @@ fn apply_operation( let scope = DecisionScope { subject_id: *subject, }; - let assignment = state.controller_assignments.get(&scope).ok_or_else(unknown)?; - if assignment.mode().is_none() || !state.affordance_catalog.contains_key(affordance) { + if !state.controller_assignments.contains_key(&scope) + || is_retired(state, *subject) + || !state.affordance_catalog.contains_key(affordance) + { return Err(unknown()); } - let granted = state - .affordance_grants - .get_mut(&scope) - .ok_or_else(unknown)?; - let held = granted.contains(affordance); - if held == granting { - return Err(KernelError::Invariant( - "affordance grant operation changes nothing".into(), - )); - } if granting { - granted.insert(*affordance); - } else { - if granted.len() == 1 { + if !state + .affordance_grants + .entry(scope) + .or_default() + .insert(*affordance) + { return Err(KernelError::Invariant( - "revoke would leave a controlled subject with no affordance".into(), + "affordance grant operation changes nothing".into(), )); } - granted.remove(affordance); + } else { + let granted = state + .affordance_grants + .get_mut(&scope) + .ok_or_else(unknown)?; + if !granted.remove(affordance) { + return Err(KernelError::Invariant( + "affordance grant operation changes nothing".into(), + )); + } + if granted.is_empty() { + state.affordance_grants.remove(&scope); + } } } } @@ -2910,8 +2591,7 @@ fn channel_referents_exist(state: &WorldState, record: &ChannelRecord) -> bool { /// Whether a subject's controller assignment is `Retired`. The one statement /// of retirement read by anything downstream of it (audience derivation, -/// preconditions, resolvers): a mirror's assignment is `ExternallyControlled` -/// and is never retired by this check, only an actual `Retire` sets it. +/// preconditions, resolvers): only an actual `Retire` sets it. pub(crate) fn is_retired(state: &WorldState, subject_id: SubjectId) -> bool { matches!( state.controller_assignments.get(&DecisionScope { subject_id }), @@ -3512,12 +3192,9 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> { Ok(WorldSnapshot { world_id: state.world_id, revision: state.revision, - phase: state.phase, owner: state.owner.clone(), title: state.title.clone(), grammar: state.grammar.as_ref().map(GrammarBinding::identity), - draft_approvals: state.draft_approvals.clone(), - required_approvers: required_approvers(state), subjects, affordances: state .affordance_catalog @@ -3579,228 +3256,12 @@ fn require_granted<'a>( }) } -fn required_approvers(state: &WorldState) -> BTreeSet<PrincipalId> { - std::iter::once(state.owner.clone()) - .chain( - state - .controller_assignments - .values() - .filter_map(ControllerAssignment::human_principal) - .cloned(), - ) - .collect() -} - -/// Who may admit a patch, and inside what. `None` means unconfined: the owner. -/// Reached from `reduce`'s `AdmitPatch` arm and re-reached from `apply_effect`'s -/// `PatchAdmitted` arm, per the file's idiom that `reduce` decides and -/// `apply_effect` re-decides. -fn require_patch_author( - state: &WorldState, - caller: &CallerId, -) -> Result<Option<PatchGround>, KernelError> { - match caller { - CallerId::Principal(principal) if principal == &state.owner => Ok(None), - CallerId::System(SystemCapability::Play) => Ok(None), - CallerId::System(SystemCapability::Consumer { consumer }) => { - // Authority over its own mirrors is not jurisdictional. - Ok(Some(PatchGround::Consumer(*consumer))) - } - _ => Err(KernelError::Unauthorized), - } -} - -/// Is this committed subject one of that consumer's mirrors? The consumer's -/// ground is derived here, at decision time, and never carried on the wire: a -/// binding a later commit revoked shrinks the consumer's authority with no -/// ingress change. -fn bound_to_consumer(state: &WorldState, subject: SubjectId, consumer: ConsumerId) -> bool { - state - .controller_assignments - .get(&DecisionScope { - subject_id: subject, - }) - .and_then(ControllerAssignment::consumer) - == Some(consumer) -} - - -/// The ground a patch writes on, as one map over `state ∪ patch`, so a place -/// declared and built on in the same patch confines through the chain it -/// declares. -fn candidate_places( - state: &WorldState, - resolved: &ResolvedPatch, -) -> BTreeMap<EntityId, EntityRecord> { - let mut entities = state.entities.clone(); - for declared in &resolved.entities { - entities.insert(declared.entity_id, declared.entity.clone()); - } - for declared in &resolved.facts { - entities.insert(declared.entity_id, declared.entity.clone()); - } - for declared in &resolved.channels { - entities.insert(declared.entity_id, declared.entity.clone()); - } - entities -} - -/// Every referent a confined author writes must sit on its ground. Returns the -/// complete set, like every other check. -/// -/// Placeless referents — resource kinds, catalog entries, canonical facts — -/// name no ground and are not confined. A place declared with no container is a -/// new jurisdiction root and is the owner's act. -fn confine_to_ground( - state: &WorldState, - resolved: &ResolvedPatch, - held: PatchGround, -) -> Result<(), Vec<Mismatch>> { - let entities = candidate_places(state, resolved); - // A consumer names no place ground, so every place, every route, and every - // place-shaped reach is refused with no extra rule: relocation, route - // opening and closing, cost changes, and place-subtree grants are - // unrepresentable for it because they carry a place or a route. - // - // Every subject's consumer binding over `state ∪ patch`, so a consumer's - // first document can declare its own mirror and write it in one patch. - let mut bindings: BTreeMap<SubjectId, Option<ConsumerId>> = state - .controller_assignments - .iter() - .map(|(scope, assignment)| (scope.subject_id, assignment.consumer())) - .collect(); - for declared in &resolved.subjects { - bindings.insert(declared.subject_id, declared.controller.consumer()); - } - let mut edges: BTreeMap<EdgeId, (EntityId, EntityId)> = state - .edges - .iter() - .map(|(edge_id, record)| (*edge_id, record.endpoints())) - .collect(); - for declared in &resolved.routes { - edges.insert(declared.edge_id, declared.edge.endpoints()); - } - - let mut mismatches = Vec::new(); - let confine_subject = |site: &Site, subject: SubjectId, mismatches: &mut Vec<Mismatch>| { - // Position is unconfined for a consumer: what binds a mirror is who - // controls it, not where it stands. - let PatchGround::Consumer(consumer) = held; - let admitted = bindings.get(&subject).copied().flatten() == Some(consumer); - if !admitted { - mismatches.push(Mismatch::OutsideJurisdiction { site: site.clone() }); - } - }; - let confine_place = |site: &Site, _place: EntityId, mismatches: &mut Vec<Mismatch>| { - mismatches.push(Mismatch::OutsideJurisdiction { site: site.clone() }); - }; - - for declared in &resolved.subjects { - let site = Site::Declaration(declared.handle.clone()); - confine_subject(&site, declared.subject_id, &mut mismatches); - } - for declared in &resolved.entities { - if declared.entity.kind != EntityKind::Place { - continue; - } - let site = Site::Declaration(declared.handle.clone()); - match declared.entity.container { - Some(container) => confine_place(&site, container, &mut mismatches), - // A root is the owner's act. - None => mismatches.push(Mismatch::OutsideJurisdiction { site }), - } - } - for declared in &resolved.routes { - let site = Site::Declaration(declared.handle.clone()); - let (from, to) = declared.edge.endpoints(); - confine_place(&site, from, &mut mismatches); - confine_place(&site, to, &mut mismatches); - } - for declared in &resolved.facts { - let site = Site::Declaration(declared.handle.clone()); - match declared.fact.standing { - FactStanding::Claimed { by } => confine_subject(&site, by, &mut mismatches), - // A consumer's citation is its own provenance claim, and that claim - // buys an `Admit` into its own custody and a claimed fact. It - // cannot canonize. - FactStanding::Canonical { .. } => { - if matches!(held, PatchGround::Consumer(_)) { - mismatches.push(Mismatch::OutsideJurisdiction { site }); - } - } - // Redundant with `require_ruler`, which refuses a confined caller's - // `Ruled` fact outright; kept so this match stays total. - FactStanding::Ruled => { - mismatches.push(Mismatch::OutsideJurisdiction { site }); - } - } - } - for declared in &resolved.channels { - let site = Site::Declaration(declared.handle.clone()); - match &declared.channel.reach { - Reach::Place(place) => confine_place(&site, *place, &mut mismatches), - Reach::Subjects(subjects) => { - for subject in subjects { - confine_subject(&site, *subject, &mut mismatches); - } - } - } - if let Some(controller) = declared.channel.controller { - confine_subject(&site, controller, &mut mismatches); - } - } - for (index, operation) in resolved.operations.iter().enumerate() { - let site = Site::Operation(index); - // Retirement and an affordance grant are authority over the subject's - // standing, not structure over ground: a confined author is refused - // whatever place the subject stands under, exactly as `require_ruler` - // refuses a `Ruled` fact or a `Mint` outright. The owner is unconfined - // and never reaches this clause. - if matches!( - operation, - ResolvedOp::Retire { .. } - | ResolvedOp::GrantAffordance { .. } - | ResolvedOp::RevokeAffordance { .. } - ) { - mismatches.push(Mismatch::OutsideJurisdiction { site: site.clone() }); - continue; - } - let (subjects, places, routes) = operation_ground(operation, &entities); - for subject in subjects { - confine_subject(&site, subject, &mut mismatches); - } - for place in places { - confine_place(&site, place, &mut mismatches); - } - for route in routes { - match edges.get(&route) { - Some((from, to)) => { - confine_place(&site, *from, &mut mismatches); - confine_place(&site, *to, &mut mismatches); - } - None => mismatches.push(Mismatch::OutsideJurisdiction { site: site.clone() }), - } - } - } - mismatches.sort(); - mismatches.dedup(); - if mismatches.is_empty() { - Ok(()) - } else { - Err(mismatches) - } -} - -/// The one author of a `Ruled` fact and a `Mint`. `Ok` when the caller is -/// `System(Play)`. Otherwise, one `Mismatch::RuledWithoutAuthority` per -/// `Ruled` fact and per `Mint`, and `Ok` if there are none. Called in -/// `reduce`'s `AdmitPatch` arm right after `resolve_patch` and before -/// confinement, and re-decided in `apply_effect`'s `PatchAdmitted` arm. The -/// resolver stays actor-blind: this runs after resolution, never inside it. -fn require_ruler(caller: &CallerId, resolved: &ResolvedPatch) -> Result<(), Vec<Mismatch>> { - if caller == &CallerId::System(SystemCapability::Play) { - return Ok(()); - } +/// Genesis may not rule or mint: only Play authors a `Ruled` fact or a `Mint`, +/// and Play only writes after genesis. One `Mismatch::RuledWithoutAuthority` +/// per `Ruled` fact and per `Mint`, and `Ok` if there are none. Called by +/// `prepare_creation` and by `WorldState::genesis` at replay. The resolver +/// stays actor-blind: this runs after resolution, never inside it. +fn forbid_rulings_at_genesis(resolved: &ResolvedPatch) -> Result<(), Vec<Mismatch>> { let mut mismatches = Vec::new(); for declared in &resolved.facts { if matches!(declared.fact.standing, FactStanding::Ruled) { @@ -3823,188 +3284,6 @@ fn require_ruler(caller: &CallerId, resolved: &ResolvedPatch) -> Result<(), Vec< } } -/// The ground one lowered operation touches: the subjects whose position it -/// must sit under, the places it names directly, and the routes whose endpoints -/// it must sit under. Total over `ResolvedOp`, so a new operation cannot ship -/// without saying where it lands. -fn operation_ground( - operation: &ResolvedOp, - entities: &BTreeMap<EntityId, EntityRecord>, -) -> (Vec<SubjectId>, Vec<EntityId>, Vec<EdgeId>) { - // A resource, a fact, and a channel are placeless referents: they name no - // ground, so only a place among the named entities confines. - let places = |candidates: Vec<EntityId>| { - candidates - .into_iter() - .filter(|entity_id| { - entities - .get(entity_id) - .is_some_and(|record| record.kind == EntityKind::Place) - }) - .collect() - }; - match operation { - ResolvedOp::Relocate { - subject_id, - edge_id, - } => (vec![*subject_id], Vec::new(), vec![*edge_id]), - ResolvedOp::OpenRoute { edge_id } | ResolvedOp::CloseRoute { edge_id } => { - (Vec::new(), Vec::new(), vec![*edge_id]) - } - ResolvedOp::AlterCost { edge_id, .. } => (Vec::new(), Vec::new(), vec![*edge_id]), - ResolvedOp::Transfer { - from, to, resource, .. - } => (vec![*from, *to], places(vec![*resource]), Vec::new()), - ResolvedOp::Transform { - holder, - from_resource, - into_resource, - .. - } => ( - vec![*holder], - places(vec![*from_resource, *into_resource]), - Vec::new(), - ), - ResolvedOp::Consume { - holder, resource, .. - } - | ResolvedOp::Admit { - holder, resource, .. - } - | ResolvedOp::Mint { - holder, resource, .. - } => (vec![*holder], places(vec![*resource]), Vec::new()), - ResolvedOp::Bind { subject, target } | ResolvedOp::Release { subject, target } => { - match target { - DependencyTarget::Subject(other) => { - (vec![*subject, *other], Vec::new(), Vec::new()) - } - DependencyTarget::Route(edge_id) => (vec![*subject], Vec::new(), vec![*edge_id]), - DependencyTarget::Resource(resource) => { - (vec![*subject], places(vec![*resource]), Vec::new()) - } - } - } - ResolvedOp::GrantAuthority { holder, grant } - | ResolvedOp::RevokeAuthority { holder, grant } => match grant.over { - AuthorityTarget::Subject(other) => (vec![*holder, other], Vec::new(), Vec::new()), - AuthorityTarget::PlaceSubtree(root) => (vec![*holder], vec![root], Vec::new()), - }, - ResolvedOp::OpenOffice { institution, .. } - | ResolvedOp::CloseOffice { institution, .. } - | ResolvedOp::VacateOffice { institution, .. } => { - (vec![*institution], Vec::new(), Vec::new()) - } - ResolvedOp::InstallIncumbent { - institution, - incumbent, - .. - } => (vec![*institution, *incumbent], Vec::new(), Vec::new()), - ResolvedOp::OpenForum { - forum, standing, .. - } => match standing { - AuthorityTarget::Subject(other) => (vec![*forum, *other], Vec::new(), Vec::new()), - AuthorityTarget::PlaceSubtree(root) => (vec![*forum], vec![*root], Vec::new()), - }, - ResolvedOp::CloseForum { .. } => (Vec::new(), Vec::new(), Vec::new()), - ResolvedOp::AcquireKnowledge { subject, .. } | ResolvedOp::Forget { subject, .. } => { - (vec![*subject], Vec::new(), Vec::new()) - } - ResolvedOp::Communicate { speaker, .. } | ResolvedOp::Display { actor: speaker, .. } => { - (vec![*speaker], Vec::new(), Vec::new()) - } - // The place is the whole ground. Confining by it is not weaker than - // confining by the recipients: `covers_place` is transitive, so every - // subject the fan-out selects stands under the place, and a place - // admitted under a root puts all of them under that root. Naming the - // recipients here would be a second statement of the same rule, - // computed from state this function does not read. - ResolvedOp::Witness { place, .. } => (Vec::new(), places(vec![*place]), Vec::new()), - ResolvedOp::SetReach { channel, reach } => { - let mut subjects = Vec::new(); - let mut named = Vec::new(); - match reach { - Reach::Place(place) => named.push(*place), - Reach::Subjects(members) => subjects.extend(members.iter().copied()), - } - named.push(*channel); - (subjects, places(named), Vec::new()) - } - ResolvedOp::SetController { - channel, - controller, - } => ( - controller.iter().copied().collect(), - places(vec![*channel]), - Vec::new(), - ), - // Kernel-synthesized by `action::exercise` and by nothing a patch may - // carry; it is confined by its speaker all the same. - ResolvedOp::AssertClaim { by, .. } => (vec![*by], Vec::new(), Vec::new()), - ResolvedOp::CreateCommitment { - subject, - commitment, - .. - } => ( - std::iter::once(*subject) - .chain(commitment.counterparty) - .collect(), - Vec::new(), - Vec::new(), - ), - ResolvedOp::DischargeCommitment { subject, .. } => (vec![*subject], Vec::new(), Vec::new()), - ResolvedOp::AdvancePressure { source, target, .. } - | ResolvedOp::ReducePressure { source, target, .. } - | ResolvedOp::ResolvePressure { source, target } => { - let mut subjects = vec![*target]; - let mut named = Vec::new(); - let mut routes = Vec::new(); - match source { - PressureSource::Commitment { subject, .. } | PressureSource::Subject(subject) => { - subjects.push(*subject); - } - PressureSource::Dependency(DependencyTarget::Subject(subject)) => { - subjects.push(*subject); - } - PressureSource::Dependency(DependencyTarget::Route(edge_id)) => { - routes.push(*edge_id); - } - PressureSource::Dependency(DependencyTarget::Resource(resource)) => { - named.push(*resource); - } - } - (subjects, places(named), routes) - } - // Confinement never reaches these through the ordinary ground check: - // `confine_to_ground` refuses `Retire`, `GrantAffordance`, and - // `RevokeAffordance` unconditionally for every confined author before - // this function is called for them. The subject is named here so the - // match stays total and correct if that clause is ever bypassed. - ResolvedOp::Retire { subject } - | ResolvedOp::GrantAffordance { subject, .. } - | ResolvedOp::RevokeAffordance { subject, .. } => (vec![*subject], Vec::new(), Vec::new()), - } -} - -fn require_owner(state: &WorldState, caller: &CallerId) -> Result<(), KernelError> { - if caller == &CallerId::Principal(state.owner.clone()) { - Ok(()) - } else { - Err(KernelError::Unauthorized) - } -} - -fn require_phase(state: &WorldState, expected: WorldPhase) -> Result<(), KernelError> { - if state.phase == expected { - Ok(()) - } else { - Err(KernelError::WrongPhase { - expected, - actual: state.phase, - }) - } -} - fn normalize_title(value: &str) -> Result<String, KernelError> { let value = value.trim(); if value.is_empty() { @@ -4048,23 +3327,8 @@ fn apply_effect( caller: &CallerId, effect: &WorldEffect, ) -> Result<(), KernelError> { - // The capability rule `reduce` decided, re-decided here against the effect - // the command produced. - if let CallerId::System(capability) = caller { - let admitted = matches!( - (capability, effect), - (SystemCapability::Clock, WorldEffect::TimeAdvanced { .. }) - | (SystemCapability::Play, WorldEffect::TimeAdvanced { .. }) - | ( - SystemCapability::Consumer { .. } | SystemCapability::Play, - WorldEffect::PatchAdmitted { .. } - ) - | (SystemCapability::Play, WorldEffect::Acted { .. }) - ); - if !admitted { - return Err(KernelError::Unauthorized); - } - } + // The admission rule `reduce` decided, re-decided here. + require_play(caller)?; match effect { WorldEffect::WorldCreated { .. } => { return Err(KernelError::Invariant( @@ -4072,58 +3336,10 @@ fn apply_effect( )); } WorldEffect::PatchAdmitted { resolved } => { - require_play_active(state, caller, !resolved.declares_nothing())?; - require_ruler(caller, resolved).map_err(|_| { - KernelError::Invariant( - "admitted patch rules or mints without the play authority".into(), - ) - })?; - let confinement = - require_patch_author(state, caller).map_err(|_| { - KernelError::Invariant( - "admitted patch does not satisfy admission authority".into(), - ) - })?; - if let Some(ground) = confinement { - confine_to_ground(state, resolved, ground).map_err(|_| { - KernelError::Invariant( - "admitted patch wrote outside its author's ground".into(), - ) - })?; - } let resolves_to = resolution_revision(state)?; admit_resolved(state, resolved, resolves_to)?; } - WorldEffect::DraftApproved { principal } => { - if state.phase != WorldPhase::Draft - || caller != &CallerId::Principal(principal.clone()) - || !required_approvers(state).contains(principal) - || !state.draft_approvals.insert(principal.clone()) - { - return Err(KernelError::Invariant( - "draft-approval effect is unauthorized or duplicate".into(), - )); - } - } - WorldEffect::WorldActivated => { - if caller != &CallerId::Principal(state.owner.clone()) - || state.phase != WorldPhase::Draft - || !required_approvers(state).is_subset(&state.draft_approvals) - { - return Err(KernelError::Invariant( - "activation does not satisfy lifecycle authority".into(), - )); - } - state.phase = WorldPhase::Active; - } WorldEffect::Acted { invocation, event } => { - if state.phase != WorldPhase::Active - || caller != &CallerId::System(SystemCapability::Play) - { - return Err(KernelError::Invariant( - "acted effect does not match Play's authority".into(), - )); - } let granted = require_granted(state, event.actor, invocation.affordance)?; // The whole event is re-derived by the function that produced the // honest one, so a forged band, operation, magnitude, minted claim, @@ -4148,8 +3364,6 @@ fn apply_effect( to, motion, } => { - require_phase(state, WorldPhase::Active)?; - require_clock_caller(state, caller)?; let derived_to = state .now .checked_add(*minutes) @@ -4369,7 +3583,18 @@ mod tests { } } - pub(crate) fn submit_owner( + /// The smallest Play command that commits: a one-minute clock advance. + pub(crate) fn tick_body(minutes: u32) -> CommandBody { + CommandBody::AdvanceTime { + minutes: TickMinutes::new(minutes).expect("a valid span"), + } + } + + pub(crate) fn play_command(snapshot: &WorldSnapshot, id: CommandId, body: CommandBody) -> CommandEnvelope { + command(snapshot, id, CallerId::Play, body) + } + + pub(crate) fn submit_play( kernel: &mut WorldKernel, snapshot: &WorldSnapshot, body: CommandBody, @@ -4379,34 +3604,14 @@ mod tests { command( snapshot, CommandId::new(), - CallerId::Principal(owner()), + CallerId::Play, body, ), - &auth_principal(owner()), + &AuthenticatedCaller::verified_play(), ) .unwrap() } - pub(crate) fn activate(kernel: &mut WorldKernel) -> WorldSnapshot { - let genesis = kernel.snapshot().unwrap(); - submit_owner(kernel, &genesis, CommandBody::ApproveDraft); - let after_owner = kernel.snapshot().unwrap(); - kernel - .submit( - command( - &after_owner, - CommandId::new(), - CallerId::Principal(human_principal()), - CommandBody::ApproveDraft, - ), - &auth_principal(human_principal()), - ) - .unwrap(); - let approved = kernel.snapshot().unwrap(); - submit_owner(kernel, &approved, CommandBody::ActivateWorld); - kernel.snapshot().unwrap() - } - /// The canonical IDs of the shared topology fixture: three places, four /// routes with every access and open combination the operations read, and one /// subject standing in the yard. @@ -4509,7 +3714,7 @@ mod tests { pub(crate) fn admit_topology(kernel: &mut WorldKernel) -> Topology { let before = kernel.snapshot().unwrap(); - let receipt = submit_owner( + let receipt = submit_play( kernel, &before, CommandBody::AdmitPatch { @@ -4828,7 +4033,7 @@ mod tests { pub(crate) fn admit_custody(kernel: &mut WorldKernel, topology: &Topology) -> Custody { let before = kernel.snapshot().unwrap(); - let receipt = submit_owner( + let receipt = submit_play( kernel, &before, CommandBody::AdmitPatch { @@ -4867,7 +4072,7 @@ mod tests { pub(crate) fn custody_world(kernel: &mut WorldKernel) -> (Topology, Custody, WorldSnapshot) { let topology = admit_topology(kernel); let custody = admit_custody(kernel, &topology); - let active = activate(kernel); + let active = kernel.snapshot().unwrap(); (topology, custody, active) } @@ -5279,7 +4484,7 @@ mod tests { pub(crate) fn admit_civic(kernel: &mut WorldKernel, topology: &Topology) -> Civic { let before = kernel.snapshot().unwrap(); - let receipt = submit_owner( + let receipt = submit_play( kernel, &before, CommandBody::AdmitPatch { @@ -5332,7 +4537,7 @@ mod tests { pub(crate) fn civic_world(kernel: &mut WorldKernel) -> (Topology, Civic, WorldSnapshot) { let topology = admit_topology(kernel); let civic = admit_civic(kernel, &topology); - let active = activate(kernel); + let active = kernel.snapshot().unwrap(); (topology, civic, active) } @@ -5379,7 +4584,7 @@ mod tests { import_key: None, }) }; - submit_owner( + submit_play( kernel, &before, CommandBody::AdmitPatch { @@ -5490,7 +4695,7 @@ mod tests { }, }, ); - let active = activate(kernel); + let active = kernel.snapshot().unwrap(); let place = |label: &str| { active .places @@ -5539,8 +4744,8 @@ mod tests { ) } - /// Submits as owner and returns the complete mismatch set. - pub(crate) fn reject_owner( + /// Submits as Play and returns the complete mismatch set. + pub(crate) fn reject_play( kernel: &mut WorldKernel, snapshot: &WorldSnapshot, body: CommandBody, @@ -5550,10 +4755,10 @@ mod tests { command( snapshot, CommandId::new(), - CallerId::Principal(owner()), + CallerId::Play, body, ), - &auth_principal(owner()), + &AuthenticatedCaller::verified_play(), ) .unwrap_err(); let KernelError::PatchRejected(mismatches) = error else { @@ -5634,7 +4839,7 @@ mod tests { } pub(crate) fn play_caller() -> CallerId { - CallerId::System(SystemCapability::Play) + CallerId::Play } pub(crate) fn act( @@ -5644,134 +4849,12 @@ mod tests { ) -> Result<SubmitReceipt, KernelError> { act_as( kernel, - CallerId::System(SystemCapability::Play), + CallerId::Play, actor, invocation, ) } - #[test] - fn draft_activation_human_and_autonomous_actions_share_one_reducer() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("world.cc"); - let (mut kernel, _) = WorldKernel::create( - &path, - creation(CommandId::new(), " Delvehold "), - &auth_principal(owner()), - ) - .unwrap(); - let genesis = kernel.snapshot().unwrap(); - assert_eq!(genesis.title, "Delvehold"); - assert_eq!(genesis.phase, WorldPhase::Draft); - let active = activate(&mut kernel); - assert_eq!(active.phase, WorldPhase::Active); - - let human = subject_by_mode(&kernel.state, ControllerMode::Human); - act( - &mut kernel, - human, - speak(first_grant(&active, human), "I open the door."), - ) - .unwrap(); - let after_human = kernel.snapshot().unwrap(); - assert_eq!(kernel.state.events.len(), 1); - assert_eq!( - spoken(&kernel.state, &kernel.state.events[0]), - Some("I open the door.") - ); - - let persona = subject_by_mode(&kernel.state, ControllerMode::NarrativePersona); - act( - &mut kernel, - persona, - speak(first_grant(&after_human, persona), "Then mind the hinge."), - ) - .unwrap(); - assert_eq!(kernel.state.events.len(), 2); - assert_eq!(kernel.state.events[1].actor, persona); - } - - #[test] - fn lifecycle_and_controller_authority_fail_closed_without_commits() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("world.cc"); - let (mut kernel, _) = WorldKernel::create( - &path, - creation(CommandId::new(), "Held"), - &auth_principal(owner()), - ) - .unwrap(); - let genesis = kernel.snapshot().unwrap(); - assert!(matches!( - kernel.submit( - command( - &genesis, - CommandId::new(), - CallerId::Principal(owner()), - CommandBody::ActivateWorld, - ), - &auth_principal(owner()) - ), - Err(KernelError::MissingApprovals(_)) - )); - assert_eq!(kernel.journal.commit_count(), 1); - - submit_owner(&mut kernel, &genesis, CommandBody::ApproveDraft); - let owner_approved = kernel.snapshot().unwrap(); - assert!(matches!( - kernel.submit( - command( - &owner_approved, - CommandId::new(), - CallerId::Principal(human_principal()), - CommandBody::ActivateWorld, - ), - &auth_principal(human_principal()) - ), - Err(KernelError::Unauthorized) - )); - assert!(matches!( - kernel.submit( - command( - &owner_approved, - CommandId::new(), - CallerId::Principal(owner()), - CommandBody::ApproveDraft, - ), - &auth_principal(owner()) - ), - Err(KernelError::DraftAlreadyApproved) - )); - assert_eq!(kernel.journal.commit_count(), 2); - - kernel - .submit( - command( - &owner_approved, - CommandId::new(), - CallerId::Principal(human_principal()), - CommandBody::ApproveDraft, - ), - &auth_principal(human_principal()), - ) - .unwrap(); - let approved = kernel.snapshot().unwrap(); - submit_owner(&mut kernel, &approved, CommandBody::ActivateWorld); - let active = kernel.snapshot().unwrap(); - let persona = subject_by_mode(&kernel.state, ControllerMode::NarrativePersona); - let commits_before_forgery = kernel.journal.commit_count(); - let error = act_as( - &mut kernel, - CallerId::Principal(human_principal()), - persona, - speak(first_grant(&active, persona), "Puppet"), - ) - .unwrap_err(); - assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); - assert_eq!(kernel.journal.commit_count(), commits_before_forgery); - assert_eq!(kernel.snapshot().unwrap(), active); - } - #[test] fn create_submit_restart_and_replay_are_exact() { let dir = tempfile::tempdir().unwrap(); @@ -5779,7 +4862,7 @@ mod tests { let creation = creation(CommandId::new(), "First"); let (mut kernel, creation_receipt) = WorldKernel::create(&path, creation.clone(), &auth_principal(owner())).unwrap(); - let active = activate(&mut kernel); + let active = kernel.snapshot().unwrap(); let operator = subject_by_mode(&kernel.state, ControllerMode::OperationalAgent); let caller = play_caller(); let command = command( @@ -5819,7 +4902,7 @@ mod tests { } #[test] - fn duplicate_and_stale_commands_do_not_commit() { + fn stale_commands_do_not_commit() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( @@ -5830,30 +4913,13 @@ mod tests { .unwrap(); let genesis = kernel.snapshot().unwrap(); assert!(matches!( - submit_owner(&mut kernel, &genesis, CommandBody::ApproveDraft), + submit_play(&mut kernel, &genesis, tick_body(1)), SubmitReceipt::Applied(_) )); let after = kernel.snapshot().unwrap(); + let stale = play_command(&genesis, CommandId::new(), tick_body(1)); assert!(matches!( - kernel.submit( - command( - &after, - CommandId::new(), - CallerId::Principal(owner()), - CommandBody::ApproveDraft, - ), - &auth_principal(owner()) - ), - Err(KernelError::DraftAlreadyApproved) - )); - let stale = command( - &genesis, - CommandId::new(), - CallerId::Principal(owner()), - CommandBody::ApproveDraft, - ); - assert!(matches!( - kernel.submit(stale, &auth_principal(owner())), + kernel.submit(stale, &AuthenticatedCaller::verified_play()), Err(KernelError::RevisionMismatch { .. }) )); assert_eq!(kernel.snapshot().unwrap(), after); @@ -5872,43 +4938,30 @@ mod tests { .unwrap(); let genesis = kernel.snapshot().unwrap(); let id = CommandId::new(); - let first = command( - &genesis, - id, - CallerId::Principal(owner()), - CommandBody::ApproveDraft, - ); + let first = play_command(&genesis, id, tick_body(1)); let first_receipt = kernel - .submit(first.clone(), &auth_principal(owner())) + .submit(first.clone(), &AuthenticatedCaller::verified_play()) .unwrap(); let second_snapshot = kernel.snapshot().unwrap(); kernel .submit( - command( - &second_snapshot, - CommandId::new(), - CallerId::Principal(human_principal()), - CommandBody::ApproveDraft, - ), - &auth_principal(human_principal()), + play_command(&second_snapshot, CommandId::new(), tick_body(1)), + &AuthenticatedCaller::verified_play(), ) .unwrap(); let after_second = kernel.snapshot().unwrap(); assert_eq!( - kernel.submit(first, &auth_principal(owner())).unwrap(), + kernel + .submit(first, &AuthenticatedCaller::verified_play()) + .unwrap(), match first_receipt { SubmitReceipt::Applied(value) => SubmitReceipt::AlreadyApplied(value), _ => unreachable!(), } ); - let conflict = command( - &genesis, - id, - CallerId::Principal(owner()), - CommandBody::ActivateWorld, - ); + let conflict = play_command(&genesis, id, tick_body(2)); assert!(matches!( - kernel.submit(conflict, &auth_principal(owner())), + kernel.submit(conflict, &AuthenticatedCaller::verified_play()), Err(KernelError::CommandIdConflict) )); assert_eq!(kernel.snapshot().unwrap(), after_second); @@ -6002,15 +5055,10 @@ mod tests { .unwrap(); let genesis = kernel.snapshot().unwrap(); let uncertain = CommandId::new(); - let attempted = command( - &genesis, - uncertain, - CallerId::Principal(owner()), - CommandBody::ApproveDraft, - ); + let attempted = play_command(&genesis, uncertain, tick_body(1)); kernel.journal.fail_after_durable_commit_for_test(); assert!(matches!( - kernel.submit(attempted.clone(), &auth_principal(owner())), + kernel.submit(attempted.clone(), &AuthenticatedCaller::verified_play()), Err(KernelError::RecoveryRequired { command_id }) if command_id == uncertain )); assert!(matches!( @@ -6022,10 +5070,9 @@ mod tests { let mut reopened = WorldKernel::open(&path, genesis.world_id).unwrap(); let durable = reopened.snapshot().unwrap(); assert_eq!(durable.revision, 1); - assert_eq!(durable.draft_approvals, BTreeSet::from([owner()])); assert!(matches!( reopened - .submit(attempted, &auth_principal(owner())) + .submit(attempted, &AuthenticatedCaller::verified_play()) .unwrap(), SubmitReceipt::AlreadyApplied(_) )); @@ -6075,13 +5122,8 @@ mod tests { assert!(matches!(kernel.snapshot(), Err(KernelError::OwnershipLost))); assert!(matches!( kernel.submit( - command( - &snapshot, - CommandId::new(), - CallerId::Principal(owner()), - CommandBody::ApproveDraft, - ), - &auth_principal(owner()) + play_command(&snapshot, CommandId::new(), tick_body(1)), + &AuthenticatedCaller::verified_play() ), Err(KernelError::OwnershipLost) )); @@ -6108,7 +5150,7 @@ mod tests { &snapshot, CommandId::new(), CallerId::Principal(human_principal()), - CommandBody::ApproveDraft, + tick_body(1), ); assert!(matches!( kernel.submit(forged, &auth_principal(owner())), @@ -6117,11 +5159,11 @@ mod tests { assert_eq!(kernel.snapshot().unwrap(), snapshot); } - /// Soul falsification: the preimage must exclude the revision, the phase, + /// Soul falsification: the preimage must exclude the revision /// and every component outside the scope. Each step below is a real commit /// that moves the world, not a hand-edited state. #[test] - fn soul_scope_components_exclude_revision_phase_and_everything_outside_the_scope() { + fn soul_scope_components_exclude_revision_and_everything_outside_the_scope() { let dir = tempfile::tempdir().unwrap(); let (mut kernel, _) = WorldKernel::create( dir.path().join("world.cc"), @@ -6140,7 +5182,7 @@ mod tests { // place nor it, and a second placed subject: all outside the scope. let speak = speak_entry(&kernel); let before = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &before, CommandBody::AdmitPatch { @@ -6178,11 +5220,6 @@ mod tests { assert_ne!(kernel.state.revision, start_revision); assert_eq!(scope_components(&kernel.state, scope.subject_id), base); - // Activation changes the phase, the approvals, and the revision. - let active = activate(&mut kernel); - assert_eq!(active.phase, WorldPhase::Active); - assert_eq!(scope_components(&kernel.state, scope.subject_id), base); - // Another subject's Position moving is not this scope's business. let annexway = *kernel .state @@ -6199,7 +5236,7 @@ mod tests { .expect("the declared subject") .0; let active = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &active, CommandBody::AdmitPatch { @@ -6229,7 +5266,7 @@ mod tests { // A route incident to the walker's own place is inside the scope. let moved = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &moved, CommandBody::AdmitPatch { @@ -6259,7 +5296,7 @@ mod tests { &auth_principal(owner()), ) .unwrap(); - let active = activate(&mut kernel); + let active = kernel.snapshot().unwrap(); let speak = affordance_named(&active, "speak"); let convened = affordance_named(&active, "convene"); @@ -6325,7 +5362,7 @@ mod tests { ) .unwrap(); let topology = admit_topology(&mut kernel); - let active = activate(&mut kernel); + let active = kernel.snapshot().unwrap(); let speak = affordance_named(&active, "speak"); // A route the actor does not stand beside is outside its scope. @@ -6333,7 +5370,7 @@ mod tests { // stale topology. let before_components = scope_components(&kernel.state, topology.walker); let before = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &before, operations(vec![ComponentOp::CloseRoute { @@ -6495,7 +5532,7 @@ mod tests { let (_, civic, _) = civic_world(&mut kernel); let refuse = |kernel: &mut WorldKernel, ops: Vec<ComponentOp>| { let before = kernel.snapshot().unwrap(); - reject_owner(kernel, &before, operations(ops)) + reject_play(kernel, &before, operations(ops)) }; // An institution cannot occupy its own office. @@ -6545,11 +5582,11 @@ mod tests { let (_, civic, _) = civic_world(&mut kernel); let refuse = |kernel: &mut WorldKernel, ops: Vec<ComponentOp>| { let before = kernel.snapshot().unwrap(); - reject_owner(kernel, &before, operations(ops)) + reject_play(kernel, &before, operations(ops)) }; let admit = |kernel: &mut WorldKernel, ops: Vec<ComponentOp>| { let before = kernel.snapshot().unwrap(); - submit_owner(kernel, &before, operations(ops)) + submit_play(kernel, &before, operations(ops)) }; // A direct grant under what the reeve's office already lends. @@ -6649,7 +5686,7 @@ mod tests { ]; expected.sort(); assert_eq!( - reject_owner(&mut kernel, &before, operations(broken)), + reject_play(&mut kernel, &before, operations(broken)), expected ); assert_eq!(kernel.snapshot().unwrap(), before); @@ -6672,7 +5709,7 @@ mod tests { }, ]; assert!(matches!( - submit_owner(&mut kernel, &before, operations(repaired)), + submit_play(&mut kernel, &before, operations(repaired)), SubmitReceipt::Applied(_) )); } @@ -6707,7 +5744,7 @@ mod tests { ] { let before = kernel.snapshot().unwrap(); assert_eq!( - reject_owner(&mut kernel, &before, operations(vec![operation])), + reject_play(&mut kernel, &before, operations(vec![operation])), vec![Mismatch::NoOperationEffect { operation: 0 }] ); } @@ -6725,7 +5762,7 @@ mod tests { }; let admit = |kernel: &mut WorldKernel, ops: Vec<ComponentOp>| { let before = kernel.snapshot().unwrap(); - submit_owner(kernel, &before, operations(ops)); + submit_play(kernel, &before, operations(ops)); }; // Moving an unrelated subject into and out of the jurisdiction, and @@ -6898,7 +5935,7 @@ mod tests { evidence: Vec::new(), }; assert_eq!( - reject_owner( + reject_play( &mut kernel, &before, CommandBody::AdmitPatch { @@ -6928,7 +5965,7 @@ mod tests { "the reeve holds levy only through the warden office before retirement" ); - submit_owner( + submit_play( &mut kernel, &before, operations(vec![ComponentOp::Retire { @@ -6957,9 +5994,9 @@ mod tests { #[cfg(test)] mod custody_tests { use super::tests::{ - OPENING_BALANCE, TITHE_RECEIPT, act, activate, admit_custody, admit_topology, - auth_principal, creation, custody_world, first_grant, operations, owner, reject_owner, - speak, speak_entry, submit_owner, + OPENING_BALANCE, TITHE_RECEIPT, act, admit_custody, admit_topology, + auth_principal, creation, custody_world, first_grant, operations, owner, reject_play, + speak, speak_entry, submit_play, }; use super::*; @@ -7014,7 +6051,7 @@ mod custody_tests { let error = apply_effect( &mut candidate, CommandId::issue(), - &CallerId::Principal(owner()), + &CallerId::Play, &forged, ) .unwrap_err(); @@ -7056,7 +6093,7 @@ mod custody_tests { let before = kernel.snapshot().unwrap(); let commits = kernel.journal.commit_count(); - let mismatches = reject_owner( + let mismatches = reject_play( &mut kernel, &before, CommandBody::AdmitPatch { @@ -7107,7 +6144,7 @@ mod custody_tests { let edges = kernel.state.edges.clone(); let positions = kernel.state.positions.clone(); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![ComponentOp::Transfer { @@ -7134,7 +6171,7 @@ mod custody_tests { let mut kernel = custody_kernel(directory.path(), "Consume"); let (_, custody, active) = custody_world(&mut kernel); - let after_three = submit_owner( + let after_three = submit_play( &mut kernel, &active, operations(vec![ComponentOp::Consume { @@ -7147,7 +6184,7 @@ mod custody_tests { assert_eq!(holding(&kernel, custody.holder, custody.tithe), 4); let snapshot = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &snapshot, operations(vec![ComponentOp::Consume { @@ -7173,7 +6210,7 @@ mod custody_tests { let mut kernel = custody_kernel(directory.path(), "Transform"); let (_, custody, active) = custody_world(&mut kernel); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![ComponentOp::Transform { @@ -7219,7 +6256,7 @@ mod custody_tests { for attempt in attempts { let snapshot = kernel.snapshot().unwrap(); let commits = kernel.journal.commit_count(); - let mismatches = reject_owner(&mut kernel, &snapshot, operations(vec![attempt])); + let mismatches = reject_play(&mut kernel, &snapshot, operations(vec![attempt])); assert_eq!( mismatches, vec![Mismatch::InsufficientCustody { operation: 0 }] @@ -7237,7 +6274,7 @@ mod custody_tests { let mut kernel = custody_kernel(directory.path(), "Absent"); let (_, custody, active) = custody_world(&mut kernel); - let mismatches = reject_owner( + let mismatches = reject_play( &mut kernel, &active, operations(vec![ComponentOp::Consume { @@ -7270,7 +6307,7 @@ mod custody_tests { // `Admit` is Draft-only, because Active refuses a patch carrying // evidence, so its zero case is proven before activation. let draft = kernel.snapshot().unwrap(); - let mismatches = reject_owner( + let mismatches = reject_play( &mut kernel, &draft, CommandBody::AdmitPatch { @@ -7288,7 +6325,7 @@ mod custody_tests { ); assert_eq!(mismatches, vec![Mismatch::ZeroQuantity { operation: 0 }]); - let active = activate(&mut kernel); + let active = kernel.snapshot().unwrap(); for attempt in [ ComponentOp::Transfer { from: Ref::Existing(custody.holder), @@ -7303,7 +6340,7 @@ mod custody_tests { }, ] { let snapshot = kernel.snapshot().unwrap(); - let mismatches = reject_owner(&mut kernel, &snapshot, operations(vec![attempt])); + let mismatches = reject_play(&mut kernel, &snapshot, operations(vec![attempt])); assert_eq!(mismatches, vec![Mismatch::ZeroQuantity { operation: 0 }]); } assert_eq!(kernel.snapshot().unwrap(), active); @@ -7316,7 +6353,7 @@ mod custody_tests { let (_, custody, active) = custody_world(&mut kernel); let before = kernel.state.dependencies.clone(); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![ComponentOp::Bind { @@ -7330,7 +6367,7 @@ mod custody_tests { ); let bound = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &bound, operations(vec![ComponentOp::Release { @@ -7354,15 +6391,15 @@ mod custody_tests { subject: Ref::Existing(custody.holder), target: DependencyRef::Resource(Ref::Existing(custody.tithe)), }; - submit_owner(&mut kernel, &active, operations(vec![bind.clone()])); + submit_play(&mut kernel, &active, operations(vec![bind.clone()])); let bound = kernel.snapshot().unwrap(); assert_eq!( - reject_owner(&mut kernel, &bound, operations(vec![bind])), + reject_play(&mut kernel, &bound, operations(vec![bind])), vec![Mismatch::NoOperationEffect { operation: 0 }] ); assert_eq!( - reject_owner( + reject_play( &mut kernel, &bound, operations(vec![ComponentOp::Release { @@ -7373,7 +6410,7 @@ mod custody_tests { vec![Mismatch::NoOperationEffect { operation: 0 }] ); assert_eq!( - reject_owner( + reject_play( &mut kernel, &bound, operations(vec![ComponentOp::Bind { @@ -7395,7 +6432,7 @@ mod custody_tests { let (topology, custody, active) = custody_world(&mut kernel); assert!(!kernel.state.edges[&topology.shutter].is_open()); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![ComponentOp::Bind { @@ -7425,7 +6462,6 @@ mod custody_tests { let mut kernel = custody_kernel(directory.path(), "ScopeCustody"); let topology = admit_topology(&mut kernel); let custody = admit_custody(&mut kernel, &topology); - activate(&mut kernel); let scope = DecisionScope { subject_id: custody.holder, }; @@ -7478,7 +6514,7 @@ mod custody_tests { let tithe_before = resource_total(&kernel.state, custody.tithe); let ingot_before = resource_total(&kernel.state, custody.ingot); - let receipt = submit_owner( + let receipt = submit_play( &mut kernel, &active, operations(vec![ @@ -7561,7 +6597,7 @@ mod custody_tests { let error = apply_effect( &mut candidate, CommandId::issue(), - &CallerId::Principal(owner()), + &CallerId::Play, &forge(vec![transfer(5), transfer(5)]), ) .unwrap_err(); @@ -7578,7 +6614,7 @@ mod custody_tests { apply_effect( &mut conserving, CommandId::issue(), - &CallerId::Principal(owner()), + &CallerId::Play, &forge(vec![ transfer(5), ResolvedOp::Transfer { @@ -7612,7 +6648,7 @@ mod custody_tests { let error = apply_effect( &mut candidate, CommandId::issue(), - &CallerId::Principal(owner()), + &CallerId::Play, &forge(vec![degenerate]), ) .unwrap_err(); @@ -7628,7 +6664,7 @@ mod custody_tests { let error = apply_effect( &mut unevidenced, CommandId::issue(), - &CallerId::Principal(owner()), + &CallerId::Play, &forge(vec![ResolvedOp::Admit { holder: custody.holder, resource: custody.tithe, @@ -7662,7 +6698,7 @@ mod custody_tests { qty: Quantity(qty), evidence: EvidenceRef::new(TITHE_RECEIPT), }; - let mismatches = reject_owner( + let mismatches = reject_play( &mut kernel, &before, CommandBody::AdmitPatch { @@ -7710,7 +6746,7 @@ mod custody_tests { let receiver_before = scope_components(&kernel.state, custody.counterparty); let bystander_before = scope_components(&kernel.state, topology.walker); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![ComponentOp::Transfer { @@ -7752,7 +6788,7 @@ mod knowledge_tests { use super::tests::{ act, play_caller, affordance_named, FLOOD_EVIDENCE, FLOOD_STATEMENT, Speech, auth_principal, command, creation, operations, - owner, reject_owner, speech_world, spoken, submit_owner, + owner, reject_play, speech_world, spoken, submit_play, }; use super::*; use std::path::Path; @@ -7838,7 +6874,7 @@ mod knowledge_tests { let before = kernel.state.clone(); assert_eq!( - reject_owner( + reject_play( &mut kernel, &active, operations(vec![acquire( @@ -7854,7 +6890,7 @@ mod knowledge_tests { ); // A live referent of the wrong kind names the kind it actually is. assert_eq!( - reject_owner( + reject_play( &mut kernel, &active, operations(vec![acquire( @@ -7872,7 +6908,7 @@ mod knowledge_tests { ); assert_eq!(kernel.state, before); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![acquire( @@ -7915,7 +6951,7 @@ mod knowledge_tests { }; assert_eq!( - reject_owner( + reject_play( &mut draft, &start, declare( @@ -7930,7 +6966,7 @@ mod knowledge_tests { }] ); assert_eq!( - reject_owner( + reject_play( &mut draft, &start, declare( @@ -7948,7 +6984,7 @@ mod knowledge_tests { ); assert!(draft.state.facts.is_empty()); - submit_owner( + submit_play( &mut draft, &start, declare( @@ -7982,7 +7018,7 @@ mod knowledge_tests { let active = kernel.snapshot().unwrap(); assert_eq!( - reject_owner( + reject_play( &mut kernel, &active, operations(vec![acquire( @@ -7993,7 +7029,7 @@ mod knowledge_tests { ), vec![Mismatch::EvidencedKnowledgeOfClaim { operation: 0 }] ); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![acquire( @@ -8091,7 +7127,7 @@ mod knowledge_tests { // Moving the bystander up the stair puts it in both audiences. let active = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![ComponentOp::Relocate { @@ -8337,7 +7373,7 @@ mod knowledge_tests { fn a_channel_controller_may_speak_outside_its_own_reach() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, speech, active) = speech_kernel(directory.path(), "Controller"); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![ComponentOp::SetReach { @@ -8356,7 +7392,7 @@ mod knowledge_tests { .expect("the controller may speak on its own channel"); let active = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![ComponentOp::SetController { @@ -8389,7 +7425,7 @@ mod knowledge_tests { vec![ActionMismatch::CannotReach { precondition: 0 }] ); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![ComponentOp::Relocate { @@ -8428,7 +7464,7 @@ mod knowledge_tests { vec![ActionMismatch::FactUnknown { precondition: 0 }] ); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![ComponentOp::AcquireKnowledge { @@ -8445,7 +7481,7 @@ mod knowledge_tests { "Believed falls short of Certain" ); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![acquire( @@ -8461,7 +7497,7 @@ mod knowledge_tests { let active = kernel.snapshot().unwrap(); assert_eq!( - reject_owner( + reject_play( &mut kernel, &active, operations(vec![ComponentOp::Forget { @@ -8479,7 +7515,7 @@ mod knowledge_tests { fn a_telling_never_overwrites_a_holder() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, speech, active) = speech_kernel(directory.path(), "NoOverwrite"); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![acquire( @@ -8491,7 +7527,7 @@ mod knowledge_tests { let before = knows(&kernel, speech.listener, speech.flood); let active = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![ComponentOp::Communicate { @@ -8521,7 +7557,7 @@ mod knowledge_tests { let directory = tempfile::tempdir().unwrap(); let (mut kernel, speech, active) = speech_kernel(directory.path(), "OutsideAudience"); assert_eq!( - reject_owner( + reject_play( &mut kernel, &active, operations(vec![ComponentOp::Communicate { @@ -8533,7 +7569,7 @@ mod knowledge_tests { vec![Mismatch::SpeakerOutsideAudience { operation: 0 }] ); assert_eq!( - reject_owner( + reject_play( &mut kernel, &active, operations(vec![ComponentOp::Communicate { @@ -8630,7 +7666,7 @@ mod knowledge_tests { ) .expect("the whisper commits"); let active = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![ComponentOp::Communicate { @@ -8757,7 +7793,7 @@ mod knowledge_tests { let active = kernel.snapshot().unwrap(); let hearer_before = digest(&kernel, speech.listener); let speaker_before = digest(&kernel, speech.speaker); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![ComponentOp::SetReach { @@ -8802,13 +7838,13 @@ mod knowledge_tests { }, }; assert_eq!( - reject_owner(&mut kernel, &before, declare(Vec::new())), + reject_play(&mut kernel, &before, declare(Vec::new())), vec![Mismatch::SpeechWithoutAudience { handle: DraftHandle::new("herald"), }] ); assert_eq!( - reject_owner( + reject_play( &mut kernel, &before, declare(vec![ @@ -8878,7 +7914,7 @@ mod knowledge_tests { mod soul_knowledge_tests { use super::tests::{ act, play_caller, FLOOD_STATEMENT, Speech, affordance_named, auth_principal, command, creation, operations, - owner, speech_world, submit_owner, + owner, speech_world, submit_play, }; use super::*; use std::path::Path; @@ -8954,7 +7990,7 @@ mod soul_knowledge_tests { let (mut kernel, speech, active) = speech_kernel(directory.path(), "ControllerHears"); // The horn now reaches exactly one subject. The speaker controls it and // is not in that set. - submit_owner( + submit_play( &mut kernel, &active, operations(vec![ComponentOp::SetReach { @@ -9254,10 +8290,10 @@ mod soul_knowledge_tests { command( &active, CommandId::new(), - CallerId::Principal(owner()), + CallerId::Play, operations(vec![tell.clone(), forget.clone()]), ), - &auth_principal(owner()), + &AuthenticatedCaller::verified_play(), ) .unwrap_err(); let KernelError::PatchRejected(mismatches) = error else { @@ -9271,7 +8307,7 @@ mod soul_knowledge_tests { // The legitimate order. The listener holds the fact first, forgets it, // and the telling in the same patch lands it again as a telling, which // is what the committed state carries. - submit_owner( + submit_play( &mut kernel, &active, operations(vec![ComponentOp::AcquireKnowledge { @@ -9282,7 +8318,7 @@ mod soul_knowledge_tests { }]), ); let active = kernel.snapshot().unwrap(); - submit_owner(&mut kernel, &active, operations(vec![forget, tell])); + submit_play(&mut kernel, &active, operations(vec![forget, tell])); assert_eq!( knows(&kernel, speech.listener, speech.flood), Some(Knowledge { @@ -9325,7 +8361,7 @@ mod soul_knowledge_tests { command( &active, CommandId::new(), - CallerId::System(SystemCapability::Play), + CallerId::Play, CommandBody::AdmitPatch { patch: WorldPatch { declarations: vec![Declaration::Fact(FactDeclaration { @@ -9341,7 +8377,7 @@ mod soul_knowledge_tests { }, }, ), - &AuthenticatedCaller::fixture(CallerId::System(SystemCapability::Play)), + &AuthenticatedCaller::fixture(CallerId::Play), ) .expect("the play table declares a claim in Active"); assert!(matches!(receipt, SubmitReceipt::Applied(_))); @@ -9371,7 +8407,7 @@ mod soul_knowledge_tests { ) .expect("the proclamation commits"); let active = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![ @@ -9397,7 +8433,7 @@ mod soul_knowledge_tests { ]), ); let active = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![ComponentOp::Forget { @@ -9483,10 +8519,9 @@ mod soul_knowledge_tests { /// alone, where it is refused, and what it costs an in-flight binding. #[cfg(test)] mod witness_tests { - use super::patch::Site; use super::tests::{ - play_caller, activate, auth_principal, command, creation, operations, owner, - reject_owner, submit_owner, + play_caller, auth_principal, command, creation, operations, owner, + reject_play, submit_play, }; use super::*; @@ -9560,7 +8595,7 @@ mod witness_tests { .0; let before = kernel.snapshot().unwrap(); let speak = super::tests::speak_entry(&kernel); - submit_owner( + submit_play( &mut kernel, &before, CommandBody::AdmitPatch { @@ -9680,7 +8715,7 @@ mod witness_tests { .expect("a declared route") .0, }; - let active = activate(&mut kernel); + let active = kernel.snapshot().unwrap(); (kernel, nesting, active) } @@ -9707,7 +8742,7 @@ mod witness_tests { fn a_witness_reaches_every_subject_under_the_place_and_no_other() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, world, active) = nesting_kernel(directory.path(), "Reach"); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![witness( @@ -9728,7 +8763,7 @@ mod witness_tests { assert_eq!(knows(&kernel, world.drifter, world.asteroid), None); let after = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &after, operations(vec![witness( @@ -9832,7 +8867,7 @@ mod witness_tests { }; assert_eq!( - reject_owner( + reject_play( &mut kernel, &active, operations(vec![witness( @@ -9850,7 +8885,7 @@ mod witness_tests { )); // Every stander already holds it, which is the same refusal. - submit_owner( + submit_play( &mut kernel, &active, operations(vec![witness( @@ -9861,7 +8896,7 @@ mod witness_tests { ); let after = kernel.snapshot().unwrap(); assert_eq!( - reject_owner( + reject_play( &mut kernel, &after, operations(vec![witness( @@ -9907,7 +8942,7 @@ mod witness_tests { let (mut kernel, world, active) = nesting_kernel(directory.path(), "Relocation"); // The village's own standers already hold it, so the relocated coaster // is the only candidate recipient left. - submit_owner( + submit_play( &mut kernel, &active, operations(vec![witness( @@ -9917,7 +8952,7 @@ mod witness_tests { )]), ); let seeded = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &seeded, operations(vec![ @@ -9943,7 +8978,7 @@ mod witness_tests { // the coast reaches nobody. Both layers say so. let moved = kernel.snapshot().unwrap(); assert_eq!( - reject_owner( + reject_play( &mut kernel, &moved, operations(vec![witness(world.moon, world.coast, Confidence::Certain)]), @@ -9969,40 +9004,13 @@ mod witness_tests { )); } - /// A consumer names no ground, and a jurisdiction over placeless subjects - /// names no place. Both refuse every witness through the same closure, with - /// no rule in `confine_to_ground` naming the operation. - #[test] - fn a_consumer_cannot_witness() { - let directory = tempfile::tempdir().unwrap(); - let (kernel, world, _) = nesting_kernel(directory.path(), "Consumer"); - let resolved = patch::resolve_patch( - &kernel.state, - CommandId::new(), - &WorldPatch { - declarations: Vec::new(), - operations: vec![witness(world.asteroid, world.village, Confidence::Certain)], - evidence: Vec::new(), - }, - ) - .expect("the witness resolves over committed state"); - let ground = PatchGround::Consumer(ConsumerId::of_name("witness.consumer")); - assert_eq!( - confine_to_ground(&kernel.state, &resolved, ground), - Err(vec![Mismatch::OutsideJurisdiction { - site: Site::Operation(0) - }]), - "{ground:?} admitted a witness" - ); - } - /// The components carry the keys of a subject's own knowledge, so a witness /// moves exactly the components of the subjects that learned something. #[test] fn a_witness_moves_every_recipients_scope_components_and_nobody_elses() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, world, active) = nesting_kernel(directory.path(), "Digest"); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![ComponentOp::AcquireKnowledge { @@ -10020,7 +9028,7 @@ mod witness_tests { let outsider = digest(&kernel, world.coaster); let seeded = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &seeded, operations(vec![witness( @@ -10135,7 +9143,7 @@ mod witness_tests { fn a_world_with_a_witness_replays() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, world, active) = nesting_kernel(directory.path(), "Replay"); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![witness( @@ -10212,7 +9220,7 @@ mod witness_tests { fn a_later_commits_knowledge_row_is_acquired_at_that_commits_revision() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, world, active) = nesting_kernel(directory.path(), "PAf49Later"); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![ComponentOp::AcquireKnowledge { @@ -10237,7 +9245,7 @@ mod witness_tests { fn a_shape_check_refuses_a_knowledge_row_forged_ahead_of_the_world_revision() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, world, active) = nesting_kernel(directory.path(), "PAf49Shape"); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![witness( @@ -10407,7 +9415,7 @@ mod witness_tests { fn soul_a_subject_declared_and_placed_in_one_patch_is_a_recipient_at_both_layers() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, world, active) = nesting_kernel(directory.path(), "Draft stander"); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![witness( @@ -10426,7 +9434,7 @@ mod witness_tests { let arrival = |kernel: &mut WorldKernel, handle: &str, label: &str, position: Option<EntityId>| { let snapshot = kernel.snapshot().unwrap(); - let caller = CallerId::System(SystemCapability::Play); + let caller = CallerId::Play; kernel.submit( command( &snapshot, @@ -10446,7 +9454,6 @@ mod witness_tests { label: label.into(), kind: SubjectKind::Person, controller: NewController::NarrativePersona, - // Every non-mirror subject must hold one. affordances: BTreeSet::from([Ref::Existing(beacon)]), position: position.map(Ref::Existing), import_key: None, @@ -10522,7 +9529,7 @@ mod witness_tests { fn soul_a_forget_before_a_witness_agrees_at_both_layers() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, world, active) = nesting_kernel(directory.path(), "Forget first"); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![witness( @@ -10534,7 +9541,7 @@ mod witness_tests { // Everyone under the village holds it, so the witness alone is refused. let seeded = kernel.snapshot().unwrap(); assert_eq!( - reject_owner( + reject_play( &mut kernel, &seeded, operations(vec![witness( @@ -10547,7 +9554,7 @@ mod witness_tests { ); let seeded = kernel.snapshot().unwrap(); - let receipt = submit_owner( + let receipt = submit_play( &mut kernel, &seeded, operations(vec![ @@ -10583,7 +9590,7 @@ mod witness_tests { let directory = tempfile::tempdir().unwrap(); let (mut kernel, world, active) = nesting_kernel(directory.path(), "Anonymous"); let before = scope_components(&kernel.state, world.villager); - submit_owner( + submit_play( &mut kernel, &active, operations(vec![witness( @@ -10624,9 +9631,9 @@ mod witness_tests { mod clock_tests { use super::patch::{PreconditionRef, PressureSourceRef}; use super::tests::{ - act, act_as, activate, affordance_named, auth_principal, authority_kind, command, creation, - human_principal, office, operations, owner, play_caller, reject_owner, speak, - speech_world, submit_owner, + act, affordance_named, auth_principal, authority_kind, command, creation, + human_principal, office, operations, owner, play_caller, reject_play, + speech_world, submit_play, }; use super::*; use std::path::Path; @@ -10686,7 +9693,7 @@ mod clock_tests { }) }; let subject = |handle: &str| Ref::Draft(DraftHandle::new(handle)); - submit_owner( + submit_play( kernel, &before, CommandBody::AdmitPatch { @@ -10846,7 +9853,7 @@ mod clock_tests { }, }, ); - let active = activate(kernel); + let active = kernel.snapshot().unwrap(); let place = |label: &str| { active .places @@ -10900,22 +9907,18 @@ mod clock_tests { ) } - fn clock_caller() -> CallerId { - CallerId::System(SystemCapability::Clock) - } - fn tick(kernel: &mut WorldKernel, span: u32) -> Result<SubmitReceipt, KernelError> { let snapshot = kernel.snapshot().unwrap(); kernel.submit( command( &snapshot, CommandId::new(), - clock_caller(), + CallerId::Play, CommandBody::AdvanceTime { minutes: minutes(span), }, ), - &AuthenticatedCaller::fixture(clock_caller()), + &AuthenticatedCaller::fixture(CallerId::Play), ) } @@ -11024,7 +10027,7 @@ mod clock_tests { .id }; let snapshot = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &snapshot, operations(vec![ComponentOp::Relocate { @@ -11043,7 +10046,7 @@ mod clock_tests { ); let snapshot = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &snapshot, operations(vec![ComponentOp::Relocate { @@ -11092,7 +10095,7 @@ mod clock_tests { assert_eq!(pressure(&kernel, clockwork.reeve, sourced), 0); let snapshot = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &snapshot, operations(vec![ComponentOp::CloseRoute { @@ -11104,7 +10107,7 @@ mod clock_tests { // Repair stops the pressing but never unwrites what accrued. let snapshot = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &snapshot, operations(vec![ComponentOp::OpenRoute { @@ -11115,7 +10118,7 @@ mod clock_tests { assert_eq!(pressure(&kernel, clockwork.reeve, sourced), 1); let snapshot = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &snapshot, operations(vec![ComponentOp::ResolvePressure { @@ -11149,7 +10152,7 @@ mod clock_tests { assert_eq!(kernel.state.now, now); let snapshot = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &snapshot, operations(vec![ComponentOp::CloseRoute { @@ -11159,46 +10162,6 @@ mod clock_tests { assert_eq!(kernel.state.now, now); } - /// The clock capability is admitted for one body and nothing else. - #[test] - fn the_clock_capability_can_do_nothing_else() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Capability"); - let before = kernel.state.clone(); - let snapshot = kernel.snapshot().unwrap(); - - for body in [ - CommandBody::ApproveDraft, - CommandBody::ActivateWorld, - CommandBody::Act { - actor: clockwork.reeve, - invocation: DecisionInvocation { - affordance: clockwork.threaten, - bindings: vec![binding("target", Target::Subject(clockwork.farmer))], - proposed: vec![ProposedEffect { - slot: 0, - magnitude: Magnitude::None, - }], - speech: None, - display: None, - }, - }, - operations(vec![ComponentOp::CloseRoute { - route: Ref::Existing(clockwork.gate), - }]), - ] { - let error = kernel - .submit( - command(&snapshot, CommandId::new(), clock_caller(), body), - &AuthenticatedCaller::fixture(clock_caller()), - ) - .unwrap_err(); - assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); - } - assert_eq!(kernel.state, before); - tick(&mut kernel, 1).expect("the same caller may tick"); - } - /// Who may tick, when, and how far. #[test] fn advance_time_negatives() { @@ -11211,30 +10174,7 @@ mod clock_tests { .expect("a created world") .0; - // There is no time in Draft. - let draft = kernel.snapshot().unwrap(); - let error = kernel - .submit( - command( - &draft, - CommandId::new(), - clock_caller(), - CommandBody::AdvanceTime { - minutes: minutes(1), - }, - ), - &AuthenticatedCaller::fixture(clock_caller()), - ) - .unwrap_err(); - assert!(matches!( - error, - KernelError::WrongPhase { - expected: WorldPhase::Active, - actual: WorldPhase::Draft, - } - )); - - let active = activate(&mut kernel); + let active = kernel.snapshot().unwrap(); // A span is constructor-checked, so a malformed one never reaches a // command at all. assert!(TickMinutes::new(0).is_none()); @@ -11242,7 +10182,7 @@ mod clock_tests { for caller in [ CallerId::Principal(human_principal()), - CallerId::Controller(ControllerId::issue()), + CallerId::Principal(owner()), ] { let error = kernel .submit( @@ -11260,8 +10200,8 @@ mod clock_tests { assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); } - // The owner may tick from an interface. - submit_owner( + // Play ticks. + submit_play( &mut kernel, &active, CommandBody::AdvanceTime { @@ -11279,12 +10219,12 @@ mod clock_tests { command( &snapshot, CommandId::new(), - clock_caller(), + CallerId::Play, CommandBody::AdvanceTime { minutes: minutes(1), }, ), - &AuthenticatedCaller::fixture(clock_caller()), + &AuthenticatedCaller::fixture(CallerId::Play), ) .unwrap_err(); assert!(matches!(error, KernelError::Serialization(_)), "{error:?}"); @@ -11357,7 +10297,7 @@ mod clock_tests { ]; for forged in forgeries { let mut candidate = kernel.state.clone(); - let error = apply_effect(&mut candidate, CommandId::issue(), &clock_caller(), &forged) + let error = apply_effect(&mut candidate, CommandId::issue(), &CallerId::Play, &forged) .unwrap_err(); assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); assert_eq!(candidate, kernel.state); @@ -11368,7 +10308,7 @@ mod clock_tests { apply_effect( &mut candidate, CommandId::issue(), - &clock_caller(), + &CallerId::Play, &WorldEffect::TimeAdvanced { minutes: minutes(120), to, @@ -11400,14 +10340,14 @@ mod clock_tests { let repeat = command( &snapshot, CommandId::new(), - CallerId::Principal(owner()), + CallerId::Play, operations(vec![ComponentOp::DischargeCommitment { subject: Ref::Existing(clockwork.farmer), key: clockwork.obligation, }]), ); kernel - .submit(repeat.clone(), &auth_principal(owner())) + .submit(repeat.clone(), &AuthenticatedCaller::verified_play()) .expect("the discharge commits"); // Discharge removes every pressure row it sourced. assert_eq!( @@ -11429,7 +10369,7 @@ mod clock_tests { assert_eq!(replayed.state, before); assert_eq!(replayed.snapshot().unwrap(), before_snapshot); assert!(matches!( - replayed.submit(repeat, &auth_principal(owner())), + replayed.submit(repeat, &AuthenticatedCaller::verified_play()), Ok(SubmitReceipt::AlreadyApplied(_)) )); } @@ -11457,7 +10397,7 @@ mod clock_tests { }; assert_eq!( - reject_owner( + reject_play( &mut kernel, &active, operations(vec![ @@ -11532,7 +10472,7 @@ mod clock_tests { assert_eq!(kernel.state, before); // Repairing exactly those commits. - submit_owner( + submit_play( &mut kernel, &active, operations(vec![ @@ -11608,7 +10548,7 @@ mod clock_tests { let directory = tempfile::tempdir().unwrap(); let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "DischargeThenAct"); let snapshot = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &snapshot, operations(vec![ComponentOp::DischargeCommitment { @@ -11665,7 +10605,7 @@ mod clock_tests { let directory = tempfile::tempdir().unwrap(); let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "CommittedKind"); let snapshot = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &snapshot, operations(vec![ComponentOp::CreateCommitment { @@ -11726,7 +10666,7 @@ mod clock_tests { // Past the obligation and the goal, but the routine is blocked out of // the yard first so only pressure moves. let snapshot = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &snapshot, operations(vec![ComponentOp::DischargeCommitment { @@ -11741,7 +10681,7 @@ mod clock_tests { // A routine fulfilment moves exactly its own subject's digest. let snapshot = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &snapshot, operations(vec![ComponentOp::CreateCommitment { @@ -11796,7 +10736,7 @@ mod clock_tests { tick(&mut kernel, u32::try_from(LATE_DUE).unwrap()).expect("the tick commits"); assert_eq!(pressure(&kernel, clockwork.farmer, sourced), 1); let snapshot = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &snapshot, operations(vec![ComponentOp::ReducePressure { @@ -11816,7 +10756,7 @@ mod clock_tests { // Resolving an absent row changes nothing and is refused. let snapshot = kernel.snapshot().unwrap(); - let mismatches = reject_owner( + let mismatches = reject_play( &mut kernel, &snapshot, operations(vec![ComponentOp::ResolvePressure { @@ -11857,12 +10797,60 @@ mod clock_tests { assert_eq!(digests(&kernel), before, "the clock entered a scope"); } - // ---- PA.f26: the genesis lane obeys `require_ruler` too ------------ + // ---- genesis may not rule or mint ---------------------------------- - /// PA.f26: `prepare_creation` and `WorldState::genesis` both call - /// `require_ruler` exactly where every other admission lane does. A - /// creation patch that carries a `Ruled` fact is refused before a world - /// is ever written. + /// Only Play rules or mints, and Play writes only after genesis: the + /// check reports every offender, not the first, so a scan narrowed to one + /// fact or one operation fails here. + #[test] + fn genesis_may_not_rule_or_mint() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let mut input = creation(CommandId::new(), "RulesAndMints"); + for handle in ["first-rule", "second-rule"] { + input + .patch + .declarations + .push(Declaration::Fact(FactDeclaration { + handle: DraftHandle::new(handle), + label: format!("The {handle}"), + statement: Statement::new("Stated by the table.").unwrap(), + standing: FactStandingRef::Ruled, + })); + } + input + .patch + .declarations + .push(super::tests::resource("loot", "Roadside Loot")); + for _ in 0..2 { + input.patch.operations.push(ComponentOp::Mint { + holder: Ref::Draft(DraftHandle::new("human")), + resource: Ref::Draft(DraftHandle::new("loot")), + qty: Quantity(4), + }); + } + let Err(error) = WorldKernel::create(&path, input, &auth_principal(owner())) else { + panic!("a genesis patch that rules and mints was admitted"); + }; + let KernelError::PatchRejected(set) = error else { + panic!("expected a rejected patch, got {error:?}"); + }; + let offender = |site| Mismatch::RuledWithoutAuthority { site }; + assert_eq!( + set, + vec![ + offender(patch::Site::Declaration(DraftHandle::new("first-rule"))), + offender(patch::Site::Declaration(DraftHandle::new("second-rule"))), + offender(patch::Site::Operation(0)), + offender(patch::Site::Operation(1)), + ] + ); + assert!(!path.exists(), "a refused genesis wrote a world file"); + } + + /// `prepare_creation` and `WorldState::genesis` both forbid rulings at + /// genesis. A creation patch that carries a `Ruled` fact is refused before + /// a world is ever written. #[test] fn a_genesis_patch_carrying_a_ruled_fact_is_refused() { let directory = tempfile::tempdir().unwrap(); @@ -11890,8 +10878,8 @@ mod clock_tests { assert!(!path.exists(), "a refused genesis wrote a world file"); } - /// PA.f26, the `Mint` half: a creation patch that carries a `Mint` is - /// refused the same way. + /// The `Mint` half: a creation patch that carries a `Mint` is refused the + /// same way. #[test] fn a_genesis_patch_carrying_a_mint_is_refused() { let directory = tempfile::tempdir().unwrap(); @@ -11919,7 +10907,7 @@ mod clock_tests { assert!(!path.exists(), "a refused genesis wrote a world file"); } - /// PA.f26: `WorldState::genesis` re-decides `require_ruler` on its own + /// `WorldState::genesis` re-decides `forbid_rulings_at_genesis` on its own /// terms, independent of `prepare_creation` — that is what protects /// journal replay of a stored genesis commit, not only a freshly /// admitted one. Called directly, bypassing `prepare_creation` entirely, @@ -11988,7 +10976,7 @@ mod clock_tests { // The farmer's obligation, claimed by the reeve. let snapshot = kernel.snapshot().unwrap(); assert_eq!( - reject_owner( + reject_play( &mut kernel, &snapshot, operations(vec![ComponentOp::DischargeCommitment { @@ -12001,7 +10989,7 @@ mod clock_tests { // Discharged once, and then not again. let snapshot = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &snapshot, operations(vec![ComponentOp::DischargeCommitment { @@ -12011,7 +10999,7 @@ mod clock_tests { ); let snapshot = kernel.snapshot().unwrap(); assert_eq!( - reject_owner( + reject_play( &mut kernel, &snapshot, operations(vec![ComponentOp::DischargeCommitment { @@ -12052,7 +11040,7 @@ mod clock_tests { // Checks belong to routines alone. let snapshot = kernel.snapshot().unwrap(); assert_eq!( - reject_owner( + reject_play( &mut kernel, &snapshot, operations(vec![ComponentOp::CreateCommitment { @@ -12080,7 +11068,7 @@ mod clock_tests { let directory = tempfile::tempdir().unwrap(); let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Pure"); let snapshot = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &snapshot, operations(vec![ComponentOp::CloseRoute { @@ -12106,7 +11094,7 @@ mod clock_tests { let ticking = command( &snapshot, CommandId::new(), - clock_caller(), + CallerId::Play, CommandBody::AdvanceTime { minutes: minutes(span), }, @@ -12123,10 +11111,10 @@ mod clock_tests { // Applying the re-derived effect to a copy reproduces the committed // state exactly, which is the replay identity the journal relies on. let mut replayed = kernel.state.clone(); - apply_effect(&mut replayed, ticking.id, &clock_caller(), &expected) + apply_effect(&mut replayed, ticking.id, &CallerId::Play, &expected) .expect("the re-derived effect applies"); kernel - .submit(ticking, &AuthenticatedCaller::fixture(clock_caller())) + .submit(ticking, &AuthenticatedCaller::fixture(CallerId::Play)) .expect("the tick commits"); assert_eq!(replayed.now, kernel.state.now); assert_eq!(replayed.commitments, kernel.state.commitments); @@ -12160,52 +11148,6 @@ mod clock_tests { } } - /// The one admission rule at the top of `reduce` refuses four bodies before - /// any of them is read, and the clock's capability is refused the fifth. - #[test] - fn a_system_capability_is_admitted_for_exactly_one_body() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "Capability"); - let held = CallerId::System(SystemCapability::Consumer { - consumer: ConsumerId::of_name("capability-consumer"), - }); - let forbidden = [ - CommandBody::ApproveDraft, - CommandBody::ActivateWorld, - CommandBody::Act { - actor: clockwork.reeve, - invocation: DecisionInvocation { - affordance: clockwork.threaten, - bindings: vec![binding("target", Target::Subject(clockwork.farmer))], - proposed: vec![ProposedEffect { - slot: 0, - magnitude: Magnitude::None, - }], - speech: None, - display: None, - }, - }, - CommandBody::AdvanceTime { - minutes: minutes(60), - }, - ]; - for body in forbidden { - let error = submit_as(&mut kernel, held.clone(), body).unwrap_err(); - assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); - } - // The mirror: the clock may not author. - let error = submit_as( - &mut kernel, - clock_caller(), - CommandBody::AdmitPatch { - patch: shed_under(clockwork.dead_end, "shed"), - }, - ) - .unwrap_err(); - assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); - assert_eq!(kernel.state.revision, active.revision); - } - /// The mismatch vocabulary is kernel-internal plus controller telemetry. It /// never enters a commit, and `verify_state_shape` never grows a clause for /// it because no partition holds one. @@ -12278,39 +11220,6 @@ mod clock_tests { assert!(matches!(receipt, SubmitReceipt::Applied(_))); } - /// Declaring in Active is the play table's act alone: the owner is refused - /// for new structure and for evidence, and an operations-only owner patch - /// is still admitted (the other tests here do it). - #[test] - fn the_owner_cannot_declare_in_active() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "OwnerDeclares"); - let revision = kernel.state.revision; - let evidence_only = WorldPatch { - declarations: Vec::new(), - operations: Vec::new(), - evidence: vec![EvidenceRef::new("vault:loose")], - }; - for patch in [shed_under(clockwork.dead_end, "shed"), evidence_only] { - let error = submit_as( - &mut kernel, - CallerId::Principal(owner()), - CommandBody::AdmitPatch { patch }, - ) - .unwrap_err(); - assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); - } - assert_eq!(kernel.state.revision, revision); - submit_as( - &mut kernel, - play_caller(), - CommandBody::AdmitPatch { - patch: shed_under(clockwork.dead_end, "shed"), - }, - ) - .expect("the play table declares the same patch"); - } - /// Invariant 5: the play authority reaches the whole world, unconfined to /// a ground. Writing under a place no jurisdiction covers is exactly what /// a confined author cannot do. @@ -12328,38 +11237,6 @@ mod clock_tests { .expect("the play authority is confined to no ground"); } - /// P3.6: the play authority cannot act in Draft. - #[test] - fn the_play_authority_is_refused_in_draft() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = WorldKernel::create( - directory.path().join("world.cc"), - creation(CommandId::new(), "PlayDraft"), - &auth_principal(owner()), - ) - .expect("a created world") - .0; - let commons = kernel.snapshot().unwrap().places[0].id; - let error = submit_as( - &mut kernel, - play_caller(), - CommandBody::AdmitPatch { - patch: shed_under(commons, "shed"), - }, - ) - .unwrap_err(); - assert!( - matches!( - error, - KernelError::WrongPhase { - expected: WorldPhase::Active, - actual: WorldPhase::Draft, - } - ), - "{error:?}" - ); - } - /// Invariant 5: the play authority advances time, the clock's precedent. #[test] fn the_play_authority_advances_time() { @@ -12377,147 +11254,6 @@ mod clock_tests { assert!(kernel.state.now > active.now); } - /// Act is Play's alone: the owner, the clock, a controller and a - /// non-owner principal are refused and commit nothing; Play applies. - #[test] - fn only_play_may_act() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "OnlyPlayActs"); - let invocation = DecisionInvocation { - affordance: clockwork.threaten, - bindings: vec![binding("target", Target::Subject(clockwork.farmer))], - proposed: vec![ProposedEffect { - slot: 0, - magnitude: Magnitude::None, - }], - speech: None, - display: None, - }; - let before = kernel.state.clone(); - for caller in [ - CallerId::Principal(owner()), - CallerId::Principal(human_principal()), - clock_caller(), - CallerId::Controller(ControllerId::issue()), - ] { - let error = - act_as(&mut kernel, caller.clone(), clockwork.reeve, invocation.clone()) - .unwrap_err(); - assert!( - matches!(error, KernelError::Unauthorized), - "{caller:?}: {error:?}" - ); - } - assert_eq!(kernel.state, before, "a refused act commits nothing"); - let receipt = act(&mut kernel, clockwork.reeve, invocation).expect("Play acts"); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); - assert_eq!(kernel.state.events.len(), before.events.len() + 1); - assert_eq!(kernel.state.events.last().unwrap().actor, clockwork.reeve); - } - - /// The commit-time re-decision of an `Acted` effect is Play's, in Active: - /// the same honest effect is refused for the owner and in Draft. - #[test] - fn an_acted_effect_applies_only_for_play_in_active() { - let directory = tempfile::tempdir().unwrap(); - let (kernel, clockwork, _) = clock_kernel(directory.path(), "ActedGate"); - let invocation = DecisionInvocation { - affordance: clockwork.threaten, - bindings: vec![binding("target", Target::Subject(clockwork.farmer))], - proposed: vec![ProposedEffect { - slot: 0, - magnitude: Magnitude::None, - }], - speech: None, - display: None, - }; - let command_id = CommandId::new(); - let granted = - require_granted(&kernel.state, clockwork.reeve, invocation.affordance).unwrap(); - let event = - action::exercise(&kernel.state, command_id, clockwork.reeve, &granted, &invocation) - .unwrap(); - let effect = WorldEffect::Acted { invocation, event }; - - let mut candidate = kernel.state.clone(); - let error = apply_effect( - &mut candidate, - command_id, - &CallerId::Principal(owner()), - &effect, - ) - .unwrap_err(); - assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); - assert_eq!(candidate, kernel.state); - - let mut draft = kernel.state.clone(); - draft.phase = WorldPhase::Draft; - let error = apply_effect(&mut draft, command_id, &play_caller(), &effect).unwrap_err(); - assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); - - let mut honest = kernel.state.clone(); - apply_effect(&mut honest, command_id, &play_caller(), &effect).unwrap(); - assert_eq!(honest.events.len(), kernel.state.events.len() + 1); - } - - /// There is no acting before activation. - #[test] - fn act_in_draft_is_wrong_phase() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, _) = WorldKernel::create( - directory.path().join("world.cc"), - creation(CommandId::new(), "ActInDraft"), - &auth_principal(owner()), - ) - .unwrap(); - let error = act( - &mut kernel, - SubjectId::issue(), - speak(AffordanceId::issue(), "Too soon."), - ) - .unwrap_err(); - assert!( - matches!( - error, - KernelError::WrongPhase { - expected: WorldPhase::Active, - actual: WorldPhase::Draft, - } - ), - "{error:?}" - ); - } - - /// P3.6: the play authority may not approve or activate. - /// `require_system_capability`, at the top of `reduce`, refuses both - /// before any body-specific arm is read. - #[test] - fn the_play_authority_cannot_approve_or_activate() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, _, _) = clock_kernel(directory.path(), "PlayForbidden"); - let forbidden = [CommandBody::ApproveDraft, CommandBody::ActivateWorld]; - for body in &forbidden { - let error = submit_as(&mut kernel, play_caller(), body.clone()).unwrap_err(); - assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); - } - // The end-to-end check above cannot tell "refused before any - // body-specific arm is read" apart from a downstream refusal that - // would fail Play just as closed (`require_owner`, for one, refuses - // every non-owner caller regardless of what admitted it). Pin - // `require_system_capability` directly, so widening its table for - // `Play` is caught even though every arm behind it still happens to - // refuse `Play` on its own. - for body in &forbidden { - assert!( - matches!( - require_system_capability(&play_caller(), body), - Err(KernelError::Unauthorized) - ), - "require_system_capability admitted {body:?} for the play authority" - ); - } - } - /// P3.4: a ruled fact is world truth to every subject that knows it. #[test] fn the_play_authority_rules_a_fact_and_a_witness_knows_it_as_canon() { @@ -12625,12 +11361,11 @@ mod clock_tests { ); } - /// The evidence gate on `Canonical` facts and `Admit` is byte-for-byte the - /// same predicate at the same sites for every author, `Play` included - /// (P3.3). `Play` carries no receipts, so its `Admit` is refused like - /// anyone's without one. + /// The evidence gate on `Canonical` facts and `Admit` is one predicate at + /// the same sites for genesis and for Play (P3.3). `Play` carries no + /// receipts, so its `Admit` is refused without one. #[test] - fn the_evidence_gate_is_unchanged_for_every_author() { + fn the_evidence_gate_holds_for_play() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PlayEvidenceGate"); let grain = resource_named(&kernel, "Winter Grain"); @@ -12678,301 +11413,6 @@ mod clock_tests { }, ) .expect("an evidenced admit is admitted for the play authority too"); - - // PA.f29a: the owner in Draft — the seed's caller. - { - let seed_directory = tempfile::tempdir().unwrap(); - let (mut seed_kernel, _) = WorldKernel::create( - seed_directory.path().join("world.cc"), - creation(CommandId::new(), "OwnerDraftEvidence"), - &auth_principal(owner()), - ) - .expect("a created world"); - let fact = |evidence: &str| { - Declaration::Fact(FactDeclaration { - handle: DraftHandle::new("draft-fact"), - label: "The Draft Count".into(), - statement: Statement::new("The draft is counted.").unwrap(), - standing: FactStandingRef::Canonical { - evidence: EvidenceRef::new(evidence), - }, - }) - }; - let snapshot = seed_kernel.snapshot().unwrap(); - let uncited = seed_kernel - .submit( - command( - &snapshot, - CommandId::new(), - CallerId::Principal(owner()), - CommandBody::AdmitPatch { - patch: WorldPatch { - declarations: vec![fact("vault:draft-uncited")], - operations: Vec::new(), - evidence: Vec::new(), - }, - }, - ), - &auth_principal(owner()), - ) - .unwrap_err(); - assert!( - matches!(&uncited, KernelError::PatchRejected(set) - if set.contains(&Mismatch::FactWithoutEvidence { - handle: DraftHandle::new("draft-fact"), - })), - "{uncited:?}" - ); - let snapshot = seed_kernel.snapshot().unwrap(); - seed_kernel - .submit( - command( - &snapshot, - CommandId::new(), - CallerId::Principal(owner()), - CommandBody::AdmitPatch { - patch: WorldPatch { - declarations: vec![fact("vault:draft-cited")], - operations: Vec::new(), - evidence: vec![EvidenceRef::new("vault:draft-cited")], - }, - }, - ), - &auth_principal(owner()), - ) - .expect("a cited canonical fact is admitted for the owner in Draft"); - } - } - - /// `reduce` decides and `apply_effect` re-decides: a forged - /// `PatchAdmitted` under the owner, carrying a `Mint` the resolver would - /// accept (the resolver is actor-blind) and that fully satisfies - /// confinement (the owner is unconfined), is still refused at apply. Only - /// `require_ruler`'s re-decision can be refusing this. - #[test] - fn apply_effect_re_decides_the_ruler() { - let directory = tempfile::tempdir().unwrap(); - let (kernel, clockwork, _) = clock_kernel(directory.path(), "RedecideRulerMint"); - let grain = resource_named(&kernel, "Winter Grain"); - let command_id = CommandId::issue(); - let patch = WorldPatch { - declarations: Vec::new(), - operations: vec![ComponentOp::Mint { - holder: Ref::Existing(clockwork.reeve), - resource: Ref::Existing(grain), - qty: Quantity(4), - }], - evidence: Vec::new(), - }; - let resolved = patch::resolve_patch(&kernel.state, command_id, &patch) - .expect("the patch resolves; the resolver is actor-blind"); - let effect = WorldEffect::PatchAdmitted { resolved }; - - let mut candidate = kernel.state.clone(); - let error = apply_effect( - &mut candidate, - command_id, - &CallerId::Principal(owner()), - &effect, - ) - .unwrap_err(); - assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); - assert_eq!(candidate, kernel.state); - - let mut candidate = kernel.state.clone(); - apply_effect(&mut candidate, command_id, &play_caller(), &effect) - .expect("the play authority applies through the same arm"); - assert_ne!(candidate, kernel.state); - } - - /// `apply_effect` re-decides confinement: a forged `PatchAdmitted` under a - /// consumer, carrying an operations-only route cost change the resolver - /// accepts and no consumer ground covers, is refused at apply. - #[test] - fn apply_effect_re_decides_confinement() { - let directory = tempfile::tempdir().unwrap(); - let (kernel, clockwork, _) = clock_kernel(directory.path(), "RedecideGround"); - let command_id = CommandId::issue(); - let patch = WorldPatch { - declarations: Vec::new(), - operations: vec![ComponentOp::AlterCost { - route: Ref::Existing(clockwork.gate), - cost: Cost(2), - }], - evidence: Vec::new(), - }; - let resolved = patch::resolve_patch(&kernel.state, command_id, &patch) - .expect("the patch resolves; the resolver is actor-blind"); - let effect = WorldEffect::PatchAdmitted { resolved }; - let consumer = CallerId::System(SystemCapability::Consumer { - consumer: ConsumerId::of_name("redecide-ground"), - }); - let mut candidate = kernel.state.clone(); - let error = apply_effect(&mut candidate, command_id, &consumer, &effect).unwrap_err(); - assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); - assert_eq!(candidate, kernel.state); - - let mut candidate = kernel.state.clone(); - apply_effect(&mut candidate, command_id, &CallerId::Principal(owner()), &effect) - .expect("the unconfined owner applies the same effect"); - assert_ne!(candidate, kernel.state); - } - - /// `apply_effect` re-decides that declaring in Active is the play table's - /// act: a forged `PatchAdmitted` that declares, under the owner, is refused - /// at apply, and the play table applies it through the same arm. - #[test] - fn apply_effect_re_decides_that_declaring_in_active_is_plays() { - let directory = tempfile::tempdir().unwrap(); - let (kernel, clockwork, _) = clock_kernel(directory.path(), "RedecideDeclares"); - let command_id = CommandId::issue(); - let resolved = patch::resolve_patch( - &kernel.state, - command_id, - &shed_under(clockwork.dead_end, "shed"), - ) - .expect("the patch resolves; the resolver is actor-blind"); - let effect = WorldEffect::PatchAdmitted { resolved }; - let mut candidate = kernel.state.clone(); - let error = apply_effect( - &mut candidate, - command_id, - &CallerId::Principal(owner()), - &effect, - ) - .unwrap_err(); - assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); - assert_eq!(candidate, kernel.state); - - let mut candidate = kernel.state.clone(); - apply_effect(&mut candidate, command_id, &play_caller(), &effect) - .expect("the play table applies it"); - assert_ne!(candidate, kernel.state); - } - - /// PA.f27a: the owner is a `CallerId::Principal` like any other, and - /// `apply_effect`'s re-decision of `require_ruler` carries no exemption - /// for that variant. A forged `PatchAdmitted` under the owner, carrying - /// a `Ruled` fact the resolver accepts (actor-blind) and that fully - /// satisfies confinement (the owner is unconfined), is still refused at - /// apply. Follows `apply_effect_re_decides_the_ruler`. - #[test] - fn apply_effect_re_decides_the_ruler_for_the_owner_too() { - let directory = tempfile::tempdir().unwrap(); - let (kernel, _) = WorldKernel::create( - directory.path().join("world.cc"), - creation(CommandId::new(), "RedecideRulerOwner"), - &auth_principal(owner()), - ) - .unwrap(); - let command_id = CommandId::issue(); - let patch = ruled_fact_patch("rule"); - let resolved = patch::resolve_patch(&kernel.state, command_id, &patch) - .expect("the patch resolves; the resolver is actor-blind"); - let effect = WorldEffect::PatchAdmitted { resolved }; - - let mut candidate = kernel.state.clone(); - let error = apply_effect( - &mut candidate, - command_id, - &CallerId::Principal(owner()), - &effect, - ) - .unwrap_err(); - assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); - assert_eq!(candidate, kernel.state); - } - - /// PA.f27b: `require_ruler` walks every operation, not only the first. - /// A harmless `Relocate` at index 0 followed by a `Mint` at index 1, - /// from a non-`Play` author, is refused at index 1. Kills a scan - /// narrowed to `.take(1)`. - #[test] - fn require_ruler_catches_a_mint_past_the_first_operation() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RulerScansEveryOp"); - let grain = resource_named(&kernel, "Winter Grain"); - let stair = *kernel - .state - .edges - .iter() - .find(|(_, record)| record.label() == "The Yard Stair") - .expect("the declared route") - .0; - let snapshot = kernel.snapshot().unwrap(); - let Err(error) = kernel.submit( - command( - &snapshot, - CommandId::new(), - CallerId::Principal(owner()), - operations(vec![ - ComponentOp::Relocate { - subject: Ref::Existing(clockwork.reeve), - via: Ref::Existing(stair), - }, - ComponentOp::Mint { - holder: Ref::Existing(clockwork.reeve), - resource: Ref::Existing(grain), - qty: Quantity(4), - }, - ]), - ), - &auth_principal(owner()), - ) else { - panic!("a non-Play Mint past the first operation was admitted"); - }; - assert!( - matches!(&error, KernelError::PatchRejected(set) - if set.contains(&Mismatch::RuledWithoutAuthority { - site: patch::Site::Operation(1), - })), - "{error:?}" - ); - } - - /// PA.f27c: `require_ruler` reports every `Ruled` declaration, not only - /// the first. Two `Ruled` facts from a non-`Play` author are both - /// reported. Kills a check narrowed to the first ruled fact. - #[test] - fn require_ruler_reports_every_ruled_fact() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let (mut kernel, _) = WorldKernel::create( - &path, - creation(CommandId::new(), "RulerScansEveryFact"), - &auth_principal(owner()), - ) - .expect("a created world"); - let snapshot = kernel.snapshot().unwrap(); - let mut patch = ruled_fact_patch("first-rule"); - patch.declarations.push(Declaration::Fact(FactDeclaration { - handle: DraftHandle::new("second-rule"), - label: "The Second Ruling".into(), - statement: Statement::new("Stated by the table, again.").unwrap(), - standing: FactStandingRef::Ruled, - })); - let Err(error) = kernel.submit( - command( - &snapshot, - CommandId::new(), - CallerId::Principal(owner()), - CommandBody::AdmitPatch { - patch, - }, - ), - &auth_principal(owner()), - ) else { - panic!("two non-Play Ruled facts were admitted"); - }; - assert!( - matches!(&error, KernelError::PatchRejected(set) - if set.contains(&Mismatch::RuledWithoutAuthority { - site: patch::Site::Declaration(DraftHandle::new("first-rule")), - }) && set.contains(&Mismatch::RuledWithoutAuthority { - site: patch::Site::Declaration(DraftHandle::new("second-rule")), - })), - "{error:?}" - ); } /// P3.5, replay half, folded with a ruled fact: reopening the journal @@ -13020,56 +11460,17 @@ mod clock_tests { } } - /// The owner retires a subject in Active. `retire_patch` declares - /// nothing and cites no evidence, so `require_answer`'s `declares` gate - /// never opens for it and no answer is needed, exactly as an owner's - /// ordinary bare operation needs none. - fn owner_retires(kernel: &mut WorldKernel, subject: SubjectId) -> Result<SubmitReceipt, KernelError> { + /// Play retires a subject. + fn play_retires(kernel: &mut WorldKernel, subject: SubjectId) -> Result<SubmitReceipt, KernelError> { submit_as( kernel, - CallerId::Principal(owner()), + CallerId::Play, CommandBody::AdmitPatch { patch: retire_patch(subject), }, ) } - /// Declares a mirror bound to a consumer this test invents, at the yard, - /// via the play table in Active. Shared by the retirement and grant tests that - /// need a subject `mode()` already excludes. - fn declare_mirror(kernel: &mut WorldKernel, clockwork: &Clockwork, name: &str) -> SubjectId { - submit_as( - kernel, - play_caller(), - CommandBody::AdmitPatch { - patch: WorldPatch { - declarations: vec![Declaration::Subject(SubjectDeclaration { - handle: DraftHandle::new("mirror"), - label: "The Bound Hold".into(), - kind: SubjectKind::Institution, - controller: NewController::External { - consumer: ConsumerId::of_name(name), - }, - affordances: BTreeSet::new(), - position: Some(Ref::Existing(clockwork.dead_end)), - import_key: None, - })], - operations: Vec::new(), - evidence: Vec::new(), - }, - }, - ) - .expect("the play table declares a mirror in Active"); - kernel - .snapshot() - .unwrap() - .subjects - .iter() - .find(|subject| subject.label == "The Bound Hold") - .expect("the declared mirror") - .id - } - /// P4.1, replay half: reopening the journal reproduces a retirement — no /// grants and `retired` both survive the round trip. #[test] @@ -13088,7 +11489,7 @@ mod clock_tests { .is_empty(), "the reeve holds grants before retirement" ); - owner_retires(&mut kernel, clockwork.reeve).expect("the owner retires the reeve"); + play_retires(&mut kernel, clockwork.reeve).expect("play retires the reeve"); (kernel.state.world_id, clockwork.reeve) }; let replayed = WorldKernel::open(&path, world_id).expect("the store replays"); @@ -13108,7 +11509,7 @@ mod clock_tests { fn a_retired_subject_cannot_act() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RetireCannotAct"); - owner_retires(&mut kernel, clockwork.reeve).expect("the owner retires the reeve"); + play_retires(&mut kernel, clockwork.reeve).expect("play retires the reeve"); let error = exercise( &mut kernel, clockwork.reeve, @@ -13126,7 +11527,7 @@ mod clock_tests { fn a_retired_subject_hears_nothing() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RetireHearsNothing"); - owner_retires(&mut kernel, clockwork.reeve).expect("the owner retires the reeve"); + play_retires(&mut kernel, clockwork.reeve).expect("play retires the reeve"); let mut patch = ruled_fact_patch("news"); patch.operations.push(ComponentOp::Witness { fact: Ref::Draft(DraftHandle::new("news")), @@ -13166,7 +11567,7 @@ mod clock_tests { let before_commitments = kernel.state.commitments.get(&clockwork.farmer).cloned(); assert!(before_holdings.is_some()); assert!(before_commitments.is_some()); - owner_retires(&mut kernel, clockwork.farmer).expect("the owner retires the farmer"); + play_retires(&mut kernel, clockwork.farmer).expect("play retires the farmer"); assert_eq!( kernel.state.holdings.get(&clockwork.farmer).cloned(), before_holdings @@ -13183,8 +11584,8 @@ mod clock_tests { fn retiring_twice_is_no_effect() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RetireTwice"); - owner_retires(&mut kernel, clockwork.reeve).expect("the first retirement commits"); - let error = owner_retires(&mut kernel, clockwork.reeve).unwrap_err(); + play_retires(&mut kernel, clockwork.reeve).expect("the first retirement commits"); + let error = play_retires(&mut kernel, clockwork.reeve).unwrap_err(); assert!( matches!(&error, KernelError::PatchRejected(set) if set.contains(&Mismatch::NoOperationEffect { operation: 0 })), @@ -13192,96 +11593,6 @@ mod clock_tests { ); } - /// `confine_to_ground` refuses `Retire`, `GrantAffordance` and - /// `RevokeAffordance` for a confined author unconditionally, even over a - /// subject bound to that author's own ground. The resolver refuses these - /// on a mirror before confinement runs, so the arm is probed directly on - /// a hand-built resolved patch: only the unconditional arm can refuse it. - #[test] - fn a_confined_author_cannot_retire_grant_or_revoke_its_own_mirror() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "ConfinedOwn"); - let mirror = declare_mirror(&mut kernel, &clockwork, "confined-own"); - let ground = PatchGround::Consumer(ConsumerId::of_name("confined-own")); - for operation in [ - ResolvedOp::Retire { subject: mirror }, - ResolvedOp::GrantAffordance { - subject: mirror, - affordance: clockwork.threaten, - }, - ResolvedOp::RevokeAffordance { - subject: mirror, - affordance: clockwork.threaten, - }, - ] { - let resolved = ResolvedPatch { - subjects: Vec::new(), - entities: Vec::new(), - routes: Vec::new(), - affordances: Vec::new(), - facts: Vec::new(), - channels: Vec::new(), - operations: vec![operation.clone()], - evidence: Vec::new(), - }; - assert_eq!( - confine_to_ground(&kernel.state, &resolved, ground), - Err(vec![Mismatch::OutsideJurisdiction { - site: Site::Operation(0) - }]), - "{operation:?}" - ); - } - } - - /// P4.3: a mirror is owned by another world; this one cannot retire it. - #[test] - fn a_mirror_cannot_be_retired() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RetireMirror"); - let mirror = declare_mirror(&mut kernel, &clockwork, "cut4-retire-mirror"); - let error = owner_retires(&mut kernel, mirror).unwrap_err(); - assert!( - matches!(&error, KernelError::PatchRejected(set) - if set.contains(&Mismatch::RetiresAMirror { operation: 0 })), - "{error:?}" - ); - } - - /// P4.3: the owner and the play authority are the two callers a - /// `Retire` admits. - #[test] - fn the_owner_and_the_play_authority_may_retire() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RetireOwnerAndPlay"); - owner_retires(&mut kernel, clockwork.reeve).expect("the owner retires the reeve"); - submit_as( - &mut kernel, - play_caller(), - CommandBody::AdmitPatch { - patch: retire_patch(clockwork.farmer), - }, - ) - .expect("the play authority retires the farmer"); - let snapshot = kernel.snapshot().unwrap(); - assert!( - snapshot - .subjects - .iter() - .find(|subject| subject.id == clockwork.reeve) - .unwrap() - .retired - ); - assert!( - snapshot - .subjects - .iter() - .find(|subject| subject.id == clockwork.farmer) - .unwrap() - .retired - ); - } - // ---- Cut 5: granting and revoking affordances --------------------- fn wave_affordance() -> Declaration { @@ -13323,7 +11634,7 @@ mod clock_tests { let before = kernel.snapshot().unwrap(); let commons = before.places[0].id; let speak = super::tests::speak_entry(&kernel); - submit_owner( + submit_play( &mut kernel, &before, CommandBody::AdmitPatch { @@ -13414,104 +11725,6 @@ mod clock_tests { assert!(!reeve.affordances.contains(&clockwork.threaten)); } - /// P5.2: the never-mute rule requires at least one grant; a revoke - /// that would leave the reeve mute is refused before it ever reaches - /// that invariant. - #[test] - fn a_revoke_cannot_leave_a_subject_mute() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RevokeMute"); - let speak = super::tests::speak_entry(&kernel); - for affordance in [clockwork.deliver, clockwork.threaten] { - submit_as( - &mut kernel, - play_caller(), - CommandBody::AdmitPatch { - patch: WorldPatch { - declarations: Vec::new(), - operations: vec![ComponentOp::RevokeAffordance { - subject: Ref::Existing(clockwork.reeve), - affordance: Ref::Existing(affordance), - }], - evidence: Vec::new(), - }, - }, - ) - .expect("the play authority revokes down toward one verb"); - } - let Ref::Existing(speak_id) = speak else { - panic!("speak is a standing affordance"); - }; - let error = submit_as( - &mut kernel, - play_caller(), - CommandBody::AdmitPatch { - patch: WorldPatch { - declarations: Vec::new(), - operations: vec![ComponentOp::RevokeAffordance { - subject: Ref::Existing(clockwork.reeve), - affordance: Ref::Existing(speak_id), - }], - evidence: Vec::new(), - }, - }, - ) - .unwrap_err(); - assert!( - matches!(&error, KernelError::PatchRejected(set) - if set.contains(&Mismatch::WouldLeaveSubjectMute { operation: 0 })), - "{error:?}" - ); - } - - /// PA.f30b: the last-verb refusal for `RevokeAffordance` (P5.2) holds for - /// a `Human`-controlled subject exactly as it does for any other - /// controller kind. Kills an exemption that only checks non-`Human` - /// subjects. - #[test] - fn a_revoke_cannot_leave_a_human_subject_mute() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, _, active) = clock_kernel(directory.path(), "RevokeHumanMute"); - let human = active - .subjects - .iter() - .find(|subject| subject.controller_mode == Some(ControllerMode::Human)) - .expect("the fixture world declares a human-controlled subject"); - let speak_affordance = *human - .affordances - .iter() - .next() - .expect("the human subject holds at least the kernel speak grant"); - let error = submit_as( - &mut kernel, - play_caller(), - CommandBody::AdmitPatch { - patch: WorldPatch { - declarations: Vec::new(), - operations: vec![ComponentOp::RevokeAffordance { - subject: Ref::Existing(human.id), - affordance: Ref::Existing(speak_affordance), - }], - evidence: Vec::new(), - }, - }, - ) - .unwrap_err(); - assert!( - matches!(&error, KernelError::PatchRejected(set) - if set.contains(&Mismatch::WouldLeaveSubjectMute { operation: 0 })), - "{error:?}" - ); - } - - /// PA.f30c: `ControllerAssignment::Retired.expected_caller()` is `None` - /// — a direct unit pin so an accidental `Some` for `Retired` is caught - /// here rather than only transitively through a submission test. - #[test] - fn retired_expects_no_caller() { - assert_eq!(ControllerAssignment::Retired.expected_caller(), None); - } - // ---- Retirement fix batch (PA.f31-PA.f35) ------------------------------ fn human_subject(snapshot: &WorldSnapshot) -> SubjectId { @@ -13541,7 +11754,7 @@ mod clock_tests { vec![binding("target", Target::Subject(clockwork.farmer))], ) .expect("the threat commits"); - owner_retires(&mut kernel, clockwork.reeve) + play_retires(&mut kernel, clockwork.reeve) .expect("a subject with history can be retired"); kernel.state.world_id }; @@ -13575,7 +11788,7 @@ mod clock_tests { ) .expect("the threat commits"); let before = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &before, operations(vec![ComponentOp::RevokeAffordance { @@ -13589,28 +11802,6 @@ mod clock_tests { assert_eq!(reopened.state.events.len(), 1); } - /// PA.f32(a): the resolver refuses `Retire` for a `Human`-controlled - /// subject while the world is Draft, before the owner can retire the - /// human, approve alone, and activate without the human's approval. - #[test] - fn retiring_the_human_in_draft_is_refused() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = WorldKernel::create( - directory.path().join("world.cc"), - creation(CommandId::new(), "PAf32DraftRefusal"), - &auth_principal(owner()), - ) - .expect("a created world") - .0; - let human = human_subject(&kernel.snapshot().unwrap()); - let error = owner_retires(&mut kernel, human).unwrap_err(); - assert!( - matches!(&error, KernelError::PatchRejected(set) - if set.contains(&Mismatch::RetiresAnApprover { operation: 0 })), - "{error:?}" - ); - } - /// PA.f32(b, c): once the world is Active, the human's Draft approval is /// frozen history, so the owner may retire the human — the player's /// subject may die — and the retire survives reopen-and-replay because @@ -13624,7 +11815,7 @@ mod clock_tests { let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "PAf32ActiveRetire"); let _ = &clockwork; let human = human_subject(&active); - owner_retires(&mut kernel, human).expect("the owner retires the human subject"); + play_retires(&mut kernel, human).expect("play retires the human subject"); (kernel.state.world_id, human) }; let reopened = WorldKernel::open(&path, world_id).expect("the store replays"); @@ -13647,7 +11838,7 @@ mod clock_tests { fn channel_audience_excludes_a_retired_member() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf33Audience"); - owner_retires(&mut kernel, clockwork.reeve).expect("retire"); + play_retires(&mut kernel, clockwork.reeve).expect("retire"); let mut patch = ruled_fact_patch("news"); patch.declarations.push(Declaration::Channel(ChannelDeclaration { handle: DraftHandle::new("wire"), @@ -13693,7 +11884,7 @@ mod clock_tests { })); submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { patch: declare }) .expect("declare"); - owner_retires(&mut kernel, clockwork.reeve).expect("retire"); + play_retires(&mut kernel, clockwork.reeve).expect("retire"); let wire = *kernel.state.channels.keys().next().unwrap(); let mut patch = ruled_fact_patch("news"); patch.operations.push(ComponentOp::Communicate { @@ -13724,7 +11915,7 @@ mod clock_tests { .expect("a created world") .0; let (speech, _) = speech_world(&mut kernel); - owner_retires(&mut kernel, speech.listener).expect("the owner retires the listener"); + play_retires(&mut kernel, speech.listener).expect("play retires the listener"); let invocation = DecisionInvocation { affordance: speech.whisper, bindings: vec![binding("target", Target::Subject(speech.listener))], @@ -13753,7 +11944,7 @@ mod clock_tests { fn a_retired_subject_cannot_acquire_knowledge() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf34Acquire"); - owner_retires(&mut kernel, clockwork.reeve).expect("retire"); + play_retires(&mut kernel, clockwork.reeve).expect("retire"); let mut patch = ruled_fact_patch("news"); patch.operations.push(ComponentOp::AcquireKnowledge { subject: Ref::Existing(clockwork.reeve), @@ -13785,9 +11976,9 @@ mod clock_tests { submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { patch: declare }) .expect("the reeve learns the fact"); let fact = *kernel.state.knowledge[&clockwork.reeve].keys().next().unwrap(); - owner_retires(&mut kernel, clockwork.reeve).expect("retire"); + play_retires(&mut kernel, clockwork.reeve).expect("retire"); let before = kernel.snapshot().unwrap(); - let error = reject_owner( + let error = reject_play( &mut kernel, &before, operations(vec![ComponentOp::Forget { @@ -13803,9 +11994,9 @@ mod clock_tests { fn a_retired_subject_cannot_take_office() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf34Office"); - owner_retires(&mut kernel, clockwork.farmer).expect("retire"); + play_retires(&mut kernel, clockwork.farmer).expect("retire"); let before = kernel.snapshot().unwrap(); - let error = reject_owner( + let error = reject_play( &mut kernel, &before, operations(vec![ @@ -13830,7 +12021,7 @@ mod clock_tests { fn holdings_are_still_transferable_from_a_retired_holder() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf34Loot"); - owner_retires(&mut kernel, clockwork.farmer).expect("retire"); + play_retires(&mut kernel, clockwork.farmer).expect("retire"); let before = kernel.snapshot().unwrap(); let grain = *kernel .state @@ -13840,7 +12031,7 @@ mod clock_tests { .keys() .next() .expect("at least one resource"); - submit_owner( + submit_play( &mut kernel, &before, operations(vec![ComponentOp::Transfer { @@ -13873,7 +12064,7 @@ mod clock_tests { .unwrap() .0; let before = kernel.snapshot().unwrap(); - let error = reject_owner( + let error = reject_play( &mut kernel, &before, operations(vec![ @@ -13887,51 +12078,6 @@ mod clock_tests { assert_eq!(error, vec![Mismatch::UnplacedSubject { operation: 1 }]); } - /// PA.f35, MuC: `retired` on a subject snapshot row is read from - /// `ControllerAssignment::Retired` specifically, not from - /// `mode().is_none()` — a mirror's mode is also `None`, and a mirror must - /// never be reported retired. - #[test] - fn a_mirror_is_not_reported_retired() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf35MirrorFlag"); - let mirror = declare_mirror(&mut kernel, &clockwork, "pa-f35-mirror"); - let snapshot = kernel.snapshot().unwrap(); - let row = snapshot.subjects.iter().find(|s| s.id == mirror).unwrap(); - assert!(!row.retired); - } - - /// PA.f35, MuD: the affordance-holdings candidate set is updated after - /// every grant and revoke in a patch, not only the first, so three - /// revokes in one patch still catch the one that would leave the subject - /// mute. - #[test] - fn three_revokes_in_one_patch_cannot_mute_the_subject() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf35ThreeRevokes"); - let speak = super::tests::speak_entry(&kernel); - let before = kernel.snapshot().unwrap(); - let error = reject_owner( - &mut kernel, - &before, - operations(vec![ - ComponentOp::RevokeAffordance { - subject: Ref::Existing(clockwork.reeve), - affordance: Ref::Existing(clockwork.threaten), - }, - ComponentOp::RevokeAffordance { - subject: Ref::Existing(clockwork.reeve), - affordance: Ref::Existing(clockwork.deliver), - }, - ComponentOp::RevokeAffordance { - subject: Ref::Existing(clockwork.reeve), - affordance: speak, - }, - ]), - ); - assert_eq!(error, vec![Mismatch::WouldLeaveSubjectMute { operation: 2 }]); - } - /// PA.f35, MuE: the resolver's `Retire` arm inserts the subject into its /// own-patch `retired` candidate set, so a second `Retire` of the same /// subject in one patch is caught as a no-op rather than silently @@ -13941,7 +12087,7 @@ mod clock_tests { let directory = tempfile::tempdir().unwrap(); let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf35DoubleRetire"); let before = kernel.snapshot().unwrap(); - let error = reject_owner( + let error = reject_play( &mut kernel, &before, operations(vec![ @@ -13954,67 +12100,6 @@ mod clock_tests { // ---- Retirement fix batch (PA.f36-PA.f38) ------------------------------ - /// PA.f36: the resolver refuses a genesis patch that declares a - /// Human-controlled subject and retires it in the same patch. The - /// resolver's `humans` candidate set tracks a freshly declared human the - /// same way `mirrors` tracks a freshly declared mirror, so this is caught - /// before `open_owner` ever commits an empty `world.cc` for a human who - /// never approved anything. - #[test] - fn genesis_cannot_declare_and_retire_the_human_in_one_patch() { - let directory = tempfile::tempdir().unwrap(); - let mut genesis = creation(CommandId::new(), "PAf36GenesisRetire"); - genesis.patch.operations.push(ComponentOp::Retire { - subject: Ref::Draft(DraftHandle::new("human")), - }); - let Err(error) = WorldKernel::create( - directory.path().join("world.cc"), - genesis, - &auth_principal(owner()), - ) else { - panic!("genesis admitted a patch that declares and retires the human"); - }; - assert!( - matches!(&error, KernelError::PatchRejected(set) - if set.contains(&Mismatch::RetiresAnApprover { operation: 0 })), - "{error:?}" - ); - } - - /// PA.f36: pins the apply-time re-check directly, beside the resolver's - /// refusal above, since resolution is speculative and this arm is the - /// actual commit. If the resolver's `humans` tracking were ever disabled - /// or bypassed, this is the arm that must still refuse removing a Draft - /// approver. - #[test] - fn apply_refuses_removing_a_draft_approver_directly() { - let directory = tempfile::tempdir().unwrap(); - let kernel = WorldKernel::create( - directory.path().join("world.cc"), - creation(CommandId::new(), "PAf36ApplyArm"), - &auth_principal(owner()), - ) - .expect("a created world") - .0; - let human = human_subject(&kernel.snapshot().unwrap()); - let mut state = kernel.state.clone(); - let resolves_to = state.revision + 1; - assert!( - matches!( - apply_operation( - &mut state, - &ResolvedOp::Retire { subject: human }, - &[], - resolves_to - ) - .unwrap_err(), - KernelError::Invariant(message) - if message == "retire operation would remove a Draft approver" - ), - "the apply-time arm no longer refuses removing the Draft human" - ); - } - /// PA.f37: a retired subject cannot become a promisor. `CreateCommitment` /// refuses it with `RetiredSubjectActed`, the same mismatch a retired /// office incumbent draws. @@ -14022,9 +12107,9 @@ mod clock_tests { fn a_retired_subject_cannot_be_a_promisor() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf37Promisor"); - owner_retires(&mut kernel, clockwork.farmer).expect("retire"); + play_retires(&mut kernel, clockwork.farmer).expect("retire"); let before = kernel.snapshot().unwrap(); - let error = reject_owner( + let error = reject_play( &mut kernel, &before, operations(vec![ComponentOp::CreateCommitment { @@ -14052,14 +12137,14 @@ mod clock_tests { let directory = tempfile::tempdir().unwrap(); let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf37Frozen"); let snapshot = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &snapshot, operations(vec![ComponentOp::CloseRoute { route: Ref::Existing(clockwork.gate), }]), ); - owner_retires(&mut kernel, clockwork.farmer).expect("retire the farmer"); + play_retires(&mut kernel, clockwork.farmer).expect("retire the farmer"); let routine_before = due(&kernel, clockwork.farmer, clockwork.routine); let dependency_source = PressureSource::Dependency(DependencyTarget::Route(clockwork.gate)); @@ -14121,14 +12206,14 @@ mod clock_tests { let directory = tempfile::tempdir().unwrap(); let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf37FrozenDep"); let snapshot = kernel.snapshot().unwrap(); - submit_owner( + submit_play( &mut kernel, &snapshot, operations(vec![ComponentOp::CloseRoute { route: Ref::Existing(clockwork.gate), }]), ); - owner_retires(&mut kernel, clockwork.reeve).expect("retire the reeve"); + play_retires(&mut kernel, clockwork.reeve).expect("retire the reeve"); let routine_before = due(&kernel, clockwork.farmer, clockwork.routine); let dependency_source = PressureSource::Dependency(DependencyTarget::Route(clockwork.gate)); @@ -14178,7 +12263,7 @@ mod clock_tests { let path = directory.path().join("world.cc"); let (world_id, farmer, routine, obligation) = { let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf37Replay"); - owner_retires(&mut kernel, clockwork.farmer).expect("retire the farmer"); + play_retires(&mut kernel, clockwork.farmer).expect("retire the farmer"); tick(&mut kernel, ROUTINE_DUE as u32 + LATE_DUE as u32).expect("the tick commits"); ( kernel.state.world_id, @@ -14219,7 +12304,7 @@ mod clock_tests { fn a_retired_subject_cannot_acquire_evidenced_knowledge() { let directory = tempfile::tempdir().unwrap(); let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf39Evidenced"); - owner_retires(&mut kernel, clockwork.farmer).expect("retire"); + play_retires(&mut kernel, clockwork.farmer).expect("retire"); let patch = WorldPatch { declarations: vec![Declaration::Fact(FactDeclaration { handle: DraftHandle::new("news"), @@ -14250,49 +12335,6 @@ mod clock_tests { ); } - /// PA.f39, M6: `is_retired` reads `ControllerAssignment::Retired` - /// specifically. If it also matched `ExternallyControlled`, a mirror - /// would be silently dropped from `Reach::Subjects` audience derivation — - /// the same site PA.f33 fixed for an actually retired member. A mirror is - /// not retired, and stays in the audience. - #[test] - fn a_mirror_in_a_subjects_channel_stays_in_the_audience() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf39MirrorAudience"); - let mirror = declare_mirror(&mut kernel, &clockwork, "pa-f39-mirror"); - let mut patch = ruled_fact_patch("news"); - patch.declarations.push(Declaration::Channel(ChannelDeclaration { - handle: DraftHandle::new("wire"), - label: "The Wire".into(), - reach: ReachRef::Subjects(BTreeSet::from([ - Ref::Existing(mirror), - Ref::Existing(clockwork.farmer), - ])), - controller: None, - })); - patch.operations.push(ComponentOp::Communicate { - speaker: Ref::Existing(clockwork.farmer), - fact: Ref::Draft(DraftHandle::new("news")), - to: AudienceRef::Channel(Ref::Draft(DraftHandle::new("wire"))), - }); - submit_as( - &mut kernel, - play_caller(), - CommandBody::AdmitPatch { patch }, - ) - .expect("admitted"); - let mirror_knows = kernel - .state - .knowledge - .get(&mirror) - .map(BTreeMap::len) - .unwrap_or(0); - assert_eq!( - mirror_knows, 1, - "a mirror was excluded from a Subjects-reach audience" - ); - } - /// PA.f39, Soul's probe S2: `CanReach` to a placeless target reachable /// only through a `Reach::Subjects` channel — no co-location is possible /// — is refused once the target retires. This exercises `audience()`'s @@ -14393,7 +12435,7 @@ mod clock_tests { ) .expect("the live outcast is reachable through the channel"); - owner_retires(&mut kernel, outcast).expect("retire the outcast"); + play_retires(&mut kernel, outcast).expect("retire the outcast"); let error = submit_as( &mut kernel, play_caller(), diff --git a/native/aetherlight/src/patch.rs b/native/aetherlight/src/patch.rs index e84d5d334..84435749d 100644 --- a/native/aetherlight/src/patch.rs +++ b/native/aetherlight/src/patch.rs @@ -257,7 +257,7 @@ pub struct AffordanceKindName(pub String); #[serde(transparent)] pub struct Role(pub(crate) String); -/// What a role must be bound to. `RefKind` is reused rather than mirrored: it +/// What a role must be bound to. `RefKind` is reused rather than restated: it /// already spells subject, entity kind, and edge kind, so the binding kind-check /// and the declaration kind-check are one predicate. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] @@ -1241,20 +1241,18 @@ pub(crate) enum ComponentOp { target: Ref<SubjectId>, }, /// Ends a subject for good: no grants, no position, no audience, its - /// history kept. Only the owner and `Play` may write it. + /// history kept. Play's alone, like every post-genesis patch. Retire { subject: Ref<SubjectId>, }, - /// Grants one more standing catalog entry to an existing subject. Only the - /// owner (including the seed lane, the owner in Draft) and `Play` may - /// write it: a grant is authority, not structure, so a confined author is - /// refused whatever ground the subject stands on. + /// Grants one more standing catalog entry to an existing subject. Play's + /// alone. GrantAffordance { subject: Ref<SubjectId>, affordance: Ref<AffordanceId>, }, - /// Revokes a grant. Refused if it would leave a controlled subject with - /// none: a controlled subject is never left mute. + /// Revokes a grant. A subject left with no verb holds no grant row and + /// simply cannot act. RevokeAffordance { subject: Ref<SubjectId>, affordance: Ref<AffordanceId>, @@ -1394,12 +1392,6 @@ pub enum Mismatch { UnadmittedController { handle: DraftHandle, }, - /// A declared subject's controller and affordance grant do not pair: a - /// mirror was granted an affordance, or an ordinary controller was granted - /// none. `admit_resolved` re-decides the same rule. - ControllerGrantMismatch { - site: Site, - }, EmptyEvidence { position: usize, }, @@ -1628,27 +1620,11 @@ pub enum Mismatch { UnknownCommitment { operation: usize, }, - /// A jurisdictional author wrote outside its jurisdiction. The owner is - /// unconfined and never sees this. - OutsideJurisdiction { - site: Site, - }, /// A `Ruled` fact or a `Mint` was written by a caller other than the play /// authority. RuledWithoutAuthority { site: Site, }, - /// `Retire` named an `ExternallyControlled` subject: a mirror is owned by - /// another world, so this one cannot retire it. - RetiresAMirror { - operation: usize, - }, - /// `Retire` named a `Human`-controlled subject while the world is still in - /// `Draft`. A human's Draft approval cannot be removed by removing the - /// human; the same retire is admitted once the world is `Active`. - RetiresAnApprover { - operation: usize, - }, /// `Communicate`, `AcquireKnowledge`, `Forget`, or `InstallIncumbent` /// named a retired subject as the one acting, learning, forgetting, or /// taking office. A retired subject is a body, not an actor: it may still @@ -1657,15 +1633,9 @@ pub enum Mismatch { RetiredSubjectActed { operation: usize, }, - /// `GrantAffordance` or `RevokeAffordance` named a retired or an - /// `ExternallyControlled` subject: neither holds a grant this patch may - /// touch. - GrantsOutsideControl { - operation: usize, - }, - /// A `RevokeAffordance` that would leave a controlled subject with no - /// affordance at all: a subject is never left mute. - WouldLeaveSubjectMute { + /// `GrantAffordance` or `RevokeAffordance` named a retired subject: it + /// holds no grant this patch may touch. + GrantsToRetired { operation: usize, }, } @@ -3225,15 +3195,6 @@ pub(super) fn resolve_patch( } } if let Declaration::Subject(subject) = declaration { - // Both ways. A mirror receives no controller, so it may hold no - // affordance; every other controller must hold one. - if matches!(subject.controller, NewController::External { .. }) - != subject.affordances.is_empty() - { - mismatches.push(Mismatch::ControllerGrantMismatch { - site: Site::Declaration(handle.clone()), - }); - } if let NewController::Human { principal } = &subject.controller && (!admits_human || super::validate_principal(principal).is_err()) { @@ -3361,39 +3322,18 @@ pub(super) fn resolve_patch( ) }) .collect(); - // `Retire` and the affordance grant operations read and write these three - // candidates. `retired` and `mirrors` seed from the committed - // `ControllerAssignment`, which the resolver otherwise never reads: a - // declared subject can only ever be a fresh, unretired controller (or a - // freshly declared mirror, added below), so drafts start out of both sets. - // `affordance_holdings` seeds from committed `affordance_grants` and is - // extended below for a subject this same patch declares. + // `Retire` and the affordance grant operations read and write these + // candidates. `retired` seeds from the committed `ControllerAssignment`, + // which the resolver otherwise never reads: a declared subject is always + // fresh and unretired, so drafts start out of the set. `affordance_holdings` + // seeds from committed `affordance_grants` and is extended below for a + // subject this same patch declares. let mut retired: BTreeSet<Key<SubjectId>> = state .controller_assignments .keys() .filter(|scope| super::is_retired(state, scope.subject_id)) .map(|scope| Key::Existing(scope.subject_id)) .collect(); - let mut mirrors: BTreeSet<Key<SubjectId>> = state - .controller_assignments - .iter() - .filter(|(_, assignment)| { - matches!(assignment, ControllerAssignment::ExternallyControlled { .. }) - }) - .map(|(scope, _)| Key::Existing(scope.subject_id)) - .collect(); - // Tracked the same way as `mirrors`: seeded from the committed human - // controller, extended below for a subject this same patch declares as - // `NewController::Human`. `Retire` refuses a Draft-phase approver out of - // this set instead of relying solely on the apply-time re-check, which - // otherwise only catches a genesis patch that declares and retires the - // human in the same breath after `open_owner` has already committed. - let mut humans: BTreeSet<Key<SubjectId>> = state - .controller_assignments - .iter() - .filter(|(_, assignment)| assignment.human_principal().is_some()) - .map(|(scope, _)| Key::Existing(scope.subject_id)) - .collect(); let mut affordance_holdings: BTreeMap<Key<SubjectId>, BTreeSet<Key<AffordanceId>>> = state .affordance_grants .iter() @@ -3607,12 +3547,6 @@ pub(super) fn resolve_patch( if !granted.is_empty() { affordance_holdings.insert(Key::Draft(subject.handle.clone()), granted); } - if matches!(subject.controller, NewController::External { .. }) { - mirrors.insert(Key::Draft(subject.handle.clone())); - } - if matches!(subject.controller, NewController::Human { .. }) { - humans.insert(Key::Draft(subject.handle.clone())); - } if let Some(reference) = &subject.position && let Some(place) = resolve_entity( Site::Declaration(subject.handle.clone()), @@ -3932,35 +3866,12 @@ pub(super) fn resolve_patch( ) else { continue; }; - if mirrors.contains(&subject_key) { - mismatches.push(Mismatch::RetiresAMirror { - operation: position, - }); - continue; - } if retired.contains(&subject_key) { mismatches.push(Mismatch::NoOperationEffect { operation: position, }); continue; } - // A human's Draft approval cannot be removed by removing the - // human: `required_approvers` reads the live controller - // assignment and `Retired` carries no human principal, so an - // owner could otherwise retire the human, approve alone, and - // activate. Once the world is Active, approvals are frozen - // history judged by replay, and the human's subject may die. - // `humans` tracks a subject declared as `NewController::Human` - // in this same patch exactly as `mirrors` tracks a freshly - // declared mirror, so a genesis patch that declares and - // retires the human in one breath is refused here rather than - // only by the apply-time re-check after admission. - if state.phase == super::WorldPhase::Draft && humans.contains(&subject_key) { - mismatches.push(Mismatch::RetiresAnApprover { - operation: position, - }); - continue; - } retired.insert(subject_key.clone()); positions.remove(&subject_key); affordance_holdings.remove(&subject_key); @@ -4410,11 +4321,9 @@ pub(super) fn resolve_patch( else { continue; }; - // A grant is authority over the catalog, not structure over - // ground: retirement and a mirror both hold no grant a patch - // may touch, whatever confinement later decides. - if retired.contains(&subject_key) || mirrors.contains(&subject_key) { - mismatches.push(Mismatch::GrantsOutsideControl { + // A retired subject holds no grant a patch may touch. + if retired.contains(&subject_key) { + mismatches.push(Mismatch::GrantsToRetired { operation: position, }); continue; @@ -4434,14 +4343,11 @@ pub(super) fn resolve_patch( .or_default() .insert(affordance_key); } else { - let granted = affordance_holdings.entry(subject_key).or_default(); - if granted.len() == 1 { - mismatches.push(Mismatch::WouldLeaveSubjectMute { - operation: position, - }); - continue; - } + let granted = affordance_holdings.entry(subject_key.clone()).or_default(); granted.remove(&affordance_key); + if granted.is_empty() { + affordance_holdings.remove(&subject_key); + } } } ComponentOp::OpenOffice { @@ -5178,10 +5084,6 @@ pub(super) fn resolve_patch( NewController::OperationalAgent => ControllerAssignment::OperationalAgent { controller_id: controller_id(), }, - // No controller id is derived, because there is no controller. - NewController::External { consumer } => { - ControllerAssignment::ExternallyControlled { consumer } - } }; let granted = input .affordances @@ -5811,12 +5713,12 @@ pub(super) fn containment_terminates( mod tests { use super::*; use crate::tests::{ - ADMIT_KIND, FIXTURE_ENTITIES, LEVY_KIND, activate, admit_topology, authority_kind, + ADMIT_KIND, FIXTURE_ENTITIES, LEVY_KIND, admit_topology, authority_kind, auth_principal, civic_world, command, creation, grant_to, human_principal, office, - over_place, owner, reject_owner, speak_entry, submit_owner, + over_place, owner, reject_play, speak_entry, submit_play, }; use crate::{ - CallerId, CommandBody, CommandId, KernelError, SubmitReceipt, WorldKernel, WorldPhase, + AuthenticatedCaller, CallerId, CommandBody, CommandId, KernelError, SubmitReceipt, WorldKernel, }; fn entity(handle: &str, label: &str, kind: EntityKind) -> Declaration { @@ -5989,7 +5891,7 @@ mod tests { }, ), ] { - let rejected = reject_owner( + let rejected = reject_play( &mut kernel, &before, admit(patch_of(vec![catalog_entry( @@ -6005,7 +5907,7 @@ mod tests { } // No effect slots and no speech: the entry could never change anything. - let rejected = reject_owner( + let rejected = reject_play( &mut kernel, &before, admit(patch_of(vec![catalog_entry( @@ -6028,7 +5930,7 @@ mod tests { // A `Transfer` takes three referents, not two. assert_eq!( - reject_owner( + reject_play( &mut kernel, &before, admit(patch_of(vec![catalog_entry( @@ -6050,7 +5952,7 @@ mod tests { // Its third referent is a resource, not a place. assert_eq!( - reject_owner( + reject_play( &mut kernel, &before, admit(patch_of(vec![catalog_entry( @@ -6076,7 +5978,7 @@ mod tests { // A `Transfer` carries a quantity, so an unbounded slot has no ceiling. assert_eq!( - reject_owner( + reject_play( &mut kernel, &before, admit(patch_of(vec![catalog_entry( @@ -6095,7 +5997,7 @@ mod tests { // A slot naming a role the entry does not declare. assert_eq!( - reject_owner( + reject_play( &mut kernel, &before, admit(patch_of(vec![catalog_entry( @@ -6137,7 +6039,7 @@ mod tests { }; assert_eq!( - reject_owner( + reject_play( &mut kernel, &before, admit(patch_of(vec![granting("verb")])) @@ -6152,7 +6054,7 @@ mod tests { assert_eq!(kernel.state.subjects.len(), subjects_before); // Declaring the entry in the same patch commits both atomically. - let receipt = submit_owner( + let receipt = submit_play( &mut kernel, &before, admit(patch_of(vec![ @@ -6191,7 +6093,7 @@ mod tests { let mut kernel = draft_world(directory.path()); let before = kernel.snapshot().unwrap(); let slot = transfer_slot(vec!["from", "to", "goods"], Bounds::Quantity(Quantity(2))); - let rejected = reject_owner( + let rejected = reject_play( &mut kernel, &before, admit(patch_of(vec![ @@ -6220,7 +6122,7 @@ mod tests { // A kind name outside the tool-name alphabet is refused for the same // reason: it becomes a generated tool name. - let rejected = reject_owner( + let rejected = reject_play( &mut kernel, &before, admit(patch_of(vec![catalog_entry( @@ -6266,7 +6168,7 @@ mod tests { command( &before, CommandId::new(), - CallerId::Principal(owner()), + CallerId::Play, admit(patch_of(vec![institution( &kernel, "rhythm-authority", @@ -6274,7 +6176,7 @@ mod tests { Some(Ref::Draft(DraftHandle::new("kharad-rhythm-road"))), )])), ), - &auth_principal(owner()), + &AuthenticatedCaller::verified_play(), ) .unwrap_err(); @@ -6321,7 +6223,7 @@ mod tests { Some(Ref::Draft(draft("kharad-rhythm-road"))), ), ]); - let receipt = submit_owner(&mut kernel, &before, admit(patch)); + let receipt = submit_play(&mut kernel, &before, admit(patch)); assert!(matches!(receipt, SubmitReceipt::Applied(_))); let after = kernel.snapshot().unwrap(); @@ -6376,7 +6278,7 @@ mod tests { command( &before, CommandId::new(), - CallerId::Principal(owner()), + CallerId::Play, admit(patch_of(vec![ entity("rhythm-tithe", "The Rhythm Tithe", EntityKind::Resource), institution( @@ -6387,7 +6289,7 @@ mod tests { ), ])), ), - &auth_principal(owner()), + &AuthenticatedCaller::verified_play(), ) .unwrap_err(); @@ -6441,10 +6343,10 @@ mod tests { command( &before, CommandId::new(), - CallerId::Principal(owner()), + CallerId::Play, admit(broken), ), - &auth_principal(owner()), + &AuthenticatedCaller::verified_play(), ) .unwrap_err(); let KernelError::PatchRejected(mismatches) = error else { @@ -6489,7 +6391,7 @@ mod tests { import_key: None, }), ]); - let receipt = submit_owner(&mut kernel, &before, admit(repaired)); + let receipt = submit_play(&mut kernel, &before, admit(repaired)); assert!(matches!(receipt, SubmitReceipt::Applied(_))); assert_eq!(kernel.state.entities.len(), 3); } @@ -6505,10 +6407,10 @@ mod tests { command( &before, CommandId::new(), - CallerId::Principal(owner()), + CallerId::Play, admit(patch_of(Vec::new())), ), - &auth_principal(owner()), + &AuthenticatedCaller::verified_play(), ) .unwrap_err(); let KernelError::PatchRejected(mismatches) = error else { @@ -6532,7 +6434,7 @@ mod tests { command( &before, CommandId::new(), - CallerId::Principal(owner()), + CallerId::Play, admit(patch_of(vec![ contained("yard", "The Cavity Yard", "road"), contained("road", "The Rhythm Road", "gate"), @@ -6540,7 +6442,7 @@ mod tests { entity("orphan", " ", EntityKind::Place), ])), ), - &auth_principal(owner()), + &AuthenticatedCaller::verified_play(), ) .unwrap_err(); let KernelError::PatchRejected(mismatches) = error else { @@ -6577,14 +6479,14 @@ mod tests { command( &before, CommandId::new(), - CallerId::Principal(owner()), + CallerId::Play, admit(patch_of(vec![ entity("yard", "The Cavity Yard", EntityKind::Place), entity("tithe", "The Rhythm Tithe", EntityKind::Resource), route("ramp", "The Yard Ramp", "yard", "tithe", 12), ])), ), - &auth_principal(owner()), + &AuthenticatedCaller::verified_play(), ) .unwrap_err(); let KernelError::PatchRejected(mismatches) = error else { @@ -6617,7 +6519,7 @@ mod tests { command( &before, CommandId::new(), - CallerId::Principal(owner()), + CallerId::Play, admit(WorldPatch { declarations: vec![Declaration::Route(RouteDeclaration { handle: draft("free-ride"), @@ -6634,7 +6536,7 @@ mod tests { evidence: Vec::new(), }), ), - &auth_principal(owner()), + &AuthenticatedCaller::verified_play(), ) .unwrap_err(); let KernelError::PatchRejected(mismatches) = error else { @@ -6660,7 +6562,7 @@ mod tests { let directory = tempfile::tempdir().unwrap(); let mut kernel = draft_world(directory.path()); let topology = admit_topology(&mut kernel); - let active = activate(&mut kernel); + let active = kernel.snapshot().unwrap(); let commits_before = kernel.journal.commit_count(); for (edge_id, expected) in [ @@ -6676,13 +6578,13 @@ mod tests { command( &active, CommandId::new(), - CallerId::Principal(owner()), + CallerId::Play, admit(operations_of(vec![ComponentOp::Relocate { subject: Ref::Existing(topology.walker), via: Ref::Existing(edge_id), }])), ), - &auth_principal(owner()), + &AuthenticatedCaller::verified_play(), ) .unwrap_err(); let KernelError::PatchRejected(mismatches) = error else { @@ -6715,7 +6617,7 @@ mod tests { // directly over the chamber the hall contains, so a resolver that // still counted the dead lend would see two distinct, overlapping // `GrantKey`s (not one collapsed duplicate) and refuse. - let receipt = submit_owner( + let receipt = submit_play( &mut kernel, &before, admit(operations_of(vec![ @@ -6745,7 +6647,7 @@ mod tests { // `topology.walker` already exists and already stands at `yard`, so // this delegation patch is operations-only: no declaration. - let delegated = submit_owner( + let delegated = submit_play( &mut kernel, &before, admit(operations_of(vec![ @@ -6769,7 +6671,7 @@ mod tests { let after_delegation = kernel.snapshot().unwrap(); let commits_before = kernel.journal.commit_count(); - let mismatches = reject_owner( + let mismatches = reject_play( &mut kernel, &after_delegation, admit(operations_of(vec![ @@ -6796,11 +6698,11 @@ mod tests { let directory = tempfile::tempdir().unwrap(); let mut kernel = draft_world(directory.path()); let topology = admit_topology(&mut kernel); - let active = activate(&mut kernel); + let active = kernel.snapshot().unwrap(); let entities_before = kernel.state.entities.clone(); let edges_before = kernel.state.edges.clone(); - let receipt = submit_owner( + let receipt = submit_play( &mut kernel, &active, admit(operations_of(vec![ComponentOp::Relocate { @@ -6840,18 +6742,18 @@ mod tests { ) .unwrap(); let topology = admit_topology(&mut kernel); - let active = activate(&mut kernel); + let active = kernel.snapshot().unwrap(); let envelope = command( &active, CommandId::new(), - CallerId::Principal(owner()), + CallerId::Play, admit(operations_of(vec![ComponentOp::Relocate { subject: Ref::Existing(topology.walker), via: Ref::Existing(topology.ramp), }])), ); kernel - .submit(envelope.clone(), &auth_principal(owner())) + .submit(envelope.clone(), &AuthenticatedCaller::verified_play()) .unwrap(); let committed = kernel.snapshot().unwrap(); let world_id = committed.world_id; @@ -6866,7 +6768,7 @@ mod tests { }) ); assert!(matches!( - reopened.submit(envelope, &auth_principal(owner())).unwrap(), + reopened.submit(envelope, &AuthenticatedCaller::verified_play()).unwrap(), SubmitReceipt::AlreadyApplied(_) )); } @@ -6953,7 +6855,7 @@ mod tests { let envelope = command( &before, CommandId::new(), - CallerId::Principal(owner()), + CallerId::Play, admit(patch_of(vec![ entity("rhythm-road", "The Rhythm Road", EntityKind::Place), institution( @@ -6965,7 +6867,7 @@ mod tests { ])), ); kernel - .submit(envelope.clone(), &auth_principal(owner())) + .submit(envelope.clone(), &AuthenticatedCaller::verified_play()) .unwrap(); let committed = kernel.snapshot().unwrap(); let world_id = committed.world_id; @@ -6974,7 +6876,7 @@ mod tests { let mut reopened = WorldKernel::open(&path, world_id).unwrap(); assert_eq!(reopened.snapshot().unwrap(), committed); assert!(matches!( - reopened.submit(envelope, &auth_principal(owner())).unwrap(), + reopened.submit(envelope, &AuthenticatedCaller::verified_play()).unwrap(), SubmitReceipt::AlreadyApplied(_) )); } @@ -7003,7 +6905,7 @@ mod tests { position: None, import_key: None, })]); - submit_owner(&mut kernel, &before, admit(patch.clone())); + submit_play(&mut kernel, &before, admit(patch.clone())); let admitted = *kernel .state .subjects @@ -7041,7 +6943,7 @@ mod tests { command( &before, command_id, - CallerId::Principal(owner()), + CallerId::Play, admit(patch_of(vec![institution( &kernel, "rhythm-authority", @@ -7049,7 +6951,7 @@ mod tests { Some(Ref::Draft(DraftHandle::new("kharad-rhythm-road"))), )])), ), - &auth_principal(owner()), + &AuthenticatedCaller::verified_play(), ) .unwrap_err(); assert!(matches!(error, KernelError::PatchRejected(_))); @@ -7173,7 +7075,7 @@ mod tests { let forged_error = super::super::apply_effect( &mut candidate, CommandId::issue(), - &CallerId::Principal(owner()), + &CallerId::Play, &super::super::WorldEffect::PatchAdmitted { resolved: forged, }, @@ -7186,20 +7088,20 @@ mod tests { super::super::apply_effect( &mut candidate, CommandId::issue(), - &CallerId::Principal(owner()), + &CallerId::Play, &honest, ) .unwrap(); let stale_error = super::super::apply_effect( &mut candidate, CommandId::issue(), - &CallerId::Principal(owner()), + &CallerId::Play, &honest, ) .unwrap_err(); assert!(matches!(stale_error, KernelError::Invariant(_))); - // A non-owner caller never reaches admission. + // A non-Play caller never reaches admission. let mut candidate = kernel.state.clone(); let unauthorized = super::super::apply_effect( &mut candidate, @@ -7208,7 +7110,7 @@ mod tests { &honest, ) .unwrap_err(); - assert!(matches!(unauthorized, KernelError::Invariant(_))); + assert!(matches!(unauthorized, KernelError::Unauthorized)); assert_eq!(candidate, kernel.state); } @@ -7226,13 +7128,13 @@ mod tests { command( &before, CommandId::new(), - CallerId::Principal(owner()), + CallerId::Play, admit(patch_of(vec![ entity("hollow", "The Hollow", EntityKind::Place), route("noose", "The Noose", "hollow", "hollow", 4), ])), ), - &auth_principal(owner()), + &AuthenticatedCaller::verified_play(), ) .unwrap_err(); let KernelError::PatchRejected(mismatches) = error else { @@ -7250,7 +7152,7 @@ mod tests { // declared here rather than borrowed from a genesis accident. let before = kernel.snapshot().unwrap(); let speak = speak_entry(&kernel); - submit_owner( + submit_play( &mut kernel, &before, admit(patch_of(vec![Declaration::Subject(SubjectDeclaration { @@ -7263,7 +7165,7 @@ mod tests { import_key: None, })])), ); - let active = activate(&mut kernel); + let active = kernel.snapshot().unwrap(); let commits_before = kernel.journal.commit_count(); let unplaced = *kernel .state @@ -7279,13 +7181,13 @@ mod tests { command( &active, CommandId::new(), - CallerId::Principal(owner()), + CallerId::Play, admit(operations_of(vec![ComponentOp::Relocate { subject: Ref::Existing(unplaced), via: Ref::Existing(topology.ramp), }])), ), - &auth_principal(owner()), + &AuthenticatedCaller::verified_play(), ) .unwrap_err(); let KernelError::PatchRejected(mismatches) = error else { @@ -7300,7 +7202,7 @@ mod tests { command( &active, CommandId::new(), - CallerId::Principal(owner()), + CallerId::Play, admit(operations_of(vec![ ComponentOp::OpenRoute { route: Ref::Existing(topology.ramp), @@ -7314,7 +7216,7 @@ mod tests { }, ])), ), - &auth_principal(owner()), + &AuthenticatedCaller::verified_play(), ) .unwrap_err(); let KernelError::PatchRejected(mismatches) = error else { @@ -7340,7 +7242,6 @@ mod tests { let directory = tempfile::tempdir().unwrap(); let mut kernel = draft_world(directory.path()); let topology = admit_topology(&mut kernel); - activate(&mut kernel); for edge_id in [topology.span, topology.shutter, topology.toll] { let forged = super::super::WorldEffect::PatchAdmitted { resolved: ResolvedPatch { @@ -7361,7 +7262,7 @@ mod tests { let error = super::super::apply_effect( &mut candidate, CommandId::issue(), - &CallerId::Principal(owner()), + &CallerId::Play, &forged, ) .unwrap_err(); From 475428bbd21b8429635cfafcd880dac3b77ee572 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 00:37:21 +0100 Subject: [PATCH 134/190] Aetherlight AL2b-2a: tests pin the Play-only gate, the born-Active genesis and grant rows after_genesis_only_play_writes, apply_effect_re_decides_play, a_world_is_born_active, retired_tags_do_not_decode, a_revoke_may_leave_a_subject_with_no_verbs, a_subject_may_be_declared_with_no_verbs, a_retired_subject_takes_no_grant, apply_refuses_a_grant_to_a_retired_subject, retire_applies_to_every_subject. Deletes CommandId::derived (its only caller was ConsumerId::of_name) and restates comments that named deleted lanes. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/action.rs | 6 +- native/aetherlight/src/lib.rs | 444 +++++++++++++++++++++++++++++-- native/aetherlight/src/patch.rs | 34 +-- 3 files changed, 432 insertions(+), 52 deletions(-) diff --git a/native/aetherlight/src/action.rs b/native/aetherlight/src/action.rs index 885d65f42..55d361b93 100644 --- a/native/aetherlight/src/action.rs +++ b/native/aetherlight/src/action.rs @@ -578,7 +578,7 @@ fn bound_audience(via: &AudienceSpec, bindings: &BTreeMap<Role, Target>) -> Opti /// to a complete attempt and cannot see the band. /// /// The rule is action-lane only, and that is not two truths. The patch lane's -/// `GrantAuthority`/`RevokeAuthority` is admitted by the world owner; +/// `GrantAuthority`/`RevokeAuthority` is admitted for Play; /// monotonicity *is* the action lane's authority envelope, and both lanes /// reach one `apply_operation` with the identical mutation. fn check_delegation( @@ -1134,7 +1134,7 @@ mod tests { } /// The same Carry attempt against a sibling entry: one dial moved, one - /// name. The catalog is Draft-only, so a variant is declared rather + /// name. The catalog is declared structure, so a variant is declared rather /// than patched into committed state. fn variant(&self, invocation: &DecisionInvocation, kind: &str) -> DecisionInvocation { DecisionInvocation { @@ -2019,7 +2019,7 @@ mod tests { vec![ActionMismatch::ActorRoleBound] ); - // The declaration half is Draft-only, so it runs against a fresh world. + // The declaration half runs at genesis, so it runs against a fresh world. let draft_directory = tempfile::tempdir().unwrap(); let mut draft = custody_kernel(draft_directory.path(), "ReservedRole"); let before = draft.snapshot().unwrap(); diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index 53b265fb0..a8b2fc435 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -157,22 +157,6 @@ impl CommandId { .map_err(|_| KernelError::InvalidCommandId) } - /// sha256 over a namespace and its ordered, length-prefixed parts, first - /// sixteen bytes. A command key, not a referent id: `patch::derive_id` - /// still has exactly two call sites. No `uuid/v5`. - pub(crate) fn derived(namespace: &str, parts: &[&str]) -> Self { - let mut hasher = Sha256::new(); - hasher.update(namespace.as_bytes()); - for part in parts { - hasher.update((part.len() as u64).to_be_bytes()); - hasher.update(part.as_bytes()); - } - let bytes: [u8; 16] = hasher.finalize()[..16] - .try_into() - .expect("sha256 yields at least sixteen bytes"); - Self(Uuid::from_bytes(bytes)) - } - fn key(self) -> String { self.0.to_string() } @@ -587,7 +571,7 @@ enum WorldEffect { }, } -/// The exact raw command admitted by the world owner. This is the sole +/// The exact raw command admitted by the kernel. This is the sole /// persistent command authority: IDs, callers, retry identity, and effects are /// derived from this value rather than copied into independently forgeable /// commit fields. @@ -4790,7 +4774,7 @@ mod tests { } /// The first subject whose controller has this mode. - fn subject_by_mode(state: &WorldState, mode: ControllerMode) -> SubjectId { + pub(crate) fn subject_by_mode(state: &WorldState, mode: ControllerMode) -> SubjectId { state .controller_assignments .iter() @@ -12452,3 +12436,427 @@ mod clock_tests { ); } } + +/// After genesis only Play writes, and a world is born Active. Each rule here +/// is the one the reducer's single admission gate decides, on commit and at +/// the commit-time re-decision. +#[cfg(test)] +mod agency_tests { + use super::tests::{ + act, affordance_named, auth_principal, command, creation, first_grant, human_principal, + operations, owner, play_command, reject_play, speak, subject_by_mode, submit_play, + tick_body, + }; + use super::*; + + fn world(title: &str) -> (tempfile::TempDir, std::path::PathBuf, WorldKernel) { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), title), + &auth_principal(owner()), + ) + .unwrap(); + (directory, path, kernel) + } + + fn declare_place_patch(handle: &str) -> WorldPatch { + WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: format!("The {handle}"), + kind: EntityKind::Place, + container: None, + })], + operations: Vec::new(), + evidence: Vec::new(), + } + } + + #[test] + fn after_genesis_only_play_writes() { + let (_directory, _path, mut kernel) = world("PlayOnly"); + let snapshot = kernel.snapshot().unwrap(); + let human = subject_by_mode(&kernel.state, ControllerMode::Human); + let persona = subject_by_mode(&kernel.state, ControllerMode::NarrativePersona); + let operator = subject_by_mode(&kernel.state, ControllerMode::OperationalAgent); + let convene = affordance_named(&snapshot, "convene"); + let bodies = vec![ + ( + "declare", + CommandBody::AdmitPatch { + patch: declare_place_patch("annex"), + }, + ), + ( + "retire", + operations(vec![ComponentOp::Retire { + subject: Ref::Existing(persona), + }]), + ), + ( + "grant", + operations(vec![ComponentOp::GrantAffordance { + subject: Ref::Existing(human), + affordance: Ref::Existing(convene), + }]), + ), + ( + "revoke", + operations(vec![ComponentOp::RevokeAffordance { + subject: Ref::Existing(operator), + affordance: Ref::Existing(convene), + }]), + ), + ("advance", tick_body(5)), + ( + "act", + CommandBody::Act { + actor: human, + invocation: speak(first_grant(&snapshot, human), "Hello."), + }, + ), + ]; + + for (name, body) in &bodies { + for caller in [ + CallerId::Principal(owner()), + CallerId::Principal(human_principal()), + ] { + let commits = kernel.journal.commit_count(); + let error = kernel + .submit( + command(&snapshot, CommandId::new(), caller.clone(), body.clone()), + &AuthenticatedCaller::fixture(caller.clone()), + ) + .unwrap_err(); + assert!( + matches!(error, KernelError::Unauthorized), + "{name} as {caller:?}: {error:?}" + ); + assert_eq!(kernel.journal.commit_count(), commits, "{name} committed"); + assert_eq!(kernel.snapshot().unwrap(), snapshot, "{name} moved the world"); + } + } + for (name, body) in bodies { + let before = kernel.snapshot().unwrap(); + let receipt = kernel + .submit( + play_command(&before, CommandId::new(), body), + &AuthenticatedCaller::verified_play(), + ) + .unwrap_or_else(|error| panic!("Play {name}: {error:?}")); + assert!(matches!(receipt, SubmitReceipt::Applied(_)), "Play {name}"); + } + } + + #[test] + fn apply_effect_re_decides_play() { + let (_directory, _path, kernel) = world("ReDecide"); + let state = &kernel.state; + let command_id = CommandId::issue(); + let human = subject_by_mode(state, ControllerMode::Human); + let affordance = first_grant(&kernel.snapshot().unwrap(), human); + let invocation = speak(affordance, "Spoken."); + let granted = require_granted(state, human, affordance).unwrap(); + let event = action::exercise(state, command_id, human, &granted, &invocation).unwrap(); + let minutes = TickMinutes::new(9).unwrap(); + let to = state.now.checked_add(minutes).unwrap(); + let effects = [ + ( + "patch", + WorldEffect::PatchAdmitted { + resolved: patch::resolve_patch( + state, + command_id, + &declare_place_patch("annex"), + ) + .unwrap(), + }, + ), + ("act", WorldEffect::Acted { invocation, event }), + ( + "tick", + WorldEffect::TimeAdvanced { + minutes, + to, + motion: clock::derive_motion(state, to), + }, + ), + ]; + for (name, effect) in &effects { + for caller in [ + CallerId::Principal(owner()), + CallerId::Principal(human_principal()), + ] { + let mut candidate = state.clone(); + let error = apply_effect(&mut candidate, command_id, &caller, effect).unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{name}: {error:?}"); + assert_eq!(&candidate, state, "{name} mutated before refusing"); + } + let mut candidate = state.clone(); + apply_effect(&mut candidate, command_id, &CallerId::Play, effect) + .unwrap_or_else(|error| panic!("Play {name}: {error:?}")); + assert_ne!(&candidate, state, "Play {name} changed nothing"); + } + } + + #[test] + fn a_world_is_born_active() { + let (_directory, path, mut kernel) = world("BornActive"); + let snapshot = kernel.snapshot().unwrap(); + assert_eq!(snapshot.revision, 0); + let human = subject_by_mode(&kernel.state, ControllerMode::Human); + act(&mut kernel, human, speak(first_grant(&snapshot, human), "At once.")).unwrap(); + let accepted = kernel.snapshot().unwrap(); + assert_eq!(accepted.revision, 1); + drop(kernel); + let reopened = WorldKernel::open(&path, accepted.world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), accepted); + + let (_other, _path, mut kernel) = world("BornActiveClock"); + let genesis = kernel.snapshot().unwrap(); + submit_play(&mut kernel, &genesis, tick_body(1)); + assert_eq!(kernel.snapshot().unwrap().revision, 1); + } + + #[test] + fn retired_tags_do_not_decode() { + fn refused<T: serde::de::DeserializeOwned>(json: &str) { + assert!(serde_json::from_str::<T>(json).is_err(), "{json} decoded"); + } + let id = "\"00000000-0000-4000-8000-000000000000\""; + refused::<CommandBody>(r#"{"type":"approve_draft"}"#); + refused::<CommandBody>(r#"{"type":"activate_world"}"#); + refused::<CallerId>(&format!(r#"{{"type":"controller","id":{id}}}"#)); + refused::<CallerId>(r#"{"type":"system","id":{"capability":"clock"}}"#); + refused::<CallerId>(r#"{"type":"system","id":{"capability":"play"}}"#); + refused::<CallerId>(&format!( + r#"{{"type":"system","id":{{"capability":"consumer","consumer":{id}}}}}"# + )); + refused::<NewController>(&format!(r#"{{"type":"external","consumer":{id}}}"#)); + refused::<WorldEffect>(r#"{"type":"draft_approved","principal":"p"}"#); + refused::<WorldEffect>(r#"{"type":"world_activated"}"#); + assert_eq!( + serde_json::from_str::<CallerId>(r#"{"type":"play"}"#).unwrap(), + CallerId::Play + ); + } + + #[test] + fn a_revoke_may_leave_a_subject_with_no_verbs() { + let (_directory, path, mut kernel) = world("Mute"); + let snapshot = kernel.snapshot().unwrap(); + let persona = subject_by_mode(&kernel.state, ControllerMode::NarrativePersona); + let only = first_grant(&snapshot, persona); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::RevokeAffordance { + subject: Ref::Existing(persona), + affordance: Ref::Existing(only), + }]), + ); + assert!( + !kernel + .state + .affordance_grants + .contains_key(&DecisionScope { subject_id: persona }), + "the emptied row was kept" + ); + let error = act(&mut kernel, persona, speak(only, "Silent.")).unwrap_err(); + assert!(matches!(error, KernelError::AffordanceDenied), "{error:?}"); + journal::verify_state_shape(&kernel.state).expect("a mute subject is a legal shape"); + let accepted = kernel.snapshot().unwrap(); + drop(kernel); + assert_eq!( + WorldKernel::open(&path, accepted.world_id) + .unwrap() + .snapshot() + .unwrap(), + accepted + ); + } + + #[test] + fn a_subject_may_be_declared_with_no_verbs() { + let mute = |handle: &str| { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: format!("The {handle}"), + kind: SubjectKind::Person, + controller: NewController::OperationalAgent, + affordances: BTreeSet::new(), + position: Some(Ref::Draft(DraftHandle::new(super::tests::COMMONS))), + import_key: None, + }) + }; + let directory = tempfile::tempdir().unwrap(); + let mut input = creation(CommandId::new(), "Mutes"); + input.patch.declarations.push(mute("born-mute")); + let (mut kernel, _) = WorldKernel::create( + directory.path().join("world.cc"), + input, + &auth_principal(owner()), + ) + .unwrap(); + let snapshot = kernel.snapshot().unwrap(); + let speaking = first_grant(&snapshot, subject_by_mode(&kernel.state, ControllerMode::Human)); + submit_play( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![Declaration::Subject(SubjectDeclaration { + position: None, + ..match mute("declared-mute") { + Declaration::Subject(subject) => subject, + _ => unreachable!(), + } + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + let snapshot = kernel.snapshot().unwrap(); + for label in ["The born-mute", "The declared-mute"] { + let found = snapshot + .subjects + .iter() + .find(|subject| subject.label == label) + .unwrap(); + assert!(found.affordances.is_empty(), "{label}"); + assert!( + !kernel + .state + .affordance_grants + .contains_key(&DecisionScope { subject_id: found.id }), + "{label} holds a grant row" + ); + let error = act(&mut kernel, found.id, speak(speaking, "Mute.")).unwrap_err(); + assert!(matches!(error, KernelError::AffordanceDenied), "{label}: {error:?}"); + } + } + + #[test] + fn a_retired_subject_takes_no_grant() { + let (_directory, _path, mut kernel) = world("RetiredGrants"); + let snapshot = kernel.snapshot().unwrap(); + let persona = subject_by_mode(&kernel.state, ControllerMode::NarrativePersona); + let convene = affordance_named(&snapshot, "convene"); + let grant = ComponentOp::GrantAffordance { + subject: Ref::Existing(persona), + affordance: Ref::Existing(convene), + }; + let revoke = ComponentOp::RevokeAffordance { + subject: Ref::Existing(persona), + affordance: Ref::Existing(first_grant(&snapshot, persona)), + }; + let retire = ComponentOp::Retire { + subject: Ref::Existing(persona), + }; + for op in [grant.clone(), revoke.clone()] { + let mismatches = reject_play( + &mut kernel, + &snapshot, + operations(vec![retire.clone(), op]), + ); + assert_eq!( + mismatches, + vec![Mismatch::GrantsToRetired { operation: 1 }], + "same patch" + ); + } + submit_play(&mut kernel, &snapshot, operations(vec![retire])); + let snapshot = kernel.snapshot().unwrap(); + for op in [grant, revoke] { + let mismatches = reject_play(&mut kernel, &snapshot, operations(vec![op])); + assert_eq!(mismatches, vec![Mismatch::GrantsToRetired { operation: 0 }]); + } + } + + #[test] + fn retire_applies_to_every_subject() { + let (_directory, path, mut kernel) = world("RetireAll"); + let snapshot = kernel.snapshot().unwrap(); + let everyone = [ + ControllerMode::Human, + ControllerMode::NarrativePersona, + ControllerMode::OperationalAgent, + ] + .map(|mode| subject_by_mode(&kernel.state, mode)); + submit_play( + &mut kernel, + &snapshot, + operations( + everyone + .iter() + .map(|subject| ComponentOp::Retire { + subject: Ref::Existing(*subject), + }) + .collect(), + ), + ); + let after = kernel.snapshot().unwrap(); + assert_eq!(after.subjects.len(), everyone.len()); + for subject in &after.subjects { + assert!(subject.retired, "{} was not retired", subject.label); + assert!(subject.affordances.is_empty()); + assert!(subject.position.is_none()); + } + assert!(kernel.state.affordance_grants.is_empty()); + drop(kernel); + assert_eq!( + WorldKernel::open(&path, after.world_id) + .unwrap() + .snapshot() + .unwrap(), + after + ); + } + + /// `apply_operation` re-decides the retired guard the resolver also holds: + /// a forged `PatchAdmitted` that grants a retired subject a verb is refused + /// at apply rather than leaving a grant row the shape check calls corrupt. + #[test] + fn apply_refuses_a_grant_to_a_retired_subject() { + let (_directory, _path, mut kernel) = world("ForgedGrant"); + let snapshot = kernel.snapshot().unwrap(); + let persona = subject_by_mode(&kernel.state, ControllerMode::NarrativePersona); + let convene = affordance_named(&snapshot, "convene"); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::Retire { + subject: Ref::Existing(persona), + }]), + ); + let forged = WorldEffect::PatchAdmitted { + resolved: ResolvedPatch { + subjects: Vec::new(), + entities: Vec::new(), + routes: Vec::new(), + affordances: Vec::new(), + facts: Vec::new(), + channels: Vec::new(), + operations: vec![ResolvedOp::GrantAffordance { + subject: persona, + affordance: convene, + }], + evidence: Vec::new(), + }, + }; + let mut candidate = kernel.state.clone(); + let error = + apply_effect(&mut candidate, CommandId::issue(), &CallerId::Play, &forged).unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + assert!( + !candidate + .affordance_grants + .contains_key(&DecisionScope { subject_id: persona }), + "a retired subject was granted a verb" + ); + } +} diff --git a/native/aetherlight/src/patch.rs b/native/aetherlight/src/patch.rs index 84435749d..28a2dd804 100644 --- a/native/aetherlight/src/patch.rs +++ b/native/aetherlight/src/patch.rs @@ -1400,9 +1400,8 @@ pub enum Mismatch { }, NoCanonicalChange, /// A genesis-lane resolution (the same empty-state case `admits_human` - /// tests) declared no subject, so the world would have no decision - /// subject to admit. This is a rejected patch, not a corrupt journal: the - /// mailbox actor must survive it. + /// tests) declared no subject, so the world would have nobody to act. This + /// is a rejected patch, not a corrupt journal: the kernel must survive it. NoDecisionSubject, /// A declared place contains itself through its container chain. ContainmentCycle { @@ -3828,7 +3827,7 @@ pub(super) fn resolve_patch( } // The resolver reads authority for the subject being moved, not // for whoever proposed the patch, which is what keeps it - // actor-blind: the owner-admitted lane and the action lane get + // actor-blind: the patch lane and the action lane get // the same answer for the same move. A destination this patch // declares is canonically unknown, so only a `Public` route // reaches it. @@ -6814,33 +6813,6 @@ mod tests { } } - #[test] - fn admit_patch_from_a_non_owner_is_rejected() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = draft_world(directory.path()); - let before = kernel.snapshot().unwrap(); - let commits_before = kernel.journal.commit_count(); - - let error = kernel - .submit( - command( - &before, - CommandId::new(), - CallerId::Principal(human_principal()), - admit(patch_of(vec![entity( - "rhythm-road", - "The Rhythm Road", - EntityKind::Place, - )])), - ), - &auth_principal(human_principal()), - ) - .unwrap_err(); - assert!(matches!(error, KernelError::Unauthorized)); - assert_eq!(kernel.journal.commit_count(), commits_before); - assert_eq!(kernel.snapshot().unwrap(), before); - } - #[test] fn restart_replay_after_a_committed_patch_is_exact() { let directory = tempfile::tempdir().unwrap(); From 105632df25d9781ebbcd34c5213f8e9b5854e2b0 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 00:37:22 +0100 Subject: [PATCH 135/190] Aetherlight AL2b-2a: PROVENANCE section for the Play-only cut Records what went (with f51275c61 locations), the born-Active genesis and the one gate; restates the AL2b-1 residue as what AL2b-2b still owns and drops the leave-set bullets and the valid_until obligation this cut deleted. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/PROVENANCE.md | 86 ++++++++++++++++++++++++++------ 1 file changed, 70 insertions(+), 16 deletions(-) diff --git a/native/aetherlight/PROVENANCE.md b/native/aetherlight/PROVENANCE.md index 7ad559f15..ccdd9f276 100644 --- a/native/aetherlight/PROVENANCE.md +++ b/native/aetherlight/PROVENANCE.md @@ -181,22 +181,18 @@ Kept untouched for AL2b: controllers and `ControllerMode`, consumers `#![allow(dead_code)]` still hides the dead code of a crate with no entry point. What the cut deletes is gone; what remains is part B's: -- Consumer lane: `ConsumerId`, `CONSUMER_ID_NAMESPACE`, `bound_to_consumer`, - `PatchGround::Consumer` and the consumer arm of `confine_to_ground`, - `VerifiedPrincipalEvidence`. -- Controller lane: `verified_controller`, `resolve_controller`, `controller_mode`, +- Controller lane (AL2b-2b's): `resolve_controller`, `controller_mode`, `controller_key`. -- `CreateWorldIntent` (no consumer after the mailbox left). - Authenticated-caller vocabulary: `AuthenticatedCaller::fixture`, - `verified_principal`, `verified_controller`, `verified_system`, and + `verified_principal`, `verified_play`, and `requires_owner_restart`; id helpers `text` and `nil_for_test`; `commits_for_test`; grammar `verbs`. AL4's ABI decides which of these it needs. - Patch ingress: `decode_patch`, `check_patch_caps`, `PatchDecodeError` and `MAX_PATCH_BYTES`, `MAX_PATCH_DECLARATIONS`, `MAX_PATCH_OPERATIONS`, `MAX_PATCH_EVIDENCE`; the consumer ingress and elaboration lane read them, and - nothing here does. AL2b deletes them with the consumer lane unless AL4's ABI - decodes patches itself. + nothing here does. They stay: AL4's ABI decides whether it decodes patches + itself. - Mailbox and vault comments (`WorldMailbox`, `vault:` evidence strings). Reproduce the list with `RUSTFLAGS=--force-warn dead_code cargo test --lib --no-run`: @@ -237,20 +233,78 @@ kernel Speak entry, the grammar, `preconditions_hold`). `DecisionScope` stays th grant key and `ControllerAssignment` stays; the owner's `AdmitPatch` and `AdvanceTime` doors and `SystemCapability::Clock` stay. -AL2b-2 still owns, under `aetherlight-play-only-after-genesis`: the owner's and -`Clock`'s post-genesis doors (`AdmitPatch` and `AdvanceTime`), `CallerId::Controller` -and the controller assignment, the consumer lane and ground, the draft phase and -approvals, `VerifiedPrincipalEvidence`, the never-mute rule -(`WouldLeaveSubjectMute`) and the `verify_state_shape` clause requiring a grant per -controlled scope. +AL2b-2a (below) took the writers; AL2b-2b still owns the controller half under +`aetherlight-play-only-after-genesis`: `ControllerAssignment` (which until then +holds only the `Retired` flag and unread identity data), `NewController`, +`ControllerId`, `ControllerMode`, `DecisionScope` as the grant key, +`SubjectState.retired`, `Mismatch::UnadmittedController`, the `admits_human` +rename and the snapshot's controller fields. `last_acted_at` and `minted_at` in `snapshot` still read `state.events` (by `event.actor`). AL3 needs keyed rows instead of a scan; that is the AL3 cut's. +## Cut AL2b-2a: after genesis only Play writes + +Base `f51275c61`. A world is born Active: the genesis commit is the owner's +only act, and `WorldState::empty` has no phase and no approvals. After it +`CallerId::Play` is the only caller any command body admits. `CallerId` is +`{ Principal, Play }`; `Principal` survives as the genesis creator (and as the +refused caller of every post-genesis body). One rule, `require_play`, decides it +at the top of `reduce` and again at the top of `apply_effect`, so it holds on +commit and at replay; the journal gains no caller rule. +`require_ruler` is `forbid_rulings_at_genesis`: genesis may not rule or mint, +Play may. A grant row exists if and only if the subject holds a verb; a subject +may be declared with none, and revoking the last verb removes the row. +`GrantsOutsideControl` is `GrantsToRetired`. `STATE_SCHEMA` and `COMMIT_SCHEMA` +moved to `consumer.v9`. + +Deleted, with their `f51275c61` locations in `lib.rs` unless noted: + +- The Clock and Consumer capabilities and `CallerId::Controller`: + `SystemCapability` (388-406), `AuthenticatedCaller::verified_controller` (433), + `require_system_capability`, `require_clock_caller`, `require_play_active`, + `require_owner` and `require_patch_author` (1456-1514, 3594-3625, 3989-4006), + and `apply_effect`'s capability table. +- The consumer lane: `ConsumerId` and its namespace (317-338), `PatchGround` + (408-419), `NewController::External`, `ControllerAssignment:: + ExternallyControlled`, `expected_caller`, `consumer()`, `bound_to_consumer`, + `candidate_places`, `confine_to_ground` (3628-3792), `operation_ground` + (3826-3987), and in `patch.rs` the mirror and human candidate sets, + `Mismatch::OutsideJurisdiction`, `RetiresAMirror`, `ControllerGrantMismatch`. +- The draft phase: `WorldPhase`, `WorldState.phase` and `draft_approvals`, + `CommandBody::ApproveDraft` and `ActivateWorld`, `WorldEffect::DraftApproved` + and `WorldActivated`, `required_approvers`, `KernelError::WrongPhase`, + `NotDraftApprover`, `DraftAlreadyApproved`, `MissingApprovals`, the snapshot's + `phase`, `draft_approvals` and `required_approvers`, `Mismatch::RetiresAnApprover`, + and the Draft-only shape clause in `journal.rs`. +- The never-mute rule and the controller/grant pairing: in `admit_resolved`, the + resolver, `Mismatch::WouldLeaveSubjectMute`, and the shape clauses in + `verify_state_shape` that required a grant row per controlled scope. +- `CommandId::derived`, whose only caller was `ConsumerId::of_name`. +- `VerifiedPrincipalEvidence` (106-146), `CreateWorldIntent` (366-376) and + `PrincipalCommandIntent` (521-529). The `valid_until` enforcement that + Ghostlight's mailbox did is no longer an AL4 obligation: the type that carried + it is gone. + +Kept: the whole dialogue lane, `decode_patch`, `check_patch_caps`, +`PatchDecodeError` and the `MAX_PATCH_*` constants (AL4's ABI decides whether +it decodes patches itself), the `ghostlight.*` schema namespaces (AL3 renames +them), `Retire`, `GrantAffordance` and `RevokeAffordance` as Play's patch +operations, and `#![allow(dead_code)]`. + +Nothing decides with a controller after this cut. `ControllerAssignment`, +`NewController::{Human, NarrativePersona, OperationalAgent}`, `ControllerId`, +`ControllerMode`, `DecisionScope` as the grant key, `validate_assignment`, +`Mismatch::UnadmittedController` and `admits_human` (the genesis predicate three +places read) stay compiled for AL2b-2b, which removes the controllers and +renames the predicate. + +`last_acted_at` and `minted_at` in `snapshot` still read `state.events`; the +count of code readers of `state.events` did not rise (idea +`cutspecs-1119.al3-needs-keyed-rows`). + ## Obligations this cut hands to AL4 - A cross-crate proof that forged opportunities and ids are refused, equivalent to the dropped `tests/external_admission.rs`, against the ABI's surface. -- Enforcement of `VerifiedPrincipalEvidence::valid_until`, which Ghostlight's - mailbox did and the fork does not. - Removal of `#![allow(dead_code)]`. From 9df34ea28a372650a513b3db037da20645bdd754 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 00:59:20 +0100 Subject: [PATCH 136/190] Aetherlight AL2b-2a: pin the reduce gate and the title clause A non-Play caller's broken patch and ungranted act are Unauthorized, so dropping require_play from reduce fails a test (it was not equivalent: the refusal would leak world structure). A forged empty or padded stored title is Corrupt. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/journal.rs | 24 +++++++++++++++++++ native/aetherlight/src/lib.rs | 38 +++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index 41c293e80..027bf91bc 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -2302,6 +2302,30 @@ mod custody_tests { ); } + /// The title clause of the shape check refuses an empty title and a + /// noncanonical one, each on its own. + #[test] + fn a_forged_empty_or_padded_title_is_corrupt() { + use crate::tests::{auth_principal, creation, owner}; + + let directory = tempfile::tempdir().unwrap(); + let (kernel, _) = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "Titled"), + &auth_principal(owner()), + ) + .unwrap(); + verify_state_shape(&kernel.state).expect("a canonical title passes"); + for title in ["", " ", " Titled", "Titled "] { + let mut forged = kernel.state.clone(); + forged.title = title.into(); + assert!( + matches!(verify_state_shape(&forged), Err(JournalError::Corrupt(_))), + "title {title:?} passed the shape check" + ); + } + } + /// A grant row is a verb list for a live subject: each clause of the shape /// check is pinned on `verify_state_shape` directly, one forged state per /// clause, so deleting any one of them fails a case. diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index a8b2fc435..9ddf725f9 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -12602,6 +12602,44 @@ mod agency_tests { } } + /// The gate sits at the top of `reduce`, so a non-Play caller learns + /// nothing about the world through a refusal: a patch that would be + /// rejected for naming an unknown subject, and an act the actor has no + /// grant for, both come back Unauthorized. + #[test] + fn a_non_play_caller_is_refused_before_the_world_is_read() { + let (_directory, _path, mut kernel) = world("Blind"); + let snapshot = kernel.snapshot().unwrap(); + let persona = subject_by_mode(&kernel.state, ControllerMode::NarrativePersona); + let ungranted = affordance_named(&snapshot, "convene"); + let broken = operations(vec![ComponentOp::Retire { + subject: Ref::Existing(SubjectId::issue()), + }]); + let denied = CommandBody::Act { + actor: persona, + invocation: speak(ungranted, "Not mine."), + }; + for caller in [ + CallerId::Principal(owner()), + CallerId::Principal(human_principal()), + ] { + for body in [broken.clone(), denied.clone()] { + let error = kernel + .submit( + command(&snapshot, CommandId::new(), caller.clone(), body), + &AuthenticatedCaller::fixture(caller.clone()), + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + } + } + // The same commands from Play are refused for what they are. + let error = reject_play(&mut kernel, &snapshot, broken); + assert!(!error.is_empty()); + let error = act(&mut kernel, persona, speak(ungranted, "Not mine.")).unwrap_err(); + assert!(matches!(error, KernelError::AffordanceDenied), "{error:?}"); + } + #[test] fn a_world_is_born_active() { let (_directory, path, mut kernel) = world("BornActive"); From c79f9b5671e45d454a830b4f4a0e541a4998b559 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 01:11:45 +0100 Subject: [PATCH 137/190] Aetherlight AL2b-2b: retirement lives on SubjectState; grants keyed by SubjectId SubjectState.retired is the one stored statement; is_retired reads it. The Retire arm sets it; affordance_grants is keyed by SubjectId. Controllers still compiled; removed in the next commit. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/journal.rs | 19 +++------ native/aetherlight/src/lib.rs | 68 +++++++++++++++---------------- native/aetherlight/src/patch.rs | 14 +++---- 3 files changed, 47 insertions(+), 54 deletions(-) diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index 027bf91bc..b067f2195 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -833,9 +833,9 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> } // A grant row is a verb list: non-empty, for a live subject, catalog // entries only. A subject holding no verb holds no row. - for (scope, granted) in &state.affordance_grants { - if !state.controller_assignments.contains_key(scope) - || super::is_retired(state, scope.subject_id) + for (subject_id, granted) in &state.affordance_grants { + if !state.subjects.contains_key(subject_id) + || super::is_retired(state, *subject_id) || granted.is_empty() || granted .iter() @@ -2332,7 +2332,7 @@ mod custody_tests { #[test] fn a_malformed_grant_row_is_corrupt() { use crate::tests::{auth_principal, creation, owner}; - use crate::{AffordanceId, ControllerAssignment, DecisionScope, SubjectId}; + use crate::{AffordanceId, SubjectId}; let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("world.cc"); @@ -2354,21 +2354,14 @@ mod custody_tests { ); }; corrupt("a grant row for a retired subject", &|state| { - state - .controller_assignments - .insert(held, ControllerAssignment::Retired); + state.subjects.get_mut(&held).unwrap().retired = true; }); corrupt("an empty grant row", &|state| { state.affordance_grants.get_mut(&held).unwrap().clear(); }); corrupt("a grant row for no subject", &|state| { let verbs = state.affordance_grants[&held].clone(); - state.affordance_grants.insert( - DecisionScope { - subject_id: SubjectId::issue(), - }, - verbs, - ); + state.affordance_grants.insert(SubjectId::issue(), verbs); }); corrupt("a grant row naming an uncataloged verb", &|state| { state diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index 9ddf725f9..e54b690fc 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -401,6 +401,14 @@ struct SubjectState { /// subject nobody imported, so its digests are unchanged. #[serde(default, skip_serializing_if = "Option::is_none")] import_key: Option<ImportKey>, + /// Set once by `Retire`; the one place retirement is stored. A live + /// subject's row serializes without it. + #[serde(default, skip_serializing_if = "is_false")] + retired: bool, +} + +fn is_false(value: &bool) -> bool { + !*value } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] @@ -536,7 +544,7 @@ struct WorldState { /// Who may exercise which entry: a row exists if and only if the subject /// holds at least one verb. A grant carries no payload, so a duplicate /// grant is unrepresentable rather than checked. - affordance_grants: BTreeMap<DecisionScope, BTreeSet<AffordanceId>>, + affordance_grants: BTreeMap<SubjectId, BTreeSet<AffordanceId>>, events: Vec<DecisionEvent>, state_digest: String, last_commit_digest: Option<String>, @@ -1481,7 +1489,7 @@ fn admit_resolved( } state .affordance_grants - .entry(scope) + .entry(subject.subject_id) .or_default() .insert(*affordance_id); } @@ -2397,30 +2405,23 @@ fn apply_operation( let scope = DecisionScope { subject_id: *subject, }; - let assignment = state.controller_assignments.get(&scope).ok_or_else(unknown)?; - match assignment { - ControllerAssignment::Retired => { - return Err(KernelError::Invariant( - "retire operation names an already retired subject".into(), - )); - } - ControllerAssignment::Human { .. } - | ControllerAssignment::NarrativePersona { .. } - | ControllerAssignment::OperationalAgent { .. } => {} + let held = state.subjects.get_mut(subject).ok_or_else(unknown)?; + if held.retired { + return Err(KernelError::Invariant( + "retire operation names an already retired subject".into(), + )); } + held.retired = true; state .controller_assignments .insert(scope, ControllerAssignment::Retired); state.positions.remove(subject); - state.affordance_grants.remove(&scope); + state.affordance_grants.remove(subject); } ResolvedOp::GrantAffordance { subject, affordance } | ResolvedOp::RevokeAffordance { subject, affordance } => { let granting = matches!(operation, ResolvedOp::GrantAffordance { .. }); - let scope = DecisionScope { - subject_id: *subject, - }; - if !state.controller_assignments.contains_key(&scope) + if !state.subjects.contains_key(subject) || is_retired(state, *subject) || !state.affordance_catalog.contains_key(affordance) { @@ -2429,7 +2430,7 @@ fn apply_operation( if granting { if !state .affordance_grants - .entry(scope) + .entry(*subject) .or_default() .insert(*affordance) { @@ -2440,7 +2441,7 @@ fn apply_operation( } else { let granted = state .affordance_grants - .get_mut(&scope) + .get_mut(subject) .ok_or_else(unknown)?; if !granted.remove(affordance) { return Err(KernelError::Invariant( @@ -2448,7 +2449,7 @@ fn apply_operation( )); } if granted.is_empty() { - state.affordance_grants.remove(&scope); + state.affordance_grants.remove(subject); } } } @@ -2573,14 +2574,14 @@ fn channel_referents_exist(state: &WorldState, record: &ChannelRecord) -> bool { .is_none_or(|subject_id| state.subjects.contains_key(&subject_id)) } -/// Whether a subject's controller assignment is `Retired`. The one statement -/// of retirement read by anything downstream of it (audience derivation, -/// preconditions, resolvers): only an actual `Retire` sets it. +/// Whether a subject is retired: the one statement of retirement, read by +/// audience derivation, preconditions and resolvers. Only an actual `Retire` +/// sets `SubjectState.retired`. pub(crate) fn is_retired(state: &WorldState, subject_id: SubjectId) -> bool { - matches!( - state.controller_assignments.get(&DecisionScope { subject_id }), - Some(ControllerAssignment::Retired) - ) + state + .subjects + .get(&subject_id) + .is_some_and(|subject| subject.retired) } /// Everyone standing anywhere under one place. The one downward-facing read of @@ -2988,7 +2989,7 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> { })?; let affordances = state .affordance_grants - .get(&scope) + .get(subject_id) .cloned() .unwrap_or_default(); let components = scope_components(state, *subject_id); @@ -3072,7 +3073,7 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> { human_controller: controller.human_principal().cloned(), affordances, position: components.position.map(|position| position.place), - retired: matches!(controller, ControllerAssignment::Retired), + retired: subject.retired, offices_held, offices_granted, redress, @@ -3222,10 +3223,9 @@ fn require_granted<'a>( actor: SubjectId, affordance: AffordanceId, ) -> Result<GrantedAffordance<'a>, KernelError> { - let scope = DecisionScope { subject_id: actor }; if !state .affordance_grants - .get(&scope) + .get(&actor) .is_some_and(|granted| granted.contains(&affordance)) { return Err(KernelError::AffordanceDenied); @@ -12700,7 +12700,7 @@ mod agency_tests { !kernel .state .affordance_grants - .contains_key(&DecisionScope { subject_id: persona }), + .contains_key(&persona), "the emptied row was kept" ); let error = act(&mut kernel, persona, speak(only, "Silent.")).unwrap_err(); @@ -12770,7 +12770,7 @@ mod agency_tests { !kernel .state .affordance_grants - .contains_key(&DecisionScope { subject_id: found.id }), + .contains_key(&found.id), "{label} holds a grant row" ); let error = act(&mut kernel, found.id, speak(speaking, "Mute.")).unwrap_err(); @@ -12893,7 +12893,7 @@ mod agency_tests { assert!( !candidate .affordance_grants - .contains_key(&DecisionScope { subject_id: persona }), + .contains_key(&persona), "a retired subject was granted a verb" ); } diff --git a/native/aetherlight/src/patch.rs b/native/aetherlight/src/patch.rs index 28a2dd804..75fc3fac0 100644 --- a/native/aetherlight/src/patch.rs +++ b/native/aetherlight/src/patch.rs @@ -3322,23 +3322,22 @@ pub(super) fn resolve_patch( }) .collect(); // `Retire` and the affordance grant operations read and write these - // candidates. `retired` seeds from the committed `ControllerAssignment`, - // which the resolver otherwise never reads: a declared subject is always + // candidates. `retired` seeds from the committed subject rows: a declared subject is always // fresh and unretired, so drafts start out of the set. `affordance_holdings` // seeds from committed `affordance_grants` and is extended below for a // subject this same patch declares. let mut retired: BTreeSet<Key<SubjectId>> = state - .controller_assignments + .subjects .keys() - .filter(|scope| super::is_retired(state, scope.subject_id)) - .map(|scope| Key::Existing(scope.subject_id)) + .filter(|subject_id| super::is_retired(state, **subject_id)) + .map(|subject_id| Key::Existing(*subject_id)) .collect(); let mut affordance_holdings: BTreeMap<Key<SubjectId>, BTreeSet<Key<AffordanceId>>> = state .affordance_grants .iter() - .map(|(scope, granted)| { + .map(|(subject_id, granted)| { ( - Key::Existing(scope.subject_id), + Key::Existing(*subject_id), granted.iter().map(|id| Key::Existing(*id)).collect(), ) }) @@ -5096,6 +5095,7 @@ pub(super) fn resolve_patch( label: input.label.clone(), kind: input.kind, import_key: input.import_key.clone(), + retired: false, }, controller, affordances: granted, From bdda374f2076a417bb06d7682a54054899b5c279 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 01:25:32 +0100 Subject: [PATCH 138/190] Aetherlight AL2b-2b: delete controllers ControllerAssignment, ControllerId/Mode, NewController, DecisionScope, SubjectDeclaration.controller, UnadmittedController, validate_assignment and the snapshot controller fields go. admits_human becomes is_genesis. The fixture lookup is by label. The channel controller is untouched. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/action.rs | 2 +- native/aetherlight/src/import_key_tests.rs | 3 +- native/aetherlight/src/journal.rs | 46 +--- native/aetherlight/src/lib.rs | 250 ++++----------------- native/aetherlight/src/patch.rs | 82 +------ 5 files changed, 53 insertions(+), 330 deletions(-) diff --git a/native/aetherlight/src/action.rs b/native/aetherlight/src/action.rs index 55d361b93..66882dab2 100644 --- a/native/aetherlight/src/action.rs +++ b/native/aetherlight/src/action.rs @@ -1727,7 +1727,7 @@ mod tests { let human = active .subjects .iter() - .find(|subject| subject.human_controller.is_some()) + .find(|subject| subject.label == "The Human") .expect("the human subject") .id; let holdings = kernel.state.holdings.clone(); diff --git a/native/aetherlight/src/import_key_tests.rs b/native/aetherlight/src/import_key_tests.rs index 65eb5700c..85149e51e 100644 --- a/native/aetherlight/src/import_key_tests.rs +++ b/native/aetherlight/src/import_key_tests.rs @@ -9,7 +9,7 @@ use crate::patch::{ use crate::tests::{auth_principal, command, creation, owner}; use crate::{ CallerId, CommandBody, CommandId, CreateWorld, EntityId, KernelError, - NewController, SubjectDeclaration, SubjectKind, SubmitReceipt, + SubjectDeclaration, SubjectKind, SubmitReceipt, WorldKernel, WorldPatch, }; use std::collections::BTreeSet; @@ -95,7 +95,6 @@ fn keyed(handle: &str, import_key: Option<ImportKey>, place: EntityId) -> Declar handle: DraftHandle::new(handle), label: format!("The {handle}"), kind: SubjectKind::Person, - controller: NewController::OperationalAgent, affordances: BTreeSet::new(), position: Some(Ref::Existing(place)), import_key, diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index b067f2195..50c44227e 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -491,12 +491,8 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> )); } super::validate_principal(&state.owner).map_err(kernel_error)?; - if state.subjects.is_empty() - || state.controller_assignments.len() != state.subjects.len() - { - return Err(JournalError::Corrupt( - "world ontology is empty or has split subject/controller ownership".into(), - )); + if state.subjects.is_empty() { + return Err(JournalError::Corrupt("world ontology is empty".into())); } let is_place = |entity_id: &super::EntityId| { state @@ -798,38 +794,12 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> )); } } - let mut controller_ids = BTreeSet::new(); - for (subject_id, subject) in &state.subjects { + for subject in state.subjects.values() { if !super::patch::is_canonical_text(&subject.label) { return Err(JournalError::Corrupt( "subject label is empty or noncanonical".into(), )); } - let scope = super::DecisionScope { - subject_id: *subject_id, - }; - let assignment = state - .controller_assignments - .get(&scope) - .ok_or_else(|| JournalError::Corrupt("decision subject has no controller".into()))?; - super::validate_assignment(assignment).map_err(kernel_error)?; - // A retired subject has no controller id, so it joins no uniqueness set. - if let Some(controller_id) = assignment.id() - && !controller_ids.insert(controller_id) - { - return Err(JournalError::Corrupt( - "controller ID owns more than one canonical scope".into(), - )); - } - } - if state - .controller_assignments - .keys() - .any(|scope| !state.subjects.contains_key(&scope.subject_id)) - { - return Err(JournalError::Corrupt( - "controller assignment references an unknown subject".into(), - )); } // A grant row is a verb list: non-empty, for a live subject, catalog // entries only. A subject holding no verb holds no row. @@ -1004,7 +974,7 @@ mod tests { use crate::tests::speak_entry; use crate::{ AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, CreateWorld, Declaration, - DraftHandle, EntityDeclaration, EntityId, EntityKind, NewController, Position, PrincipalId, + DraftHandle, EntityDeclaration, EntityId, EntityKind, Position, PrincipalId, Ref, SubjectDeclaration, SubjectKind, WorldKernel, WorldPatch, }; @@ -1047,9 +1017,6 @@ mod tests { handle: DraftHandle::new("owner"), label: "Owner".into(), kind: SubjectKind::Person, - controller: NewController::Human { - principal: owner.clone(), - }, affordances: kernel_speak_grant(), position: None, import_key: None, @@ -1136,9 +1103,6 @@ mod tests { handle: DraftHandle::new("owner"), label: "Owner".into(), kind: SubjectKind::Person, - controller: NewController::Human { - principal: owner.clone(), - }, affordances: kernel_speak_grant(), position: None, import_key: None, @@ -1168,7 +1132,6 @@ mod tests { handle: DraftHandle::new("rhythm-authority"), label: "The Rhythm Authority".into(), kind: SubjectKind::Institution, - controller: NewController::OperationalAgent, affordances: BTreeSet::from([speak_entry(&kernel)]), position: Some(Ref::Draft(DraftHandle::new("rhythm-road"))), import_key: None, @@ -1646,7 +1609,6 @@ mod tests { handle: DraftHandle::new("owner"), label: "Owner".into(), kind: SubjectKind::Person, - controller: NewController::Human { principal: owner }, affordances: kernel_speak_grant(), position: None, import_key: None, diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index e54b690fc..b3ec753b0 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -138,7 +138,6 @@ opaque_uuid!(CommandId, pub); opaque_uuid!(SubjectId, pub); opaque_uuid!(EntityId, pub); opaque_uuid!(EdgeId, pub); -opaque_uuid!(ControllerId); opaque_uuid!(AffordanceId, pub); opaque_uuid!(EventId); @@ -203,13 +202,6 @@ impl EntityId { } } -#[cfg(test)] -impl ControllerId { - fn issue() -> Self { - Self(Uuid::new_v4()) - } -} - #[cfg(test)] impl AffordanceId { fn issue() -> Self { @@ -241,24 +233,6 @@ pub enum SubjectKind { Population, } -#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] -#[serde(rename_all = "snake_case")] -pub enum ControllerMode { - Human, - NarrativePersona, - OperationalAgent, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(tag = "type", rename_all = "snake_case")] -pub(crate) enum NewController { - Human { - principal: PrincipalId, - }, - NarrativePersona, - OperationalAgent, -} - #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] struct CreateWorld { id: CommandId, @@ -306,12 +280,6 @@ impl AuthenticatedCaller { } } -#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] -#[serde(deny_unknown_fields)] -pub struct DecisionScope { - pub subject_id: SubjectId, -} - /// The referent a role is bound to. Canonical IDs only: an invocation happens /// in Active, where no declaration exists, so a draft reference is /// unrepresentable here and the action lane runs no draft resolution. @@ -411,53 +379,6 @@ fn is_false(value: &bool) -> bool { !*value } -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(tag = "type", rename_all = "snake_case")] -enum ControllerAssignment { - Human { - controller_id: ControllerId, - principal: PrincipalId, - }, - NarrativePersona { - controller_id: ControllerId, - }, - OperationalAgent { - controller_id: ControllerId, - }, - /// A subject `Retire` ended for good. It has no controller id and no mode, - /// so it holds no grants and is never an audience. - Retired, -} - -impl ControllerAssignment { - fn id(&self) -> Option<ControllerId> { - match self { - Self::Human { controller_id, .. } - | Self::NarrativePersona { controller_id } - | Self::OperationalAgent { controller_id } => Some(*controller_id), - Self::Retired => None, - } - } - - fn mode(&self) -> Option<ControllerMode> { - match self { - Self::Human { .. } => Some(ControllerMode::Human), - Self::NarrativePersona { .. } => Some(ControllerMode::NarrativePersona), - Self::OperationalAgent { .. } => Some(ControllerMode::OperationalAgent), - Self::Retired => None, - } - } - - fn human_principal(&self) -> Option<&PrincipalId> { - match self { - Self::Human { principal, .. } => Some(principal), - Self::NarrativePersona { .. } - | Self::OperationalAgent { .. } - | Self::Retired => None, - } - } -} - #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] pub(crate) struct DecisionEvent { pub(crate) id: EventId, @@ -537,7 +458,6 @@ struct WorldState { /// command body and read by no wall clock. It enters `state_digest` and no /// scope: it is world truth, and it is read by no precondition. now: FictionalMinutes, - controller_assignments: BTreeMap<DecisionScope, ControllerAssignment>, /// What an affordance *is*. World-authored and written by `admit_resolved` /// alone. affordance_catalog: BTreeMap<AffordanceId, Affordance>, @@ -628,11 +548,6 @@ pub struct SubjectSnapshot { pub kind: SubjectKind, /// The Aetheria record this subject was imported from, if it was. pub import_key: Option<ImportKey>, - /// Absent for a retired subject, which has no controller and no turn. - /// Every reader fails closed on `None`; none gets a default. - pub(crate) controller_id: Option<ControllerId>, - pub controller_mode: Option<ControllerMode>, - pub human_controller: Option<PrincipalId>, pub affordances: BTreeSet<AffordanceId>, pub(crate) position: Option<EntityId>, /// Set for a subject `Retire` ended: no grants, no position, no @@ -1210,12 +1125,12 @@ fn require_play(caller: &CallerId) -> Result<(), KernelError> { } /// The genesis predicate: the world is being built from nothing, so the one -/// lane that builds revision 0 may bind a human controller. It reads state, -/// never the caller. It takes the two fields it inspects rather than a whole +/// lane that builds revision 0 may build the kernel Speak entry and the first +/// subjects. It reads state, never the caller. It takes the two fields it inspects rather than a whole /// `WorldState` so the genesis lane, which resolves declarations before any /// `WorldState` exists, can call the same owner instead of hand-copying the /// literal it would otherwise always evaluate to. -fn admits_human(revision: u64, subjects: &BTreeMap<SubjectId, SubjectState>) -> bool { +fn is_genesis(revision: u64, subjects: &BTreeMap<SubjectId, SubjectState>) -> bool { revision == 0 && subjects.is_empty() } @@ -1251,7 +1166,6 @@ impl WorldState { commitments: BTreeMap::new(), pressures: BTreeMap::new(), now: FictionalMinutes::default(), - controller_assignments: BTreeMap::new(), affordance_catalog: BTreeMap::new(), affordance_grants: BTreeMap::new(), events: Vec::new(), @@ -1324,7 +1238,6 @@ fn admit_resolved( "admitted patch carries no canonical change".into(), )); } - let humans_admitted = admits_human(state.revision, &state.subjects); for entity in &resolved.entities { if !patch::is_canonical_text(&entity.entity.label) { return Err(KernelError::Invariant( @@ -1383,11 +1296,6 @@ fn admit_resolved( return Err(KernelError::Invariant("admitted route ID collision".into())); } } - let mut controller_ids: BTreeSet<ControllerId> = state - .controller_assignments - .values() - .filter_map(ControllerAssignment::id) - .collect(); for entry in &resolved.affordances { // The catalog's only writer holds the same grammar check the resolver // runs, so an effect resolved elsewhere cannot install an entry the @@ -1427,20 +1335,11 @@ fn admit_resolved( } } for subject in &resolved.subjects { - let scope = DecisionScope { - subject_id: subject.subject_id, - }; if !patch::is_canonical_text(&subject.subject.label) { return Err(KernelError::Invariant( "admitted subject label is not canonical".into(), )); } - validate_assignment(&subject.controller)?; - if matches!(subject.controller, ControllerAssignment::Human { .. }) && !humans_admitted { - return Err(KernelError::Invariant( - "only world genesis may bind a human controller".into(), - )); - } if let Some(position) = subject.position && state .entities @@ -1451,24 +1350,13 @@ fn admit_resolved( "admitted position does not name a canonical place".into(), )); } - if let Some(controller_id) = subject.controller.id() - && !controller_ids.insert(controller_id) - { - return Err(KernelError::Invariant( - "admitted controller ID collision".into(), - )); - } if state .subjects .insert(subject.subject_id, subject.subject.clone()) .is_some() - || state - .controller_assignments - .insert(scope, subject.controller.clone()) - .is_some() { return Err(KernelError::Invariant( - "admitted subject or scope ID collision".into(), + "admitted subject ID collision".into(), )); } if let Some(position) = subject.position @@ -2402,9 +2290,6 @@ fn apply_operation( set_pressure(state, *target, *source, 0); } ResolvedOp::Retire { subject } => { - let scope = DecisionScope { - subject_id: *subject, - }; let held = state.subjects.get_mut(subject).ok_or_else(unknown)?; if held.retired { return Err(KernelError::Invariant( @@ -2412,9 +2297,6 @@ fn apply_operation( )); } held.retired = true; - state - .controller_assignments - .insert(scope, ControllerAssignment::Retired); state.positions.remove(subject); state.affordance_grants.remove(subject); } @@ -2981,12 +2863,6 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> { .subjects .iter() .map(|(subject_id, subject)| { - let scope = DecisionScope { - subject_id: *subject_id, - }; - let controller = state.controller_assignments.get(&scope).ok_or_else(|| { - KernelError::Invariant("subject has no controller assignment".into()) - })?; let affordances = state .affordance_grants .get(subject_id) @@ -3068,9 +2944,6 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> { label: subject.label.clone(), kind: subject.kind, import_key: subject.import_key.clone(), - controller_id: controller.id(), - controller_mode: controller.mode(), - human_controller: controller.human_principal().cloned(), affordances, position: components.position.map(|position| position.place), retired: subject.retired, @@ -3285,13 +3158,6 @@ fn validate_principal(value: &PrincipalId) -> Result<(), KernelError> { } } -fn validate_assignment(value: &ControllerAssignment) -> Result<(), KernelError> { - if let ControllerAssignment::Human { principal, .. } = value { - validate_principal(principal)?; - } - Ok(()) -} - /// The revision a non-genesis commit resolves to: one past `state.revision`, /// which still holds the *previous* revision here, since `submit` only bumps /// it after `apply_effect` returns. Genesis is not a caller: it resolves to @@ -3436,13 +3302,11 @@ mod tests { handle: &str, label: &str, kind: SubjectKind, - controller: NewController, ) -> Declaration { Declaration::Subject(SubjectDeclaration { handle: DraftHandle::new(handle), label: label.into(), kind, - controller, affordances: kernel_speak_grant(), // The fixture world is one room. Co-located speech needs a place to // fill, so every fixture subject stands in the commons. @@ -3524,21 +3388,16 @@ mod tests { "human", "The Human", SubjectKind::Person, - NewController::Human { - principal: human_principal(), - }, ), subject( "persona", "The Witness", SubjectKind::Person, - NewController::NarrativePersona, ), Declaration::Subject(SubjectDeclaration { handle: DraftHandle::new("operator"), label: "The Council".into(), kind: SubjectKind::Institution, - controller: NewController::OperationalAgent, affordances: kernel_speak_grant() .into_iter() .chain(std::iter::once(Ref::Draft(DraftHandle::new("convene")))) @@ -3681,7 +3540,6 @@ mod tests { handle: DraftHandle::new("walker"), label: "The Walker".into(), kind: SubjectKind::Person, - controller: NewController::OperationalAgent, affordances: BTreeSet::from([speak]), position: Some(Ref::Draft(DraftHandle::new("yard"))), import_key: None, @@ -3779,7 +3637,6 @@ mod tests { handle: DraftHandle::new(handle), label: label.into(), kind: SubjectKind::Institution, - controller: NewController::OperationalAgent, affordances: std::iter::once(speak) .chain(carry_affordances().into_iter().map(|declaration| { let Declaration::Affordance(entry) = declaration else { @@ -4306,7 +4163,6 @@ mod tests { handle: DraftHandle::new(handle), label: label.into(), kind: SubjectKind::Person, - controller: NewController::OperationalAgent, affordances: civic_grants(handles, &speak), position: Some(place), import_key: None, @@ -4358,7 +4214,6 @@ mod tests { handle: DraftHandle::new("treasury"), label: "The Tithe Treasury".into(), kind: SubjectKind::Institution, - controller: NewController::OperationalAgent, affordances: civic_grants( &[ "levy", "delegate", "deploy", "sanction", "appoint", "revoke", @@ -4372,7 +4227,6 @@ mod tests { handle: DraftHandle::new("reeve"), label: "The Hall Reeve".into(), kind: SubjectKind::Person, - controller: NewController::NarrativePersona, affordances: civic_grants( &["levy", "delegate", "petition", "sanction"], &speak, @@ -4399,7 +4253,6 @@ mod tests { handle: DraftHandle::new("nowhere"), label: "The Unhoused".into(), kind: SubjectKind::Person, - controller: NewController::NarrativePersona, affordances: civic_grants(&["levy", "petition"], &speak), position: None, import_key: None, @@ -4557,7 +4410,6 @@ mod tests { handle: DraftHandle::new(handle), label: label.into(), kind: SubjectKind::Person, - controller: NewController::NarrativePersona, affordances: BTreeSet::from([ speak.clone(), Ref::Draft(DraftHandle::new("whisper")), @@ -4773,14 +4625,15 @@ mod tests { .expect("the subject holds an affordance") } - /// The first subject whose controller has this mode. - pub(crate) fn subject_by_mode(state: &WorldState, mode: ControllerMode) -> SubjectId { + /// The one subject with this label; the fixture's three are The Human, + /// The Witness and The Council. + pub(crate) fn subject_by_label(state: &WorldState, label: &str) -> SubjectId { state - .controller_assignments + .subjects .iter() - .find(|(_, assignment)| assignment.mode() == Some(mode)) - .map(|(scope, _)| scope.subject_id) - .expect("a subject has this controller mode") + .find(|(_, subject)| subject.label == label) + .map(|(subject_id, _)| *subject_id) + .expect("a subject has this label") } pub(crate) fn speak(affordance: AffordanceId, text: &str) -> DecisionInvocation { @@ -4847,7 +4700,7 @@ mod tests { let (mut kernel, creation_receipt) = WorldKernel::create(&path, creation.clone(), &auth_principal(owner())).unwrap(); let active = kernel.snapshot().unwrap(); - let operator = subject_by_mode(&kernel.state, ControllerMode::OperationalAgent); + let operator = subject_by_label(&kernel.state, "The Council"); let caller = play_caller(); let command = command( &active, @@ -5156,10 +5009,8 @@ mod tests { ) .unwrap(); let topology = admit_topology(&mut kernel); - let scope = DecisionScope { - subject_id: topology.walker, - }; - let base = scope_components(&kernel.state, scope.subject_id); + let scope = topology.walker; + let base = scope_components(&kernel.state, scope); let start_revision = kernel.state.revision; // A new place elsewhere, a route that touches neither the walker's @@ -5190,7 +5041,6 @@ mod tests { handle: DraftHandle::new("runner"), label: "The Runner".into(), kind: SubjectKind::Person, - controller: NewController::OperationalAgent, affordances: BTreeSet::from([speak.clone()]), position: Some(Ref::Existing(topology.road)), import_key: None, @@ -5202,7 +5052,7 @@ mod tests { }, ); assert_ne!(kernel.state.revision, start_revision); - assert_eq!(scope_components(&kernel.state, scope.subject_id), base); + assert_eq!(scope_components(&kernel.state, scope), base); // Another subject's Position moving is not this scope's business. let annexway = *kernel @@ -5246,7 +5096,7 @@ mod tests { .unwrap() }) ); - assert_eq!(scope_components(&kernel.state, scope.subject_id), base); + assert_eq!(scope_components(&kernel.state, scope), base); // A route incident to the walker's own place is inside the scope. let moved = kernel.snapshot().unwrap(); @@ -5263,7 +5113,7 @@ mod tests { }, }, ); - assert_ne!(scope_components(&kernel.state, scope.subject_id), base); + assert_ne!(scope_components(&kernel.state, scope), base); } /// Soul: an `AffordanceId` now names a catalog entry, not a subject's copy @@ -5389,17 +5239,8 @@ mod tests { fn an_institution_and_its_voice_are_two_subjects_joined_by_an_office() { let directory = tempfile::tempdir().unwrap(); let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "Two"); - let (_, civic, active) = civic_world(&mut kernel); + let (_, civic, _) = civic_world(&mut kernel); - let controller_of = |subject_id: SubjectId| { - active - .subjects - .iter() - .find(|subject| subject.id == subject_id) - .unwrap() - .controller_id - }; - assert_ne!(controller_of(civic.treasury), controller_of(civic.reeve)); // Both are authorized over the hall — one directly, one by delegation — // and neither appears in the other's components. @@ -6093,7 +5934,6 @@ mod custody_tests { handle: DraftHandle::new("clerk"), label: "The Ledger Clerk".into(), kind: SubjectKind::Institution, - controller: NewController::OperationalAgent, affordances: BTreeSet::from([speak.clone()]), position: Some(Ref::Existing(topology.yard)), import_key: None, @@ -6446,18 +6286,16 @@ mod custody_tests { let mut kernel = custody_kernel(directory.path(), "ScopeCustody"); let topology = admit_topology(&mut kernel); let custody = admit_custody(&mut kernel, &topology); - let scope = DecisionScope { - subject_id: custody.holder, - }; - let base = scope_components(&kernel.state, scope.subject_id); + let scope = custody.holder; + let base = scope_components(&kernel.state, scope); let mut spent = kernel.state.clone(); set_held(&mut spent, custody.holder, custody.tithe, 1); - assert_ne!(scope_components(&spent, scope.subject_id), base); + assert_ne!(scope_components(&spent, scope), base); let mut gained = kernel.state.clone(); set_held(&mut gained, custody.holder, custody.ingot, 1); - assert_ne!(scope_components(&gained, scope.subject_id), base); + assert_ne!(scope_components(&gained, scope), base); let mut bound = kernel.state.clone(); bound @@ -6465,7 +6303,7 @@ mod custody_tests { .entry(custody.holder) .or_default() .insert(DependencyTarget::Resource(custody.tithe)); - assert_ne!(scope_components(&bound, scope.subject_id), base); + assert_ne!(scope_components(&bound, scope), base); let mut elsewhere = kernel.state.clone(); set_held(&mut elsewhere, custody.counterparty, custody.tithe, 9); @@ -6474,7 +6312,7 @@ mod custody_tests { .entry(custody.counterparty) .or_default() .insert(DependencyTarget::Resource(custody.ingot)); - assert_eq!(scope_components(&elsewhere, scope.subject_id), base); + assert_eq!(scope_components(&elsewhere, scope), base); } /// Soul, proof 4: the ledger equation stated as arithmetic over the @@ -6698,7 +6536,6 @@ mod custody_tests { handle: DraftHandle::new("clerk"), label: "The Ledger Clerk".into(), kind: SubjectKind::Institution, - controller: NewController::OperationalAgent, affordances: BTreeSet::from([speak.clone()]), position: Some(Ref::Existing(topology.yard)), import_key: None, @@ -8543,7 +8380,6 @@ mod witness_tests { handle: DraftHandle::new(handle), label: label.into(), kind: SubjectKind::Person, - controller: NewController::NarrativePersona, affordances: BTreeSet::from([speak.clone(), Ref::Draft(DraftHandle::new("beacon"))]), position: Some(Ref::Draft(DraftHandle::new(place))), import_key: None, @@ -9437,7 +9273,6 @@ mod witness_tests { handle: DraftHandle::new(handle), label: label.into(), kind: SubjectKind::Person, - controller: NewController::NarrativePersona, affordances: BTreeSet::from([Ref::Existing(beacon)]), position: position.map(Ref::Existing), import_key: None, @@ -9666,7 +9501,6 @@ mod clock_tests { handle: DraftHandle::new(handle), label: label.into(), kind, - controller: NewController::NarrativePersona, affordances: BTreeSet::from([ speak.clone(), Ref::Draft(DraftHandle::new("deliver")), @@ -11629,7 +11463,6 @@ mod clock_tests { handle: DraftHandle::new("player"), label: "The Player".into(), kind: SubjectKind::Person, - controller: NewController::NarrativePersona, affordances: BTreeSet::from([speak]), position: Some(Ref::Existing(commons)), import_key: None, @@ -11715,7 +11548,7 @@ mod clock_tests { snapshot .subjects .iter() - .find(|subject| subject.controller_mode == Some(ControllerMode::Human)) + .find(|subject| subject.label == "The Human") .expect("the genesis human") .id } @@ -12340,7 +12173,6 @@ mod clock_tests { handle: DraftHandle::new("outcast"), label: "The Placeless Outcast".into(), kind: SubjectKind::Person, - controller: NewController::NarrativePersona, affordances: BTreeSet::from([speak.clone()]), position: None, import_key: None, @@ -12444,7 +12276,7 @@ mod clock_tests { mod agency_tests { use super::tests::{ act, affordance_named, auth_principal, command, creation, first_grant, human_principal, - operations, owner, play_command, reject_play, speak, subject_by_mode, submit_play, + operations, owner, play_command, reject_play, speak, subject_by_label, submit_play, tick_body, }; use super::*; @@ -12478,9 +12310,9 @@ mod agency_tests { fn after_genesis_only_play_writes() { let (_directory, _path, mut kernel) = world("PlayOnly"); let snapshot = kernel.snapshot().unwrap(); - let human = subject_by_mode(&kernel.state, ControllerMode::Human); - let persona = subject_by_mode(&kernel.state, ControllerMode::NarrativePersona); - let operator = subject_by_mode(&kernel.state, ControllerMode::OperationalAgent); + let human = subject_by_label(&kernel.state, "The Human"); + let persona = subject_by_label(&kernel.state, "The Witness"); + let operator = subject_by_label(&kernel.state, "The Council"); let convene = affordance_named(&snapshot, "convene"); let bodies = vec![ ( @@ -12556,7 +12388,7 @@ mod agency_tests { let (_directory, _path, kernel) = world("ReDecide"); let state = &kernel.state; let command_id = CommandId::issue(); - let human = subject_by_mode(state, ControllerMode::Human); + let human = subject_by_label(state, "The Human"); let affordance = first_grant(&kernel.snapshot().unwrap(), human); let invocation = speak(affordance, "Spoken."); let granted = require_granted(state, human, affordance).unwrap(); @@ -12610,7 +12442,7 @@ mod agency_tests { fn a_non_play_caller_is_refused_before_the_world_is_read() { let (_directory, _path, mut kernel) = world("Blind"); let snapshot = kernel.snapshot().unwrap(); - let persona = subject_by_mode(&kernel.state, ControllerMode::NarrativePersona); + let persona = subject_by_label(&kernel.state, "The Witness"); let ungranted = affordance_named(&snapshot, "convene"); let broken = operations(vec![ComponentOp::Retire { subject: Ref::Existing(SubjectId::issue()), @@ -12645,7 +12477,7 @@ mod agency_tests { let (_directory, path, mut kernel) = world("BornActive"); let snapshot = kernel.snapshot().unwrap(); assert_eq!(snapshot.revision, 0); - let human = subject_by_mode(&kernel.state, ControllerMode::Human); + let human = subject_by_label(&kernel.state, "The Human"); act(&mut kernel, human, speak(first_grant(&snapshot, human), "At once.")).unwrap(); let accepted = kernel.snapshot().unwrap(); assert_eq!(accepted.revision, 1); @@ -12673,7 +12505,6 @@ mod agency_tests { refused::<CallerId>(&format!( r#"{{"type":"system","id":{{"capability":"consumer","consumer":{id}}}}}"# )); - refused::<NewController>(&format!(r#"{{"type":"external","consumer":{id}}}"#)); refused::<WorldEffect>(r#"{"type":"draft_approved","principal":"p"}"#); refused::<WorldEffect>(r#"{"type":"world_activated"}"#); assert_eq!( @@ -12686,7 +12517,7 @@ mod agency_tests { fn a_revoke_may_leave_a_subject_with_no_verbs() { let (_directory, path, mut kernel) = world("Mute"); let snapshot = kernel.snapshot().unwrap(); - let persona = subject_by_mode(&kernel.state, ControllerMode::NarrativePersona); + let persona = subject_by_label(&kernel.state, "The Witness"); let only = first_grant(&snapshot, persona); submit_play( &mut kernel, @@ -12724,7 +12555,6 @@ mod agency_tests { handle: DraftHandle::new(handle), label: format!("The {handle}"), kind: SubjectKind::Person, - controller: NewController::OperationalAgent, affordances: BTreeSet::new(), position: Some(Ref::Draft(DraftHandle::new(super::tests::COMMONS))), import_key: None, @@ -12740,7 +12570,7 @@ mod agency_tests { ) .unwrap(); let snapshot = kernel.snapshot().unwrap(); - let speaking = first_grant(&snapshot, subject_by_mode(&kernel.state, ControllerMode::Human)); + let speaking = first_grant(&snapshot, subject_by_label(&kernel.state, "The Human")); submit_play( &mut kernel, &snapshot, @@ -12782,7 +12612,7 @@ mod agency_tests { fn a_retired_subject_takes_no_grant() { let (_directory, _path, mut kernel) = world("RetiredGrants"); let snapshot = kernel.snapshot().unwrap(); - let persona = subject_by_mode(&kernel.state, ControllerMode::NarrativePersona); + let persona = subject_by_label(&kernel.state, "The Witness"); let convene = affordance_named(&snapshot, "convene"); let grant = ComponentOp::GrantAffordance { subject: Ref::Existing(persona), @@ -12819,12 +12649,8 @@ mod agency_tests { fn retire_applies_to_every_subject() { let (_directory, path, mut kernel) = world("RetireAll"); let snapshot = kernel.snapshot().unwrap(); - let everyone = [ - ControllerMode::Human, - ControllerMode::NarrativePersona, - ControllerMode::OperationalAgent, - ] - .map(|mode| subject_by_mode(&kernel.state, mode)); + let everyone = ["The Human", "The Witness", "The Council"] + .map(|label| subject_by_label(&kernel.state, label)); submit_play( &mut kernel, &snapshot, @@ -12862,7 +12688,7 @@ mod agency_tests { fn apply_refuses_a_grant_to_a_retired_subject() { let (_directory, _path, mut kernel) = world("ForgedGrant"); let snapshot = kernel.snapshot().unwrap(); - let persona = subject_by_mode(&kernel.state, ControllerMode::NarrativePersona); + let persona = subject_by_label(&kernel.state, "The Witness"); let convene = affordance_named(&snapshot, "convene"); submit_play( &mut kernel, diff --git a/native/aetherlight/src/patch.rs b/native/aetherlight/src/patch.rs index 75fc3fac0..c63939012 100644 --- a/native/aetherlight/src/patch.rs +++ b/native/aetherlight/src/patch.rs @@ -14,8 +14,7 @@ use super::clock::{FictionalMinutes, TickMinutes}; use super::grammar::GrammarRefusal; use super::{ - AffordanceId, CommandId, ControllerAssignment, ControllerId, EdgeId, EntityId, - NewController, SubjectId, SubjectKind, SubjectState, WorldId, + AffordanceId, CommandId, EdgeId, EntityId, SubjectId, SubjectKind, SubjectState, WorldId, }; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; @@ -59,7 +58,7 @@ pub(crate) enum AccessKind { #[serde(transparent)] pub(crate) struct AuthorityKindName(pub(crate) String); -/// What an authority covers. Distinct from `DecisionScope`, which says *whose* +/// What an authority covers. Distinct from a subject, which says *whose* /// authority it is and stays one field. #[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] #[serde(tag = "over", content = "id", rename_all = "snake_case")] @@ -988,7 +987,6 @@ pub(crate) struct SubjectDeclaration { pub(crate) handle: DraftHandle, pub(crate) label: String, pub(crate) kind: SubjectKind, - pub(crate) controller: NewController, /// The catalog entries this subject may exercise. Every entry is a /// reference, so a genesis patch declares a catalog and grants from it /// atomically. @@ -1389,9 +1387,6 @@ pub enum Mismatch { site: Site, expected: RefKind, }, - UnadmittedController { - handle: DraftHandle, - }, EmptyEvidence { position: usize, }, @@ -1399,7 +1394,7 @@ pub enum Mismatch { handle: DraftHandle, }, NoCanonicalChange, - /// A genesis-lane resolution (the same empty-state case `admits_human` + /// A genesis-lane resolution (the same empty-state case `is_genesis` /// tests) declared no subject, so the world would have nobody to act. This /// is a rejected patch, not a corrupt journal: the kernel must survive it. NoDecisionSubject, @@ -1713,7 +1708,6 @@ pub(super) struct ResolvedSubject { pub(super) handle: DraftHandle, pub(super) subject_id: SubjectId, pub(super) subject: SubjectState, - pub(super) controller: ControllerAssignment, pub(super) affordances: BTreeSet<AffordanceId>, pub(super) position: Option<Position>, } @@ -2006,7 +2000,6 @@ impl ResolvedPatch { const SUBJECT_NAMESPACE: &str = "ghostlight.id.subject.v1"; pub(super) const ENTITY_NAMESPACE: &str = "ghostlight.id.entity.v1"; const EDGE_NAMESPACE: &str = "ghostlight.id.edge.v1"; -const CONTROLLER_NAMESPACE: &str = "ghostlight.id.controller.v1"; const AFFORDANCE_NAMESPACE: &str = "ghostlight.id.affordance.v1"; const PLACE: RefKind = RefKind::Entity(EntityKind::Place); @@ -3065,7 +3058,7 @@ pub(super) fn resolve_patch( patch: &WorldPatch, ) -> Result<ResolvedPatch, Vec<Mismatch>> { let world_id = state.world_id; - let admits_human = super::admits_human(state.revision, &state.subjects); + let genesis = super::is_genesis(state.revision, &state.subjects); let mut mismatches = Vec::new(); let mut index: BTreeMap<DraftHandle, RefKind> = BTreeMap::new(); @@ -3073,10 +3066,10 @@ pub(super) fn resolve_patch( // one, before the declaration loop, so a world reusing its handle collides // as a duplicate handle rather than through a reserved-name check. let speak_handle = DraftHandle::new(KERNEL_SPEAK_HANDLE); - if admits_human { + if genesis { index.insert(speak_handle.clone(), RefKind::Affordance); } - if admits_human { + if genesis { // The kernel-built entry is held to the grammar like any declaration. let speak = kernel_speak_entry(); check_against_grammar(state, &speak_handle, &speak.kind, &speak.roles, &mut mismatches); @@ -3086,7 +3079,7 @@ pub(super) fn resolve_patch( .values() .map(|entry| entry.kind.clone()) .collect(); - if admits_human { + if genesis { kind_names.insert(kernel_speak_entry().kind); } @@ -3193,15 +3186,6 @@ pub(super) fn resolve_patch( }); } } - if let Declaration::Subject(subject) = declaration { - if let NewController::Human { principal } = &subject.controller - && (!admits_human || super::validate_principal(principal).is_err()) - { - mismatches.push(Mismatch::UnadmittedController { - handle: handle.clone(), - }); - } - } } for (position, evidence) in patch.evidence.iter().enumerate() { @@ -4852,7 +4836,7 @@ pub(super) fn resolve_patch( mismatches.push(Mismatch::NoCanonicalChange); } - if admits_human + if genesis && !patch .declarations .iter() @@ -5006,7 +4990,7 @@ pub(super) fn resolve_patch( affordance: entry, }); }; - if admits_human { + if genesis { allocate_affordance( &speak_handle, kernel_speak_entry(), @@ -5062,27 +5046,6 @@ pub(super) fn resolve_patch( }); } allocated_subjects.insert(input.handle.clone(), subject_id); - let controller_id = || { - ControllerId(derive_id( - CONTROLLER_NAMESPACE, - world_id, - command_id, - &input.handle, - None, - )) - }; - let controller = match input.controller.clone() { - NewController::Human { principal } => ControllerAssignment::Human { - controller_id: controller_id(), - principal, - }, - NewController::NarrativePersona => ControllerAssignment::NarrativePersona { - controller_id: controller_id(), - }, - NewController::OperationalAgent => ControllerAssignment::OperationalAgent { - controller_id: controller_id(), - }, - }; let granted = input .affordances .iter() @@ -5097,7 +5060,6 @@ pub(super) fn resolve_patch( import_key: input.import_key.clone(), retired: false, }, - controller, affordances: granted, position: input.position.as_ref().map(|reference| Position { place: entity_id_of(&key_of(reference)), @@ -5763,7 +5725,6 @@ mod tests { handle: DraftHandle::new(handle), label: label.into(), kind: SubjectKind::Institution, - controller: NewController::OperationalAgent, affordances: BTreeSet::from([speak_entry(kernel)]), position, import_key: None, @@ -6030,7 +5991,6 @@ mod tests { handle: DraftHandle::new("late-arrival"), label: "A Late Arrival".into(), kind: SubjectKind::Person, - controller: NewController::NarrativePersona, affordances: BTreeSet::from([Ref::Draft(DraftHandle::new(handle))]), position: None, import_key: None, @@ -6325,17 +6285,6 @@ mod tests { "The Rhythm Authority", Some(Ref::Draft(DraftHandle::new("cavity-yard"))), ), - Declaration::Subject(SubjectDeclaration { - handle: DraftHandle::new("late-arrival"), - label: "A Late Arrival".into(), - kind: SubjectKind::Person, - controller: NewController::Human { - principal: human_principal(), - }, - affordances: BTreeSet::from([speak_entry(&kernel)]), - position: None, - import_key: None, - }), ]); let error = kernel .submit( @@ -6363,9 +6312,6 @@ mod tests { referent: draft("cavity-yard"), expected: PLACE, }, - Mismatch::UnadmittedController { - handle: DraftHandle::new("late-arrival"), - }, ]; expected.sort(); assert_eq!(mismatches, expected); @@ -6384,7 +6330,6 @@ mod tests { handle: DraftHandle::new("late-arrival"), label: "A Late Arrival".into(), kind: SubjectKind::Person, - controller: NewController::NarrativePersona, affordances: BTreeSet::from([speak_entry(&kernel)]), position: None, import_key: None, @@ -6872,7 +6817,6 @@ mod tests { handle: DraftHandle::new("human"), label: "Another Human".into(), kind: SubjectKind::Person, - controller: NewController::NarrativePersona, affordances: BTreeSet::from([speak_entry(&kernel)]), position: None, import_key: None, @@ -6937,13 +6881,6 @@ mod tests { &handle, None, ), - derive_id( - CONTROLLER_NAMESPACE, - before.world_id, - command_id, - &handle, - None, - ), derive_id( AFFORDANCE_NAMESPACE, before.world_id, @@ -7131,7 +7068,6 @@ mod tests { handle: draft("nowhere"), label: "The Unplaced".into(), kind: SubjectKind::Person, - controller: NewController::NarrativePersona, affordances: BTreeSet::from([speak]), position: None, import_key: None, From 39c50acfcda96b7e253f5febce589f0f610ed73f Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 01:28:06 +0100 Subject: [PATCH 139/190] Aetherlight AL2b-2b: schema consumer.v10, v9 refused; pins and PROVENANCE Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/PROVENANCE.md | 18 ++++++++- native/aetherlight/src/journal.rs | 18 +++++---- native/aetherlight/src/lib.rs | 62 ++++++++++++++++++++++++++++++- 3 files changed, 86 insertions(+), 12 deletions(-) diff --git a/native/aetherlight/PROVENANCE.md b/native/aetherlight/PROVENANCE.md index ccdd9f276..447f1ad70 100644 --- a/native/aetherlight/PROVENANCE.md +++ b/native/aetherlight/PROVENANCE.md @@ -181,8 +181,6 @@ Kept untouched for AL2b: controllers and `ControllerMode`, consumers `#![allow(dead_code)]` still hides the dead code of a crate with no entry point. What the cut deletes is gone; what remains is part B's: -- Controller lane (AL2b-2b's): `resolve_controller`, `controller_mode`, - `controller_key`. - Authenticated-caller vocabulary: `AuthenticatedCaller::fixture`, `verified_principal`, `verified_play`, and `requires_owner_restart`; id helpers `text` and `nil_for_test`; @@ -308,3 +306,19 @@ count of code readers of `state.events` did not rise (idea - A cross-crate proof that forged opportunities and ids are refused, equivalent to the dropped `tests/external_admission.rs`, against the ABI's surface. - Removal of `#![allow(dead_code)]`. + +## AL2b-2b: controllers go, retirement on the subject + +The subject controller is gone: `ControllerAssignment`, `ControllerId`, +`ControllerMode`, `NewController`, `DecisionScope`, `SubjectDeclaration.controller`, +`Mismatch::UnadmittedController`, `validate_assignment`, the snapshot's controller +fields and `ControllerId::issue`. Retirement is `SubjectState.retired`, and +`is_retired` is its only statement. `affordance_grants` is keyed by `SubjectId`. +`admits_human` is `is_genesis`: it says what the from-nothing lane may build (the +kernel Speak entry and the first subjects), not who may be bound. The schema is +`consumer.v10`; v9 rows are refused at the schema gate, with no migration. + +Not this cut's, and kept: the channel controller (`ChannelRecord.controller`, +`SetController`, `resolve_controller`), which is dialogue +(`dialogue-is-world-action`). An earlier version of this file listed +`resolve_controller` and `controller_key` as AL2b-2b's; that was wrong. diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index 50c44227e..fa4e8303f 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -1225,6 +1225,8 @@ mod tests { (COMMIT_ROW, "ghostlight.world_commit.consumer.v6"), (STATE_ROW, "ghostlight.world_state.consumer.v8"), (COMMIT_ROW, "ghostlight.world_commit.consumer.v8"), + (STATE_ROW, "ghostlight.world_state.consumer.v9"), + (COMMIT_ROW, "ghostlight.world_commit.consumer.v9"), ] { let row = CultCacheEnvelope { key: "state".into(), @@ -2390,13 +2392,13 @@ mod custody_tests { /// state row and commit row each on their own: reverting either constant /// to v8 would let its half of the store in. #[test] - fn v8_state_and_commit_rows_are_refused() { + fn v9_state_and_commit_rows_are_refused() { use crate::tests::{act, auth_principal, creation, first_grant, owner, speak}; let directory = tempfile::tempdir().unwrap(); let (mut kernel, _) = WorldKernel::create( directory.path().join("world.cc"), - creation(CommandId::new(), "SchemaV8"), + creation(CommandId::new(), "SchemaV9"), &auth_principal(owner()), ) .unwrap(); @@ -2413,8 +2415,8 @@ mod custody_tests { let state_row = |schema: &str| { envelope(STATE_ROW, schema, kernel.state.world_id.key(), &kernel.state).unwrap() }; - assert_eq!(STATE_SCHEMA, "ghostlight.world_state.consumer.v9"); - assert_eq!(COMMIT_SCHEMA, "ghostlight.world_commit.consumer.v9"); + assert_eq!(STATE_SCHEMA, "ghostlight.world_state.consumer.v10"); + assert_eq!(COMMIT_SCHEMA, "ghostlight.world_commit.consumer.v10"); recover( [commit_rows(COMMIT_SCHEMA), vec![state_row(STATE_SCHEMA)]].concat(), None, @@ -2423,17 +2425,17 @@ mod custody_tests { for (what, rows) in [ ( - "v8 state row", + "v9 state row", [ commit_rows(COMMIT_SCHEMA), - vec![state_row("ghostlight.world_state.consumer.v8")], + vec![state_row("ghostlight.world_state.consumer.v9")], ] .concat(), ), ( - "v8 commit rows", + "v9 commit rows", [ - commit_rows("ghostlight.world_commit.consumer.v8"), + commit_rows("ghostlight.world_commit.consumer.v9"), vec![state_row(STATE_SCHEMA)], ] .concat(), diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index b3ec753b0..94b323244 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -103,8 +103,8 @@ use std::path::Path; use thiserror::Error; use uuid::Uuid; -pub const STATE_SCHEMA: &str = "ghostlight.world_state.consumer.v9"; -pub(crate) const COMMIT_SCHEMA: &str = "ghostlight.world_commit.consumer.v9"; +pub const STATE_SCHEMA: &str = "ghostlight.world_state.consumer.v10"; +pub(crate) const COMMIT_SCHEMA: &str = "ghostlight.world_commit.consumer.v10"; /// Compatibility tag derived from [`STATE_SCHEMA`]: the trailing /// `<family>-<version>` pair (e.g. `foundation-v1`). Callers that publish a @@ -12491,6 +12491,64 @@ mod agency_tests { assert_eq!(kernel.snapshot().unwrap().revision, 1); } + /// Retirement is stored once, on the subject, and a live subject's row is + /// the shape it had before the flag existed. + #[test] + fn a_live_subjects_row_is_unchanged_by_the_flag() { + let live = SubjectState { + label: "Walker".into(), + kind: SubjectKind::Person, + import_key: None, + retired: false, + }; + let live_json = serde_json::to_value(&live).unwrap(); + assert!(live_json.get("retired").is_none()); + let retired = SubjectState { retired: true, ..live.clone() }; + let retired_json = serde_json::to_value(&retired).unwrap(); + assert_eq!(retired_json["retired"], true); + assert_eq!(serde_json::from_value::<SubjectState>(live_json).unwrap(), live); + assert_eq!(serde_json::from_value::<SubjectState>(retired_json).unwrap(), retired); + } + + #[test] + fn a_patch_carrying_a_controller_does_not_decode() { + let Declaration::Subject(declared) = crate::tests::subject("walker", "Walker", SubjectKind::Person) + else { + unreachable!() + }; + let mut json = serde_json::to_value(&declared).unwrap(); + serde_json::from_value::<SubjectDeclaration>(json.clone()) + .expect("the declaration decodes as built"); + json["controller"] = serde_json::json!({"type": "operational_agent"}); + assert!(serde_json::from_value::<SubjectDeclaration>(json).is_err()); + } + + /// Retire sets the flag `is_retired` reads, and nothing else retires. + #[test] + fn retirement_lives_on_the_subject() { + let (_directory, path, mut kernel) = world("RetireFlag"); + let snapshot = kernel.snapshot().unwrap(); + let persona = subject_by_label(&kernel.state, "The Witness"); + assert!(!is_retired(&kernel.state, persona)); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::Retire { + subject: Ref::Existing(persona), + }]), + ); + assert!(kernel.state.subjects[&persona].retired); + assert!(is_retired(&kernel.state, persona)); + assert!(!kernel.state.positions.contains_key(&persona)); + assert!(!kernel.state.affordance_grants.contains_key(&persona)); + let after = kernel.snapshot().unwrap(); + assert!(after.subjects.iter().find(|s| s.id == persona).unwrap().retired); + drop(kernel); + let reopened = WorldKernel::open(&path, after.world_id).unwrap(); + assert!(is_retired(&reopened.state, persona)); + assert_eq!(reopened.snapshot().unwrap(), after); + } + #[test] fn retired_tags_do_not_decode() { fn refused<T: serde::de::DeserializeOwned>(json: &str) { From 92b13c2fd57d86cb40215642b6d0d73271f81040 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Thu, 19 Nov 2026 23:15:07 +0100 Subject: [PATCH 140/190] Split ScenarioStage: ZoneStage owns placement and admission, Summon places into a running zone ZoneStage holds the placement vocabulary and AdmitPlaced (stance both ways, Zone.Admit, pilot knowledge); ScenarioStage : ZoneStage keeps player, credits and starting hull and Admit() in the run-start order. RunStart.Stage no longer writes stance, admission or knowledge. ZoneStage.Summon admits a script's placements into a zone the player is a member of, with no Player verb. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/RunStart.cs | 25 +--- Assets/Scripts/ServerShared/ScenarioStage.cs | 126 ++++++++++++++----- 2 files changed, 98 insertions(+), 53 deletions(-) diff --git a/Assets/Scripts/ServerShared/RunStart.cs b/Assets/Scripts/ServerShared/RunStart.cs index 282693eb2..6278c0cbc 100644 --- a/Assets/Scripts/ServerShared/RunStart.cs +++ b/Assets/Scripts/ServerShared/RunStart.cs @@ -45,8 +45,8 @@ public static class RunStart return staged; } - // Runs the scenario's Stage, then admits its player and everything it placed: each entity's stance set both ways - // with the player, a pilot for each piloted one. Returns null, with every failure listed and the arena unchanged, + // Runs the scenario's Stage, then has the stage admit its player and everything it placed. + // Returns null, with every failure listed and the arena unchanged, // unless the whole scenario staged. public static Staged Stage(ItemManager itemManager, Zone arena, Scenario scenario, string startingHull, List<string> failures) @@ -59,25 +59,8 @@ public static class RunStart if (!stage.PlayerPlaced) failures.Add("player: the scenario places no player"); if (failures.Count > reported) return null; - stage.StockUnauthoredAmmunition(); - - var player = stage.PlayerShip; - player.IsPlayerShip = true; - arena.Admit(player, piloted: false); - foreach (var placed in stage.Placed) - { - var hostile = placed.Stance == ScenarioStance.Hostile; - placed.Entity.SetIff(player, hostile); - player.SetIff(placed.Entity, hostile); - arena.Admit(placed.Entity, placed.Piloted, placed.Task); - } - - // A start state includes what a pilot knows (ruling stage-states-pilot-knowledge): its anchor is tracked from the first - // step, by the sensors' own path (info gathered past the detection threshold), so they can lose it like any track. - foreach (var placed in stage.Placed) - if (placed.Knows != null && placed.Piloted) - placed.Entity.EntityInfoGathered[placed.Knows] = (itemManager.GameplaySettings.TargetDetectionInfoThreshold + 1f) / 2f; - return new Staged { Player = player, Credits = stage.Credits, Entities = stage.Placed.Select(placed => placed.Entity).ToList() }; + stage.Admit(); + return new Staged { Player = stage.PlayerShip, Credits = stage.Credits, Entities = stage.Placed.Select(placed => placed.Entity).ToList() }; } // A new run's item draws (each lot's quality, each generated fit) come from its galaxy's seed, not the process clock, diff --git a/Assets/Scripts/ServerShared/ScenarioStage.cs b/Assets/Scripts/ServerShared/ScenarioStage.cs index 622a5972b..46996d482 100644 --- a/Assets/Scripts/ServerShared/ScenarioStage.cs +++ b/Assets/Scripts/ServerShared/ScenarioStage.cs @@ -8,14 +8,17 @@ using float2 = CultMath.float2; using float3 = CultMath.float3; // The run half of a scenario's vocabulary (docs/scenarios-cut.md, R.4). A scenario's Stage builds its fits and places -// them here; nothing joins the arena until Stage returns with no failure, and then RunStart admits it all at once. +// them here; nothing joins the arena until Stage returns with no failure, and then the stage admits it all at once. // Every verb names what it could not do instead of throwing, so one bad name in a script lists every bad name. -// Designs, hulls and products are named as the catalog names them. Only RunStart builds a stage. -public sealed class ScenarioStage +// Designs, hulls and products are named as the catalog names them. +// ZoneStage is the placement vocabulary and the admission of what it placed; Zone.Admit stays the only admission. +// RunStart builds a ScenarioStage (a ZoneStage that also stages the player); ZoneStage.Summon builds a ZoneStage for a +// running zone. A ZoneStage has no Player verb, so a summon placing a player is unrepresentable. +public class ZoneStage { private readonly ItemManager _items; private readonly Func<CraftedItemData, FactionProductData> _choose; - private readonly List<string> _failures = new List<string>(); + private protected readonly List<string> _failures = new List<string>(); private readonly List<Placement> _placed = new List<Placement>(); private int _placements; // The entities this stage built from a fit (a packed fit is a saved ship, whose cargo is its own) and those whose cargo the scenario @@ -23,12 +26,10 @@ public sealed class ScenarioStage private readonly HashSet<Entity> _fitted = new HashSet<Entity>(); private readonly HashSet<Entity> _cargoAuthored = new HashSet<Entity>(); - internal ScenarioStage(ItemManager items, Zone arena, string startingHull) + internal ZoneStage(ItemManager items, Zone arena) { _items = items; Arena = arena; - StartingHull = startingHull; - Credits = items.GameplaySettings.StartingCredits; // A design named without a product is chosen by the generator's ChooseProduct. The stage outfits with no faction, // so every maker is reachable and the run's seed draws. _choose = new LoadoutGenerator(ref items.Random, items, arena.Galaxy, arena.GalaxyZone, null, 2).ChooseProduct; @@ -36,22 +37,16 @@ public sealed class ScenarioStage public Galaxy Galaxy => Arena.Galaxy; public Zone Arena { get; } - public string StartingHull { get; } - - // What the run starts with: the gameplay settings' starting credits unless the scenario sets another amount. - public int Credits { get; set; } internal IReadOnlyList<string> Failures => _failures; // Staging's last step: a fitted entity whose cargo the scenario did not author gets the crates its weapons draw, like every other // newly built armed entity (Loadouts.StockAmmunition). Draws nothing, so it moves no item roll. - internal void StockUnauthoredAmmunition() + private protected void StockUnauthoredAmmunition() { foreach (var entity in _fitted.Where(entity => !_cargoAuthored.Contains(entity))) Loadouts.StockAmmunition(_items, entity); } - internal bool PlayerPlaced { get; private set; } - internal Ship PlayerShip { get; private set; } internal IReadOnlyList<Placement> Placed => _placed; internal sealed class Placement @@ -118,22 +113,6 @@ public sealed class ScenarioStage return null; } - // The player's ship. A run has exactly one, and it is a ship hull. - public Ship Player(ScenarioFit fit, float2 at, float2 facing = default) - { - if (PlayerPlaced) - { - _failures.Add("player: the scenario places a second player"); - return null; - } - PlayerPlaced = true; - var entity = Build(fit, "player", at, facing); - if (entity == null) return null; - if (entity is Ship ship) return PlayerShip = ship; - _failures.Add($"player: {entity.Name} is not a ship hull"); - return null; - } - // Anything else in the arena. A stance holds both ways between it and the player. A piloted ship gets the zone's // pilot; an unpiloted entity has none and goes nowhere on its own unless it is placed moving: velocity is the planar // velocity it starts with, and the sim carries it from there. A turret hull stays where it is put. @@ -193,7 +172,45 @@ public sealed class ScenarioStage } } - private Entity Build(ScenarioFit fit, string where, float2 at, float2 facing) + // Admits what was placed: each entity's stance set both ways with the player, then Zone.Admit with a pilot for each + // piloted one. A start state includes what a pilot knows (ruling stage-states-pilot-knowledge): its anchor is tracked + // from the first step, by the sensors' own path (info gathered past the detection threshold), so they can lose it + // like any track. The one owner of admitting placements. + private protected void AdmitPlaced(Ship player) + { + foreach (var placed in _placed) + { + var hostile = placed.Stance == ScenarioStance.Hostile; + placed.Entity.SetIff(player, hostile); + player.SetIff(placed.Entity, hostile); + Arena.Admit(placed.Entity, placed.Piloted, placed.Task); + } + foreach (var placed in _placed) + if (placed.Knows != null && placed.Piloted) + placed.Entity.EntityInfoGathered[placed.Knows] = (_items.GameplaySettings.TargetDetectionInfoThreshold + 1f) / 2f; + } + + // Places ships into a running zone through the admission a run start uses: the script places with the stage's verbs, + // and the entities join with their stance toward the player, a pilot when piloted and the knowledge the script stated. + // Returns the placed entities in order, or null with every failure listed and the zone unchanged. It draws from the + // live item stream and does not reseed (a reseed would give every summon the same fits). + public static IReadOnlyList<Entity> Summon(ItemManager items, Zone zone, Ship player, Action<ZoneStage> script, List<string> failures) + { + if (!zone.Entities.Contains(player)) + { + failures.Add("summon: the player is not in this zone"); + return null; + } + var stage = new ZoneStage(items, zone); + script(stage); + failures.AddRange(stage._failures); + if (stage._failures.Count > 0) return null; + stage.StockUnauthoredAmmunition(); + stage.AdmitPlaced(player); + return stage._placed.Select(placed => placed.Entity).ToList(); + } + + private protected Entity Build(ScenarioFit fit, string where, float2 at, float2 facing) { if (fit == null) return null; // the verb that made it named why @@ -233,8 +250,53 @@ public sealed class ScenarioStage } } +// The run-start stage: a ZoneStage that also stages the player, the credits the run starts with and the hull it +// starts in. Only RunStart builds one. +public sealed class ScenarioStage : ZoneStage +{ + internal ScenarioStage(ItemManager items, Zone arena, string startingHull) : base(items, arena) + { + StartingHull = startingHull; + Credits = items.GameplaySettings.StartingCredits; + } + + public string StartingHull { get; } + + // What the run starts with: the gameplay settings' starting credits unless the scenario sets another amount. + public int Credits { get; set; } + + internal bool PlayerPlaced { get; private set; } + internal Ship PlayerShip { get; private set; } + + // The player's ship. A run has exactly one, and it is a ship hull. + public Ship Player(ScenarioFit fit, float2 at, float2 facing = default) + { + if (PlayerPlaced) + { + _failures.Add("player: the scenario places a second player"); + return null; + } + PlayerPlaced = true; + var entity = Build(fit, "player", at, facing); + if (entity == null) return null; + if (entity is Ship ship) return PlayerShip = ship; + _failures.Add($"player: {entity.Name} is not a ship hull"); + return null; + } + + // Run start's admission, in this order: stock unauthored ammunition (Activate reads cargo-driven behaviours, so it + // comes before admission), the player, then everything placed. + internal void Admit() + { + StockUnauthoredAmmunition(); + PlayerShip.IsPlayerShip = true; + Arena.Admit(PlayerShip, piloted: false); + AdmitPlaced(PlayerShip); + } +} + // What a scenario places: a fit built from named designs or a preset, or a ship generated as the game generates them. -// Only ScenarioStage makes one. +// Only a ZoneStage makes one. public sealed class ScenarioFit { internal readonly Loadout Loadout; From 439c7d1b4f29352934980cdb7a9fc9af5ab6ad68 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Thu, 19 Nov 2026 23:15:08 +0100 Subject: [PATCH 141/190] Test ZoneStage.Summon: joins a running zone, refusals admit nothing, fed ships carry crates Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../AmmunitionStockingTests.cs | 21 ++++++ tests/Aetheria.Shared.Tests/ScenarioTests.cs | 70 +++++++++++++++++++ 2 files changed, 91 insertions(+) diff --git a/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs b/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs index dfdb9d040..02cd19c73 100644 --- a/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs +++ b/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs @@ -104,6 +104,27 @@ public sealed partial class RunStartTests Assert.Equal(LoadoutGenerator.AmmunitionCrates, weapon.Reserve); } + // A ship summoned into a running zone is stocked like one a run start stages: a fed fit carries the crates its weapon draws, + // and one whose scenario authored its cargo keeps exactly that. Kills: Summon skipping StockUnauthoredAmmunition. + [Fact] + public void ASummonedFedShipCarriesItsCrates() + { + var (hull, slots) = FedFit(bay: true); + var (_, arena, staged, failures) = Launch(new Scripted(false, stage => stage.Player(stage.Bare("Djinni"), float2(0, 0))), Inputs(() => GalaxySeed)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + + var summoned = ZoneStage.Summon(_items, arena, staged.Player, stage => + { + stage.Place(stage.Fit(hull, slots), float2(300, 0)); + var authored = stage.Place(stage.Fit(hull, slots), float2(-300, 0)); + stage.Cargo(authored); + }, failures); + + Assert.True(failures.Count == 0, string.Join("; ", failures)); + Assert.Equal(LoadoutGenerator.AmmunitionCrates, Assert.Single(summoned[0].Weapons).Reserve); + Assert.Equal(0, Assert.Single(summoned[1].Weapons).Reserve); + } + // The Loadout path with the DEFAULT stocking argument (what the boss in ZoneGenerator and the console `fly` call): a ship built from a // Loadout holds the crates its fed weapon draws, and one whose only weapon draws nothing holds none. Kills: Materialize // dropping its default StockAmmunition (every Loadout-built armed ship fires one magazine). diff --git a/tests/Aetheria.Shared.Tests/ScenarioTests.cs b/tests/Aetheria.Shared.Tests/ScenarioTests.cs index 03dcb9f9a..69135d879 100644 --- a/tests/Aetheria.Shared.Tests/ScenarioTests.cs +++ b/tests/Aetheria.Shared.Tests/ScenarioTests.cs @@ -399,6 +399,76 @@ public sealed partial class RunStartTests Assert.Equal(0, AgentsOf(zone, neutral)); } + // A summon places into a running zone through the stage's admission (ruling ifl-ships-in-demo-as-tactical-view): after a run + // has started and stepped, a hostile piloted generated ship that approaches the player is a member with one agent, hostile + // both ways, and its pilot knows the player by the sensors' own path. Kills: a summon that skips the stance, the pilot or + // the knowledge seed. + [Fact] + public void ASummonJoinsARunningZone() + { + var zone = Arena(true); + var player = Stage(zone, new Scripted(true, stage => stage.Player(stage.Bare("Djinni"), float2(0, 0)))).Player; + for (var tick = 0; tick < 20; tick++) zone.Update(.1f); + + var failures = new List<string>(); + var summoned = ZoneStage.Summon(_items, zone, player, stage => + { + var placed = stage.Place(stage.Generated("Longinus"), float2(400, 0), stance: ScenarioStance.Hostile, piloted: true); + stage.Approach(placed, player); + }, failures); + + Assert.True(failures.Count == 0, string.Join("; ", failures)); + var raider = Assert.Single(summoned); + SafeAssert.In(zone, raider, "the summoned ship is admitted"); + Assert.Equal(1, AgentsOf(zone, raider)); + Assert.True(player.IsHostileTo(raider) && raider.IsHostileTo(player), "hostile both ways"); + Assert.Equal((_items.GameplaySettings.TargetDetectionInfoThreshold + 1f) / 2f, raider.EntityInfoGathered[player]); + for (var tick = 0; tick < 20; tick++) zone.Update(.1f); + Assert.True(player.EntityHostility[raider] && raider.EntityHostility[player], "the live hostility agrees"); + Assert.Equal(1, AgentsOf(zone, raider)); + } + + // A summon naming a design the catalog lacks admits nothing, and names it. Kills: admitting before the failure check. + [Fact] + public void ARefusedSummonAdmitsNothing() + { + var zone = Arena(true); + var player = Stage(zone, new Scripted(true, stage => stage.Player(stage.Bare("Djinni"), float2(0, 0)))).Player; + var entities = zone.Entities.ToList(); + var agents = zone.Agents.ToList(); + var failures = new List<string>(); + + var summoned = ZoneStage.Summon(_items, zone, player, stage => + { + stage.Place(stage.Generated("Longinus"), float2(400, 0), stance: ScenarioStance.Hostile, piloted: true); + stage.Place(stage.Bare("No Such Hull"), float2(-400, 0)); + }, failures); + + Assert.Null(summoned); + Assert.Contains(failures, failure => failure.Contains("No Such Hull")); + SafeAssert.Unchanged(zone, entities, agents); + } + + // A summon needs the player to be in the zone it summons into: with the player docked it refuses, names why and admits nothing. + // Kills: dropping the membership check, which would write stance onto a non-member. + [Fact] + public void ASummonNeedsThePlayerInTheZone() + { + var zone = Arena(true); + var player = Stage(zone, new Scripted(true, stage => stage.Player(stage.Bare("Djinni"), float2(0, 0)))).Player; + Assert.True(zone.Remove(player)); + var entities = zone.Entities.ToList(); + var agents = zone.Agents.ToList(); + var failures = new List<string>(); + + var summoned = ZoneStage.Summon(_items, zone, player, stage => + stage.Place(stage.Bare("Longinus"), float2(400, 0), stance: ScenarioStance.Hostile), failures); + + Assert.Null(summoned); + Assert.Equal(new[] { "summon: the player is not in this zone" }, failures); + SafeAssert.Unchanged(zone, entities, agents); + } + // A stance lasts the sitting: the player docking and undocking leaves it standing both ways. It goes with an entity // gone for good: once an entity is destroyed, the player holds no stance toward it. [Fact] From 0c9ab54048cfcc16cf5850c7935676d30de6e1b6 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 01:14:15 +0100 Subject: [PATCH 142/190] Fix Soul s1: boss presets refused, refusal restores the item stream, anchor must be the player ship, drop the dead stocking-order claim Nothing at admission or activation reads cargo (ammunition is read at fire time), so the comment's ordering rule is removed. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/ScenarioStage.cs | 37 +++++++++--- tests/Aetheria.Shared.Tests/ScenarioTests.cs | 62 ++++++++++++++++++++ 2 files changed, 91 insertions(+), 8 deletions(-) diff --git a/Assets/Scripts/ServerShared/ScenarioStage.cs b/Assets/Scripts/ServerShared/ScenarioStage.cs index 46996d482..ed13ae27b 100644 --- a/Assets/Scripts/ServerShared/ScenarioStage.cs +++ b/Assets/Scripts/ServerShared/ScenarioStage.cs @@ -108,9 +108,18 @@ public class ZoneStage public ScenarioFit Preset(string name) { var preset = _items.ItemData.GetAll<Loadout>().FirstOrDefault(loadout => loadout.Name == name); - if (preset != null) return new ScenarioFit(preset); - _failures.Add($"preset {name}: no such preset"); - return null; + if (preset == null) + { + _failures.Add($"preset {name}: no such preset"); + return null; + } + // A faction's boss is the zone generator's to place (boss-hulls-exclusive): Loadouts.BossOf owns which loadout it is. + if (_items.ItemData.GetAll<Faction>().Any(faction => Loadouts.BossOf(_items.ItemData, faction, out _)?.Name == preset.Name)) + { + _failures.Add($"preset {name}: a faction's boss loadout is placed only by the zone generator"); + return null; + } + return new ScenarioFit(preset); } // Anything else in the arena. A stance holds both ways between it and the player. A piloted ship gets the zone's @@ -192,19 +201,30 @@ public class ZoneStage // Places ships into a running zone through the admission a run start uses: the script places with the stage's verbs, // and the entities join with their stance toward the player, a pilot when piloted and the knowledge the script stated. - // Returns the placed entities in order, or null with every failure listed and the zone unchanged. It draws from the - // live item stream and does not reseed (a reseed would give every summon the same fits). + // Returns the placed entities in order, or null with every failure listed and the zone and the item stream unchanged. + // It draws from the live item stream and does not reseed (a reseed would give every summon the same fits). The anchor + // is the player's ship: the stance is written against it. public static IReadOnlyList<Entity> Summon(ItemManager items, Zone zone, Ship player, Action<ZoneStage> script, List<string> failures) { + if (player == null || !player.IsPlayerShip) + { + failures.Add("summon: the anchor is not the player's ship"); + return null; + } if (!zone.Entities.Contains(player)) { failures.Add("summon: the player is not in this zone"); return null; } + var stream = items.Random; var stage = new ZoneStage(items, zone); script(stage); failures.AddRange(stage._failures); - if (stage._failures.Count > 0) return null; + if (stage._failures.Count > 0) + { + items.Random = stream; // a refusal draws nothing: the fits it built are discarded with it + return null; + } stage.StockUnauthoredAmmunition(); stage.AdmitPlaced(player); return stage._placed.Select(placed => placed.Entity).ToList(); @@ -284,8 +304,9 @@ public sealed class ScenarioStage : ZoneStage return null; } - // Run start's admission, in this order: stock unauthored ammunition (Activate reads cargo-driven behaviours, so it - // comes before admission), the player, then everything placed. + // Run start's admission: stock unauthored ammunition, the player, then everything placed. Nothing at admission or + // activation reads cargo (ammunition is read when a weapon fires), so stocking is not ordered by admission; it keeps + // the run start's order. internal void Admit() { StockUnauthoredAmmunition(); diff --git a/tests/Aetheria.Shared.Tests/ScenarioTests.cs b/tests/Aetheria.Shared.Tests/ScenarioTests.cs index 69135d879..74df3f8eb 100644 --- a/tests/Aetheria.Shared.Tests/ScenarioTests.cs +++ b/tests/Aetheria.Shared.Tests/ScenarioTests.cs @@ -469,6 +469,68 @@ public sealed partial class RunStartTests SafeAssert.Unchanged(zone, entities, agents); } + // A refused summon leaves the item stream where it was, so a refusal is not a draw: the next fit is the one it would have been. + // Kills: a summon that keeps the draws of the fits it built before refusing. + [Fact] + public void ARefusedSummonLeavesTheItemStream() + { + var zone = Arena(true); + var player = Stage(zone, new Scripted(true, stage => stage.Player(stage.Bare("Djinni"), float2(0, 0)))).Player; + var before = _items.Random; + var failures = new List<string>(); + + Assert.Null(ZoneStage.Summon(_items, zone, player, stage => + { + stage.Place(stage.Generated("Longinus"), float2(400, 0)); + stage.Place(stage.Bare("No Such Hull"), float2(-400, 0)); + }, failures)); + + var after = _items.Random; + Assert.Equal(before.NextUInt(), after.NextUInt()); + } + + // The anchor of a summon is the player's ship, not any ship in the zone. Kills: a summon that takes any zone member as the player. + [Fact] + public void ASummonNeedsThePlayersShipAsItsAnchor() + { + var zone = Arena(true); + var player = Stage(zone, new Scripted(true, stage => stage.Player(stage.Bare("Djinni"), float2(0, 0)))).Player; + var other = zone.Entities.OfType<Ship>().First(ship => !ship.IsPlayerShip); + var entities = zone.Entities.ToList(); + var agents = zone.Agents.ToList(); + var failures = new List<string>(); + + Assert.Null(ZoneStage.Summon(_items, zone, other, stage => stage.Place(stage.Bare("Longinus"), float2(400, 0), stance: ScenarioStance.Hostile), failures)); + + Assert.Equal(new[] { "summon: the anchor is not the player's ship" }, failures); + SafeAssert.Unchanged(zone, entities, agents); + } + + // A faction's boss is the zone generator's to place (boss-hulls-exclusive): a preset naming the loadout Loadouts.BossOf + // returns is refused, through a summon as through a run start. Kills: a Preset that places any catalog loadout. + [Fact] + public void APresetCannotPlaceAFactionsBoss() + { + var zone = Arena(true); + var player = Stage(zone, new Scripted(true, stage => stage.Player(stage.Bare("Djinni"), float2(0, 0)))).Player; + var boss = _cache.GetAll<Faction>().Select(faction => Loadouts.BossOf(_cache, faction, out _)).First(loadout => loadout != null); + var entities = zone.Entities.ToList(); + var agents = zone.Agents.ToList(); + var failures = new List<string>(); + + Assert.Null(ZoneStage.Summon(_items, zone, player, stage => + stage.Place(stage.Preset(boss.Name), float2(400, 0), stance: ScenarioStance.Hostile, piloted: true), failures)); + + Assert.Contains(failures, failure => failure.Contains(boss.Name) && failure.Contains("boss")); + SafeAssert.Unchanged(zone, entities, agents); + var started = Refused(Arena(true), new Scripted(true, stage => + { + stage.Player(stage.Bare("Djinni"), float2(0, 0)); + stage.Place(stage.Preset(boss.Name), float2(400, 0)); + })); + Assert.Contains(started, failure => failure.Contains("boss")); + } + // A stance lasts the sitting: the player docking and undocking leaves it standing both ways. It goes with an entity // gone for good: once an entity is destroyed, the player holds no stance toward it. [Fact] From 09a1c32560f197b8ba79cafbdb921702450ce879 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 01:49:18 +0100 Subject: [PATCH 143/190] Make a refused summon ledger-neutral: ItemManager.Mark/Rewind restore the stream and the lot ledger together Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/ItemManager.cs | 19 +++++++++++++++++++ Assets/Scripts/ServerShared/ScenarioStage.cs | 6 +++--- tests/Aetheria.Shared.Tests/ScenarioTests.cs | 8 ++++++-- 3 files changed, 28 insertions(+), 5 deletions(-) diff --git a/Assets/Scripts/ServerShared/ItemManager.cs b/Assets/Scripts/ServerShared/ItemManager.cs index c91568efd..d5c1e05dd 100644 --- a/Assets/Scripts/ServerShared/ItemManager.cs +++ b/Assets/Scripts/ServerShared/ItemManager.cs @@ -45,6 +45,25 @@ public class ItemManager _logger = logger; } + // A restore point over everything building items draws or mints: the item stream and the lot ledger, which a run save + // persists. Rewind puts both back, so a refused build is neither a draw nor a lot. + public readonly struct Checkpoint + { + internal readonly Random Stream; + internal readonly int NextLot; + internal Checkpoint(Random stream, int nextLot) { Stream = stream; NextLot = nextLot; } + } + + public Checkpoint Mark() => new Checkpoint(Random, Lots.NextLot); + + public void Rewind(Checkpoint mark) + { + Random = mark.Stream; + foreach (var id in Lots.Lots.Keys.Where(id => id >= mark.NextLot).ToList()) Lots.Lots.Remove(id); + Lots.NextLot = mark.NextLot; + foreach (var key in _extracted.Where(entry => entry.Value >= mark.NextLot).Select(entry => entry.Key).ToList()) _extracted.Remove(key); + } + public void Log(string s) { _logger(s); diff --git a/Assets/Scripts/ServerShared/ScenarioStage.cs b/Assets/Scripts/ServerShared/ScenarioStage.cs index ed13ae27b..56bb50ea8 100644 --- a/Assets/Scripts/ServerShared/ScenarioStage.cs +++ b/Assets/Scripts/ServerShared/ScenarioStage.cs @@ -201,7 +201,7 @@ public class ZoneStage // Places ships into a running zone through the admission a run start uses: the script places with the stage's verbs, // and the entities join with their stance toward the player, a pilot when piloted and the knowledge the script stated. - // Returns the placed entities in order, or null with every failure listed and the zone and the item stream unchanged. + // Returns the placed entities in order, or null with every failure listed and the zone and the item stream and lot ledger unchanged. // It draws from the live item stream and does not reseed (a reseed would give every summon the same fits). The anchor // is the player's ship: the stance is written against it. public static IReadOnlyList<Entity> Summon(ItemManager items, Zone zone, Ship player, Action<ZoneStage> script, List<string> failures) @@ -216,13 +216,13 @@ public class ZoneStage failures.Add("summon: the player is not in this zone"); return null; } - var stream = items.Random; + var mark = items.Mark(); var stage = new ZoneStage(items, zone); script(stage); failures.AddRange(stage._failures); if (stage._failures.Count > 0) { - items.Random = stream; // a refusal draws nothing: the fits it built are discarded with it + items.Rewind(mark); // a refusal draws and mints nothing: the fits it built are discarded with it return null; } stage.StockUnauthoredAmmunition(); diff --git a/tests/Aetheria.Shared.Tests/ScenarioTests.cs b/tests/Aetheria.Shared.Tests/ScenarioTests.cs index 74df3f8eb..7144fffbf 100644 --- a/tests/Aetheria.Shared.Tests/ScenarioTests.cs +++ b/tests/Aetheria.Shared.Tests/ScenarioTests.cs @@ -469,14 +469,16 @@ public sealed partial class RunStartTests SafeAssert.Unchanged(zone, entities, agents); } - // A refused summon leaves the item stream where it was, so a refusal is not a draw: the next fit is the one it would have been. - // Kills: a summon that keeps the draws of the fits it built before refusing. + // A refused summon leaves the item stream and the lot ledger (which a run save persists) where they were, so a refusal is neither + // a draw nor a mint. Kills: a summon that keeps the draws or the lots of the fits it built before refusing. [Fact] public void ARefusedSummonLeavesTheItemStream() { var zone = Arena(true); var player = Stage(zone, new Scripted(true, stage => stage.Player(stage.Bare("Djinni"), float2(0, 0)))).Player; var before = _items.Random; + var nextLot = _items.Lots.NextLot; + var lots = _items.Lots.Lots.Keys.ToList(); var failures = new List<string>(); Assert.Null(ZoneStage.Summon(_items, zone, player, stage => @@ -487,6 +489,8 @@ public sealed partial class RunStartTests var after = _items.Random; Assert.Equal(before.NextUInt(), after.NextUInt()); + Assert.Equal(nextLot, _items.Lots.NextLot); + Assert.Equal(lots.OrderBy(id => id), _items.Lots.Lots.Keys.OrderBy(id => id)); } // The anchor of a summon is the player's ship, not any ship in the zone. Kills: a summon that takes any zone member as the player. From 84a48f3f6044c823019de8ead7de95905417fed5 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 02:24:26 +0100 Subject: [PATCH 144/190] aetherlight: derive command, creation and world ids from content; drop committed_at; rename schemas A command is named by sha256 over world, expected revision, caller and body; a creation by its own bytes; a world by its creation. The id fields, the random CommandId::new / WorldId::issue and WorldCommit.committed_at are gone, so equal commands commit equal bytes. Retry identity goes with them: SubmitReceipt collapses into CommitReceipt and a resubmitted command is a RevisionMismatch. Schemas are aetherlight.world_state.v1 and aetherlight.world_commit.v1; ghostlight rows stay refused. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/action.rs | 130 +++--- native/aetherlight/src/grammar/tests.rs | 24 +- native/aetherlight/src/import_key_tests.rs | 21 +- native/aetherlight/src/journal.rs | 184 ++++---- native/aetherlight/src/lib.rs | 505 +++++++++------------ native/aetherlight/src/patch.rs | 78 ++-- 6 files changed, 398 insertions(+), 544 deletions(-) diff --git a/native/aetherlight/src/action.rs b/native/aetherlight/src/action.rs index 66882dab2..64b18f413 100644 --- a/native/aetherlight/src/action.rs +++ b/native/aetherlight/src/action.rs @@ -1015,13 +1015,13 @@ mod tests { }; use crate::tests::{ ADMIT_KIND, COMMAND_KIND, Civic, LEVY_KIND, OPENING_BALANCE, SEIZURE_GRIEVANCE, Topology, - WARDEN_OFFICE, act, act_command, affordance_named, authority_kind, civic_world, + WARDEN_OFFICE, act, affordance_named, authority_kind, civic_world, command, custody_world, grant_to, grievance, office, operations, over_place, - over_subject, play_caller, reject_play, submit_play, + over_subject, play_caller, reject_play, submit_play, tick_body, }; use crate::{ AffordanceKindName, AuthenticatedCaller, AuthoredSource, CommandBody, Confidence, - Declaration, EffectSlot, EntityKind, ProposedEffect, RoleBinding, Statement, SubmitReceipt, + Declaration, EffectSlot, EntityKind, ProposedEffect, RoleBinding, Statement, CommitReceipt, WorldEffect, WorldKernel, WorldPatch, WorldSnapshot, apply_effect, }; use std::collections::BTreeSet; @@ -1069,6 +1069,40 @@ mod tests { exercise(state, command_id, actor, &granted, invocation) } + /// Commit `invocation` as the first command whose derived id draws `band`. + /// A band is a pure function of the pre-commit state and the command id, + /// and a command's id derives from the revision it targets, so a test + /// reaches a band by committing ordinary ticks until the id it would + /// carry draws it. + fn act_drawing( + kernel: &mut WorldKernel, + actor: SubjectId, + invocation: &DecisionInvocation, + band: usize, + ) -> CommitReceipt { + for _ in 0..256 { + let snapshot = kernel.snapshot().unwrap(); + let envelope = command( + &snapshot, + play_caller(), + CommandBody::Act { + actor, + invocation: invocation.clone(), + }, + ); + let draws = draw_once(&kernel.state, envelope.id(), actor, invocation) + .expect("the invocation is admissible") + .band; + if draws == band { + return kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .expect("the invocation commits"); + } + submit_play(kernel, &snapshot, tick_body(1)); + } + panic!("a two-band entry reaches both bands within 256 revisions"); + } + fn binding(role: &str, target: Target) -> RoleBinding { RoleBinding { role: Role(role.into()), @@ -1120,7 +1154,7 @@ mod tests { } } - fn commit(&mut self, invocation: DecisionInvocation) -> SubmitReceipt { + fn commit(&mut self, invocation: DecisionInvocation) -> CommitReceipt { act(&mut self.kernel, self.clerk, invocation).expect("the invocation commits") } @@ -1324,7 +1358,7 @@ mod tests { let clerk_before = bench.held(bench.clerk); let keeper_before = bench.held(bench.keeper); let receipt = bench.commit(bench.carry(3, bench.yard)); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); assert_eq!(bench.held(bench.clerk), clerk_before - 3); assert_eq!(bench.held(bench.keeper), keeper_before + 3); assert_eq!( @@ -1470,7 +1504,7 @@ mod tests { assert!(event.effects.is_empty()); let receipt = bench.commit(idle); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); assert_eq!(bench.kernel.state.holdings, holdings); assert_eq!(bench.kernel.state.positions, positions); assert_eq!(bench.kernel.state.edges, edges); @@ -1483,7 +1517,7 @@ mod tests { let directory = tempfile::tempdir().unwrap(); let mut bench = bench(directory.path(), "Lowering"); let receipt = bench.commit(bench.carry(2, bench.yard)); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); let event = bench .kernel .state @@ -1539,30 +1573,12 @@ mod tests { let mut seen: BTreeSet<usize> = BTreeSet::new(); for wanted in [0usize, 1] { - // The draw is a pure function of the pre-commit revision and the - // command id, so the command id that reaches a band is findable - // before the envelope is built rather than hunted by retrying. - let command_id = (0..256) - .map(|_| CommandId::issue()) - .find(|candidate| { - draw_once(&bench.kernel.state, *candidate, bench.clerk, &split) - .expect("the invocation is admissible") - .band - == wanted - }) - .expect("a two-band entry reaches both bands over 256 command ids"); - + // The draw is a pure function of the pre-commit state and the + // command id; `act_drawing` finds the revision whose id reaches it. let before_clerk = bench.held(bench.clerk); let before_keeper = bench.held(bench.keeper); - let receipt = act_command( - &mut bench.kernel, - command_id, - play_caller(), - bench.clerk, - split.clone(), - ) - .expect("the invocation commits"); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + let receipt = act_drawing(&mut bench.kernel, bench.clerk, &split, wanted); + assert!(receipt.resulting_revision > 0); bench.refresh(); let event = bench .kernel @@ -1743,7 +1759,7 @@ mod tests { }, ) .expect("the Speak entry commits"); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); let event = kernel.state.events.last().unwrap(); assert_eq!(event.band, 0); // The two the speech lowering prepends, and nothing from a slot. @@ -1890,7 +1906,7 @@ mod tests { } } - fn commit_as(&mut self, actor: SubjectId, invocation: DecisionInvocation) -> SubmitReceipt { + fn commit_as(&mut self, actor: SubjectId, invocation: DecisionInvocation) -> CommitReceipt { let receipt = act(&mut self.kernel, actor, invocation).expect("the invocation commits"); self.refresh(); receipt @@ -1899,7 +1915,7 @@ mod tests { fn admit(&mut self, ops: Vec<ComponentOp>) { let before = self.kernel.snapshot().unwrap(); let receipt = submit_play(&mut self.kernel, &before, operations(ops)); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); self.refresh(); } @@ -2094,10 +2110,7 @@ mod tests { // The chamber is inside it, so the same act commits and the deputy can // then levy there. let inside = bench.delegate(outsider, bench.civic.chamber); - assert!(matches!( - bench.commit_as(treasury, inside), - SubmitReceipt::Applied(_) - )); + assert!(bench.commit_as(treasury, inside).resulting_revision > 0); assert!( bench .try_as(outsider, &bench.levy(bench.civic.farmer, 1)) @@ -2151,10 +2164,7 @@ mod tests { // The treasury's own `levy` grant over the hall covers the hall, so // the treasury may strip its own grant, and the ledger loses it. - assert!(matches!( - bench.commit_as(treasury, bench.revoke(treasury, hall)), - SubmitReceipt::Applied(_) - )); + assert!(bench.commit_as(treasury, bench.revoke(treasury, hall)).resulting_revision > 0); assert!( !bench .kernel @@ -2202,10 +2212,7 @@ mod tests { .map(|position| position.place), Some(chamber) ); - assert!(matches!( - bench.commit_as(treasury, bench.deploy(farmer, passage)), - SubmitReceipt::Applied(_) - )); + assert!(bench.commit_as(treasury, bench.deploy(farmer, passage)).resulting_revision > 0); assert_eq!( bench .kernel @@ -2235,10 +2242,7 @@ mod tests { ); let farmer = bench.civic.farmer; - assert!(matches!( - bench.commit_as(farmer, petition.clone()), - SubmitReceipt::Applied(_) - )); + assert!(bench.commit_as(farmer, petition.clone()).resulting_revision > 0); let event = bench .kernel .state @@ -2351,24 +2355,8 @@ mod tests { // The treasury commands the hall, and the passage has both endpoints // under it. The draw decides whether the interdiction lands. - let closing = (0..256) - .map(|_| CommandId::issue()) - .find(|candidate| { - draw_once(&bench.kernel.state, *candidate, treasury, &sanction) - .expect("the invocation is admissible") - .band - == 0 - }) - .expect("a two-band entry reaches its first band over 256 command ids"); - let receipt = act_command( - &mut bench.kernel, - closing, - play_caller(), - treasury, - sanction, - ) - .expect("the sanction commits"); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + let receipt = act_drawing(&mut bench.kernel, treasury, &sanction, 0); + assert!(receipt.resulting_revision > 0); bench.refresh(); assert!(!bench.kernel.state.edges[&passage].is_open()); @@ -2386,10 +2374,7 @@ mod tests { }], None, ); - assert!(matches!( - bench.commit_as(treasury, appoint), - SubmitReceipt::Applied(_) - )); + assert!(bench.commit_as(treasury, appoint).resulting_revision > 0); assert_eq!( bench.kernel.state.selection[&treasury][&office("bailiff")].incumbent, Some(farmer) @@ -2404,7 +2389,7 @@ mod tests { bench: &mut Civics, actor: SubjectId, invocation: DecisionInvocation, - ) -> Result<SubmitReceipt, KernelError> { + ) -> Result<CommitReceipt, KernelError> { act(&mut bench.kernel, actor, invocation) } @@ -2587,7 +2572,6 @@ mod tests { let caller = play_caller(); let envelope = command( &bench.active, - CommandId::new(), caller.clone(), CommandBody::Act { actor: treasury, @@ -2601,7 +2585,7 @@ mod tests { .kernel .submit(envelope, &AuthenticatedCaller::fixture(caller)) .expect("the act commits"); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); bench.refresh(); let WorldEffect::Acted { event, .. } = first else { panic!("an acted effect"); diff --git a/native/aetherlight/src/grammar/tests.rs b/native/aetherlight/src/grammar/tests.rs index 9c31ff39d..3743f2a9a 100644 --- a/native/aetherlight/src/grammar/tests.rs +++ b/native/aetherlight/src/grammar/tests.rs @@ -5,7 +5,7 @@ use crate::patch::{ }; use crate::tests::{auth_principal, command, creation, owner}; use crate::{ - CallerId, CommandBody, CommandId, CreateWorld, KernelError, SubjectKind, SubmitReceipt, + CallerId, CommandBody, CommandId, CreateWorld, KernelError, SubjectKind, CommitReceipt, WorldKernel, WorldPatch, }; @@ -38,7 +38,7 @@ fn grammar_with(extra: &[(&str, GrammarVerb)]) -> GrammarBinding { } fn bound(grammar: Option<GrammarBinding>, title: &str) -> CreateWorld { - let mut world = creation(CommandId::new(), title); + let mut world = creation(title); world.grammar = grammar; world } @@ -96,12 +96,11 @@ fn create(world: CreateWorld) -> (tempfile::TempDir, Result<WorldKernel, KernelE (directory, result) } -fn admit(kernel: &mut WorldKernel, patch: WorldPatch) -> Result<SubmitReceipt, KernelError> { +fn admit(kernel: &mut WorldKernel, patch: WorldPatch) -> Result<CommitReceipt, KernelError> { let snapshot = kernel.snapshot().unwrap(); kernel.submit( command( &snapshot, - CommandId::new(), CallerId::Play, CommandBody::AdmitPatch { patch, @@ -151,7 +150,7 @@ fn grammar_world_refuses_an_affordance_kind_outside_the_grammar() { not_in_grammar("wave") ); let receipt = admit(&mut kernel, patch_of(vec![declare("hail", "hail", &[])])).unwrap(); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); } #[test] @@ -203,7 +202,7 @@ fn grammar_world_refuses_a_role_signature_the_grammar_does_not_carry() { )]), ) .unwrap(); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); } #[test] @@ -235,7 +234,7 @@ fn each_grammar_referent_kind_admits_exactly_its_own_kernel_kind() { ); if offered == own { assert!( - matches!(result, Ok(SubmitReceipt::Applied(_))), + matches!(result, Ok(_)), "{referent:?} refused its own kind" ); } else { @@ -298,7 +297,7 @@ fn unbound_world_keeps_the_open_catalog() { patch_of(vec![declare("beacon", "beacon", &[])]), ) .unwrap(); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); let snapshot = kernel.snapshot().unwrap(); assert!(snapshot.grammar.is_none()); assert!(snapshot.affordances.len() >= 4); @@ -487,12 +486,11 @@ fn submit_as( kernel: &mut WorldKernel, caller: CallerId, patch: WorldPatch, -) -> Result<SubmitReceipt, KernelError> { +) -> Result<CommitReceipt, KernelError> { let snapshot = kernel.snapshot().unwrap(); kernel.submit( command( &snapshot, - CommandId::new(), caller.clone(), CommandBody::AdmitPatch { patch }, ), @@ -576,7 +574,7 @@ fn play_refuses_outside_the_grammar_after_the_revision_has_moved() { patch_of(vec![declare("hail", "hail", &[])]), ) .unwrap(); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); } #[test] @@ -636,7 +634,7 @@ fn an_effect_resolved_elsewhere_cannot_install_an_entry_outside_the_grammar() { let resolve = |kind: &str, roles: &[(&str, RefKind)]| { crate::patch::resolve_patch( &twin, - CommandId::new(), + CommandId::issue(), &patch_of(vec![declare("probe", kind, roles)]), ) .expect("the unbound twin admits any canonical kind") @@ -650,7 +648,7 @@ fn an_effect_resolved_elsewhere_cannot_install_an_entry_outside_the_grammar() { let catalog = state.affordance_catalog.len(); let result = crate::apply_effect( &mut state, - CommandId::new(), + CommandId::issue(), &CallerId::Play, &crate::WorldEffect::PatchAdmitted { resolved, diff --git a/native/aetherlight/src/import_key_tests.rs b/native/aetherlight/src/import_key_tests.rs index 85149e51e..5c5e28340 100644 --- a/native/aetherlight/src/import_key_tests.rs +++ b/native/aetherlight/src/import_key_tests.rs @@ -9,7 +9,7 @@ use crate::patch::{ use crate::tests::{auth_principal, command, creation, owner}; use crate::{ CallerId, CommandBody, CommandId, CreateWorld, EntityId, KernelError, - SubjectDeclaration, SubjectKind, SubmitReceipt, + SubjectDeclaration, SubjectKind, CommitReceipt, WorldKernel, WorldPatch, }; use std::collections::BTreeSet; @@ -24,7 +24,7 @@ fn alpha() -> ImportKey { /// The fixture genesis with its witness imported from `alpha()`. fn keyed_creation(title: &str) -> CreateWorld { - let mut world = creation(CommandId::new(), title); + let mut world = creation(title); for declaration in &mut world.patch.declarations { if let Declaration::Subject(subject) = declaration && subject.handle == DraftHandle::new("persona") @@ -71,12 +71,11 @@ fn submit_as( kernel: &mut WorldKernel, caller: CallerId, patch: WorldPatch, -) -> Result<SubmitReceipt, KernelError> { +) -> Result<CommitReceipt, KernelError> { let snapshot = kernel.snapshot().unwrap(); kernel.submit( command( &snapshot, - CommandId::new(), caller.clone(), CommandBody::AdmitPatch { patch }, ), @@ -132,7 +131,7 @@ fn keys_in(kernel: &WorldKernel) -> Vec<ImportKey> { #[test] fn one_patch_cannot_declare_two_subjects_with_one_import_key() { // At genesis. - let mut world = creation(CommandId::new(), "Twins"); + let mut world = creation("Twins"); for declaration in &mut world.patch.declarations { if let Declaration::Subject(subject) = declaration && (subject.handle == DraftHandle::new("persona") @@ -236,7 +235,7 @@ fn a_held_import_key_is_refused_at_every_door_after_the_revision_has_moved() { patch_of(vec![keyed("fresh", Some(fresh.clone()), dead_end)]), ) .unwrap(); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); let again = submit_as( &mut kernel, CallerId::Play, @@ -404,7 +403,7 @@ fn the_subjects_map_refuses_a_second_subject_for_one_key_even_when_resolved_else let resolve = |handle: &str| { crate::patch::resolve_patch( &kernel.state, - CommandId::new(), + CommandId::issue(), &patch_of(vec![keyed( handle, Some(key("aetheria.ship", "Omega")), @@ -421,7 +420,7 @@ fn the_subjects_map_refuses_a_second_subject_for_one_key_even_when_resolved_else }; crate::apply_effect( &mut state, - CommandId::new(), + CommandId::issue(), &CallerId::Play, &effect(first), ) @@ -429,7 +428,7 @@ fn the_subjects_map_refuses_a_second_subject_for_one_key_even_when_resolved_else assert_eq!(state.subjects.len(), before + 1); let result = crate::apply_effect( &mut state, - CommandId::new(), + CommandId::issue(), &CallerId::Play, &effect(second), ); @@ -452,7 +451,7 @@ fn contains(haystack: &[u8], needle: &[u8]) -> bool { fn keyless_world_digests_unchanged() { // A subject nobody imported serialises without the field at all, so every // digest written before keys existed is the digest of the same bytes. - let (_dir, kernel) = create(creation(CommandId::new(), "Keyless")); + let (_dir, kernel) = create(creation("Keyless")); let kernel = kernel.unwrap(); let state = rmp_serde::to_vec_named(&kernel.state).unwrap(); assert!( @@ -616,7 +615,7 @@ fn admitting_a_resolved_effect_refuses_two_subjects_with_one_key() { let resolve = || { crate::patch::resolve_patch( &kernel.state, - CommandId::new(), + CommandId::issue(), &patch_of(vec![ keyed("first", Some(key("aetheria.ship", "Beta")), place), keyed("second", Some(key("aetheria.ship", "Gamma")), place), diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index fa4e8303f..96efb340f 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -911,7 +911,7 @@ fn apply_committed_command( } apply_effect( state, - command.id, + command.id(), &commit.command.caller(), &expected_effect, ) @@ -983,6 +983,15 @@ mod tests { value: u8, } + /// The commit a forgery test rewrites: the one the test just committed. + pub(super) fn last_commit(commits: &mut BTreeMap<CommandId, WorldCommit>) -> &mut WorldCommit { + commits.values_mut().max_by_key(|commit| commit.resulting_revision).unwrap() + } + + pub(super) fn genesis_commit(commits: &mut BTreeMap<CommandId, WorldCommit>) -> &mut WorldCommit { + commits.values_mut().min_by_key(|commit| commit.resulting_revision).unwrap() + } + fn owner_patch(subject: SubjectDeclaration) -> WorldPatch { WorldPatch { declarations: vec![Declaration::Subject(subject)], @@ -1010,7 +1019,6 @@ mod tests { let owner = PrincipalId::new("owner@example.test"); let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); let creation = CreateWorld { - id: CommandId::new(), owner: owner.clone(), title: "Before".into(), patch: owner_patch(SubjectDeclaration { @@ -1025,11 +1033,9 @@ mod tests { }; let (mut kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap(); let snapshot = kernel.snapshot().unwrap(); - let command_id = CommandId::new(); kernel .submit( CommandEnvelope { - id: command_id, world_id: snapshot.world_id, expected_revision: snapshot.revision, caller: CallerId::Play, @@ -1043,7 +1049,7 @@ mod tests { let mut command_forged_head = kernel.state.clone(); let mut command_forged_commits = kernel.journal.commits.clone(); - let command_forged = command_forged_commits.get_mut(&command_id).unwrap(); + let command_forged = last_commit(&mut command_forged_commits); let CommittedCommand::WorldCommand(command) = &mut command_forged.command else { panic!("expected a world command"); }; @@ -1060,7 +1066,7 @@ mod tests { let mut caller_forged_head = kernel.state.clone(); let mut caller_forged_commits = kernel.journal.commits.clone(); - let caller_forged = caller_forged_commits.get_mut(&command_id).unwrap(); + let caller_forged = last_commit(&mut caller_forged_commits); let CommittedCommand::WorldCommand(command) = &mut caller_forged.command else { panic!("expected a world command"); }; @@ -1075,7 +1081,7 @@ mod tests { let mut effect_forged_head = kernel.state.clone(); let mut effect_forged_commits = kernel.journal.commits.clone(); - let effect_forged = effect_forged_commits.get_mut(&command_id).unwrap(); + let effect_forged = last_commit(&mut effect_forged_commits); let WorldEffect::TimeAdvanced { to, .. } = &mut effect_forged.effect else { panic!("expected a time effect"); }; @@ -1096,7 +1102,6 @@ mod tests { let owner = PrincipalId::new("owner@example.test"); let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); let creation = CreateWorld { - id: CommandId::new(), owner: owner.clone(), title: "Kharad".into(), patch: owner_patch(SubjectDeclaration { @@ -1111,11 +1116,9 @@ mod tests { }; let (mut kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap(); let snapshot = kernel.snapshot().unwrap(); - let command_id = CommandId::new(); kernel .submit( CommandEnvelope { - id: command_id, world_id: snapshot.world_id, expected_revision: snapshot.revision, caller: CallerId::Play, @@ -1148,7 +1151,7 @@ mod tests { let mut forged_head = kernel.state.clone(); let mut forged_commits = kernel.journal.commits.clone(); - let forged = forged_commits.get_mut(&command_id).unwrap(); + let forged = last_commit(&mut forged_commits); let WorldEffect::PatchAdmitted { resolved, .. } = &mut forged.effect else { panic!("expected an admitted patch effect"); }; @@ -1255,7 +1258,7 @@ mod tests { let directory = tempfile::tempdir().unwrap(); let (mut kernel, _) = WorldKernel::create( directory.path().join("world.cc"), - creation(CommandId::new(), "Clock History"), + creation("Clock History"), &auth_principal(owner()), ) .unwrap(); @@ -1392,18 +1395,16 @@ mod tests { let authenticated = auth_principal(owner()); let (mut kernel, _) = WorldKernel::create( &path, - crate::tests::creation(CommandId::new(), "Chronicle"), + crate::tests::creation("Chronicle"), &authenticated, ) .unwrap(); let active = kernel.snapshot().unwrap(); - let command_id = CommandId::new(); let caller = CallerId::Play; kernel .submit( command( &active, - command_id, caller.clone(), CommandBody::AdvanceTime { minutes: TickMinutes::new(30).unwrap(), @@ -1415,7 +1416,7 @@ mod tests { let mut forged_head = kernel.state.clone(); let mut forged_commits = kernel.journal.commits.clone(); - let forged = forged_commits.get_mut(&command_id).unwrap(); + let forged = last_commit(&mut forged_commits); let WorldEffect::TimeAdvanced { to, .. } = &mut forged.effect else { panic!("expected a time-advanced effect"); }; @@ -1440,18 +1441,16 @@ mod tests { let authenticated = auth_principal(owner()); let (mut kernel, _) = WorldKernel::create( &path, - crate::tests::creation(CommandId::new(), "Kharad"), + crate::tests::creation("Kharad"), &authenticated, ) .unwrap(); let topology = admit_topology(&mut kernel); let active = kernel.snapshot().unwrap(); - let command_id = CommandId::new(); kernel .submit( command( &active, - command_id, CallerId::Play, CommandBody::AdmitPatch { patch: WorldPatch { @@ -1470,7 +1469,7 @@ mod tests { let mut forged_head = kernel.state.clone(); let mut forged_commits = kernel.journal.commits.clone(); - let forged = forged_commits.get_mut(&command_id).unwrap(); + let forged = last_commit(&mut forged_commits); let WorldEffect::PatchAdmitted { resolved, .. } = &mut forged.effect else { panic!("expected an admitted patch effect"); }; @@ -1511,7 +1510,7 @@ mod tests { let authenticated = auth_principal(owner()); let (mut kernel, _) = WorldKernel::create( &path, - crate::tests::creation(CommandId::new(), "ForgedDecision"), + crate::tests::creation("ForgedDecision"), &authenticated, ) .unwrap(); @@ -1520,7 +1519,6 @@ mod tests { let active = kernel.snapshot().unwrap(); let entry = affordance_named(&active, kind); let caller = play_caller(); - let command_id = CommandId::new(); let role = |name: &str, target| RoleBinding { role: crate::Role(name.into()), target, @@ -1529,7 +1527,6 @@ mod tests { .submit( command( &active, - command_id, caller.clone(), CommandBody::Act { actor: custody.holder, @@ -1559,7 +1556,7 @@ mod tests { let mut forged_head = kernel.state.clone(); let mut forged_commits = kernel.journal.commits.clone(); - let forged = forged_commits.get_mut(&command_id).unwrap(); + let forged = last_commit(&mut forged_commits); let WorldEffect::Acted { event, .. } = &mut forged.effect else { panic!("expected an acted effect"); }; @@ -1602,9 +1599,7 @@ mod tests { let path = directory.path().join("world.cc"); let owner = PrincipalId::new("owner@example.test"); let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); - let creation_id = CommandId::new(); let creation = CreateWorld { - id: creation_id, owner: owner.clone(), title: "Admitted".into(), patch: owner_patch(SubjectDeclaration { @@ -1620,7 +1615,7 @@ mod tests { let (kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap(); let mut forged_head = kernel.state.clone(); let mut forged_commits = kernel.journal.commits.clone(); - let forged = forged_commits.get_mut(&creation_id).unwrap(); + let forged = genesis_commit(&mut forged_commits); let CommittedCommand::CreateWorld(command) = &mut forged.command else { panic!("expected genesis creation command"); }; @@ -1635,7 +1630,7 @@ mod tests { let mut binding_forged_head = kernel.state.clone(); let mut binding_forged_commits = kernel.journal.commits.clone(); - let binding_forged = binding_forged_commits.get_mut(&creation_id).unwrap(); + let binding_forged = genesis_commit(&mut binding_forged_commits); let WorldEffect::WorldCreated { resolved, .. } = &mut binding_forged.effect else { panic!("expected genesis effect"); }; @@ -1662,7 +1657,7 @@ mod tests { let path = directory.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( &path, - crate::tests::creation(CommandId::new(), "Forged Rows"), + crate::tests::creation("Forged Rows"), &auth_principal(owner()), ) .unwrap(); @@ -1743,7 +1738,7 @@ mod tests { let path = directory.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( &path, - crate::tests::creation(CommandId::new(), "Old Store"), + crate::tests::creation("Old Store"), &auth_principal(owner()), ) .unwrap(); @@ -1789,14 +1784,14 @@ mod tests { use crate::tests::{affordance_named, civic_world, command, owner, play_caller}; use crate::{ DecisionInvocation, Magnitude, ProposedEffect, Quantity, Role, RoleBinding, - SubmitReceipt, Target, + Target, }; let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( &path, - crate::tests::creation(CommandId::new(), "Replayed Levy"), + crate::tests::creation("Replayed Levy"), &crate::tests::auth_principal(owner()), ) .unwrap(); @@ -1804,7 +1799,6 @@ mod tests { let caller = play_caller(); let envelope = command( &active, - CommandId::new(), caller.clone(), CommandBody::Act { actor: civic.treasury, @@ -1846,10 +1840,8 @@ mod tests { assert_eq!(replayed.band, event.band); assert_eq!(replayed.effects, event.effects); assert!(matches!( - reopened - .submit(envelope, &AuthenticatedCaller::fixture(caller)) - .unwrap(), - SubmitReceipt::AlreadyApplied(_) + reopened .submit(envelope, &AuthenticatedCaller::fixture(caller)), + Err(KernelError::RevisionMismatch { .. }) )); } @@ -1869,7 +1861,7 @@ mod tests { let path = directory.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( &path, - crate::tests::creation(CommandId::new(), "Forged Civics"), + crate::tests::creation("Forged Civics"), &auth_principal(owner()), ) .unwrap(); @@ -1977,7 +1969,7 @@ mod tests { let path = directory.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( &path, - crate::tests::creation(CommandId::new(), "Pre-Authority"), + crate::tests::creation("Pre-Authority"), &auth_principal(owner()), ) .unwrap(); @@ -2028,13 +2020,13 @@ mod tests { LEVY_KIND, auth_principal, civic_world, operations, over_subject, owner, reject_play, submit_play, }; - use crate::{ComponentOp, Mismatch, SubmitReceipt}; + use crate::{ComponentOp, Mismatch}; let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( &path, - crate::tests::creation(CommandId::new(), "Moving Civics"), + crate::tests::creation("Moving Civics"), &auth_principal(owner()), ) .unwrap(); @@ -2042,10 +2034,7 @@ mod tests { let admit = |kernel: &mut WorldKernel, ops: Vec<ComponentOp>| { let before = kernel.snapshot().unwrap(); - assert!(matches!( - submit_play(kernel, &before, operations(ops)), - SubmitReceipt::Applied(_) - )); + assert!(submit_play(kernel, &before, operations(ops)).resulting_revision > 0); verify_state_shape(&kernel.state).expect("the committed store keeps its shape"); assert!( crate::overlapping_holder(&kernel.state).is_none(), @@ -2108,9 +2097,10 @@ mod tests { #[cfg(test)] mod custody_tests { use super::*; + use super::tests::last_commit; use crate::{ - CallerId, CommandBody, CommandId, ComponentOp, DependencyRef, EntityKind, Quantity, Ref, - SubmitReceipt, WorldKernel, WorldPatch, + CallerId, CommandBody, ComponentOp, DependencyRef, EntityKind, Quantity, Ref, + WorldKernel, WorldPatch, tests::{admit_custody, admit_topology, auth_principal, command, creation, owner}, }; @@ -2123,7 +2113,7 @@ mod custody_tests { let path = directory.path().join("world.cc"); let authenticated = auth_principal(owner()); let (mut kernel, _) = - WorldKernel::create(&path, creation(CommandId::new(), "Replay"), &authenticated) + WorldKernel::create(&path, creation("Replay"), &authenticated) .unwrap(); let topology = admit_topology(&mut kernel); let custody = admit_custody(&mut kernel, &topology); @@ -2131,7 +2121,6 @@ mod custody_tests { let envelope = command( &active, - CommandId::new(), CallerId::Play, CommandBody::AdmitPatch { patch: WorldPatch { @@ -2146,21 +2135,17 @@ mod custody_tests { }, }, ); - let SubmitReceipt::Applied(receipt) = - kernel.submit(envelope.clone(), &crate::AuthenticatedCaller::verified_play()).unwrap() - else { - panic!("expected an applied transfer"); - }; + kernel.submit(envelope.clone(), &crate::AuthenticatedCaller::verified_play()).unwrap(); let accepted = kernel.snapshot().unwrap(); let world_id = accepted.world_id; drop(kernel); let mut reopened = WorldKernel::open(&path, world_id).unwrap(); assert_eq!(reopened.snapshot().unwrap(), accepted); - assert_eq!( - reopened.submit(envelope, &crate::AuthenticatedCaller::verified_play()).unwrap(), - SubmitReceipt::AlreadyApplied(receipt) - ); + assert!(matches!( + reopened.submit(envelope, &crate::AuthenticatedCaller::verified_play()), + Err(KernelError::RevisionMismatch { .. }) + )); } /// Replay recomputes `reduce`, so the band and the lowered operations are @@ -2176,7 +2161,7 @@ mod custody_tests { let authenticated = auth_principal(owner()); let (mut kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), "ActionReplay"), + creation("ActionReplay"), &authenticated, ) .unwrap(); @@ -2192,7 +2177,6 @@ mod custody_tests { }; let envelope = command( &active, - CommandId::new(), caller.clone(), CommandBody::Act { actor: custody.holder, @@ -2214,12 +2198,9 @@ mod custody_tests { }, ); let authenticated_controller = AuthenticatedCaller::fixture(caller); - let SubmitReceipt::Applied(receipt) = kernel + kernel .submit(envelope.clone(), &authenticated_controller) - .unwrap() - else { - panic!("expected an applied invocation"); - }; + .unwrap(); let accepted = kernel.snapshot().unwrap(); let committed = kernel .state @@ -2237,12 +2218,10 @@ mod custody_tests { reopened.state.events.last().expect("the replayed event"), &committed ); - assert_eq!( - reopened - .submit(envelope, &authenticated_controller) - .unwrap(), - SubmitReceipt::AlreadyApplied(receipt) - ); + assert!(matches!( + reopened .submit(envelope, &authenticated_controller), + Err(KernelError::RevisionMismatch { .. }) + )); } /// A store written at the pass-2 schema is refused outright. There is no @@ -2275,7 +2254,7 @@ mod custody_tests { let directory = tempfile::tempdir().unwrap(); let (kernel, _) = WorldKernel::create( directory.path().join("world.cc"), - creation(CommandId::new(), "Titled"), + creation("Titled"), &auth_principal(owner()), ) .unwrap(); @@ -2302,7 +2281,7 @@ mod custody_tests { let path = directory.path().join("world.cc"); let (kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), "GrantRows"), + creation("GrantRows"), &auth_principal(owner()), ) .unwrap(); @@ -2348,7 +2327,7 @@ mod custody_tests { let path = directory.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), "ActedChain"), + creation("ActedChain"), &auth_principal(owner()), ) .unwrap(); @@ -2392,13 +2371,13 @@ mod custody_tests { /// state row and commit row each on their own: reverting either constant /// to v8 would let its half of the store in. #[test] - fn v9_state_and_commit_rows_are_refused() { + fn ghostlight_state_and_commit_rows_are_refused() { use crate::tests::{act, auth_principal, creation, first_grant, owner, speak}; let directory = tempfile::tempdir().unwrap(); let (mut kernel, _) = WorldKernel::create( directory.path().join("world.cc"), - creation(CommandId::new(), "SchemaV9"), + creation("SchemaV9"), &auth_principal(owner()), ) .unwrap(); @@ -2415,8 +2394,8 @@ mod custody_tests { let state_row = |schema: &str| { envelope(STATE_ROW, schema, kernel.state.world_id.key(), &kernel.state).unwrap() }; - assert_eq!(STATE_SCHEMA, "ghostlight.world_state.consumer.v10"); - assert_eq!(COMMIT_SCHEMA, "ghostlight.world_commit.consumer.v10"); + assert_eq!(STATE_SCHEMA, "aetherlight.world_state.v1"); + assert_eq!(COMMIT_SCHEMA, "aetherlight.world_commit.v1"); recover( [commit_rows(COMMIT_SCHEMA), vec![state_row(STATE_SCHEMA)]].concat(), None, @@ -2425,17 +2404,17 @@ mod custody_tests { for (what, rows) in [ ( - "v9 state row", + "ghostlight state row", [ commit_rows(COMMIT_SCHEMA), - vec![state_row("ghostlight.world_state.consumer.v9")], + vec![state_row("ghostlight.world_state.consumer.v10")], ] .concat(), ), ( - "v9 commit rows", + "ghostlight commit rows", [ - commit_rows("ghostlight.world_commit.consumer.v9"), + commit_rows("ghostlight.world_commit.consumer.v10"), vec![state_row(STATE_SCHEMA)], ] .concat(), @@ -2462,7 +2441,7 @@ mod custody_tests { let directory = tempfile::tempdir().unwrap(); let (mut kernel, _) = WorldKernel::create( directory.path().join("world.cc"), - creation(CommandId::new(), "SilentForgery"), + creation("SilentForgery"), &auth_principal(owner()), ) .unwrap(); @@ -2520,7 +2499,7 @@ mod custody_tests { let path = directory.path().join("world.cc"); let authenticated = auth_principal(owner()); let (mut kernel, _) = - WorldKernel::create(&path, creation(CommandId::new(), "Shape"), &authenticated) + WorldKernel::create(&path, creation("Shape"), &authenticated) .unwrap(); let topology = admit_topology(&mut kernel); let custody = admit_custody(&mut kernel, &topology); @@ -2579,7 +2558,7 @@ mod custody_tests { let authenticated = auth_principal(owner()); let (mut kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), "EveryOperation"), + creation("EveryOperation"), &authenticated, ) .unwrap(); @@ -2591,7 +2570,6 @@ mod custody_tests { let envelope = command( &active, - CommandId::new(), CallerId::Play, CommandBody::AdmitPatch { patch: WorldPatch { @@ -2627,11 +2605,7 @@ mod custody_tests { }, }, ); - let SubmitReceipt::Applied(receipt) = - kernel.submit(envelope.clone(), &crate::AuthenticatedCaller::verified_play()).unwrap() - else { - panic!("expected an applied custody patch"); - }; + kernel.submit(envelope.clone(), &crate::AuthenticatedCaller::verified_play()).unwrap(); let accepted = kernel.snapshot().unwrap(); let holdings = kernel.state.holdings.clone(); let dependencies = kernel.state.dependencies.clone(); @@ -2644,10 +2618,10 @@ mod custody_tests { assert_eq!(reopened.state.holdings, holdings); assert_eq!(reopened.state.dependencies, dependencies); assert_eq!(reopened.state.state_digest, digest); - assert_eq!( - reopened.submit(envelope, &crate::AuthenticatedCaller::verified_play()).unwrap(), - SubmitReceipt::AlreadyApplied(receipt) - ); + assert!(matches!( + reopened.submit(envelope, &crate::AuthenticatedCaller::verified_play()), + Err(KernelError::RevisionMismatch { .. }) + )); } /// Soul: a dependency naming a target of the wrong kind, or no canonical @@ -2660,7 +2634,7 @@ mod custody_tests { let authenticated = auth_principal(owner()); let (mut kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), "DependencyShape"), + creation("DependencyShape"), &authenticated, ) .unwrap(); @@ -2704,7 +2678,7 @@ mod custody_tests { /// A world with one routine, one past-due goal, and a commit chain that /// reaches them: the fixture the two clock-forgery checks below need. - fn ticking_world(path: &std::path::Path) -> (WorldKernel, super::super::SubjectId, CommandId) { + fn ticking_world(path: &std::path::Path) -> (WorldKernel, super::super::SubjectId) { use crate::tests::{auth_principal, command, operations, owner}; use crate::{ AuthenticatedCaller, CallerId, CommandBody, CommitmentKind, ComponentOp, @@ -2714,7 +2688,7 @@ mod custody_tests { let authenticated = auth_principal(owner()); let (mut kernel, _) = WorldKernel::create( path, - crate::tests::creation(CommandId::new(), "Ticking"), + crate::tests::creation("Ticking"), &authenticated, ) .unwrap(); @@ -2725,7 +2699,6 @@ mod custody_tests { .submit( command( &snapshot, - CommandId::new(), CallerId::Play, operations(vec![ ComponentOp::CreateCommitment { @@ -2752,14 +2725,12 @@ mod custody_tests { ) .unwrap(); - let tick_id = CommandId::new(); let caller = CallerId::Play; let snapshot = kernel.snapshot().unwrap(); kernel .submit( command( &snapshot, - tick_id, caller.clone(), CommandBody::AdvanceTime { minutes: TickMinutes::new(30).unwrap(), @@ -2768,7 +2739,7 @@ mod custody_tests { &AuthenticatedCaller::fixture(caller), ) .unwrap(); - (kernel, subject, tick_id) + (kernel, subject) } /// Soul falsification: the replay gate and the `apply_effect` gate are two @@ -2781,11 +2752,12 @@ mod custody_tests { let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("world.cc"); - let (kernel, subject, tick_id) = ticking_world(&path); + let (kernel, subject) = ticking_world(&path); let WorldEffect::TimeAdvanced { motion, .. } = &kernel .journal .commits - .get(&tick_id) + .values() + .max_by_key(|commit| commit.resulting_revision) .expect("the tick's commit") .effect else { @@ -2797,7 +2769,7 @@ mod custody_tests { let forge = |rewrite: fn(&mut crate::Motion)| { let mut forged_head = kernel.state.clone(); let mut forged_commits = kernel.journal.commits.clone(); - let forged = forged_commits.get_mut(&tick_id).unwrap(); + let forged = last_commit(&mut forged_commits); let WorldEffect::TimeAdvanced { motion, .. } = &mut forged.effect else { panic!("expected a time-advanced effect"); }; @@ -2839,7 +2811,7 @@ mod custody_tests { fn soul_a_zero_period_is_refused_by_the_shape_check() { let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("world.cc"); - let (kernel, subject, _) = ticking_world(&path); + let (kernel, subject) = ticking_world(&path); // The forgery an in-crate caller cannot write: `TickMinutes::new` // refuses zero, and the field is private, so the only door is serde. diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index 94b323244..ce2483ab9 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -94,7 +94,6 @@ pub(crate) use patch::{ }; use patch::{EdgeRecord, EntityRecord, LedgerDelta, ResolvedOp, ResolvedPatch}; -use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet}; @@ -103,18 +102,20 @@ use std::path::Path; use thiserror::Error; use uuid::Uuid; -pub const STATE_SCHEMA: &str = "ghostlight.world_state.consumer.v10"; -pub(crate) const COMMIT_SCHEMA: &str = "ghostlight.world_commit.consumer.v10"; +pub const STATE_SCHEMA: &str = "aetherlight.world_state.v1"; +pub(crate) const COMMIT_SCHEMA: &str = "aetherlight.world_commit.v1"; -/// Compatibility tag derived from [`STATE_SCHEMA`]: the trailing -/// `<family>-<version>` pair (e.g. `foundation-v1`). Callers that publish a -/// compatibility marker alongside the schema string must derive it from here -/// rather than hand-copying a second literal that can drift from the schema. -pub fn state_schema_compatibility_tag() -> String { - let mut segments = STATE_SCHEMA.rsplit('.'); - let version = segments.next().unwrap_or_default(); - let family = segments.next().unwrap_or_default(); - format!("{family}-{version}") +/// Domain strings of the three content-derived identities. A command is named +/// by what it says, so no caller draws an id and no retry needs one. +const COMMAND_DOMAIN: &[u8] = b"aetherlight.command.v1"; +const CREATE_DOMAIN: &[u8] = b"aetherlight.create.v1"; +const WORLD_DOMAIN: &[u8] = b"aetherlight.world.v1"; + +/// The first 16 bytes of a digest as a `Uuid`, as `patch::derive_id` truncates. +fn truncated_uuid(hasher: Sha256) -> Uuid { + let mut bytes = [0u8; 16]; + bytes.copy_from_slice(&hasher.finalize()[..16]); + Uuid::from_bytes(bytes) } /// The visibility argument is the whole boundary decision for an ID type: the @@ -142,23 +143,15 @@ opaque_uuid!(AffordanceId, pub); opaque_uuid!(EventId); impl CommandId { - fn issue() -> Self { - Self(Uuid::new_v4()) - } - - pub fn new() -> Self { - Self::issue() - } - - pub fn parse_uuid(value: &str) -> Result<Self, KernelError> { - Uuid::parse_str(value) - .map(Self) - .map_err(|_| KernelError::InvalidCommandId) - } - fn key(self) -> String { self.0.to_string() } + + /// A named random id for tests that need a command id and no command. + #[cfg(test)] + fn issue() -> Self { + Self(Uuid::new_v4()) + } } impl WorldId { @@ -173,8 +166,12 @@ impl WorldId { Self(Uuid::nil()) } - fn issue() -> Self { - Self(Uuid::new_v4()) + /// The world is named by the creation that made it. + fn of(creation: CommandId) -> Self { + let mut hasher = Sha256::new(); + hasher.update(WORLD_DOMAIN); + hasher.update(creation.0.as_bytes()); + Self(truncated_uuid(hasher)) } fn key(self) -> String { @@ -235,7 +232,6 @@ pub enum SubjectKind { #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] struct CreateWorld { - id: CommandId, owner: PrincipalId, title: String, patch: WorldPatch, @@ -245,6 +241,16 @@ struct CreateWorld { grammar: Option<GrammarBinding>, } +impl CreateWorld { + /// The creation is named by its own bytes: equal creations are one command. + fn id(&self) -> CommandId { + let mut hasher = Sha256::new(); + hasher.update(CREATE_DOMAIN); + hasher.update(rmp_serde::to_vec_named(self).expect("a creation command serializes")); + CommandId(truncated_uuid(hasher)) + } +} + /// Who wrote a command. The owner principal authors genesis and nothing after /// it; after genesis `Play` is the only caller any command body admits. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] @@ -335,13 +341,27 @@ pub struct DecisionInvocation { #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] struct CommandEnvelope { - id: CommandId, world_id: WorldId, expected_revision: u64, caller: CallerId, body: CommandBody, } +impl CommandEnvelope { + /// A command is named by the world, revision, caller and body it carries. + /// The revision is in the preimage so the same body at two revisions is + /// two commands, and every id derived from it is distinct. + fn id(&self) -> CommandId { + let mut hasher = Sha256::new(); + hasher.update(COMMAND_DOMAIN); + hasher.update(self.world_id.0.as_bytes()); + hasher.update(self.expected_revision.to_be_bytes()); + hasher.update(rmp_serde::to_vec_named(&self.caller).expect("a caller serializes")); + hasher.update(rmp_serde::to_vec_named(&self.body).expect("a command body serializes")); + CommandId(truncated_uuid(hasher)) + } +} + #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type", rename_all = "snake_case")] pub enum CommandBody { @@ -500,7 +520,7 @@ enum WorldEffect { } /// The exact raw command admitted by the kernel. This is the sole -/// persistent command authority: IDs, callers, retry identity, and effects are +/// persistent command authority: IDs, callers, and effects are /// derived from this value rather than copied into independently forgeable /// commit fields. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] @@ -513,8 +533,8 @@ enum CommittedCommand { impl CommittedCommand { fn id(&self) -> CommandId { match self { - Self::CreateWorld(command) => command.id, - Self::WorldCommand(command) => command.id, + Self::CreateWorld(command) => command.id(), + Self::WorldCommand(command) => command.id(), } } @@ -537,7 +557,6 @@ struct WorldCommit { resulting_state_digest: String, previous_commit_digest: Option<String>, effect: WorldEffect, - committed_at: DateTime<Utc>, digest: String, } @@ -790,7 +809,7 @@ impl CreationReceipt { )); }; Ok(Self { - command_id: command.id, + command_id: command.id(), world_id: commit.world_id, resulting_state_digest: commit.resulting_state_digest.clone(), commit_digest: commit.digest.clone(), @@ -809,16 +828,8 @@ impl From<&WorldCommit> for CommitReceipt { } } -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum SubmitReceipt { - Applied(CommitReceipt), - AlreadyApplied(CommitReceipt), -} - #[derive(Debug, Error)] pub enum KernelError { - #[error("command ID must be a UUID")] - InvalidCommandId, #[error("world title must not be empty")] EmptyTitle, #[error("world owner principal must be canonical and nonempty")] @@ -837,8 +848,6 @@ pub enum KernelError { AffordanceDenied, #[error("expected revision {expected}, current revision {actual}")] RevisionMismatch { expected: u64, actual: u64 }, - #[error("command ID was reused with different content")] - CommandIdConflict, #[error("world creation ID was reused with different content")] CreationConflict, #[error("world creation target already contains another world")] @@ -915,7 +924,7 @@ fn prepare_creation( let title = normalize_title(&input.title)?; // The world's own identity is not world structure, and it feeds every // derived ID, so it is minted before resolution rather than by it. - let world_id = WorldId::issue(); + let world_id = WorldId::of(input.id()); let resolved = patch::resolve_patch( &WorldState::empty( world_id, @@ -923,7 +932,7 @@ fn prepare_creation( title.clone(), input.grammar.clone(), ), - input.id, + input.id(), &input.patch, ) .map_err(KernelError::PatchRejected)?; @@ -959,7 +968,6 @@ impl WorldKernel { resulting_state_digest: state.state_digest.clone(), previous_commit_digest: None, effect, - committed_at: Utc::now(), digest: String::new(), }; genesis.digest = commit_digest(&genesis)?; @@ -971,7 +979,7 @@ impl WorldKernel { fn retry_creation(&self, prepared: &PreparedCreation) -> Result<CreationReceipt, KernelError> { self.journal.ensure_healthy()?; - let Some(commit) = self.journal.commit_for(prepared.command.id) else { + let Some(commit) = self.journal.commit_for(prepared.command.id()) else { return Err(KernelError::CreationTargetOccupied); }; if commit.command != CommittedCommand::CreateWorld(prepared.command.clone()) @@ -1014,28 +1022,15 @@ impl WorldKernel { &mut self, command: CommandEnvelope, authenticated: &AuthenticatedCaller, - ) -> Result<SubmitReceipt, KernelError> { - let committed_at = Utc::now(); + ) -> Result<CommitReceipt, KernelError> { self.journal.ensure_healthy()?; + let command_id = command.id(); if command.world_id != self.state.world_id { return Err(KernelError::WorldMismatch); } if command.caller != authenticated.caller { return Err(KernelError::AuthenticationMismatch); } - // Retry identity is caller plus body. The expected revision is stamped by - // the mailbox owner rather than supplied by the caller, so it is not part - // of what makes a command the same command. - if let Some(commit) = self.committed_command(command.id) { - let CommittedCommand::WorldCommand(committed) = &commit.command else { - return Err(KernelError::CommandIdConflict); - }; - return if committed.caller == command.caller && committed.body == command.body { - Ok(SubmitReceipt::AlreadyApplied(CommitReceipt::from(commit))) - } else { - Err(KernelError::CommandIdConflict) - }; - } if command.expected_revision != self.state.revision { return Err(KernelError::RevisionMismatch { expected: command.expected_revision, @@ -1045,7 +1040,7 @@ impl WorldKernel { let effect = reduce(&self.state, &command)?; let mut candidate = self.state.clone(); - apply_effect(&mut candidate, command.id, &command.caller, &effect)?; + apply_effect(&mut candidate, command_id, &command.caller, &effect)?; candidate.revision = candidate .revision .checked_add(1) @@ -1062,7 +1057,6 @@ impl WorldKernel { resulting_state_digest: candidate.state_digest.clone(), previous_commit_digest: self.state.last_commit_digest.clone(), effect, - committed_at, digest: String::new(), }; commit.digest = commit_digest(&commit)?; @@ -1070,11 +1064,7 @@ impl WorldKernel { self.journal.commit(&candidate, &commit)?; self.state = candidate; - Ok(SubmitReceipt::Applied(CommitReceipt::from(&commit))) - } - - fn committed_command(&self, command_id: CommandId) -> Option<&WorldCommit> { - self.journal.commit_for(command_id) + Ok(CommitReceipt::from(&commit)) } } @@ -1084,10 +1074,11 @@ fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result<WorldEffect, // `apply_effect`: `reduce` decides and `apply_effect` re-decides, which is // how every gate in this file is written. require_play(&command.caller)?; + let command_id = command.id(); match &command.body { CommandBody::Act { actor, invocation } => { let granted = require_granted(state, *actor, invocation.affordance)?; - let event = action::exercise(state, command.id, *actor, &granted, invocation)?; + let event = action::exercise(state, command_id, *actor, &granted, invocation)?; Ok(WorldEffect::Acted { invocation: invocation.clone(), event, @@ -1108,7 +1099,7 @@ fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result<WorldEffect, }) } CommandBody::AdmitPatch { patch } => { - let resolved = patch::resolve_patch(state, command.id, patch) + let resolved = patch::resolve_patch(state, command_id, patch) .map_err(KernelError::PatchRejected)?; Ok(WorldEffect::PatchAdmitted { resolved }) } @@ -1202,7 +1193,7 @@ impl WorldState { let mut state = Self::empty(world_id, owner.clone(), title.clone(), command.grammar.clone()); let expected = patch::resolve_patch( &state, - command.id, + command.id(), &command.patch, ) .map_err(KernelError::PatchRejected)?; @@ -3350,9 +3341,8 @@ mod tests { .expect("the fixture world declares this affordance") } - pub(crate) fn creation(id: CommandId, title: &str) -> CreateWorld { + pub(crate) fn creation(title: &str) -> CreateWorld { CreateWorld { - id, owner: owner(), title: title.into(), patch: WorldPatch { @@ -3413,12 +3403,10 @@ mod tests { pub(crate) fn command( snapshot: &WorldSnapshot, - id: CommandId, caller: CallerId, body: CommandBody, ) -> CommandEnvelope { CommandEnvelope { - id, world_id: snapshot.world_id, expected_revision: snapshot.revision, caller, @@ -3433,20 +3421,19 @@ mod tests { } } - pub(crate) fn play_command(snapshot: &WorldSnapshot, id: CommandId, body: CommandBody) -> CommandEnvelope { - command(snapshot, id, CallerId::Play, body) + pub(crate) fn play_command(snapshot: &WorldSnapshot, body: CommandBody) -> CommandEnvelope { + command(snapshot, CallerId::Play, body) } pub(crate) fn submit_play( kernel: &mut WorldKernel, snapshot: &WorldSnapshot, body: CommandBody, - ) -> SubmitReceipt { + ) -> CommitReceipt { kernel .submit( command( snapshot, - CommandId::new(), CallerId::Play, body, ), @@ -3563,7 +3550,7 @@ mod tests { patch: topology_patch(speak_entry(kernel)), }, ); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); let entity = |label: &str| { *kernel .state @@ -3881,7 +3868,7 @@ mod tests { patch: custody_patch(topology, speak_entry(kernel)), }, ); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); let entity = |label: &str| { *kernel .state @@ -4328,7 +4315,7 @@ mod tests { patch: civic_patch(topology, speak_entry(kernel)), }, ); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); let entity = |label: &str| { *kernel .state @@ -4590,7 +4577,6 @@ mod tests { .submit( command( snapshot, - CommandId::new(), CallerId::Play, body, ), @@ -4652,22 +4638,11 @@ mod tests { caller: CallerId, actor: SubjectId, invocation: DecisionInvocation, - ) -> Result<SubmitReceipt, KernelError> { - act_command(kernel, CommandId::new(), caller, actor, invocation) - } - - pub(crate) fn act_command( - kernel: &mut WorldKernel, - command_id: CommandId, - caller: CallerId, - actor: SubjectId, - invocation: DecisionInvocation, - ) -> Result<SubmitReceipt, KernelError> { + ) -> Result<CommitReceipt, KernelError> { let snapshot = kernel.snapshot().unwrap(); kernel.submit( command( &snapshot, - command_id, caller.clone(), CommandBody::Act { actor, invocation }, ), @@ -4683,7 +4658,7 @@ mod tests { kernel: &mut WorldKernel, actor: SubjectId, invocation: DecisionInvocation, - ) -> Result<SubmitReceipt, KernelError> { + ) -> Result<CommitReceipt, KernelError> { act_as( kernel, CallerId::Play, @@ -4696,7 +4671,7 @@ mod tests { fn create_submit_restart_and_replay_are_exact() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("world.cc"); - let creation = creation(CommandId::new(), "First"); + let creation = creation("First"); let (mut kernel, creation_receipt) = WorldKernel::create(&path, creation.clone(), &auth_principal(owner())).unwrap(); let active = kernel.snapshot().unwrap(); @@ -4704,22 +4679,18 @@ mod tests { let caller = play_caller(); let command = command( &active, - CommandId::new(), caller.clone(), CommandBody::Act { actor: operator, invocation: speak(first_grant(&active, operator), "The vote carries."), }, ); - let applied = kernel + kernel .submit( command.clone(), &AuthenticatedCaller::fixture(caller.clone()), ) .unwrap(); - let SubmitReceipt::Applied(receipt) = applied else { - panic!("expected applied receipt") - }; let accepted = kernel.snapshot().unwrap(); drop(kernel); @@ -4727,12 +4698,10 @@ mod tests { WorldKernel::create(&path, creation, &auth_principal(owner())).unwrap(); assert_eq!(retried_creation_receipt, creation_receipt); assert_eq!(reopened.snapshot().unwrap(), accepted); - assert_eq!( - reopened - .submit(command, &AuthenticatedCaller::fixture(caller)) - .unwrap(), - SubmitReceipt::AlreadyApplied(receipt) - ); + assert!(matches!( + reopened .submit(command, &AuthenticatedCaller::fixture(caller)), + Err(KernelError::RevisionMismatch { .. }) + )); drop(reopened); let reopened = WorldKernel::open(&path, accepted.world_id).unwrap(); assert_eq!(reopened.snapshot().unwrap(), accepted); @@ -4744,17 +4713,14 @@ mod tests { let path = dir.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), "Still"), + creation("Still"), &auth_principal(owner()), ) .unwrap(); let genesis = kernel.snapshot().unwrap(); - assert!(matches!( - submit_play(&mut kernel, &genesis, tick_body(1)), - SubmitReceipt::Applied(_) - )); + assert!(submit_play(&mut kernel, &genesis, tick_body(1)).resulting_revision > 0); let after = kernel.snapshot().unwrap(); - let stale = play_command(&genesis, CommandId::new(), tick_body(1)); + let stale = play_command(&genesis, tick_body(1)); assert!(matches!( kernel.submit(stale, &AuthenticatedCaller::verified_play()), Err(KernelError::RevisionMismatch { .. }) @@ -4764,75 +4730,57 @@ mod tests { } #[test] - fn durable_idempotency_precedes_revision_and_detects_conflicts() { + fn ids_are_derived_from_the_command() { let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("world.cc"); - let (mut kernel, _) = WorldKernel::create( - &path, - creation(CommandId::new(), "A"), - &auth_principal(owner()), - ) - .unwrap(); - let genesis = kernel.snapshot().unwrap(); - let id = CommandId::new(); - let first = play_command(&genesis, id, tick_body(1)); - let first_receipt = kernel - .submit(first.clone(), &AuthenticatedCaller::verified_play()) - .unwrap(); - let second_snapshot = kernel.snapshot().unwrap(); - kernel - .submit( - play_command(&second_snapshot, CommandId::new(), tick_body(1)), - &AuthenticatedCaller::verified_play(), - ) - .unwrap(); - let after_second = kernel.snapshot().unwrap(); - assert_eq!( - kernel - .submit(first, &AuthenticatedCaller::verified_play()) - .unwrap(), - match first_receipt { - SubmitReceipt::Applied(value) => SubmitReceipt::AlreadyApplied(value), - _ => unreachable!(), - } - ); - let conflict = play_command(&genesis, id, tick_body(2)); - assert!(matches!( - kernel.submit(conflict, &AuthenticatedCaller::verified_play()), - Err(KernelError::CommandIdConflict) - )); - assert_eq!(kernel.snapshot().unwrap(), after_second); - } + let create = |name: &str, title: &str| { + WorldKernel::create(dir.path().join(name), creation(title), &auth_principal(owner())) + .unwrap() + }; + let (mut kernel, receipt) = create("a.cc", "Same"); + let (twin, twin_receipt) = create("b.cc", "Same"); + assert_eq!(receipt, twin_receipt); + assert_eq!(kernel.state.world_id, twin.state.world_id); + assert_eq!(receipt.world_id, WorldId::of(receipt.command_id)); + let (other, _) = create("c.cc", "Other"); + assert_ne!(kernel.state.world_id, other.state.world_id); - #[test] - fn creation_retry_is_bound_to_the_exact_raw_command() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("world.cc"); - let id = CommandId::new(); - let raw = creation(id, " Canonical Result "); - let (kernel, first) = - WorldKernel::create(&path, raw.clone(), &auth_principal(owner())).unwrap(); - assert_eq!(kernel.snapshot().unwrap().title, "Canonical Result"); - drop(kernel); - - let (kernel, retry) = - WorldKernel::create(&path, raw.clone(), &auth_principal(owner())).unwrap(); - assert_eq!(retry, first); - drop(kernel); - - let mut merely_equivalent = raw; - merely_equivalent.title = "Canonical Result".into(); - assert!(matches!( - WorldKernel::create(&path, merely_equivalent, &auth_principal(owner())), - Err(KernelError::CreationConflict) - )); + // The same patch at two revisions is two commands, so the entity it + // declares is minted twice under two ids. + let patch = WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("cairn"), + label: "A Cairn".into(), + kind: EntityKind::Place, + container: None, + })], + operations: Vec::new(), + evidence: Vec::new(), + }; + let mut ids = BTreeSet::new(); + for _ in 0..2 { + let snapshot = kernel.snapshot().unwrap(); + let envelope = play_command(&snapshot, CommandBody::AdmitPatch { patch: patch.clone() }); + let expected = envelope.id(); + let receipt = kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .unwrap(); + assert_eq!(receipt.command_id, expected); + assert!(ids.insert(receipt.command_id), "two commands share an id"); + } + let cairns = kernel + .state + .entities + .values() + .filter(|entity| entity.label == "A Cairn") + .count(); + assert_eq!(cairns, 2); } #[test] fn invalid_seed_never_allocates_a_world() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("world.cc"); - let mut invalid = creation(CommandId::new(), "Nope"); + let mut invalid = creation("Nope"); invalid.patch.declarations[3] = invalid.patch.declarations[2].clone(); let Err(KernelError::PatchRejected(rejected)) = WorldKernel::create(&path, invalid, &auth_principal(owner())) @@ -4848,7 +4796,7 @@ mod tests { assert!( WorldKernel::create( &path, - creation(CommandId::new(), "Valid"), + creation("Valid"), &auth_principal(owner()) ) .is_ok() @@ -4859,7 +4807,7 @@ mod tests { fn a_second_live_owner_is_refused() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("world.cc"); - let creation = creation(CommandId::new(), "Held"); + let creation = creation("Held"); let (kernel, _) = WorldKernel::create(&path, creation.clone(), &auth_principal(owner())).unwrap(); let world_id = kernel.snapshot().unwrap().world_id; @@ -4875,7 +4823,7 @@ mod tests { let kernel = WorldKernel::open(&path, world_id).unwrap(); drop(kernel); assert!(matches!( - WorldKernel::open(&path, WorldId::issue()), + WorldKernel::open(&path, WorldId::of(CommandId::issue())), Err(KernelError::OpenedWorldMismatch) )); } @@ -4886,13 +4834,13 @@ mod tests { let path = dir.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), "Certain"), + creation("Certain"), &auth_principal(owner()), ) .unwrap(); let genesis = kernel.snapshot().unwrap(); - let uncertain = CommandId::new(); - let attempted = play_command(&genesis, uncertain, tick_body(1)); + let attempted = play_command(&genesis, tick_body(1)); + let uncertain = attempted.id(); kernel.journal.fail_after_durable_commit_for_test(); assert!(matches!( kernel.submit(attempted.clone(), &AuthenticatedCaller::verified_play()), @@ -4908,10 +4856,8 @@ mod tests { let durable = reopened.snapshot().unwrap(); assert_eq!(durable.revision, 1); assert!(matches!( - reopened - .submit(attempted, &AuthenticatedCaller::verified_play()) - .unwrap(), - SubmitReceipt::AlreadyApplied(_) + reopened .submit(attempted, &AuthenticatedCaller::verified_play()), + Err(KernelError::RevisionMismatch { .. }) )); } @@ -4919,8 +4865,8 @@ mod tests { fn lost_genesis_ack_reopens_as_the_same_world_and_exact_receipt() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("world.cc"); - let command_id = CommandId::new(); - let input = creation(command_id, "Durable Genesis"); + let input = creation("Durable Genesis"); + let command_id = input.id(); let authenticated = auth_principal(owner()); let mut empty = match journal::WorldJournal::open_owner(&path).unwrap() { journal::JournalOpen::Empty(empty) => empty, @@ -4949,7 +4895,7 @@ mod tests { let displaced = dir.path().join("displaced.cc"); let (mut kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), "Pinned"), + creation("Pinned"), &auth_principal(owner()), ) .unwrap(); @@ -4959,7 +4905,7 @@ mod tests { assert!(matches!(kernel.snapshot(), Err(KernelError::OwnershipLost))); assert!(matches!( kernel.submit( - play_command(&snapshot, CommandId::new(), tick_body(1)), + play_command(&snapshot, tick_body(1)), &AuthenticatedCaller::verified_play() ), Err(KernelError::OwnershipLost) @@ -4978,14 +4924,13 @@ mod tests { let path = dir.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), "Owned"), + creation("Owned"), &auth_principal(owner()), ) .unwrap(); let snapshot = kernel.snapshot().unwrap(); let forged = command( &snapshot, - CommandId::new(), CallerId::Principal(human_principal()), tick_body(1), ); @@ -5004,7 +4949,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let (mut kernel, _) = WorldKernel::create( dir.path().join("world.cc"), - creation(CommandId::new(), "Preimage"), + creation("Preimage"), &auth_principal(owner()), ) .unwrap(); @@ -5126,7 +5071,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let (mut kernel, _) = WorldKernel::create( dir.path().join("world.cc"), - creation(CommandId::new(), "SharedCatalogIds"), + creation("SharedCatalogIds"), &auth_principal(owner()), ) .unwrap(); @@ -5165,10 +5110,7 @@ mod tests { }; // The grantee's scope commits with that id. - assert!(matches!( - invoke(&mut kernel, holders[0]).unwrap(), - SubmitReceipt::Applied(_) - )); + assert!(invoke(&mut kernel, holders[0]).unwrap().resulting_revision > 0); // A scope that does not hold the entry is denied the very same id, and // nothing commits. @@ -5191,7 +5133,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let (mut kernel, _) = WorldKernel::create( dir.path().join("world.cc"), - creation(CommandId::new(), "BindingAndAdmission"), + creation("BindingAndAdmission"), &auth_principal(owner()), ) .unwrap(); @@ -5229,7 +5171,7 @@ mod tests { }, ) .expect("a distant route closing does not stop this act"); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); } /// The mvp doc's disjointness requirement: an institution with an @@ -5286,7 +5228,6 @@ mod tests { .submit( command( &active, - CommandId::new(), caller.clone(), CommandBody::Act { actor: civic.treasury, @@ -5314,7 +5255,7 @@ mod tests { &AuthenticatedCaller::fixture(caller), ) .unwrap(); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); let held = |holder: SubjectId| { kernel @@ -5453,16 +5394,7 @@ mod tests { // A different kind over the same ground commits, and so does the same // kind held by a different subject: two holders authorized over one // target is not a contradiction, because nothing arbitrates. - assert!(matches!( - admit( - &mut kernel, - vec![ - grant_to(civic.reeve, JUDGE_KIND, over_place(civic.chamber)), - grant_to(civic.outsider, LEVY_KIND, over_place(civic.chamber)), - ] - ), - SubmitReceipt::Applied(_) - )); + assert!(admit( &mut kernel, vec![ grant_to(civic.reeve, JUDGE_KIND, over_place(civic.chamber)), grant_to(civic.outsider, LEVY_KIND, over_place(civic.chamber)), ] ).resulting_revision > 0); } /// Contract 6 on the civic surface: one patch, the complete sorted set, no @@ -5533,10 +5465,7 @@ mod tests { standing: over_place(civic.hall), }, ]; - assert!(matches!( - submit_play(&mut kernel, &before, operations(repaired)), - SubmitReceipt::Applied(_) - )); + assert!(submit_play(&mut kernel, &before, operations(repaired)).resulting_revision > 0); } /// A civic operation that changes nothing is not a canonical change. @@ -5828,7 +5757,7 @@ mod custody_tests { pub(crate) fn custody_kernel(path: &Path, title: &str) -> WorldKernel { WorldKernel::create( path.join("world.cc"), - creation(CommandId::new(), title), + creation(title), &auth_principal(owner()), ) .expect("a created world") @@ -6004,7 +5933,7 @@ mod custody_tests { qty: Quantity(3), }]), ); - assert!(matches!(after_three, SubmitReceipt::Applied(_))); + assert!(after_three.resulting_revision > 0); assert_eq!(holding(&kernel, custody.holder, custody.tithe), 4); let snapshot = kernel.snapshot().unwrap(); @@ -6359,7 +6288,7 @@ mod custody_tests { }, ]), ); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); // Transfer contributes to no term; transform contributes one spent and // one gained; consume contributes one consumed. Nothing was admitted. @@ -6596,7 +6525,7 @@ mod custody_tests { speak(first_grant(&moved, topology.walker), "Unmoved."), ) .expect("an unrelated subject acts at the later revision"); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); } } @@ -6617,7 +6546,7 @@ mod knowledge_tests { fn speech_kernel(path: &Path, title: &str) -> (WorldKernel, Speech, WorldSnapshot) { let mut kernel = WorldKernel::create( path.join("world.cc"), - creation(CommandId::new(), title), + creation(title), &auth_principal(owner()), ) .expect("a created world") @@ -6630,7 +6559,7 @@ mod knowledge_tests { kernel: &mut WorldKernel, actor: SubjectId, invocation: DecisionInvocation, - ) -> Result<SubmitReceipt, KernelError> { + ) -> Result<CommitReceipt, KernelError> { act(kernel, actor, invocation) } @@ -6651,7 +6580,7 @@ mod knowledge_tests { } } - fn rejected(result: Result<SubmitReceipt, KernelError>) -> Vec<ActionMismatch> { + fn rejected(result: Result<CommitReceipt, KernelError>) -> Vec<ActionMismatch> { match result { Err(KernelError::ActionRejected(mismatches)) => mismatches, other => panic!("expected a rejected invocation, got {other:?}"), @@ -6751,7 +6680,7 @@ mod knowledge_tests { let directory = tempfile::tempdir().unwrap(); let mut draft = WorldKernel::create( directory.path().join("world.cc"), - creation(CommandId::new(), "Standing"), + creation("Standing"), &auth_principal(owner()), ) .expect("a draft world") @@ -7151,7 +7080,7 @@ mod knowledge_tests { let (speech, world_id, expected) = { let mut kernel = WorldKernel::create( &path, - creation(CommandId::new(), "ReplayDisplay"), + creation("ReplayDisplay"), &auth_principal(owner()), ) .expect("a created world") @@ -7412,26 +7341,23 @@ mod knowledge_tests { let directory = tempfile::tempdir().unwrap(); let (mut kernel, speech, active) = speech_kernel(directory.path(), "Allocation"); let world_id = kernel.state.world_id; - let command_id = CommandId::new(); let caller = play_caller(); let entities_before = kernel.state.entities.len(); - kernel - .submit( - command( - &active, - command_id, - caller.clone(), - CommandBody::Act { - actor: speech.speaker, - invocation: say( - speech.whisper, - vec![binding("target", Target::Subject(speech.listener))], - "Counted.", - ), - }, + let whisper = command( + &active, + caller.clone(), + CommandBody::Act { + actor: speech.speaker, + invocation: say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + "Counted.", ), - &AuthenticatedCaller::fixture(caller), - ) + }, + ); + let command_id = whisper.id(); + kernel + .submit(whisper, &AuthenticatedCaller::fixture(caller)) .expect("the whisper commits"); let claim = minted_claim(&kernel); @@ -7464,7 +7390,7 @@ mod knowledge_tests { let (speech, world_id, expected) = { let mut kernel = WorldKernel::create( &path, - creation(CommandId::new(), "ReplaySpeech"), + creation("ReplaySpeech"), &auth_principal(owner()), ) .expect("a created world") @@ -7516,7 +7442,7 @@ mod knowledge_tests { fn a_forged_claim_or_forged_recipient_does_not_apply() { let directory = tempfile::tempdir().unwrap(); let (kernel, speech, _) = speech_kernel(directory.path(), "Forgery"); - let command_id = CommandId::new(); + let command_id = CommandId::issue(); let caller = play_caller(); let invocation = say( speech.proclaim, @@ -7633,7 +7559,7 @@ mod knowledge_tests { let directory = tempfile::tempdir().unwrap(); let mut kernel = WorldKernel::create( directory.path().join("world.cc"), - creation(CommandId::new(), "SpeechAudience"), + creation("SpeechAudience"), &auth_principal(owner()), ) .expect("a draft world") @@ -7702,7 +7628,7 @@ mod knowledge_tests { ), ) .expect("both statements commit identically"); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); let event = kernel.state.events.last().unwrap().clone(); (kernel, speech, event) }; @@ -7743,7 +7669,7 @@ mod soul_knowledge_tests { fn speech_kernel(path: &Path, title: &str) -> (WorldKernel, Speech, WorldSnapshot) { let mut kernel = WorldKernel::create( path.join("world.cc"), - creation(CommandId::new(), title), + creation(title), &auth_principal(owner()), ) .expect("a created world") @@ -7773,7 +7699,7 @@ mod soul_knowledge_tests { kernel: &mut WorldKernel, actor: SubjectId, invocation: DecisionInvocation, - ) -> Result<SubmitReceipt, KernelError> { + ) -> Result<CommitReceipt, KernelError> { act(kernel, actor, invocation) } @@ -7943,7 +7869,7 @@ mod soul_knowledge_tests { fn soul_a_forged_wider_audience_does_not_apply() { let directory = tempfile::tempdir().unwrap(); let (kernel, speech, _) = speech_kernel(directory.path(), "WiderAudience"); - let command_id = CommandId::new(); + let command_id = CommandId::issue(); let caller = play_caller(); let invocation = say( speech.whisper, @@ -8110,7 +8036,6 @@ mod soul_knowledge_tests { .submit( command( &active, - CommandId::new(), CallerId::Play, operations(vec![tell.clone(), forget.clone()]), ), @@ -8181,7 +8106,6 @@ mod soul_knowledge_tests { .submit( command( &active, - CommandId::new(), CallerId::Play, CommandBody::AdmitPatch { patch: WorldPatch { @@ -8201,7 +8125,7 @@ mod soul_knowledge_tests { &AuthenticatedCaller::fixture(CallerId::Play), ) .expect("the play table declares a claim in Active"); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); assert_eq!(kernel.state.facts.len(), before.facts.len() + 1); let facts = kernel.state.facts.clone(); drop(kernel); @@ -8408,7 +8332,7 @@ mod witness_tests { fn nesting_kernel(path: &Path, title: &str) -> (WorldKernel, Nesting, WorldSnapshot) { let mut kernel = WorldKernel::create( path.join("world.cc"), - creation(CommandId::new(), title), + creation(title), &auth_principal(owner()), ) .expect("a created world") @@ -8888,7 +8812,6 @@ mod witness_tests { .submit( command( &active, - CommandId::new(), caller.clone(), CommandBody::Act { actor: world.villager, @@ -8995,7 +8918,7 @@ mod witness_tests { fn a_genesis_seeded_knowledge_row_is_acquired_at_revision_zero() { let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("world.cc"); - let mut creation = creation(CommandId::new(), "PAf49Genesis"); + let mut creation = creation("PAf49Genesis"); creation.patch.declarations.push(Declaration::Fact(FactDeclaration { handle: DraftHandle::new("founding"), label: "The Founding Ruling".into(), @@ -9258,7 +9181,6 @@ mod witness_tests { kernel.submit( command( &snapshot, - CommandId::new(), caller.clone(), CommandBody::AdmitPatch { patch: WorldPatch { @@ -9313,7 +9235,7 @@ mod witness_tests { Some(world.village), ); assert!( - matches!(receipt, Ok(SubmitReceipt::Applied(_))), + matches!(receipt, Ok(_)), "{receipt:?}" ); let arrived = *kernel @@ -9384,7 +9306,7 @@ mod witness_tests { witness(world.asteroid, world.village, Confidence::Certain), ]), ); - assert!(matches!(receipt, SubmitReceipt::Applied(_)), "{receipt:?}"); + assert!(receipt.resulting_revision > 0, "{receipt:?}"); assert_eq!( knows(&kernel, world.villager, world.asteroid), seen(Confidence::Certain, seeded.revision + 1), @@ -9484,7 +9406,7 @@ mod clock_tests { fn clock_kernel(path: &Path, title: &str) -> (WorldKernel, Clockwork, WorldSnapshot) { let mut kernel = WorldKernel::create( path.join("world.cc"), - creation(CommandId::new(), title), + creation(title), &auth_principal(owner()), ) .expect("a created world") @@ -9725,12 +9647,11 @@ mod clock_tests { ) } - fn tick(kernel: &mut WorldKernel, span: u32) -> Result<SubmitReceipt, KernelError> { + fn tick(kernel: &mut WorldKernel, span: u32) -> Result<CommitReceipt, KernelError> { let snapshot = kernel.snapshot().unwrap(); kernel.submit( command( &snapshot, - CommandId::new(), CallerId::Play, CommandBody::AdvanceTime { minutes: minutes(span), @@ -9745,7 +9666,7 @@ mod clock_tests { actor: SubjectId, affordance: AffordanceId, bindings: Vec<RoleBinding>, - ) -> Result<SubmitReceipt, KernelError> { + ) -> Result<CommitReceipt, KernelError> { act( kernel, actor, @@ -9986,7 +9907,7 @@ mod clock_tests { let directory = tempfile::tempdir().unwrap(); let mut kernel = WorldKernel::create( directory.path().join("world.cc"), - creation(CommandId::new(), "Negatives"), + creation("Negatives"), &auth_principal(owner()), ) .expect("a created world") @@ -10006,7 +9927,6 @@ mod clock_tests { .submit( command( &active, - CommandId::new(), caller.clone(), CommandBody::AdvanceTime { minutes: minutes(1), @@ -10036,7 +9956,6 @@ mod clock_tests { .submit( command( &snapshot, - CommandId::new(), CallerId::Play, CommandBody::AdvanceTime { minutes: minutes(1), @@ -10157,7 +10076,6 @@ mod clock_tests { let snapshot = kernel.snapshot().unwrap(); let repeat = command( &snapshot, - CommandId::new(), CallerId::Play, operations(vec![ComponentOp::DischargeCommitment { subject: Ref::Existing(clockwork.farmer), @@ -10188,7 +10106,7 @@ mod clock_tests { assert_eq!(replayed.snapshot().unwrap(), before_snapshot); assert!(matches!( replayed.submit(repeat, &AuthenticatedCaller::verified_play()), - Ok(SubmitReceipt::AlreadyApplied(_)) + Err(KernelError::RevisionMismatch { .. }) )); } @@ -10267,7 +10185,7 @@ mod clock_tests { ComponentOp::DischargeCommitment { subject: Ref::Existing(clockwork.farmer), key: CommitmentKey { - command: CommandId::new(), + command: CommandId::issue(), index: 0, }, }, @@ -10624,7 +10542,7 @@ mod clock_tests { fn genesis_may_not_rule_or_mint() { let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("world.cc"); - let mut input = creation(CommandId::new(), "RulesAndMints"); + let mut input = creation("RulesAndMints"); for handle in ["first-rule", "second-rule"] { input .patch @@ -10673,7 +10591,7 @@ mod clock_tests { fn a_genesis_patch_carrying_a_ruled_fact_is_refused() { let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("world.cc"); - let mut input = creation(CommandId::new(), "RuledGenesis"); + let mut input = creation("RuledGenesis"); input .patch .declarations @@ -10702,7 +10620,7 @@ mod clock_tests { fn a_genesis_patch_carrying_a_mint_is_refused() { let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("world.cc"); - let mut input = creation(CommandId::new(), "MintGenesis"); + let mut input = creation("MintGenesis"); input .patch .declarations @@ -10732,8 +10650,8 @@ mod clock_tests { /// so this cannot be satisfied by `prepare_creation`'s own check. #[test] fn genesis_itself_refuses_a_ruled_fact_and_a_mint() { - let world_id = WorldId::issue(); - let mut input = creation(CommandId::new(), "GenesisRuleDirect"); + let mut input = creation("GenesisRuleDirect"); + let world_id = WorldId::of(input.id()); input .patch .declarations @@ -10746,7 +10664,7 @@ mod clock_tests { let title = normalize_title(&input.title).unwrap(); let resolved = patch::resolve_patch( &WorldState::empty(world_id, input.owner.clone(), title.clone(), None), - input.id, + input.id(), &input.patch, ) .expect("the resolver is actor-blind and accepts a Ruled fact"); @@ -10758,8 +10676,8 @@ mod clock_tests { let error = WorldState::genesis(world_id, &input, &effect).unwrap_err(); assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); - let world_id = WorldId::issue(); - let mut input = creation(CommandId::new(), "GenesisMintDirect"); + let mut input = creation("GenesisMintDirect"); + let world_id = WorldId::of(input.id()); input .patch .declarations @@ -10772,7 +10690,7 @@ mod clock_tests { let title = normalize_title(&input.title).unwrap(); let resolved = patch::resolve_patch( &WorldState::empty(world_id, input.owner.clone(), title.clone(), None), - input.id, + input.id(), &input.patch, ) .expect("the resolver is actor-blind and accepts a Mint"); @@ -10911,7 +10829,6 @@ mod clock_tests { let snapshot = kernel.snapshot().unwrap(); let ticking = command( &snapshot, - CommandId::new(), CallerId::Play, CommandBody::AdvanceTime { minutes: minutes(span), @@ -10929,7 +10846,7 @@ mod clock_tests { // Applying the re-derived effect to a copy reproduces the committed // state exactly, which is the replay identity the journal relies on. let mut replayed = kernel.state.clone(); - apply_effect(&mut replayed, ticking.id, &CallerId::Play, &expected) + apply_effect(&mut replayed, ticking.id(), &CallerId::Play, &expected) .expect("the re-derived effect applies"); kernel .submit(ticking, &AuthenticatedCaller::fixture(CallerId::Play)) @@ -10945,10 +10862,10 @@ mod clock_tests { kernel: &mut WorldKernel, caller: CallerId, body: CommandBody, - ) -> Result<SubmitReceipt, KernelError> { + ) -> Result<CommitReceipt, KernelError> { let snapshot = kernel.snapshot().unwrap(); kernel.submit( - command(&snapshot, CommandId::new(), caller.clone(), body), + command(&snapshot, caller.clone(), body), &AuthenticatedCaller::fixture(caller), ) } @@ -11035,7 +10952,7 @@ mod clock_tests { }, ) .expect("the play authority declares unanswered in Active"); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); } /// Invariant 5: the play authority reaches the whole world, unconfined to @@ -11068,7 +10985,7 @@ mod clock_tests { }, ) .expect("the play authority advances time"); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); assert!(kernel.state.now > active.now); } @@ -11279,7 +11196,7 @@ mod clock_tests { } /// Play retires a subject. - fn play_retires(kernel: &mut WorldKernel, subject: SubjectId) -> Result<SubmitReceipt, KernelError> { + fn play_retires(kernel: &mut WorldKernel, subject: SubjectId) -> Result<CommitReceipt, KernelError> { submit_as( kernel, CallerId::Play, @@ -11444,7 +11361,7 @@ mod clock_tests { let directory = tempfile::tempdir().unwrap(); let mut kernel = WorldKernel::create( directory.path().join("world.cc"), - creation(CommandId::new(), "SeedGrantsDraft"), + creation("SeedGrantsDraft"), &auth_principal(owner()), ) .expect("a created world") @@ -11726,7 +11643,7 @@ mod clock_tests { let directory = tempfile::tempdir().unwrap(); let mut kernel = WorldKernel::create( directory.path().join("world.cc"), - creation(CommandId::new(), "PAf33CanReach"), + creation("PAf33CanReach"), &auth_principal(owner()), ) .expect("a created world") @@ -12286,7 +12203,7 @@ mod agency_tests { let path = directory.path().join("world.cc"); let (kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), title), + creation(title), &auth_principal(owner()), ) .unwrap(); @@ -12359,7 +12276,7 @@ mod agency_tests { let commits = kernel.journal.commit_count(); let error = kernel .submit( - command(&snapshot, CommandId::new(), caller.clone(), body.clone()), + command(&snapshot, caller.clone(), body.clone()), &AuthenticatedCaller::fixture(caller.clone()), ) .unwrap_err(); @@ -12375,11 +12292,11 @@ mod agency_tests { let before = kernel.snapshot().unwrap(); let receipt = kernel .submit( - play_command(&before, CommandId::new(), body), + play_command(&before, body), &AuthenticatedCaller::verified_play(), ) .unwrap_or_else(|error| panic!("Play {name}: {error:?}")); - assert!(matches!(receipt, SubmitReceipt::Applied(_)), "Play {name}"); + assert!(receipt.resulting_revision > 0, "Play {name}"); } } @@ -12458,7 +12375,7 @@ mod agency_tests { for body in [broken.clone(), denied.clone()] { let error = kernel .submit( - command(&snapshot, CommandId::new(), caller.clone(), body), + command(&snapshot, caller.clone(), body), &AuthenticatedCaller::fixture(caller.clone()), ) .unwrap_err(); @@ -12619,7 +12536,7 @@ mod agency_tests { }) }; let directory = tempfile::tempdir().unwrap(); - let mut input = creation(CommandId::new(), "Mutes"); + let mut input = creation("Mutes"); input.patch.declarations.push(mute("born-mute")); let (mut kernel, _) = WorldKernel::create( directory.path().join("world.cc"), diff --git a/native/aetherlight/src/patch.rs b/native/aetherlight/src/patch.rs index c63939012..cbdc5477d 100644 --- a/native/aetherlight/src/patch.rs +++ b/native/aetherlight/src/patch.rs @@ -5679,7 +5679,7 @@ mod tests { over_place, owner, reject_play, speak_entry, submit_play, }; use crate::{ - AuthenticatedCaller, CallerId, CommandBody, CommandId, KernelError, SubmitReceipt, WorldKernel, + AuthenticatedCaller, CallerId, CommandBody, CommandId, KernelError, WorldKernel, }; fn entity(handle: &str, label: &str, kind: EntityKind) -> Declaration { @@ -6030,7 +6030,7 @@ mod tests { granting("verb"), ])), ); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); assert_eq!(kernel.state.affordance_catalog.len(), entries_before + 1); assert_eq!(kernel.state.subjects.len(), subjects_before + 1); let granted = kernel @@ -6106,7 +6106,7 @@ mod tests { fn draft_world(directory: &std::path::Path) -> WorldKernel { WorldKernel::create( directory.join("world.cc"), - creation(CommandId::new(), "Kharad"), + creation("Kharad"), &auth_principal(owner()), ) .expect("draft world") @@ -6126,7 +6126,6 @@ mod tests { .submit( command( &before, - CommandId::new(), CallerId::Play, admit(patch_of(vec![institution( &kernel, @@ -6183,7 +6182,7 @@ mod tests { ), ]); let receipt = submit_play(&mut kernel, &before, admit(patch)); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); let after = kernel.snapshot().unwrap(); assert_eq!(after.revision, before.revision + 1); @@ -6236,7 +6235,6 @@ mod tests { .submit( command( &before, - CommandId::new(), CallerId::Play, admit(patch_of(vec![ entity("rhythm-tithe", "The Rhythm Tithe", EntityKind::Resource), @@ -6290,7 +6288,6 @@ mod tests { .submit( command( &before, - CommandId::new(), CallerId::Play, admit(broken), ), @@ -6336,7 +6333,7 @@ mod tests { }), ]); let receipt = submit_play(&mut kernel, &before, admit(repaired)); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); assert_eq!(kernel.state.entities.len(), 3); } @@ -6350,7 +6347,6 @@ mod tests { .submit( command( &before, - CommandId::new(), CallerId::Play, admit(patch_of(Vec::new())), ), @@ -6377,7 +6373,6 @@ mod tests { .submit( command( &before, - CommandId::new(), CallerId::Play, admit(patch_of(vec![ contained("yard", "The Cavity Yard", "road"), @@ -6422,7 +6417,6 @@ mod tests { .submit( command( &before, - CommandId::new(), CallerId::Play, admit(patch_of(vec![ entity("yard", "The Cavity Yard", EntityKind::Place), @@ -6462,7 +6456,6 @@ mod tests { .submit( command( &before, - CommandId::new(), CallerId::Play, admit(WorldPatch { declarations: vec![Declaration::Route(RouteDeclaration { @@ -6521,7 +6514,6 @@ mod tests { .submit( command( &active, - CommandId::new(), CallerId::Play, admit(operations_of(vec![ComponentOp::Relocate { subject: Ref::Existing(topology.walker), @@ -6572,7 +6564,7 @@ mod tests { ])), ); assert!( - matches!(receipt, SubmitReceipt::Applied(_)), + receipt.resulting_revision > 0, "a dead institution's lend must not collide with a fresh direct grant over the same ground" ); } @@ -6609,7 +6601,7 @@ mod tests { ])), ); assert!( - matches!(delegated, SubmitReceipt::Applied(_)), + delegated.resulting_revision > 0, "expected the delegation patch to apply, got {delegated:?}" ); let after_delegation = kernel.snapshot().unwrap(); @@ -6654,7 +6646,7 @@ mod tests { via: Ref::Existing(topology.ramp), }])), ); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); assert_eq!( kernel.state.positions.get(&topology.walker), Some(&Position { @@ -6681,7 +6673,7 @@ mod tests { let path = directory.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), "Kharad"), + creation("Kharad"), &auth_principal(owner()), ) .unwrap(); @@ -6689,7 +6681,6 @@ mod tests { let active = kernel.snapshot().unwrap(); let envelope = command( &active, - CommandId::new(), CallerId::Play, admit(operations_of(vec![ComponentOp::Relocate { subject: Ref::Existing(topology.walker), @@ -6712,8 +6703,8 @@ mod tests { }) ); assert!(matches!( - reopened.submit(envelope, &AuthenticatedCaller::verified_play()).unwrap(), - SubmitReceipt::AlreadyApplied(_) + reopened.submit(envelope, &AuthenticatedCaller::verified_play()), + Err(KernelError::RevisionMismatch { .. }) )); } @@ -6764,14 +6755,13 @@ mod tests { let path = directory.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), "Kharad"), + creation("Kharad"), &auth_principal(owner()), ) .unwrap(); let before = kernel.snapshot().unwrap(); let envelope = command( &before, - CommandId::new(), CallerId::Play, admit(patch_of(vec![ entity("rhythm-road", "The Rhythm Road", EntityKind::Place), @@ -6793,8 +6783,8 @@ mod tests { let mut reopened = WorldKernel::open(&path, world_id).unwrap(); assert_eq!(reopened.snapshot().unwrap(), committed); assert!(matches!( - reopened.submit(envelope, &AuthenticatedCaller::verified_play()).unwrap(), - SubmitReceipt::AlreadyApplied(_) + reopened.submit(envelope, &AuthenticatedCaller::verified_play()), + Err(KernelError::RevisionMismatch { .. }) )); } @@ -6831,7 +6821,7 @@ mod tests { .0; assert_ne!(admitted, genesis_human); - let command_id = CommandId::new(); + let command_id = CommandId::issue(); let first = resolve_patch(&kernel.state, command_id, &patch).unwrap(); let second = resolve_patch(&kernel.state, command_id, &patch).unwrap(); assert_eq!(first, second); @@ -6846,29 +6836,26 @@ mod tests { let path = directory.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), "Kharad"), + creation("Kharad"), &auth_principal(owner()), ) .unwrap(); let before = kernel.snapshot().unwrap(); - let command_id = CommandId::new(); let handle = DraftHandle::new("rhythm-authority"); + let envelope = command( + &before, + CallerId::Play, + admit(patch_of(vec![institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("kharad-rhythm-road"))), + )])), + ); + let command_id = envelope.id(); let error = kernel - .submit( - command( - &before, - command_id, - CallerId::Play, - admit(patch_of(vec![institution( - &kernel, - "rhythm-authority", - "The Rhythm Authority", - Some(Ref::Draft(DraftHandle::new("kharad-rhythm-road"))), - )])), - ), - &AuthenticatedCaller::verified_play(), - ) + .submit(envelope, &AuthenticatedCaller::verified_play()) .unwrap_err(); assert!(matches!(error, KernelError::PatchRejected(_))); @@ -6920,12 +6907,12 @@ mod tests { let directory = tempfile::tempdir().unwrap(); let (kernel, _) = WorldKernel::create( &directory.path().join("world.cc"), - creation(CommandId::new(), "DeriveId"), + creation("DeriveId"), &auth_principal(owner()), ) .unwrap(); let world_id = kernel.state.world_id; - let command_id = CommandId::new(); + let command_id = CommandId::issue(); let handle = DraftHandle::new("a-handle"); assert_ne!( derive_id(SUBJECT_NAMESPACE, world_id, command_id, &handle, None), @@ -6968,7 +6955,7 @@ mod tests { Some(Ref::Draft(DraftHandle::new("rhythm-road"))), ), ]); - let resolved = resolve_patch(&kernel.state, CommandId::new(), &patch).unwrap(); + let resolved = resolve_patch(&kernel.state, CommandId::issue(), &patch).unwrap(); let honest = super::super::WorldEffect::PatchAdmitted { resolved: resolved.clone(), }; @@ -7036,7 +7023,6 @@ mod tests { .submit( command( &before, - CommandId::new(), CallerId::Play, admit(patch_of(vec![ entity("hollow", "The Hollow", EntityKind::Place), @@ -7088,7 +7074,6 @@ mod tests { .submit( command( &active, - CommandId::new(), CallerId::Play, admit(operations_of(vec![ComponentOp::Relocate { subject: Ref::Existing(unplaced), @@ -7109,7 +7094,6 @@ mod tests { .submit( command( &active, - CommandId::new(), CallerId::Play, admit(operations_of(vec![ ComponentOp::OpenRoute { From 94a3c67d6d6a5e3c78ac746197a41cd2b2f65675 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 02:35:03 +0100 Subject: [PATCH 145/190] aetherlight: the journal is an in-memory commit list with export and open The redb store, the state row, health and ownership checks, verify_append and the retry paths are gone. WorldJournal holds the commits in revision order; export() writes { schema: aetherlight.journal.v1, commits } as canonical named messagepack and open(bytes) decodes canonically and replays through verify_history, which now reads the slice and returns the head state it derives. A genesis commit must carry WorldId::of(creation id). chrono, cultcache-rs and tempfile leave the manifest; uuid v4 is dev-only. Tests build worlds in memory and reopen from export(); forgery tests build exports. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/Cargo.lock | 364 ------- native/aetherlight/Cargo.toml | 7 +- native/aetherlight/src/action.rs | 113 +- native/aetherlight/src/grammar/tests.rs | 51 +- native/aetherlight/src/import_key_tests.rs | 60 +- native/aetherlight/src/journal.rs | 1127 ++++---------------- native/aetherlight/src/lib.rs | 878 +++++---------- native/aetherlight/src/patch.rs | 112 +- 8 files changed, 613 insertions(+), 2099 deletions(-) diff --git a/native/aetherlight/Cargo.lock b/native/aetherlight/Cargo.lock index d79ad2fc6..494df4f1d 100644 --- a/native/aetherlight/Cargo.lock +++ b/native/aetherlight/Cargo.lock @@ -6,46 +6,22 @@ version = 4 name = "aetherlight" version = "0.1.0" dependencies = [ - "chrono", - "cultcache-rs", "rmp-serde", "serde", "serde_json", "sha2", - "tempfile", "thiserror", "unicode-normalization", "unicode-properties", "uuid", ] -[[package]] -name = "android_system_properties" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" -dependencies = [ - "libc", -] - -[[package]] -name = "anyhow" -version = "1.0.104" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" - [[package]] name = "autocfg" version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" -[[package]] -name = "bitflags" -version = "2.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" - [[package]] name = "block-buffer" version = "0.10.4" @@ -61,42 +37,12 @@ version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" -[[package]] -name = "cc" -version = "1.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "509591b7bcd67f4ef775afad7662703b4935daaa6ec0e5605cfb1090b32a2b6d" -dependencies = [ - "find-msvc-tools", - "shlex", -] - [[package]] name = "cfg-if" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-link", -] - -[[package]] -name = "core-foundation-sys" -version = "0.8.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" - [[package]] name = "cpufeatures" version = "0.2.17" @@ -116,34 +62,6 @@ dependencies = [ "typenum", ] -[[package]] -name = "cultcache-rs" -version = "0.1.0" -source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a0199a064526427150191#85f7024a35ea42cf9f0a0199a064526427150191" -dependencies = [ - "anyhow", - "chrono", - "cultcache-rs-derive", - "fs2", - "redb", - "rmp-serde", - "serde", - "serde_bytes", - "serde_json", - "uuid", - "windows-sys 0.59.0", -] - -[[package]] -name = "cultcache-rs-derive" -version = "0.1.0" -source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a0199a064526427150191#85f7024a35ea42cf9f0a0199a064526427150191" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "digest" version = "0.10.7" @@ -154,38 +72,6 @@ dependencies = [ "crypto-common", ] -[[package]] -name = "errno" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "fastrand" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" - -[[package]] -name = "find-msvc-tools" -version = "0.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890" - -[[package]] -name = "fs2" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213" -dependencies = [ - "libc", - "winapi", -] - [[package]] name = "futures-core" version = "0.3.34" @@ -231,30 +117,6 @@ dependencies = [ "r-efi", ] -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - [[package]] name = "itoa" version = "1.0.18" @@ -278,18 +140,6 @@ version = "0.2.189" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" -[[package]] -name = "linux-raw-sys" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" - -[[package]] -name = "log" -version = "0.4.33" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" - [[package]] name = "memchr" version = "2.8.3" @@ -341,15 +191,6 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" -[[package]] -name = "redb" -version = "4.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e925444704b5f17d32bf42f5b6e2df050bceebc3dcd6e71cc73dafe8092e839" -dependencies = [ - "libc", -] - [[package]] name = "rmp" version = "0.8.15" @@ -369,19 +210,6 @@ dependencies = [ "serde", ] -[[package]] -name = "rustix" -version = "1.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" -dependencies = [ - "bitflags", - "errno", - "libc", - "linux-raw-sys", - "windows-sys 0.61.2", -] - [[package]] name = "rustversion" version = "1.0.23" @@ -398,16 +226,6 @@ dependencies = [ "serde_derive", ] -[[package]] -name = "serde_bytes" -version = "0.11.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" -dependencies = [ - "serde", - "serde_core", -] - [[package]] name = "serde_core" version = "1.0.229" @@ -452,12 +270,6 @@ dependencies = [ "digest", ] -[[package]] -name = "shlex" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" - [[package]] name = "slab" version = "0.4.12" @@ -486,19 +298,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "tempfile" -version = "3.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" -dependencies = [ - "fastrand", - "getrandom", - "once_cell", - "rustix", - "windows-sys 0.61.2", -] - [[package]] name = "thiserror" version = "2.0.20" @@ -624,169 +423,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "windows-core" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-implement" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-interface" -version = "0.59.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-result" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-strings" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-sys" -version = "0.59.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" -dependencies = [ - "windows-targets", -] - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - [[package]] name = "zmij" version = "1.0.23" diff --git a/native/aetherlight/Cargo.toml b/native/aetherlight/Cargo.toml index ec8f9d37e..49c9a5965 100644 --- a/native/aetherlight/Cargo.toml +++ b/native/aetherlight/Cargo.toml @@ -9,8 +9,6 @@ publish = false [workspace] [dependencies] -chrono = { version = "0.4", features = ["serde"] } -cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "85f7024a35ea42cf9f0a0199a064526427150191", package = "cultcache-rs" } rmp-serde = "1.3" serde = { version = "1", features = ["derive"] } serde_json = "1" @@ -18,7 +16,8 @@ sha2 = "0.10" thiserror = "2" unicode-normalization = "0.1.25" unicode-properties = "0.1.4" -uuid = { version = "1", features = ["v4", "serde"] } +uuid = { version = "1", features = ["serde"] } [dev-dependencies] -tempfile = "3" +# Test fixtures draw random ids; no shipped path does. +uuid = { version = "1", features = ["v4"] } diff --git a/native/aetherlight/src/action.rs b/native/aetherlight/src/action.rs index 64b18f413..8f61aebac 100644 --- a/native/aetherlight/src/action.rs +++ b/native/aetherlight/src/action.rs @@ -1039,8 +1039,8 @@ mod tests { shutter: EdgeId, } - fn bench(directory: &std::path::Path, title: &str) -> Bench { - let mut kernel = custody_kernel(directory, title); + fn bench(title: &str) -> Bench { + let mut kernel = custody_kernel(title); let (topology, custody, active) = custody_world(&mut kernel); let carry = affordance_named(&active, "carry"); Bench { @@ -1184,8 +1184,7 @@ mod tests { #[test] fn a_missing_present_precondition_names_itself() { - let directory = tempfile::tempdir().unwrap(); - let bench = bench(directory.path(), "Present"); + let bench = bench("Present"); let before = bench.kernel.state.clone(); // The clerk stands in the yard, so a Carry bound to the gate fails the @@ -1201,8 +1200,7 @@ mod tests { #[test] fn spending_more_than_held_fails_the_holds_precondition() { - let directory = tempfile::tempdir().unwrap(); - let bench = bench(directory.path(), "Holds"); + let bench = bench("Holds"); let greedy = bench.variant(&bench.carry(1, bench.yard), "carry_greedy"); assert_eq!( bench.rejections(&greedy), @@ -1222,8 +1220,7 @@ mod tests { /// spends down to one ingot-equivalent, and `carry_holds` asks for one. #[test] fn holding_exactly_the_threshold_satisfies_holds() { - let directory = tempfile::tempdir().unwrap(); - let mut bench = bench(directory.path(), "HoldsBoundary"); + let mut bench = bench("HoldsBoundary"); for _ in 0..2 { bench.commit(bench.carry(3, bench.yard)); bench.refresh(); @@ -1245,8 +1242,7 @@ mod tests { #[test] fn a_reachable_precondition_reads_only_open_public_routes() { - let directory = tempfile::tempdir().unwrap(); - let mut bench = bench(directory.path(), "Reachable"); + let mut bench = bench("Reachable"); // Yard to gate over open public routes is the ramp (12) plus the span // (7): the shutter is closed and the toll stair is restricted. A budget // of NEAR_REACH covers only the shutter, FAR_REACH covers the two-hop @@ -1291,8 +1287,7 @@ mod tests { #[test] fn an_unbound_or_miskinded_role_is_rejected_with_the_complete_set() { - let directory = tempfile::tempdir().unwrap(); - let bench = bench(directory.path(), "Roles"); + let bench = bench("Roles"); let mut invocation = bench.carry(1, bench.yard); // Drop `recipient`, add an undeclared role, and bind `resource` to a // place: one rejection carrying all three, sorted. @@ -1321,8 +1316,7 @@ mod tests { #[test] fn a_duplicated_or_unknown_binding_target_is_rejected() { - let directory = tempfile::tempdir().unwrap(); - let bench = bench(directory.path(), "Bindings"); + let bench = bench("Bindings"); let mut twice = bench.carry(1, bench.yard); twice .bindings @@ -1348,8 +1342,7 @@ mod tests { #[test] fn a_magnitude_over_its_slot_ceiling_is_rejected_and_within_it_commits() { - let directory = tempfile::tempdir().unwrap(); - let mut bench = bench(directory.path(), "Ceiling"); + let mut bench = bench("Ceiling"); assert_eq!( bench.rejections(&bench.carry(4, bench.yard)), vec![ActionMismatch::MagnitudeOverCeiling { slot: 0 }] @@ -1370,8 +1363,7 @@ mod tests { #[test] fn a_magnitude_of_the_wrong_shape_or_zero_is_rejected() { - let directory = tempfile::tempdir().unwrap(); - let bench = bench(directory.path(), "Shape"); + let bench = bench("Shape"); for magnitude in [Magnitude::Cost(Cost(2)), Magnitude::None] { let mut invocation = bench.carry(1, bench.yard); invocation.proposed[0].magnitude = magnitude; @@ -1388,8 +1380,7 @@ mod tests { #[test] fn every_slot_must_be_proposed_exactly_once() { - let directory = tempfile::tempdir().unwrap(); - let bench = bench(directory.path(), "Slots"); + let bench = bench("Slots"); let mut missing = bench.carry(1, bench.yard); missing.proposed.clear(); assert_eq!( @@ -1417,8 +1408,7 @@ mod tests { #[test] fn speech_is_required_exactly_when_the_entry_carries_it() { - let directory = tempfile::tempdir().unwrap(); - let bench = bench(directory.path(), "Speech"); + let bench = bench("Speech"); let mut spoken_carry = bench.carry(1, bench.yard); spoken_carry.speech = Some(Statement::new("Take it.").unwrap()); assert_eq!( @@ -1450,8 +1440,7 @@ mod tests { #[test] fn the_same_command_id_always_selects_the_same_band() { - let directory = tempfile::tempdir().unwrap(); - let bench = bench(directory.path(), "Bands"); + let bench = bench("Bands"); // Three equally weighted bands, so the draw alone decides. let invocation = bench.variant(&bench.carry(1, bench.yard), "carry_chance"); let draw = |command_id: CommandId, invocation: &DecisionInvocation| { @@ -1488,8 +1477,7 @@ mod tests { #[test] fn a_zero_effect_band_commits_nothing_but_the_event() { - let directory = tempfile::tempdir().unwrap(); - let mut bench = bench(directory.path(), "EmptyBand"); + let mut bench = bench("EmptyBand"); let idle = bench.variant(&bench.carry(3, bench.yard), "carry_idle"); let holdings = bench.kernel.state.holdings.clone(); @@ -1514,8 +1502,7 @@ mod tests { #[test] fn a_committed_event_carries_the_exact_lowered_operations() { - let directory = tempfile::tempdir().unwrap(); - let mut bench = bench(directory.path(), "Lowering"); + let mut bench = bench("Lowering"); let receipt = bench.commit(bench.carry(2, bench.yard)); assert!(receipt.resulting_revision > 0); let event = bench @@ -1546,8 +1533,7 @@ mod tests { /// passes by never being taken. #[test] fn soul_only_the_selected_bands_effects_are_committed() { - let directory = tempfile::tempdir().unwrap(); - let mut bench = bench(directory.path(), "SelectedBand"); + let mut bench = bench("SelectedBand"); let split_id = affordance_named(&bench.active, "carry_split"); let split = DecisionInvocation { affordance: split_id, @@ -1633,8 +1619,7 @@ mod tests { /// wrong. The fixture catalog carries four such roles. #[test] fn soul_a_stored_role_spec_over_an_optional_subject_kind_round_trips() { - let directory = tempfile::tempdir().unwrap(); - let bench = bench(directory.path(), "OptionalSubjectKind"); + let bench = bench("OptionalSubjectKind"); let entry = bench .kernel .state @@ -1661,8 +1646,7 @@ mod tests { #[test] fn a_forged_band_or_forged_effect_does_not_apply() { - let directory = tempfile::tempdir().unwrap(); - let bench = bench(directory.path(), "ForgedAction"); + let bench = bench("ForgedAction"); let command_id = CommandId::issue(); let invocation = bench.carry(2, bench.yard); let honest = draw_once(&bench.kernel.state, command_id, bench.clerk, &invocation).unwrap(); @@ -1735,8 +1719,7 @@ mod tests { #[test] fn the_kernel_speak_entry_commits_its_utterance_and_no_operation() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = custody_kernel(directory.path(), "SpeakEntry"); + let mut kernel = custody_kernel("SpeakEntry"); let _topology = kernel.snapshot().unwrap(); let active = kernel.snapshot().unwrap(); let speak = affordance_named(&active, "speak"); @@ -1781,8 +1764,8 @@ mod tests { civic: Civic, } - fn civics(directory: &std::path::Path, title: &str) -> Civics { - let mut kernel = custody_kernel(directory, title); + fn civics(title: &str) -> Civics { + let mut kernel = custody_kernel(title); let (topology, civic, active) = civic_world(&mut kernel); Civics { kernel, @@ -1929,8 +1912,7 @@ mod tests { /// exact failed precondition and no allocation. #[test] fn an_unauthorized_actor_names_the_failed_precondition() { - let directory = tempfile::tempdir().unwrap(); - let bench = civics(directory.path(), "Unauthorized"); + let bench = civics("Unauthorized"); let before = bench.kernel.state.clone(); assert_eq!( bench.rejected_as(bench.civic.farmer, &bench.levy(bench.civic.reeve, 1)), @@ -1946,8 +1928,7 @@ mod tests { /// being authorized without any digest moving. #[test] fn place_jurisdiction_reaches_a_containment_subtree_and_stops_at_its_edge() { - let directory = tempfile::tempdir().unwrap(); - let mut bench = civics(directory.path(), "Subtree"); + let mut bench = civics("Subtree"); let treasury = bench.civic.treasury; let farmer = bench.civic.farmer; @@ -1996,8 +1977,7 @@ mod tests { /// it back: the act is refused at admission. #[test] fn office_delegation_grants_and_vacating_revokes() { - let directory = tempfile::tempdir().unwrap(); - let mut bench = civics(directory.path(), "Office"); + let mut bench = civics("Office"); let reeve = bench.civic.reeve; let farmer = bench.civic.farmer; assert!(bench.kernel.state.authority.get(&reeve).is_none()); @@ -2024,8 +2004,7 @@ mod tests { /// a catalog entry may not declare it. #[test] fn a_levy_cannot_be_directed_away_from_the_actor() { - let directory = tempfile::tempdir().unwrap(); - let bench = civics(directory.path(), "ActorRole"); + let bench = civics("ActorRole"); let mut redirected = bench.levy(bench.civic.farmer, 1); redirected .bindings @@ -2036,8 +2015,7 @@ mod tests { ); // The declaration half runs at genesis, so it runs against a fresh world. - let draft_directory = tempfile::tempdir().unwrap(); - let mut draft = custody_kernel(draft_directory.path(), "ReservedRole"); + let mut draft = custody_kernel("ReservedRole"); let before = draft.snapshot().unwrap(); let handle = DraftHandle::new("thief"); let rejected = reject_play( @@ -2074,8 +2052,7 @@ mod tests { /// declared ceiling passes every affordance check and dies in the ledger. #[test] fn an_over_levy_fails_in_the_ledger_not_in_the_contract() { - let directory = tempfile::tempdir().unwrap(); - let bench = civics(directory.path(), "OverLevy"); + let bench = civics("OverLevy"); let error = bench .try_as(bench.civic.treasury, &bench.levy(bench.civic.farmer, 9)) .unwrap_err(); @@ -2092,8 +2069,7 @@ mod tests { /// does mint is still subject to disjointness. #[test] fn a_delegated_grant_may_not_exceed_the_granter() { - let directory = tempfile::tempdir().unwrap(); - let mut bench = civics(directory.path(), "Monotone"); + let mut bench = civics("Monotone"); let treasury = bench.civic.treasury; let outsider = bench.civic.outsider; @@ -2148,8 +2124,7 @@ mod tests { /// what it may otherwise touch. #[test] fn revoking_a_grant_requires_covering_authority_over_its_ground() { - let directory = tempfile::tempdir().unwrap(); - let mut bench = civics(directory.path(), "RevokeEnvelope"); + let mut bench = civics("RevokeEnvelope"); let treasury = bench.civic.treasury; let farmer = bench.civic.farmer; let hall = bench.civic.hall; @@ -2184,8 +2159,7 @@ mod tests { /// fails the same `Authorized` precondition every other civic act reads. #[test] fn deploy_relocates_a_subordinate_under_command_and_refuses_one_outside_it() { - let directory = tempfile::tempdir().unwrap(); - let mut bench = civics(directory.path(), "Deploy"); + let mut bench = civics("Deploy"); let treasury = bench.civic.treasury; let farmer = bench.civic.farmer; let outsider = bench.civic.outsider; @@ -2228,8 +2202,7 @@ mod tests { /// the forum's target, and closing the forum removes the verb's ground. #[test] fn a_petition_requires_standing() { - let directory = tempfile::tempdir().unwrap(); - let mut bench = civics(directory.path(), "Petition"); + let mut bench = civics("Petition"); let petition = bench.call( "petition", Vec::new(), @@ -2269,8 +2242,7 @@ mod tests { /// same-patch grant then move resolves through the candidate shadow. #[test] fn a_restricted_route_admits_exactly_its_named_authority() { - let directory = tempfile::tempdir().unwrap(); - let mut bench = civics(directory.path(), "Restricted"); + let mut bench = civics("Restricted"); let walker = bench.topology.walker; let step = ComponentOp::Relocate { subject: PatchRef::Existing(walker), @@ -2332,8 +2304,7 @@ mod tests { /// someone performs under authority rather than a declared method string. #[test] fn sanction_and_appoint_reach_the_reducer_under_authority() { - let directory = tempfile::tempdir().unwrap(); - let mut bench = civics(directory.path(), "Institutional"); + let mut bench = civics("Institutional"); let treasury = bench.civic.treasury; let passage = bench.civic.passage; let sanction = bench.call( @@ -2397,8 +2368,7 @@ mod tests { /// path reaches it, and the refused act commits nothing. #[test] fn soul_delegation_not_monotone_reaches_the_real_command_path() { - let directory = tempfile::tempdir().unwrap(); - let mut bench = civics(directory.path(), "SoulMonotone"); + let mut bench = civics("SoulMonotone"); let treasury = bench.civic.treasury; let road = bench.topology.road; let outsider = bench.civic.outsider; @@ -2424,8 +2394,7 @@ mod tests { /// operation succeeds the moment the key exists. #[test] fn soul_a_restricted_relocate_is_refused_by_the_component_writer() { - let directory = tempfile::tempdir().unwrap(); - let bench = civics(directory.path(), "SoulReducerGate"); + let bench = civics("SoulReducerGate"); let walker = bench.topology.walker; let step = ResolvedOp::Relocate { subject_id: walker, @@ -2465,8 +2434,7 @@ mod tests { /// admission, and nothing commits. #[test] fn soul_a_granter_revocation_refuses_the_delegates_act() { - let directory = tempfile::tempdir().unwrap(); - let mut bench = civics(directory.path(), "SoulRebind"); + let mut bench = civics("SoulRebind"); let reeve = bench.civic.reeve; let farmer = bench.civic.farmer; let treasury = bench.civic.treasury; @@ -2497,8 +2465,7 @@ mod tests { /// is refused. #[test] fn soul_a_subject_grant_inside_a_place_grant_is_a_second_source() { - let directory = tempfile::tempdir().unwrap(); - let mut bench = civics(directory.path(), "SoulOverlap"); + let mut bench = civics("SoulOverlap"); let treasury = bench.civic.treasury; let farmer = bench.civic.farmer; let hall = bench.civic.hall; @@ -2533,8 +2500,7 @@ mod tests { /// the commit stored. No clock and no draw entropy enter. #[test] fn soul_reduce_is_pure_for_every_new_civic_arm() { - let directory = tempfile::tempdir().unwrap(); - let mut bench = civics(directory.path(), "SoulReplay"); + let mut bench = civics("SoulReplay"); let treasury = bench.civic.treasury; let farmer = bench.civic.farmer; let outsider = bench.civic.outsider; @@ -2610,8 +2576,7 @@ mod tests { /// author cannot widen either without this assertion naming the change. #[test] fn no_component_op_kind_lowers_to_a_told_knowledge_write() { - let directory = tempfile::tempdir().unwrap(); - let bench = bench(directory.path(), "AcquireKnowledgeLowering"); + let bench = bench("AcquireKnowledgeLowering"); let entry = Affordance { kind: AffordanceKindName("witness".into()), roles: Vec::new(), diff --git a/native/aetherlight/src/grammar/tests.rs b/native/aetherlight/src/grammar/tests.rs index 3743f2a9a..c7486841e 100644 --- a/native/aetherlight/src/grammar/tests.rs +++ b/native/aetherlight/src/grammar/tests.rs @@ -84,16 +84,8 @@ fn rejected(result: Result<impl Sized, KernelError>) -> Vec<Mismatch> { } } -/// Each call gets its own store path: kernels are created, not reopened. -fn create(world: CreateWorld) -> (tempfile::TempDir, Result<WorldKernel, KernelError>) { - let directory = tempfile::tempdir().unwrap(); - let result = WorldKernel::create( - directory.path().join("world.cc"), - world, - &auth_principal(owner()), - ) - .map(|(kernel, _)| kernel); - (directory, result) +fn create(world: CreateWorld) -> Result<WorldKernel, KernelError> { + WorldKernel::create(world, &auth_principal(owner())).map(|(kernel, _)| kernel) } fn admit(kernel: &mut WorldKernel, patch: WorldPatch) -> Result<CommitReceipt, KernelError> { @@ -135,12 +127,12 @@ fn grammar_world_refuses_an_affordance_kind_outside_the_grammar() { // Genesis: a declared kind the binding lacks is refused. let mut world = bound(Some(grammar_with(&[])), "Outside"); world.patch.declarations.push(declare("wave", "wave", &[])); - assert_eq!(rejected(create(world).1), not_in_grammar("wave")); + assert_eq!(rejected(create(world)), not_in_grammar("wave")); // A later AdmitPatch: the same kind is refused, and a verb the grammar // does carry is admitted by the same path. let extra = [("hail", verb(RenderPath::Conversation, &[]))]; - let (_dir, kernel) = create(bound(Some(grammar_with(&extra)), "Outside")); + let kernel = create(bound(Some(grammar_with(&extra)), "Outside")); let mut kernel = kernel.unwrap(); assert_eq!( rejected(admit( @@ -168,7 +160,7 @@ fn grammar_world_refuses_a_role_signature_the_grammar_does_not_carry() { ), ("hail", verb(RenderPath::Conversation, &[])), ]; - let (_dir, kernel) = create(bound(Some(grammar_with(&extra)), "Signatures")); + let kernel = create(bound(Some(grammar_with(&extra)), "Signatures")); let mut kernel = kernel.unwrap(); for (label, roles) in [ ("renamed", vec![("whom", person()), ("where_", place())]), @@ -226,7 +218,7 @@ fn each_grammar_referent_kind_admits_exactly_its_own_kernel_kind() { for (referent, own) in &kinds { let extra = [("act", verb(RenderPath::ShipAction, &[("with", *referent)]))]; for (_, offered) in &kinds { - let (_dir, kernel) = create(bound(Some(grammar_with(&extra)), "Referents")); + let kernel = create(bound(Some(grammar_with(&extra)), "Referents")); let mut kernel = kernel.unwrap(); let result = admit( &mut kernel, @@ -257,7 +249,7 @@ fn grammar_world_without_speak_refuses_the_kernel_speak_grant() { ) .unwrap(); assert_eq!( - rejected(create(bound(Some(no_speak), "Mute")).1), + rejected(create(bound(Some(no_speak), "Mute"))), not_in_grammar(crate::patch::KERNEL_SPEAK_HANDLE) ); @@ -278,7 +270,7 @@ fn grammar_world_without_speak_refuses_the_kernel_speak_grant() { ) .unwrap(); assert_eq!( - rejected(create(bound(Some(loud), "Loud")).1), + rejected(create(bound(Some(loud), "Loud"))), disagrees(crate::patch::KERNEL_SPEAK_HANDLE) ); } @@ -290,7 +282,7 @@ fn unbound_world_keeps_the_open_catalog() { .patch .declarations .push(declare("wave", "wave", &[("at", person())])); - let (_dir, kernel) = create(world); + let kernel = create(world); let mut kernel = kernel.unwrap(); let receipt = admit( &mut kernel, @@ -317,7 +309,7 @@ fn a_bound_world_reports_its_grammar_and_derives_render_paths_from_it() { let extra = [("dock", verb(RenderPath::ShipAction, &[]))]; let grammar = grammar_with(&extra); let identity = grammar.identity(); - let (_dir, kernel) = create(bound(Some(grammar), "Reports")); + let kernel = create(bound(Some(grammar), "Reports")); let mut kernel = kernel.unwrap(); admit(&mut kernel, patch_of(vec![declare("dock", "dock", &[])])).unwrap(); let snapshot = kernel.snapshot().unwrap(); @@ -339,11 +331,11 @@ fn a_bound_world_reports_its_grammar_and_derives_render_paths_from_it() { fn a_reopened_grammar_world_still_holds_its_grammar() { let grammar = grammar_with(&[]); let identity = grammar.identity(); - let (directory, kernel) = create(bound(Some(grammar), "Reopened")); + let kernel = create(bound(Some(grammar), "Reopened")); let kernel = kernel.unwrap(); - let world_id = kernel.snapshot().unwrap().world_id; + let exported = kernel.export().unwrap(); drop(kernel); - let mut reopened = WorldKernel::open(directory.path().join("world.cc"), world_id).unwrap(); + let mut reopened = WorldKernel::open(&exported).unwrap(); assert_eq!(reopened.snapshot().unwrap().grammar, Some(identity)); assert_eq!( rejected(admit( @@ -356,7 +348,7 @@ fn a_reopened_grammar_world_still_holds_its_grammar() { #[test] fn the_bound_grammar_is_part_of_the_world_state_digest() { - let (_dir, kernel) = create(bound(Some(grammar_with(&[])), "Digested")); + let kernel = create(bound(Some(grammar_with(&[])), "Digested")); let kernel = kernel.unwrap(); let bound_digest = crate::state_digest(&kernel.state).unwrap(); let mut state = kernel.state.clone(); @@ -500,9 +492,9 @@ fn submit_as( /// A bound world whose revision has moved past genesis: one Play patch /// that adds a dead-end place. -fn advanced_grammar_world() -> (tempfile::TempDir, WorldKernel, crate::EntityId) { +fn advanced_grammar_world() -> (WorldKernel, crate::EntityId) { let extra = [("hail", verb(RenderPath::Conversation, &[]))]; - let (dir, kernel) = create(bound(Some(grammar_with(&extra)), "Advanced")); + let kernel = create(bound(Some(grammar_with(&extra)), "Advanced")); let mut kernel = kernel.unwrap(); let commons = *kernel.state.entities.keys().next().unwrap(); admit( @@ -532,7 +524,7 @@ fn advanced_grammar_world() -> (tempfile::TempDir, WorldKernel, crate::EntityId) .find(|(_, record)| record.label == "The Unwalked Road") .map(|(id, _)| id) .unwrap(); - (dir, kernel, dead_end) + (kernel, dead_end) } type Door = (&'static str, CallerId); @@ -563,7 +555,7 @@ fn refuse_at_each_door(kernel: &mut WorldKernel, doors: Vec<Door>) { #[test] fn play_refuses_outside_the_grammar_after_the_revision_has_moved() { - let (_dir, mut kernel, _) = advanced_grammar_world(); + let (mut kernel, _) = advanced_grammar_world(); assert_eq!(kernel.state.revision, 1); refuse_at_each_door(&mut kernel, vec![("play", CallerId::Play)]); // The same path admits what the grammar carries, so the refusals above are @@ -591,7 +583,7 @@ fn a_grammar_that_binds_speak_as_anything_but_conversation_is_refused_at_bind() .unwrap() }; assert_eq!( - rejected(create(bound(Some(ship(&[])), "Filmed speech")).1), + rejected(create(bound(Some(ship(&[])), "Filmed speech"))), vec![Mismatch::SpeakRenderPathDisagreesWithGrammar { handle: DraftHandle::new(crate::patch::KERNEL_SPEAK_HANDLE), }] @@ -604,12 +596,11 @@ fn a_grammar_that_binds_speak_as_anything_but_conversation_is_refused_at_bind() Some(ship(&[("to", GrammarReferentKind::Person)])), "Loud" )) - .1 ), disagrees(crate::patch::KERNEL_SPEAK_HANDLE) ); // The control: Conversation speak binds. - assert!(create(bound(Some(grammar_with(&[])), "Spoken")).1.is_ok()); + assert!(create(bound(Some(grammar_with(&[])), "Spoken")).is_ok()); } /// `apply_effect` re-decides an effect it is handed. An effect resolved against @@ -627,7 +618,7 @@ fn an_effect_resolved_elsewhere_cannot_install_an_entry_outside_the_grammar() { ), ("hail", verb(RenderPath::Conversation, &[])), ]; - let (_dir, kernel) = create(bound(Some(grammar_with(&extra)), "Forged")); + let kernel = create(bound(Some(grammar_with(&extra)), "Forged")); let kernel = kernel.unwrap(); let mut twin = kernel.state.clone(); twin.grammar = None; diff --git a/native/aetherlight/src/import_key_tests.rs b/native/aetherlight/src/import_key_tests.rs index 5c5e28340..4d217c586 100644 --- a/native/aetherlight/src/import_key_tests.rs +++ b/native/aetherlight/src/import_key_tests.rs @@ -35,20 +35,12 @@ fn keyed_creation(title: &str) -> CreateWorld { world } -fn create(world: CreateWorld) -> (tempfile::TempDir, Result<WorldKernel, KernelError>) { - let directory = tempfile::tempdir().unwrap(); - let result = WorldKernel::create( - directory.path().join("world.cc"), - world, - &auth_principal(owner()), - ) - .map(|(kernel, _)| kernel); - (directory, result) +fn create(world: CreateWorld) -> Result<WorldKernel, KernelError> { + WorldKernel::create(world, &auth_principal(owner())).map(|(kernel, _)| kernel) } -fn keyed_world() -> (tempfile::TempDir, WorldKernel) { - let (dir, kernel) = create(keyed_creation("Keyed")); - (dir, kernel.unwrap()) +fn keyed_world() -> WorldKernel { + create(keyed_creation("Keyed")).unwrap() } fn rejected(result: Result<impl Sized, KernelError>) -> Vec<Mismatch> { @@ -140,11 +132,11 @@ fn one_patch_cannot_declare_two_subjects_with_one_import_key() { subject.import_key = Some(alpha()); } } - let (_dir, result) = create(world); + let result = create(world); assert_eq!(rejected(result), vec![duplicate("operator")]); // In a later patch, with the key unheld. - let (_dir, mut kernel) = keyed_world(); + let mut kernel = keyed_world(); let place = commons(&kernel); let revision = kernel.state.revision; let beta = Some(key("aetheria.ship", "Beta")); @@ -161,8 +153,8 @@ fn one_patch_cannot_declare_two_subjects_with_one_import_key() { } /// The fixture world past genesis: Play has added an unwalked place. -fn advanced_keyed_world() -> (tempfile::TempDir, WorldKernel, EntityId) { - let (dir, mut kernel) = keyed_world(); +fn advanced_keyed_world() -> (WorldKernel, EntityId) { + let mut kernel = keyed_world(); let place = commons(&kernel); submit_as( &mut kernel, @@ -192,7 +184,7 @@ fn advanced_keyed_world() -> (tempfile::TempDir, WorldKernel, EntityId) { .find(|(_, record)| record.label == "The Unwalked Road") .map(|(id, _)| id) .unwrap(); - (dir, kernel, dead_end) + (kernel, dead_end) } /// Each door names the held key, typed, and the refusal leaves the revision @@ -219,7 +211,7 @@ fn refuse_held_key_at_each_door( #[test] fn a_held_import_key_is_refused_at_every_door_after_the_revision_has_moved() { - let (_dir, mut kernel, dead_end) = advanced_keyed_world(); + let (mut kernel, dead_end) = advanced_keyed_world(); assert!(kernel.state.revision > 0, "the world has moved past genesis"); refuse_held_key_at_each_door( &mut kernel, @@ -246,7 +238,7 @@ fn a_held_import_key_is_refused_at_every_door_after_the_revision_has_moved() { #[test] fn a_held_import_key_is_refused_in_a_later_patch() { - let (_dir, mut kernel) = keyed_world(); + let mut kernel = keyed_world(); let place = commons(&kernel); let revision = kernel.state.revision; let error = submit_as( @@ -261,7 +253,7 @@ fn a_held_import_key_is_refused_in_a_later_patch() { #[test] fn a_retired_subjects_import_key_is_never_reissued() { - let (_dir, mut kernel) = keyed_world(); + let mut kernel = keyed_world(); let place = commons(&kernel); let witness = kernel .snapshot() @@ -306,7 +298,7 @@ fn a_retired_subjects_import_key_is_never_reissued() { #[test] fn keys_that_differ_in_any_way_are_distinct_records() { - let (_dir, mut kernel) = keyed_world(); + let mut kernel = keyed_world(); let place = commons(&kernel); // Same length, case, prefix, the same concatenation split elsewhere, and // the parts swapped: none is the held key. @@ -347,7 +339,7 @@ fn keys_that_differ_in_any_way_are_distinct_records() { #[test] fn a_malformed_import_key_is_refused_without_echoing_it() { - let (_dir, mut kernel) = keyed_world(); + let mut kernel = keyed_world(); let place = commons(&kernel); let long = "x".repeat(201); let wide = "é".repeat(101); @@ -398,7 +390,7 @@ fn a_malformed_import_key_is_refused_without_echoing_it() { #[test] fn the_subjects_map_refuses_a_second_subject_for_one_key_even_when_resolved_elsewhere() { - let (_dir, kernel) = keyed_world(); + let kernel = keyed_world(); let place = commons(&kernel); let resolve = |handle: &str| { crate::patch::resolve_patch( @@ -451,7 +443,7 @@ fn contains(haystack: &[u8], needle: &[u8]) -> bool { fn keyless_world_digests_unchanged() { // A subject nobody imported serialises without the field at all, so every // digest written before keys existed is the digest of the same bytes. - let (_dir, kernel) = create(creation("Keyless")); + let kernel = create(creation("Keyless")); let kernel = kernel.unwrap(); let state = rmp_serde::to_vec_named(&kernel.state).unwrap(); assert!( @@ -459,7 +451,7 @@ fn keyless_world_digests_unchanged() { "a keyless world grew a field" ); // A keyed world carries it, round-trips, and digests differently. - let (_dir, keyed) = keyed_world(); + let keyed = keyed_world(); let keyed_state = rmp_serde::to_vec_named(&keyed.state).unwrap(); assert!(contains(&keyed_state, b"import_key")); let back: crate::WorldState = rmp_serde::from_slice(&keyed_state).unwrap(); @@ -478,11 +470,11 @@ fn keyless_world_digests_unchanged() { #[test] fn a_keyed_world_reopens_with_its_keys_and_digests() { - let (dir, kernel) = keyed_world(); + let kernel = keyed_world(); let snapshot = kernel.snapshot().unwrap(); - let world_id = snapshot.world_id; + let exported = kernel.export().unwrap(); drop(kernel); - let reopened = WorldKernel::open(dir.path().join("world.cc"), world_id).unwrap(); + let reopened = WorldKernel::open(&exported).unwrap(); let again = reopened.snapshot().unwrap(); assert_eq!(again.state_digest, snapshot.state_digest); let keys = keys_in(&reopened); @@ -495,7 +487,7 @@ fn a_keyed_world_reopens_with_its_keys_and_digests() { #[test] fn a_record_key_is_one_canonical_spelling() { - let (_dir, mut kernel) = keyed_world(); + let mut kernel = keyed_world(); let place = commons(&kernel); let nfc = "Caf\u{e9}"; let nfd = "Cafe\u{301}"; @@ -544,7 +536,7 @@ fn a_record_key_is_one_canonical_spelling() { #[test] fn a_lore_page_path_with_spaces_is_a_record_key() { - let (_dir, mut kernel) = keyed_world(); + let mut kernel = keyed_world(); let place = commons(&kernel); let record = "Worldbuilding/Pre-Elysium/Factions/Powers/Minor/Ewan Hart"; let declare = |kernel: &mut WorldKernel, handle: &str| { @@ -564,7 +556,7 @@ fn a_lore_page_path_with_spaces_is_a_record_key() { #[test] fn a_loaded_state_with_a_bad_import_key_is_refused() { - let (_dir, mut kernel) = keyed_world(); + let mut kernel = keyed_world(); let place = commons(&kernel); submit_as( &mut kernel, @@ -610,7 +602,7 @@ fn a_loaded_state_with_a_bad_import_key_is_refused() { /// effect with distinct keys, admitted by the same function. #[test] fn admitting_a_resolved_effect_refuses_two_subjects_with_one_key() { - let (_dir, kernel) = keyed_world(); + let kernel = keyed_world(); let place = commons(&kernel); let resolve = || { crate::patch::resolve_patch( @@ -646,7 +638,7 @@ fn admitting_a_resolved_effect_refuses_two_subjects_with_one_key() { /// rule cannot be a prefix, suffix or first-character check. #[test] fn a_decomposable_character_is_refused_in_nfd_at_every_position() { - let (_dir, mut kernel) = keyed_world(); + let mut kernel = keyed_world(); let place = commons(&kernel); let template: Vec<char> = "Worldbuilding/Pre-Elysium/Factions/Powers/Minor/Ewan Hart" .chars() @@ -691,7 +683,7 @@ fn a_decomposable_character_is_refused_in_nfd_at_every_position() { #[test] fn the_owner_door_is_closed_to_a_keyed_declaration() { - let (_dir, mut kernel) = keyed_world(); + let mut kernel = keyed_world(); let place = commons(&kernel); let revision = kernel.state.revision; let error = submit_as( diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index 96efb340f..e8ba77c70 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -1,380 +1,94 @@ use super::{ - COMMIT_SCHEMA, CommandId, CommittedCommand, KernelError, STATE_SCHEMA, WorldCommit, - WorldEffect, WorldId, WorldState, apply_effect, commit_digest, reduce, state_digest, -}; -use chrono::Utc; -use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore}; -use serde::{Serialize, de::DeserializeOwned}; -use std::{ - cell::Cell, - collections::{BTreeMap, BTreeSet}, - path::Path, + COMMIT_SCHEMA, CommittedCommand, KernelError, STATE_SCHEMA, WorldCommit, WorldEffect, + WorldId, WorldState, apply_effect, commit_digest, reduce, state_digest, }; +use serde::{Deserialize, Serialize, de::DeserializeOwned}; +use std::collections::{BTreeMap, BTreeSet}; use thiserror::Error; -const STATE_ROW: &str = "world_state.elaboration.v1"; -const COMMIT_ROW: &str = "world_commit.elaboration.v1"; +pub(super) const JOURNAL_SCHEMA: &str = "aetherlight.journal.v1"; #[derive(Debug, Error)] pub(super) enum JournalError { - #[error("opened store contains another world")] - WorldMismatch, - #[error("world ownership is uncertain after command {command_id:?}; drop and reopen")] - RecoveryRequired { command_id: CommandId }, - #[error("world store path no longer names the owned database")] - OwnershipLost, - #[error("world store operation failed: {0}")] - Store(String), #[error("world journal is corrupt: {0}")] Corrupt(String), } -pub(super) enum JournalOpen { - Empty(EmptyWorldJournal), - Live { - journal: WorldJournal, - state: WorldState, - }, +/// What an export carries: the schema that names the format, and the commits in +/// revision order. Nothing else is stored, because nothing else is truth: the +/// head state is the replay of these commits. +#[derive(Serialize)] +struct ExportRef<'a> { + schema: &'a str, + commits: &'a [WorldCommit], } -pub(super) struct EmptyWorldJournal { - store: OwnedRedbMessagePackBackingStore, - #[cfg(test)] - fail_after_durable_initialize: bool, -} - -#[derive(Clone, Copy)] -enum JournalHealth { - Healthy, - RecoveryRequired(CommandId), - OwnershipLost, +#[derive(Serialize, Deserialize)] +struct Export { + schema: String, + commits: Vec<WorldCommit>, } +/// The only record of a world: its commits in revision order, genesis first. pub(super) struct WorldJournal { - store: OwnedRedbMessagePackBackingStore, - state_row: CultCacheEnvelope, - commits: BTreeMap<CommandId, WorldCommit>, - health: Cell<JournalHealth>, - #[cfg(test)] - fail_after_durable_commit: bool, + commits: Vec<WorldCommit>, } impl WorldJournal { - pub(super) fn open_owner(path: &Path) -> Result<JournalOpen, JournalError> { - let store = OwnedRedbMessagePackBackingStore::new(path) - .map_err(|error| JournalError::Store(error.to_string()))?; - store - .validate_path_identity() - .map_err(|_| JournalError::OwnershipLost)?; - let rows = store - .pull_all() - .map_err(|error| JournalError::Store(error.to_string()))?; - store - .validate_path_identity() - .map_err(|_| JournalError::OwnershipLost)?; - if rows.is_empty() { - return Ok(JournalOpen::Empty(EmptyWorldJournal { - store, - #[cfg(test)] - fail_after_durable_initialize: false, - })); + pub(super) fn genesis(genesis: WorldCommit) -> Self { + Self { + commits: vec![genesis], } - let (state_row, state, commits) = recover(rows, None)?; - Ok(JournalOpen::Live { - journal: Self { - store, - state_row, - commits, - health: Cell::new(JournalHealth::Healthy), - #[cfg(test)] - fail_after_durable_commit: false, - }, - state, - }) } - pub(super) fn open( - path: &Path, - expected_world_id: WorldId, - ) -> Result<(Self, WorldState), JournalError> { - let store = OwnedRedbMessagePackBackingStore::new(path) - .map_err(|error| JournalError::Store(error.to_string()))?; - store - .validate_path_identity() - .map_err(|_| JournalError::OwnershipLost)?; - let rows = store - .pull_all() - .map_err(|error| JournalError::Store(error.to_string()))?; - store - .validate_path_identity() - .map_err(|_| JournalError::OwnershipLost)?; - let (state_row, state, commits) = recover(rows, Some(expected_world_id))?; + pub(super) fn append(&mut self, commit: WorldCommit) { + self.commits.push(commit); + } + + pub(super) fn export(&self) -> Result<Vec<u8>, KernelError> { + rmp_serde::to_vec_named(&ExportRef { + schema: JOURNAL_SCHEMA, + commits: &self.commits, + }) + .map_err(|error| KernelError::Serialization(error.to_string())) + } + + /// Decode canonically, then replay: the head state is whatever the chain + /// derives, and a chain that does not verify is not a world. + pub(super) fn open(bytes: &[u8]) -> Result<(Self, WorldState), JournalError> { + let export: Export = decode(bytes)?; + if export.schema != JOURNAL_SCHEMA { + return Err(JournalError::Corrupt(format!( + "export schema {} is not {JOURNAL_SCHEMA}", + export.schema + ))); + } + let state = verify_history(&export.commits)?; Ok(( Self { - store, - state_row, - commits, - health: Cell::new(JournalHealth::Healthy), - #[cfg(test)] - fail_after_durable_commit: false, + commits: export.commits, }, state, )) } - pub(super) fn ensure_healthy(&self) -> Result<(), JournalError> { - match self.health.get() { - JournalHealth::RecoveryRequired(command_id) => { - return Err(JournalError::RecoveryRequired { command_id }); - } - JournalHealth::OwnershipLost => return Err(JournalError::OwnershipLost), - JournalHealth::Healthy => {} - } - if self.store.validate_path_identity().is_err() { - self.health.set(JournalHealth::OwnershipLost); - return Err(JournalError::OwnershipLost); - } - Ok(()) - } - - pub(super) fn commit( - &mut self, - next: &WorldState, - commit: &WorldCommit, - ) -> Result<(), JournalError> { - self.ensure_healthy()?; - let command_id = commit.command.id(); - if self.commits.contains_key(&command_id) { - return Err(JournalError::Corrupt( - "single-owner append attempted to duplicate a committed command".into(), - )); - } - let current: WorldState = decode(&self.state_row)?; - verify_append(¤t, next, commit)?; - let next_row = envelope(STATE_ROW, STATE_SCHEMA, next.world_id.key(), next)?; - let commit_row = envelope(COMMIT_ROW, COMMIT_SCHEMA, command_id.key(), commit)?; - self.health.set(JournalHealth::RecoveryRequired(command_id)); - let swapped = self.store.compare_and_swap_batch( - std::slice::from_ref(&self.state_row), - vec![next_row.clone(), commit_row], - ); - match swapped { - Ok(true) => {} - Ok(false) | Err(_) => { - return Err(JournalError::RecoveryRequired { command_id }); - } - } - #[cfg(test)] - if self.fail_after_durable_commit { - return Err(JournalError::RecoveryRequired { command_id }); - } - if self.store.validate_path_identity().is_err() { - return Err(JournalError::RecoveryRequired { command_id }); - } - self.state_row = next_row; - self.commits.insert(command_id, commit.clone()); - self.health.set(JournalHealth::Healthy); - Ok(()) - } - - pub(super) fn commit_for(&self, command_id: CommandId) -> Option<&WorldCommit> { - self.commits.get(&command_id) - } - #[cfg(test)] pub(super) fn commit_count(&self) -> usize { self.commits.len() } - /// PA.f40: a test outside this module needs the full commit map to forge - /// one commit's effect and route the forgery through `verify_history` - /// directly, the same way this module's own forgery tests already do via - /// `self.commits.clone()`. #[cfg(test)] - pub(super) fn commits_for_test(&self) -> BTreeMap<CommandId, WorldCommit> { + pub(super) fn commits_for_test(&self) -> Vec<WorldCommit> { self.commits.clone() } - - #[cfg(test)] - pub(super) fn fail_after_durable_commit_for_test(&mut self) { - self.fail_after_durable_commit = true; - } } -impl EmptyWorldJournal { - #[cfg(test)] - pub(super) fn fail_after_durable_initialize_for_test(&mut self) { - self.fail_after_durable_initialize = true; - } - - pub(super) fn initialize( - self, - state: &WorldState, - genesis: &WorldCommit, - ) -> Result<WorldJournal, JournalError> { - self.store - .validate_path_identity() - .map_err(|_| JournalError::OwnershipLost)?; - let mut commits = BTreeMap::new(); - let command_id = genesis.command.id(); - commits.insert(command_id, genesis.clone()); - verify_history(state, &commits)?; - let state_row = envelope(STATE_ROW, STATE_SCHEMA, state.world_id.key(), state)?; - let commit_row = envelope(COMMIT_ROW, COMMIT_SCHEMA, command_id.key(), genesis)?; - let inserted = self - .store - .append_if_snapshot_unchanged(&[], vec![state_row.clone(), commit_row]); - if !matches!(inserted, Ok(true)) { - return Err(JournalError::RecoveryRequired { command_id }); - } - #[cfg(test)] - if self.fail_after_durable_initialize { - return Err(JournalError::RecoveryRequired { command_id }); - } - if self.store.validate_path_identity().is_err() { - return Err(JournalError::RecoveryRequired { command_id }); - } - Ok(WorldJournal { - store: self.store, - state_row, - commits, - health: Cell::new(JournalHealth::Healthy), - #[cfg(test)] - fail_after_durable_commit: false, - }) - } -} - -fn recover( - rows: Vec<CultCacheEnvelope>, - expected_world_id: Option<WorldId>, -) -> Result< - ( - CultCacheEnvelope, - WorldState, - BTreeMap<CommandId, WorldCommit>, - ), - JournalError, -> { - let mut state_rows = Vec::new(); - let mut commits = BTreeMap::new(); - for row in rows { - match row.r#type.as_str() { - STATE_ROW => { - require_schema(&row, STATE_SCHEMA)?; - state_rows.push(row); - } - COMMIT_ROW => { - require_schema(&row, COMMIT_SCHEMA)?; - let commit: WorldCommit = decode(&row)?; - let command_id = commit.command.id(); - if row.key != command_id.key() { - return Err(JournalError::Corrupt( - "commit row key does not match command ID".into(), - )); - } - if commits.insert(command_id, commit).is_some() { - return Err(JournalError::Corrupt("duplicate command commit".into())); - } - } - other => { - return Err(JournalError::Corrupt(format!( - "unadmitted row type {other}" - ))); - } - } - } - if state_rows.len() != 1 { - return Err(JournalError::Corrupt(format!( - "expected one state row, found {}", - state_rows.len() - ))); - } - let state_row = state_rows.pop().expect("length checked"); - let state: WorldState = decode(&state_row)?; - if state_row.key != state.world_id.key() { - return Err(JournalError::Corrupt( - "state row key does not match its world ID".into(), - )); - } - if expected_world_id.is_some_and(|expected| state.world_id != expected) { - return Err(JournalError::WorldMismatch); - } - verify_history(&state, &commits)?; - Ok((state_row, state, commits)) -} - -fn verify_append( - current: &WorldState, - next: &WorldState, - commit: &WorldCommit, -) -> Result<(), JournalError> { - verify_state_shape(current)?; - verify_state_shape(next)?; - if current.world_id != next.world_id - || commit.world_id != current.world_id - || commit.schema != COMMIT_SCHEMA - || commit.previous_revision != Some(current.revision) - || commit.resulting_revision != next.revision - || next.revision != current.revision.saturating_add(1) - || commit.previous_state_digest.as_deref() != Some(current.state_digest.as_str()) - || commit.resulting_state_digest != next.state_digest - || commit.previous_commit_digest != current.last_commit_digest - || next.last_commit_digest.as_deref() != Some(commit.digest.as_str()) - { - return Err(JournalError::Corrupt( - "commit does not bind the exact state transition".into(), - )); - } - if state_digest(current).map_err(kernel_error)? != current.state_digest - || state_digest(next).map_err(kernel_error)? != next.state_digest - || commit_digest(commit).map_err(kernel_error)? != commit.digest - { - return Err(JournalError::Corrupt("digest mismatch".into())); - } - let mut replay = current.clone(); - apply_committed_command(&mut replay, commit)?; - replay.revision = next.revision; - replay.state_digest = state_digest(&replay).map_err(kernel_error)?; - replay.last_commit_digest = Some(commit.digest.clone()); - if &replay != next { - return Err(JournalError::Corrupt( - "commit effect does not reproduce next state".into(), - )); - } - Ok(()) -} - -/// `pub(super)`, matching `verify_state_shape`: a Soul-style forgery test -/// outside this module routes its falsification through the same function -/// that actually judges a committed history, rather than through the -/// structural-only `verify_state_shape`. -pub(super) fn verify_history( - state: &WorldState, - commits: &BTreeMap<CommandId, WorldCommit>, -) -> Result<(), JournalError> { - verify_state_shape(state)?; - if commits - .iter() - .any(|(command_id, commit)| *command_id != commit.command.id()) - { - return Err(JournalError::Corrupt( - "commit index does not derive from the persisted command".into(), - )); - } - let expected_commits = usize::try_from(state.revision) - .map_err(|_| JournalError::Corrupt("revision does not fit this runtime".into()))?; - let expected_commits = expected_commits - .checked_add(1) - .ok_or_else(|| JournalError::Corrupt("commit count overflow".into()))?; - if commits.len() != expected_commits { - return Err(JournalError::Corrupt( - "commit count does not equal genesis plus head revision".into(), - )); - } - let mut ordered: Vec<_> = commits.values().collect(); - ordered.sort_by_key(|commit| commit.resulting_revision); - let genesis = ordered +/// The one judge of a stored chain, `pub(super)` so a forgery test outside this +/// module routes through the same function that `open` does. It replays the +/// commits in revision order from genesis and returns the head state they +/// derive; position `i` must hold resulting revision `i`. +pub(super) fn verify_history(commits: &[WorldCommit]) -> Result<WorldState, JournalError> { + let genesis = commits .first() .ok_or_else(|| JournalError::Corrupt("world has no genesis commit".into()))?; let CommittedCommand::CreateWorld(genesis_command) = &genesis.command else { @@ -388,9 +102,9 @@ pub(super) fn verify_history( )); }; if genesis.schema != COMMIT_SCHEMA - || genesis.world_id != state.world_id || genesis.previous_revision.is_some() || genesis.resulting_revision != 0 + || genesis.world_id != WorldId::of(genesis_command.id()) || genesis.previous_state_digest.is_some() || genesis.previous_commit_digest.is_some() || commit_digest(genesis).map_err(kernel_error)? != genesis.digest @@ -399,7 +113,7 @@ pub(super) fn verify_history( "genesis commit is not canonical or verifiable".into(), )); } - let mut replay = WorldState::genesis(state.world_id, genesis_command, &genesis.effect) + let mut replay = WorldState::genesis(genesis.world_id, genesis_command, &genesis.effect) .map_err(kernel_error)?; verify_state_shape(&replay)?; verify_commitments_are_future(&replay, &BTreeMap::new())?; @@ -410,9 +124,9 @@ pub(super) fn verify_history( } replay.last_commit_digest = Some(genesis.digest.clone()); - for commit in ordered.into_iter().skip(1) { + for commit in &commits[1..] { if commit.schema != COMMIT_SCHEMA - || commit.world_id != state.world_id + || commit.world_id != replay.world_id || commit.previous_revision != Some(replay.revision) || commit.resulting_revision != replay.revision.saturating_add(1) || commit.previous_state_digest.as_deref() != Some(replay.state_digest.as_str()) @@ -428,7 +142,7 @@ pub(super) fn verify_history( // Authority is re-decided here for free: `apply_committed_command` // re-runs `reduce` against the pre-commit state and requires effect // equality, then `apply_effect`, and both of those call - // `require_play`. A forged row recording the owner as the caller of + // `require_play`. A forged commit recording the owner as the caller of // a post-genesis command fails replay rather than being admitted by a // reducer that trusts the recorded caller. A third statement of the same rule here would be a // third owner of one decision. @@ -451,12 +165,8 @@ pub(super) fn verify_history( } replay.last_commit_digest = Some(commit.digest.clone()); } - if &replay != state { - return Err(JournalError::Corrupt( - "head state does not equal replayed history".into(), - )); - } - Ok(()) + verify_state_shape(&replay)?; + Ok(replay) } /// The replay-side twin of `Mismatch::CommitmentDueInThePast`: every commitment @@ -918,47 +628,13 @@ fn apply_committed_command( .map_err(kernel_error) } -fn require_schema(row: &CultCacheEnvelope, schema: &str) -> Result<(), JournalError> { - if row.schema_id.as_deref() != Some(schema) { - Err(JournalError::Corrupt(format!( - "row {}/{} has the wrong schema", - row.r#type, row.key - ))) - } else { - Ok(()) - } -} - -fn envelope<T: Serialize>( - row_type: &str, - schema: &str, - key: String, - value: &T, -) -> Result<CultCacheEnvelope, JournalError> { - Ok(CultCacheEnvelope { - key, - r#type: row_type.into(), - payload: rmp_serde::to_vec_named(value) - .map_err(|error| JournalError::Store(error.to_string()))?, - stored_at: Utc::now().to_rfc3339(), - schema_id: Some(schema.into()), - }) -} - -fn decode<T: DeserializeOwned + Serialize>(row: &CultCacheEnvelope) -> Result<T, JournalError> { - let value: T = rmp_serde::from_slice(&row.payload).map_err(|error| { - JournalError::Corrupt(format!( - "could not decode row {}/{}: {error}", - row.r#type, row.key - )) - })?; +fn decode<T: DeserializeOwned + Serialize>(bytes: &[u8]) -> Result<T, JournalError> { + let value: T = rmp_serde::from_slice(bytes) + .map_err(|error| JournalError::Corrupt(format!("could not decode the export: {error}")))?; let canonical = rmp_serde::to_vec_named(&value) .map_err(|error| JournalError::Corrupt(error.to_string()))?; - if canonical != row.payload { - return Err(JournalError::Corrupt(format!( - "row {}/{} is not canonical", - row.r#type, row.key - ))); + if canonical != bytes { + return Err(JournalError::Corrupt("the export is not canonical".into())); } Ok(value) } @@ -983,13 +659,36 @@ mod tests { value: u8, } - /// The commit a forgery test rewrites: the one the test just committed. - pub(super) fn last_commit(commits: &mut BTreeMap<CommandId, WorldCommit>) -> &mut WorldCommit { - commits.values_mut().max_by_key(|commit| commit.resulting_revision).unwrap() + /// The bytes an honest exporter writes for `commits`, whatever they claim. + pub(super) fn export_of(commits: &[WorldCommit]) -> Vec<u8> { + WorldJournal { + commits: commits.to_vec(), + } + .export() + .unwrap() } - pub(super) fn genesis_commit(commits: &mut BTreeMap<CommandId, WorldCommit>) -> &mut WorldCommit { - commits.values_mut().min_by_key(|commit| commit.resulting_revision).unwrap() + /// Open a world from forged commits through the door a real export takes: + /// canonical decode, then the one replay judge. + pub(super) fn reopen(commits: &[WorldCommit]) -> Result<WorldState, JournalError> { + WorldJournal::open(&export_of(commits)).map(|(_, state)| state) + } + + #[test] + fn decode_rejects_an_alternate_messagepack_shape() { + let bytes = rmp_serde::to_vec(&CanonicalFixture { value: 7 }).unwrap(); + assert!(decode::<CanonicalFixture>(&bytes).is_err()); + let canonical = rmp_serde::to_vec_named(&CanonicalFixture { value: 7 }).unwrap(); + assert!(decode::<CanonicalFixture>(&canonical).is_ok()); + } + + /// The commit a forgery test rewrites: the one the test just committed. + pub(super) fn last_commit(commits: &mut [WorldCommit]) -> &mut WorldCommit { + commits.iter_mut().max_by_key(|commit| commit.resulting_revision).unwrap() + } + + pub(super) fn genesis_commit(commits: &mut [WorldCommit]) -> &mut WorldCommit { + commits.iter_mut().min_by_key(|commit| commit.resulting_revision).unwrap() } fn owner_patch(subject: SubjectDeclaration) -> WorldPatch { @@ -1000,22 +699,8 @@ mod tests { } } - #[test] - fn decode_rejects_an_alternate_messagepack_shape() { - let row = CultCacheEnvelope { - key: "fixture".into(), - r#type: "fixture".into(), - payload: rmp_serde::to_vec(&CanonicalFixture { value: 7 }).unwrap(), - stored_at: Utc::now().to_rfc3339(), - schema_id: Some("fixture.v0".into()), - }; - assert!(decode::<CanonicalFixture>(&row).is_err()); - } - #[test] fn replay_rejects_a_forged_command_or_effect_even_with_valid_hashes() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); let owner = PrincipalId::new("owner@example.test"); let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); let creation = CreateWorld { @@ -1031,7 +716,7 @@ mod tests { }), grammar: None, }; - let (mut kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap(); + let (mut kernel, _) = WorldKernel::create(creation, &authenticated).unwrap(); let snapshot = kernel.snapshot().unwrap(); kernel .submit( @@ -1047,7 +732,6 @@ mod tests { ) .unwrap(); - let mut command_forged_head = kernel.state.clone(); let mut command_forged_commits = kernel.journal.commits.clone(); let command_forged = last_commit(&mut command_forged_commits); let CommittedCommand::WorldCommand(command) = &mut command_forged.command else { @@ -1057,14 +741,12 @@ mod tests { minutes: crate::TickMinutes::new(2).unwrap(), }; command_forged.digest = commit_digest(command_forged).unwrap(); - command_forged_head.last_commit_digest = Some(command_forged.digest.clone()); assert!(matches!( - verify_history(&command_forged_head, &command_forged_commits), + reopen(&command_forged_commits), Err(JournalError::Corrupt(_)) )); - let mut caller_forged_head = kernel.state.clone(); let mut caller_forged_commits = kernel.journal.commits.clone(); let caller_forged = last_commit(&mut caller_forged_commits); let CommittedCommand::WorldCommand(command) = &mut caller_forged.command else { @@ -1072,14 +754,12 @@ mod tests { }; command.caller = CallerId::Principal(PrincipalId::new("attacker@example.test")); caller_forged.digest = commit_digest(caller_forged).unwrap(); - caller_forged_head.last_commit_digest = Some(caller_forged.digest.clone()); assert!(matches!( - verify_history(&caller_forged_head, &caller_forged_commits), + reopen(&caller_forged_commits), Err(JournalError::Corrupt(_)) )); - let mut effect_forged_head = kernel.state.clone(); let mut effect_forged_commits = kernel.journal.commits.clone(); let effect_forged = last_commit(&mut effect_forged_commits); let WorldEffect::TimeAdvanced { to, .. } = &mut effect_forged.effect else { @@ -1087,18 +767,15 @@ mod tests { }; *to = crate::FictionalMinutes(99); effect_forged.digest = commit_digest(effect_forged).unwrap(); - effect_forged_head.last_commit_digest = Some(effect_forged.digest.clone()); assert!(matches!( - verify_history(&effect_forged_head, &effect_forged_commits), + reopen(&effect_forged_commits), Err(JournalError::Corrupt(_)) )); } #[test] fn a_forged_patch_effect_does_not_apply() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); let owner = PrincipalId::new("owner@example.test"); let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); let creation = CreateWorld { @@ -1114,7 +791,7 @@ mod tests { }), grammar: None, }; - let (mut kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap(); + let (mut kernel, _) = WorldKernel::create(creation, &authenticated).unwrap(); let snapshot = kernel.snapshot().unwrap(); kernel .submit( @@ -1149,7 +826,6 @@ mod tests { ) .unwrap(); - let mut forged_head = kernel.state.clone(); let mut forged_commits = kernel.journal.commits.clone(); let forged = last_commit(&mut forged_commits); let WorldEffect::PatchAdmitted { resolved, .. } = &mut forged.effect else { @@ -1159,106 +835,20 @@ mod tests { place: EntityId::issue(), }); forged.digest = commit_digest(forged).unwrap(); - forged_head.last_commit_digest = Some(forged.digest.clone()); assert!(matches!( - verify_history(&forged_head, &forged_commits), + reopen(&forged_commits), Err(JournalError::Corrupt(_)) )); } - /// A store written at the schema this pass replaced is refused outright. - /// There is no migration adapter, and the refusal is the behaviour. - #[test] - fn a_store_from_the_knowledge_schema_is_refused() { - let row = CultCacheEnvelope { - key: "state".into(), - r#type: "world_state.knowledge.v1".into(), - payload: Vec::new(), - stored_at: Utc::now().to_rfc3339(), - schema_id: Some("ghostlight.world_state.knowledge.v1".into()), - }; - let error = recover(vec![row], None).unwrap_err(); - let JournalError::Corrupt(message) = error else { - panic!("expected a corrupt store"); - }; - assert!( - message.contains("unadmitted row type"), - "unexpected refusal: {message}" - ); - } - - /// A `Witness` reaches the store through two rows — a commit carries the - /// admitted operations and the state row carries the event's effects — so - /// both schemas bumped and both prior versions are refused at open. There - /// is no migration adapter and no dual read. - #[test] - fn a_store_written_before_the_witness_schema_is_refused() { - for (row_type, schema) in [ - (STATE_ROW, "ghostlight.world_state.consumer.v1"), - (COMMIT_ROW, "ghostlight.world_commit.consumer.v1"), - ] { - let row = CultCacheEnvelope { - key: "state".into(), - r#type: row_type.into(), - payload: Vec::new(), - stored_at: Utc::now().to_rfc3339(), - schema_id: Some(schema.into()), - }; - let error = recover(vec![row], None).unwrap_err(); - let JournalError::Corrupt(message) = error else { - panic!("expected a corrupt store for {schema}"); - }; - assert!( - message.contains("has the wrong schema"), - "unexpected refusal for {schema}: {message}" - ); - } - } - - /// A store written under an older schema is refused at open: both - /// `consumer.v4` strings and the pre-cut `consumer.v6` and `consumer.v8` - /// ones. No migration, no dual read. - #[test] - fn a_store_written_under_an_older_schema_is_refused() { - for (row_type, schema) in [ - (STATE_ROW, "ghostlight.world_state.consumer.v4"), - (COMMIT_ROW, "ghostlight.world_commit.consumer.v4"), - (STATE_ROW, "ghostlight.world_state.consumer.v6"), - (COMMIT_ROW, "ghostlight.world_commit.consumer.v6"), - (STATE_ROW, "ghostlight.world_state.consumer.v8"), - (COMMIT_ROW, "ghostlight.world_commit.consumer.v8"), - (STATE_ROW, "ghostlight.world_state.consumer.v9"), - (COMMIT_ROW, "ghostlight.world_commit.consumer.v9"), - ] { - let row = CultCacheEnvelope { - key: "state".into(), - r#type: row_type.into(), - payload: Vec::new(), - stored_at: Utc::now().to_rfc3339(), - schema_id: Some(schema.into()), - }; - let error = recover(vec![row], None).unwrap_err(); - let JournalError::Corrupt(message) = error else { - panic!("expected a corrupt store for {schema}"); - }; - assert!( - message.contains("has the wrong schema"), - "unexpected refusal for {schema}: {message}" - ); - } - } - /// A world whose history includes a patch and a clock advance, both Play's, - /// reopened from its own store rows. - fn clock_history() -> (tempfile::TempDir, WorldKernel) { + /// reopened from its own export. + fn clock_history() -> WorldKernel { use crate::tests::{auth_principal, creation, owner, submit_play}; use crate::TickMinutes; - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, _) = WorldKernel::create( - directory.path().join("world.cc"), - creation("Clock History"), + let (mut kernel, _) = WorldKernel::create(creation("Clock History"), &auth_principal(owner()), ) .unwrap(); @@ -1289,40 +879,79 @@ mod tests { minutes: TickMinutes::new(30).unwrap(), }, ); - (directory, kernel) - } - - fn rows_of(state: &WorldState, commits: &[WorldCommit]) -> Vec<CultCacheEnvelope> { - let mut rows: Vec<CultCacheEnvelope> = commits - .iter() - .map(|commit| { - envelope(COMMIT_ROW, COMMIT_SCHEMA, commit.command.id().key(), commit).unwrap() - }) - .collect(); - rows.push(envelope(STATE_ROW, STATE_SCHEMA, state.world_id.key(), state).unwrap()); - rows + kernel } /// Replay re-derives Play's patch and clock advance: the honest history - /// reopens to the same state digest and reading, and the store on disk does too. + /// reopens to the same state digest and reading, and the exported bytes do too. #[test] fn a_history_with_a_patch_and_a_clock_advance_replays_exactly() { - let (directory, kernel) = clock_history(); - let honest: Vec<WorldCommit> = kernel.journal.commits.values().cloned().collect(); - let (_, replayed, commits) = - recover(rows_of(&kernel.state, &honest), None).expect("the honest history replays"); - assert_eq!(commits.len(), honest.len()); + let kernel = clock_history(); + let replayed = reopen(&kernel.journal.commits).expect("the honest history replays"); assert_eq!(replayed.state_digest, kernel.state.state_digest); assert_eq!(replayed.now, kernel.state.now); - let (world_id, digest, now) = - (kernel.state.world_id, kernel.state.state_digest.clone(), kernel.state.now); + let (digest, now) = (kernel.state.state_digest.clone(), kernel.state.now); + let exported = kernel.export().unwrap(); drop(kernel); - let reopened = WorldKernel::open(directory.path().join("world.cc"), world_id).unwrap(); + let reopened = WorldKernel::open(&exported).unwrap(); assert_eq!(reopened.state.state_digest, digest); assert_eq!(reopened.state.now, now); } + /// An export is a claim about a chain, and `open` believes none of it that + /// replay does not derive: a chain with a commit missing, repeated or out of + /// order, a Ghostlight commit or export schema, and a non-canonical + /// encoding of an honest chain are each refused. + #[test] + fn forged_exports_are_refused() { + let kernel = clock_history(); + let honest = kernel.journal.commits.clone(); + assert_eq!(honest.len(), 3, "genesis, a patch and a tick"); + reopen(&honest).expect("the honest chain opens"); + let refused = |what: &str, commits: &[WorldCommit]| { + assert!( + matches!(reopen(commits), Err(JournalError::Corrupt(_))), + "{what} was admitted" + ); + }; + + refused("a missing middle commit", &[honest[0].clone(), honest[2].clone()]); + refused("a world without genesis", &honest[1..]); + refused("a repeated commit", &[honest[0].clone(), honest[1].clone(), honest[1].clone(), honest[2].clone()]); + refused("reordered commits", &[honest[0].clone(), honest[2].clone(), honest[1].clone()]); + refused("no commits", &[]); + + let mut ghostlight = honest.clone(); + ghostlight[1].schema = "ghostlight.world_commit.consumer.v10".into(); + ghostlight[1].digest = commit_digest(&ghostlight[1]).unwrap(); + refused("a ghostlight commit schema", &ghostlight); + + let foreign = rmp_serde::to_vec_named(&ExportRef { + schema: "ghostlight.world_state.consumer.v10", + commits: &honest, + }) + .unwrap(); + assert!(matches!( + WorldJournal::open(&foreign), + Err(JournalError::Corrupt(_)) + )); + + let positional = rmp_serde::to_vec(&ExportRef { + schema: JOURNAL_SCHEMA, + commits: &honest, + }) + .unwrap(); + assert!(matches!( + WorldJournal::open(&positional), + Err(JournalError::Corrupt(_)) + )); + assert!(matches!( + WorldJournal::open(&[0xc1]), + Err(JournalError::Corrupt(_)) + )); + } + /// A stored command is not believed about who made it. The forgery re-seals /// the commit around its rewrite and the head's last commit digest names the /// re-sealed commit, so no digest can answer for the check; the control, the @@ -1332,14 +961,14 @@ mod tests { fn a_commit_forged_to_the_owner_fails_replay() { use crate::tests::owner; - let (_directory, kernel) = clock_history(); - let honest: Vec<WorldCommit> = kernel.journal.commits.values().cloned().collect(); + let kernel = clock_history(); + let honest: Vec<WorldCommit> = kernel.journal.commits.clone(); // Re-seals the rewritten commit and every later one around it, so the // chain of previous-commit digests agrees and only the caller check is // left to refuse the history. let forge = |is_row: &dyn Fn(&WorldEffect) -> bool, rewrite: &dyn Fn(&mut WorldCommit)| - -> (WorldState, Vec<WorldCommit>) { + -> Vec<WorldCommit> { let mut forged: Vec<WorldCommit> = honest.clone(); forged.sort_by_key(|commit| commit.resulting_revision); let rows: Vec<usize> = (0..forged.len()) @@ -1354,28 +983,24 @@ mod tests { } forged[index].digest = commit_digest(&forged[index]).unwrap(); } - let mut head = kernel.state.clone(); - head.last_commit_digest = forged.last().map(|commit| commit.digest.clone()); - (head, forged) + forged }; let patch_row = |effect: &WorldEffect| matches!(effect, WorldEffect::PatchAdmitted { .. }); let clock_row = |effect: &WorldEffect| matches!(effect, WorldEffect::TimeAdvanced { .. }); for is_row in [&patch_row as &dyn Fn(&WorldEffect) -> bool, &clock_row] { - let (head, control) = forge(is_row, &|_| {}); - recover(rows_of(&head, &control), None) + let control = forge(is_row, &|_| {}); + reopen(&control) .expect("a consistent re-sealed store replays"); - let (head, forged) = forge(is_row, &|commit| { + let forged = forge(is_row, &|commit| { if let CommittedCommand::WorldCommand(command) = &mut commit.command { command.caller = CallerId::Principal(owner()); } }); - let error = recover(rows_of(&head, &forged), None) + let error = reopen(&forged) .expect_err("a commit forged to the owner replayed"); - let JournalError::Corrupt(_) = error else { - panic!("unexpected refusal: {error:?}"); - }; + let JournalError::Corrupt(_) = error; } } @@ -1390,12 +1015,8 @@ mod tests { TickMinutes, }; - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); let authenticated = auth_principal(owner()); - let (mut kernel, _) = WorldKernel::create( - &path, - crate::tests::creation("Chronicle"), + let (mut kernel, _) = WorldKernel::create(crate::tests::creation("Chronicle"), &authenticated, ) .unwrap(); @@ -1414,7 +1035,6 @@ mod tests { ) .unwrap(); - let mut forged_head = kernel.state.clone(); let mut forged_commits = kernel.journal.commits.clone(); let forged = last_commit(&mut forged_commits); let WorldEffect::TimeAdvanced { to, .. } = &mut forged.effect else { @@ -1422,10 +1042,9 @@ mod tests { }; *to = FictionalMinutes(31); forged.digest = commit_digest(forged).unwrap(); - forged_head.last_commit_digest = Some(forged.digest.clone()); assert!(matches!( - verify_history(&forged_head, &forged_commits), + reopen(&forged_commits), Err(JournalError::Corrupt(_)) )); } @@ -1436,12 +1055,8 @@ mod tests { fn a_forged_relocate_effect_does_not_apply() { use crate::tests::{admit_topology, auth_principal, command, owner}; - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); let authenticated = auth_principal(owner()); - let (mut kernel, _) = WorldKernel::create( - &path, - crate::tests::creation("Kharad"), + let (mut kernel, _) = WorldKernel::create(crate::tests::creation("Kharad"), &authenticated, ) .unwrap(); @@ -1467,7 +1082,6 @@ mod tests { ) .unwrap(); - let mut forged_head = kernel.state.clone(); let mut forged_commits = kernel.journal.commits.clone(); let forged = last_commit(&mut forged_commits); let WorldEffect::PatchAdmitted { resolved, .. } = &mut forged.effect else { @@ -1479,10 +1093,9 @@ mod tests { }; *subject_id = crate::SubjectId::issue(); forged.digest = commit_digest(forged).unwrap(); - forged_head.last_commit_digest = Some(forged.digest.clone()); assert!(matches!( - verify_history(&forged_head, &forged_commits), + reopen(&forged_commits), Err(JournalError::Corrupt(_)) )); } @@ -1505,12 +1118,8 @@ mod tests { }; let forge = |kind: &str, mutate: &dyn Fn(&mut crate::DecisionEvent)| { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); let authenticated = auth_principal(owner()); - let (mut kernel, _) = WorldKernel::create( - &path, - crate::tests::creation("ForgedDecision"), + let (mut kernel, _) = WorldKernel::create(crate::tests::creation("ForgedDecision"), &authenticated, ) .unwrap(); @@ -1552,35 +1161,29 @@ mod tests { .unwrap(); // The honest journal recovers. - assert!(verify_history(&kernel.state, &kernel.journal.commits).is_ok()); + assert!(reopen(&kernel.journal.commits).is_ok()); - let mut forged_head = kernel.state.clone(); let mut forged_commits = kernel.journal.commits.clone(); let forged = last_commit(&mut forged_commits); let WorldEffect::Acted { event, .. } = &mut forged.effect else { panic!("expected an acted effect"); }; mutate(event); - let forged_event = event.clone(); - *forged_head.events.last_mut().unwrap() = forged_event; forged.digest = commit_digest(forged).unwrap(); - forged_head.last_commit_digest = Some(forged.digest.clone()); - forged_head.state_digest = String::new(); - forged_head.state_digest = crate::state_digest(&forged_head).unwrap(); - (forged_head, forged_commits) + forged_commits }; // A band the seed did not draw, held inside a chain that verifies. - let (head, commits) = forge("carry_chance", &|event| { + let commits = forge("carry_chance", &|event| { event.band = (event.band + 1) % 3; }); assert!(matches!( - verify_history(&head, &commits), + reopen(&commits), Err(JournalError::Corrupt(_)) )); // A magnitude the ceiling admitted but the lowering never produced. - let (head, commits) = forge("carry", &|event| { + let commits = forge("carry", &|event| { let Some(crate::ResolvedOp::Transfer { qty, .. }) = event.effects.first_mut() else { panic!("expected a lowered transfer"); @@ -1588,15 +1191,13 @@ mod tests { *qty = Quantity(1); }); assert!(matches!( - verify_history(&head, &commits), + reopen(&commits), Err(JournalError::Corrupt(_)) )); } #[test] fn replay_rejects_genesis_that_does_not_derive_from_its_creation_command() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); let owner = PrincipalId::new("owner@example.test"); let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); let creation = CreateWorld { @@ -1612,8 +1213,7 @@ mod tests { }), grammar: None, }; - let (kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap(); - let mut forged_head = kernel.state.clone(); + let (kernel, _) = WorldKernel::create(creation, &authenticated).unwrap(); let mut forged_commits = kernel.journal.commits.clone(); let forged = genesis_commit(&mut forged_commits); let CommittedCommand::CreateWorld(command) = &mut forged.command else { @@ -1621,14 +1221,12 @@ mod tests { }; command.title = "Different command".into(); forged.digest = commit_digest(forged).unwrap(); - forged_head.last_commit_digest = Some(forged.digest.clone()); assert!(matches!( - verify_history(&forged_head, &forged_commits), + reopen(&forged_commits), Err(JournalError::Corrupt(_)) )); - let mut binding_forged_head = kernel.state.clone(); let mut binding_forged_commits = kernel.journal.commits.clone(); let binding_forged = genesis_commit(&mut binding_forged_commits); let WorldEffect::WorldCreated { resolved, .. } = &mut binding_forged.effect else { @@ -1636,48 +1234,30 @@ mod tests { }; resolved.subjects[0].subject.label = "Not the creation subject".into(); binding_forged.digest = commit_digest(binding_forged).unwrap(); - binding_forged_head.last_commit_digest = Some(binding_forged.digest.clone()); assert!(matches!( - verify_history(&binding_forged_head, &binding_forged_commits), + reopen(&binding_forged_commits), Err(JournalError::Corrupt(_)) )); } /// Soul falsification: the extended replay shape check is not decoration. - /// A forged store row carrying a self-loop, a cost out of range, a + /// A forged state carrying a self-loop, a cost out of range, a /// non-place endpoint, or a position on a non-place is refused by - /// `recover`, which is the path `WorldJournal::open` takes. + /// `verify_state_shape`, which `WorldJournal::open` runs on the replayed head. #[test] - fn soul_forged_topology_store_rows_are_refused_on_recover() { + fn soul_forged_topology_states_are_refused_by_the_shape_check() { use crate::patch::{AccessKind, Cost, EdgeRecord, MAX_ROUTE_COST}; use crate::tests::{admit_topology, auth_principal, owner}; - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let (mut kernel, _) = WorldKernel::create( - &path, - crate::tests::creation("Forged Rows"), + let (mut kernel, _) = WorldKernel::create(crate::tests::creation("Forged Rows"), &auth_principal(owner()), ) .unwrap(); let topology = admit_topology(&mut kernel); - let commits: Vec<CultCacheEnvelope> = kernel - .journal - .commits - .values() - .map(|commit| { - envelope(COMMIT_ROW, COMMIT_SCHEMA, commit.command.id().key(), commit).unwrap() - }) - .collect(); - let rows_for = |state: &WorldState, row_type: &str| { - let mut rows = commits.clone(); - rows.push(envelope(row_type, STATE_SCHEMA, state.world_id.key(), state).unwrap()); - rows - }; - // The honest state recovers. - assert!(recover(rows_for(&kernel.state, STATE_ROW), None).is_ok()); + assert!(verify_state_shape(&kernel.state).is_ok()); + assert!(reopen(&kernel.journal.commits).is_ok()); let self_loop = { let mut state = kernel.state.clone(); @@ -1720,7 +1300,7 @@ mod tests { state }; for forged in [self_loop, bad_cost, non_place_endpoint, stray_position] { - let error = recover(rows_for(&forged, STATE_ROW), None).unwrap_err(); + let error = verify_state_shape(&forged).unwrap_err(); assert!( matches!(error, JournalError::Corrupt(_)), "a forged topology row recovered: {error:?}" @@ -1728,54 +1308,6 @@ mod tests { } } - /// Soul falsification: a store written before the topology partitions is - /// refused outright, with no migration adapter in the path. - #[test] - fn soul_a_pre_topology_store_row_is_refused() { - use crate::tests::{admit_topology, auth_principal, owner}; - - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let (mut kernel, _) = WorldKernel::create( - &path, - crate::tests::creation("Old Store"), - &auth_principal(owner()), - ) - .unwrap(); - admit_topology(&mut kernel); - let mut rows: Vec<CultCacheEnvelope> = kernel - .journal - .commits - .values() - .map(|commit| { - envelope( - "world_commit.foundation.v2", - COMMIT_SCHEMA, - commit.command.id().key(), - commit, - ) - .unwrap() - }) - .collect(); - rows.push( - envelope( - "world_state.foundation.v1", - STATE_SCHEMA, - kernel.state.world_id.key(), - &kernel.state, - ) - .unwrap(), - ); - let error = recover(rows, None).unwrap_err(); - let JournalError::Corrupt(message) = error else { - panic!("expected a corrupt store, got {error:?}"); - }; - assert!( - message.contains("unadmitted row type"), - "unexpected refusal: {message}" - ); - } - /// A committed levy survives a restart exactly: the snapshot, the band, the /// lowered effects, and the re-derived authority verdict all come back, and /// the same envelope is already applied. @@ -1787,11 +1319,7 @@ mod tests { Target, }; - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let (mut kernel, _) = WorldKernel::create( - &path, - crate::tests::creation("Replayed Levy"), + let (mut kernel, _) = WorldKernel::create(crate::tests::creation("Replayed Levy"), &crate::tests::auth_principal(owner()), ) .unwrap(); @@ -1831,23 +1359,23 @@ mod tests { .unwrap(); let committed = kernel.snapshot().unwrap(); let event = kernel.state.events.last().expect("the levy event").clone(); - let world_id = committed.world_id; + let exported = kernel.export().unwrap(); drop(kernel); - let mut reopened = WorldKernel::open(&path, world_id).unwrap(); + let mut reopened = WorldKernel::open(&exported).unwrap(); assert_eq!(reopened.snapshot().unwrap(), committed); let replayed = reopened.state.events.last().expect("the replayed event"); assert_eq!(replayed.band, event.band); assert_eq!(replayed.effects, event.effects); assert!(matches!( - reopened .submit(envelope, &AuthenticatedCaller::fixture(caller)), + reopened.submit(envelope, &AuthenticatedCaller::fixture(caller)), Err(KernelError::RevisionMismatch { .. }) )); } /// Soul falsification: the civic shape checks are not decoration. A forged - /// store row that widens a jurisdiction, doubles an incumbency, seats an - /// institution, or empties a delegation is refused by `recover`. + /// state that widens a jurisdiction, doubles an incumbency, seats an + /// institution, or empties a delegation is refused by the shape check. #[test] fn a_forged_authority_or_incumbency_is_corrupt() { use crate::tests::{ @@ -1857,29 +1385,13 @@ mod tests { use crate::{AuthorityGrant, AuthorityTarget, Office}; use std::collections::BTreeSet; - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let (mut kernel, _) = WorldKernel::create( - &path, - crate::tests::creation("Forged Civics"), + let (mut kernel, _) = WorldKernel::create(crate::tests::creation("Forged Civics"), &auth_principal(owner()), ) .unwrap(); let (topology, civic, _) = civic_world(&mut kernel); - let commits: Vec<CultCacheEnvelope> = kernel - .journal - .commits - .values() - .map(|commit| { - envelope(COMMIT_ROW, COMMIT_SCHEMA, commit.command.id().key(), commit).unwrap() - }) - .collect(); - let rows_for = |state: &WorldState| { - let mut rows = commits.clone(); - rows.push(envelope(STATE_ROW, STATE_SCHEMA, state.world_id.key(), state).unwrap()); - rows - }; - assert!(recover(rows_for(&kernel.state), None).is_ok()); + assert!(verify_state_shape(&kernel.state).is_ok()); + assert!(reopen(&kernel.journal.commits).is_ok()); let widened = { let mut state = kernel.state.clone(); @@ -1951,7 +1463,7 @@ mod tests { inert_office, office_on_person, ] { - let error = recover(rows_for(&forged), None).unwrap_err(); + let error = verify_state_shape(&forged).unwrap_err(); assert!( matches!(error, JournalError::Corrupt(_)), "a forged civic row recovered: {error:?}" @@ -1959,54 +1471,6 @@ mod tests { } } - /// Soul falsification: a store written before the civic partitions is - /// refused outright, with no migration adapter in the path. - #[test] - fn a_store_from_the_previous_schema_is_refused() { - use crate::tests::{auth_principal, civic_world, owner}; - - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let (mut kernel, _) = WorldKernel::create( - &path, - crate::tests::creation("Pre-Authority"), - &auth_principal(owner()), - ) - .unwrap(); - civic_world(&mut kernel); - let mut rows: Vec<CultCacheEnvelope> = kernel - .journal - .commits - .values() - .map(|commit| { - envelope( - "world_commit.affordance.v1", - COMMIT_SCHEMA, - commit.command.id().key(), - commit, - ) - .unwrap() - }) - .collect(); - rows.push( - envelope( - "world_state.affordance.v1", - STATE_SCHEMA, - kernel.state.world_id.key(), - &kernel.state, - ) - .unwrap(), - ); - let error = recover(rows, None).unwrap_err(); - let JournalError::Corrupt(message) = error else { - panic!("expected a corrupt store, got {error:?}"); - }; - assert!( - message.contains("unadmitted row type"), - "unexpected refusal: {message}" - ); - } - /// Soul falsification of the structural-overlap decision, updated for the /// admission-time covering check: a `Subject` grant naming ground a /// `PlaceSubtree` grant already covers is refused on arrival, but nothing @@ -2022,11 +1486,7 @@ mod tests { }; use crate::{ComponentOp, Mismatch}; - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let (mut kernel, _) = WorldKernel::create( - &path, - crate::tests::creation("Moving Civics"), + let (mut kernel, _) = WorldKernel::create(crate::tests::creation("Moving Civics"), &auth_principal(owner()), ) .unwrap(); @@ -2088,8 +1548,9 @@ mod tests { // The whole history replays, and the reopened world is identical. let committed = kernel.snapshot().unwrap(); + let exported = kernel.export().unwrap(); drop(kernel); - let reopened = WorldKernel::open(&path, committed.world_id).unwrap(); + let reopened = WorldKernel::open(&exported).unwrap(); assert_eq!(reopened.snapshot().unwrap(), committed); } } @@ -2097,7 +1558,7 @@ mod tests { #[cfg(test)] mod custody_tests { use super::*; - use super::tests::last_commit; + use super::tests::{last_commit, reopen}; use crate::{ CallerId, CommandBody, ComponentOp, DependencyRef, EntityKind, Quantity, Ref, WorldKernel, WorldPatch, @@ -2109,11 +1570,9 @@ mod custody_tests { /// envelope is idempotent. #[test] fn restart_replay_after_a_transfer_is_exact() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); let authenticated = auth_principal(owner()); let (mut kernel, _) = - WorldKernel::create(&path, creation("Replay"), &authenticated) + WorldKernel::create(creation("Replay"), &authenticated) .unwrap(); let topology = admit_topology(&mut kernel); let custody = admit_custody(&mut kernel, &topology); @@ -2137,10 +1596,10 @@ mod custody_tests { ); kernel.submit(envelope.clone(), &crate::AuthenticatedCaller::verified_play()).unwrap(); let accepted = kernel.snapshot().unwrap(); - let world_id = accepted.world_id; + let exported = kernel.export().unwrap(); drop(kernel); - let mut reopened = WorldKernel::open(&path, world_id).unwrap(); + let mut reopened = WorldKernel::open(&exported).unwrap(); assert_eq!(reopened.snapshot().unwrap(), accepted); assert!(matches!( reopened.submit(envelope, &crate::AuthenticatedCaller::verified_play()), @@ -2156,12 +1615,8 @@ mod custody_tests { use crate::tests::{affordance_named, play_caller}; use crate::{AuthenticatedCaller, Magnitude, ProposedEffect, RoleBinding, Target}; - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); let authenticated = auth_principal(owner()); - let (mut kernel, _) = WorldKernel::create( - &path, - creation("ActionReplay"), + let (mut kernel, _) = WorldKernel::create(creation("ActionReplay"), &authenticated, ) .unwrap(); @@ -2209,52 +1664,28 @@ mod custody_tests { .expect("the committed event") .clone(); assert!(!committed.effects.is_empty()); - let world_id = accepted.world_id; + let exported = kernel.export().unwrap(); drop(kernel); - let mut reopened = WorldKernel::open(&path, world_id).unwrap(); + let mut reopened = WorldKernel::open(&exported).unwrap(); assert_eq!(reopened.snapshot().unwrap(), accepted); assert_eq!( reopened.state.events.last().expect("the replayed event"), &committed ); assert!(matches!( - reopened .submit(envelope, &authenticated_controller), + reopened.submit(envelope, &authenticated_controller), Err(KernelError::RevisionMismatch { .. }) )); } - /// A store written at the pass-2 schema is refused outright. There is no - /// migration adapter, and the refusal is the behaviour. - #[test] - fn a_store_from_the_previous_schema_is_refused() { - let row = CultCacheEnvelope { - key: "state".into(), - r#type: "world_state.topology.v1".into(), - payload: Vec::new(), - stored_at: Utc::now().to_rfc3339(), - schema_id: Some("ghostlight.world_state.topology.v1".into()), - }; - let error = recover(vec![row], None).unwrap_err(); - let JournalError::Corrupt(message) = error else { - panic!("expected a corrupt store"); - }; - assert!( - message.contains("unadmitted row type"), - "unexpected refusal: {message}" - ); - } - /// The title clause of the shape check refuses an empty title and a /// noncanonical one, each on its own. #[test] fn a_forged_empty_or_padded_title_is_corrupt() { use crate::tests::{auth_principal, creation, owner}; - let directory = tempfile::tempdir().unwrap(); - let (kernel, _) = WorldKernel::create( - directory.path().join("world.cc"), - creation("Titled"), + let (kernel, _) = WorldKernel::create(creation("Titled"), &auth_principal(owner()), ) .unwrap(); @@ -2277,11 +1708,7 @@ mod custody_tests { use crate::tests::{auth_principal, creation, owner}; use crate::{AffordanceId, SubjectId}; - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let (kernel, _) = WorldKernel::create( - &path, - creation("GrantRows"), + let (kernel, _) = WorldKernel::create(creation("GrantRows"), &auth_principal(owner()), ) .unwrap(); @@ -2323,11 +1750,7 @@ mod custody_tests { act, auth_principal, creation, first_grant, owner, speak, }; - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let (mut kernel, _) = WorldKernel::create( - &path, - creation("ActedChain"), + let (mut kernel, _) = WorldKernel::create(creation("ActedChain"), &auth_principal(owner()), ) .unwrap(); @@ -2346,9 +1769,9 @@ mod custody_tests { ) .unwrap(); let accepted = kernel.snapshot().unwrap(); - let world_id = accepted.world_id; + let exported = kernel.export().unwrap(); drop(kernel); - let reopened = WorldKernel::open(&path, world_id).expect("the acted chain recovers"); + let reopened = WorldKernel::open(&exported).expect("the acted chain recovers"); assert_eq!(reopened.snapshot().unwrap(), accepted); verify_state_shape(&reopened.state).expect("an honest event passes the shape check"); @@ -2367,67 +1790,6 @@ mod custody_tests { ); } - /// Stores written at the previous schema ids (v8) are refused outright, - /// state row and commit row each on their own: reverting either constant - /// to v8 would let its half of the store in. - #[test] - fn ghostlight_state_and_commit_rows_are_refused() { - use crate::tests::{act, auth_principal, creation, first_grant, owner, speak}; - - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, _) = WorldKernel::create( - directory.path().join("world.cc"), - creation("SchemaV9"), - &auth_principal(owner()), - ) - .unwrap(); - let active = kernel.snapshot().unwrap(); - let actor = active.subjects[0].id; - act(&mut kernel, actor, speak(first_grant(&active, actor), "Counted.")).unwrap(); - let commits: Vec<WorldCommit> = kernel.journal.commits.values().cloned().collect(); - let commit_rows = |schema: &str| -> Vec<CultCacheEnvelope> { - commits - .iter() - .map(|commit| envelope(COMMIT_ROW, schema, commit.command.id().key(), commit).unwrap()) - .collect() - }; - let state_row = |schema: &str| { - envelope(STATE_ROW, schema, kernel.state.world_id.key(), &kernel.state).unwrap() - }; - assert_eq!(STATE_SCHEMA, "aetherlight.world_state.v1"); - assert_eq!(COMMIT_SCHEMA, "aetherlight.world_commit.v1"); - recover( - [commit_rows(COMMIT_SCHEMA), vec![state_row(STATE_SCHEMA)]].concat(), - None, - ) - .expect("the current schema ids recover"); - - for (what, rows) in [ - ( - "ghostlight state row", - [ - commit_rows(COMMIT_SCHEMA), - vec![state_row("ghostlight.world_state.consumer.v10")], - ] - .concat(), - ), - ( - "ghostlight commit rows", - [ - commit_rows("ghostlight.world_commit.consumer.v10"), - vec![state_row(STATE_SCHEMA)], - ] - .concat(), - ), - ] { - let error = recover(rows, None).unwrap_err(); - let JournalError::Corrupt(message) = error else { - panic!("{what}: expected a corrupt store, got {error:?}"); - }; - assert!(message.contains("wrong schema"), "{what}: {message}"); - } - } - /// The event shape check holds for a silent act too: a non-speech event /// whose actor is no subject is corrupt, with no minted claim to catch it. #[test] @@ -2438,10 +1800,7 @@ mod custody_tests { }; use crate::{DecisionInvocation, Magnitude, ProposedEffect, Quantity, Role, RoleBinding, Target}; - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, _) = WorldKernel::create( - directory.path().join("world.cc"), - creation("SilentForgery"), + let (mut kernel, _) = WorldKernel::create(creation("SilentForgery"), &auth_principal(owner()), ) .unwrap(); @@ -2495,11 +1854,9 @@ mod custody_tests { /// falsification. #[test] fn a_zero_or_dangling_holding_is_corrupt() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); let authenticated = auth_principal(owner()); let (mut kernel, _) = - WorldKernel::create(&path, creation("Shape"), &authenticated) + WorldKernel::create(creation("Shape"), &authenticated) .unwrap(); let topology = admit_topology(&mut kernel); let custody = admit_custody(&mut kernel, &topology); @@ -2553,12 +1910,8 @@ mod custody_tests { /// envelope is idempotent, and the whole chain still verifies. #[test] fn soul_replay_is_exact_after_every_custody_operation() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); let authenticated = auth_principal(owner()); - let (mut kernel, _) = WorldKernel::create( - &path, - creation("EveryOperation"), + let (mut kernel, _) = WorldKernel::create(creation("EveryOperation"), &authenticated, ) .unwrap(); @@ -2610,10 +1963,10 @@ mod custody_tests { let holdings = kernel.state.holdings.clone(); let dependencies = kernel.state.dependencies.clone(); let digest = kernel.state.state_digest.clone(); - let world_id = accepted.world_id; + let exported = kernel.export().unwrap(); drop(kernel); - let mut reopened = WorldKernel::open(&path, world_id).unwrap(); + let mut reopened = WorldKernel::open(&exported).unwrap(); assert_eq!(reopened.snapshot().unwrap(), accepted); assert_eq!(reopened.state.holdings, holdings); assert_eq!(reopened.state.dependencies, dependencies); @@ -2629,12 +1982,8 @@ mod custody_tests { /// referential integrity the operation arm enforces at admission. #[test] fn soul_a_dependency_on_an_absent_or_wrong_kind_target_is_corrupt() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); let authenticated = auth_principal(owner()); - let (mut kernel, _) = WorldKernel::create( - &path, - creation("DependencyShape"), + let (mut kernel, _) = WorldKernel::create(creation("DependencyShape"), &authenticated, ) .unwrap(); @@ -2678,7 +2027,7 @@ mod custody_tests { /// A world with one routine, one past-due goal, and a commit chain that /// reaches them: the fixture the two clock-forgery checks below need. - fn ticking_world(path: &std::path::Path) -> (WorldKernel, super::super::SubjectId) { + fn ticking_world() -> (WorldKernel, super::super::SubjectId) { use crate::tests::{auth_principal, command, operations, owner}; use crate::{ AuthenticatedCaller, CallerId, CommandBody, CommitmentKind, ComponentOp, @@ -2687,7 +2036,6 @@ mod custody_tests { let authenticated = auth_principal(owner()); let (mut kernel, _) = WorldKernel::create( - path, crate::tests::creation("Ticking"), &authenticated, ) @@ -2750,13 +2098,11 @@ mod custody_tests { fn soul_a_forged_tick_motion_does_not_replay() { use crate::{FictionalMinutes, PressureMagnitude, PressureSource}; - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let (kernel, subject) = ticking_world(&path); + let (kernel, subject) = ticking_world(); let WorldEffect::TimeAdvanced { motion, .. } = &kernel .journal .commits - .values() + .iter() .max_by_key(|commit| commit.resulting_revision) .expect("the tick's commit") .effect @@ -2767,7 +2113,6 @@ mod custody_tests { assert!(!motion.pressed.is_empty(), "the past-due goal pressed"); let forge = |rewrite: fn(&mut crate::Motion)| { - let mut forged_head = kernel.state.clone(); let mut forged_commits = kernel.journal.commits.clone(); let forged = last_commit(&mut forged_commits); let WorldEffect::TimeAdvanced { motion, .. } = &mut forged.effect else { @@ -2775,8 +2120,7 @@ mod custody_tests { }; rewrite(motion); forged.digest = commit_digest(forged).unwrap(); - forged_head.last_commit_digest = Some(forged.digest.clone()); - verify_history(&forged_head, &forged_commits) + reopen(&forged_commits) }; let rewrites: [fn(&mut crate::Motion); 4] = [ @@ -2809,9 +2153,7 @@ mod custody_tests { /// constructor enforces, so the forged row is refused directly. #[test] fn soul_a_zero_period_is_refused_by_the_shape_check() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let (kernel, subject) = ticking_world(&path); + let (kernel, subject) = ticking_world(); // The forgery an in-crate caller cannot write: `TickMinutes::new` // refuses zero, and the field is private, so the only door is serde. @@ -2838,19 +2180,6 @@ mod custody_tests { matches!(verify_state_shape(&forged), Err(JournalError::Corrupt(_))), "verify_state_shape admitted a period outside 1..=MAX_ROUTE_COST" ); - - // The commit chain refuses it too. - let commits: Vec<CultCacheEnvelope> = kernel - .journal - .commits - .values() - .map(|commit| { - envelope(COMMIT_ROW, COMMIT_SCHEMA, commit.command.id().key(), commit).unwrap() - }) - .collect(); - let mut rows = commits; - rows.push(envelope(STATE_ROW, STATE_SCHEMA, forged.world_id.key(), &forged).unwrap()); - assert!(matches!(recover(rows, None), Err(JournalError::Corrupt(_)))); } } diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index ce2483ab9..0647e8db3 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -1,8 +1,10 @@ //! The Aetherlight world library, a fork of Ghostlight c43eb54 (see `PROVENANCE.md`). //! //! The world owner is one deterministic authority: authenticated commands enter, -//! one reducer decides, and one journal atomically commits the resulting state. -//! The fork keeps only that synchronous kernel: no async runtime, no network, no +//! one reducer decides, and the journal, an in-memory list of commits, records +//! each result. The journal exports as bytes, and opening those bytes replays +//! the chain from genesis: the head state is whatever the replay derives. +//! The fork keeps only that single-threaded kernel: no async runtime, no network, no //! model controllers and no ports. A decision arrives as an invocation the caller //! built, a player or a brain; nothing in this crate composes one. //! @@ -97,8 +99,6 @@ use patch::{EdgeRecord, EntityRecord, LedgerDelta, ResolvedOp, ResolvedPatch}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet}; -#[cfg(test)] -use std::path::Path; use thiserror::Error; use uuid::Uuid; @@ -848,52 +848,18 @@ pub enum KernelError { AffordanceDenied, #[error("expected revision {expected}, current revision {actual}")] RevisionMismatch { expected: u64, actual: u64 }, - #[error("world creation ID was reused with different content")] - CreationConflict, - #[error("world creation target already contains another world")] - CreationTargetOccupied, - #[error("world has not been created")] - WorldNotCreated, - #[error("opened store contains another world")] - OpenedWorldMismatch, - #[error("world ownership is uncertain after command {command_id:?}; drop and reopen")] - RecoveryRequired { command_id: CommandId }, - #[error("world store path no longer names the owned database; drop and reopen explicitly")] - OwnershipLost, #[error("canonical serialization failed: {0}")] Serialization(String), - #[error("world store operation failed: {0}")] - Store(String), #[error("world journal is corrupt: {0}")] CorruptJournal(String), #[error("private reducer invariant failed: {0}")] Invariant(String), } -impl KernelError { - fn requires_owner_restart(&self) -> bool { - matches!( - self, - Self::RecoveryRequired { .. } - | Self::OwnershipLost - | Self::Store(_) - | Self::CorruptJournal(_) - | Self::Invariant(_) - ) - } -} - impl From<journal::JournalError> for KernelError { fn from(error: journal::JournalError) -> Self { - match error { - journal::JournalError::WorldMismatch => Self::OpenedWorldMismatch, - journal::JournalError::RecoveryRequired { command_id } => { - Self::RecoveryRequired { command_id } - } - journal::JournalError::OwnershipLost => Self::OwnershipLost, - journal::JournalError::Store(detail) => Self::Store(detail), - journal::JournalError::Corrupt(detail) => Self::CorruptJournal(detail), - } + let journal::JournalError::Corrupt(detail) = error; + Self::CorruptJournal(detail) } } @@ -947,10 +913,7 @@ fn prepare_creation( } impl WorldKernel { - fn initialize( - empty: journal::EmptyWorldJournal, - prepared: PreparedCreation, - ) -> Result<(Self, CreationReceipt), KernelError> { + fn initialize(prepared: PreparedCreation) -> Result<(Self, CreationReceipt), KernelError> { let world_id = prepared.world_id; let effect = WorldEffect::WorldCreated { owner: prepared.owner, @@ -973,48 +936,28 @@ impl WorldKernel { genesis.digest = commit_digest(&genesis)?; state.last_commit_digest = Some(genesis.digest.clone()); let receipt = CreationReceipt::from_commit(&genesis)?; - let journal = empty.initialize(&state, &genesis)?; + let journal = journal::WorldJournal::genesis(genesis); Ok((Self { state, journal }, receipt)) } - fn retry_creation(&self, prepared: &PreparedCreation) -> Result<CreationReceipt, KernelError> { - self.journal.ensure_healthy()?; - let Some(commit) = self.journal.commit_for(prepared.command.id()) else { - return Err(KernelError::CreationTargetOccupied); - }; - if commit.command != CommittedCommand::CreateWorld(prepared.command.clone()) - || !matches!(&commit.effect, WorldEffect::WorldCreated { .. }) - { - return Err(KernelError::CreationConflict); - } - CreationReceipt::from_commit(commit) - } - - #[cfg(test)] fn create( - path: impl AsRef<Path>, input: CreateWorld, authenticated: &AuthenticatedCaller, ) -> Result<(Self, CreationReceipt), KernelError> { - let prepared = prepare_creation(input, authenticated)?; - match journal::WorldJournal::open_owner(path.as_ref())? { - journal::JournalOpen::Empty(empty) => Self::initialize(empty, prepared), - journal::JournalOpen::Live { journal, state } => { - let kernel = Self { state, journal }; - let receipt = kernel.retry_creation(&prepared)?; - Ok((kernel, receipt)) - } - } + Self::initialize(prepare_creation(input, authenticated)?) } - #[cfg(test)] - fn open(path: impl AsRef<Path>, expected_world_id: WorldId) -> Result<Self, KernelError> { - let (journal, state) = journal::WorldJournal::open(path.as_ref(), expected_world_id)?; + /// The world an export derives: its head state is the replay of its commits. + fn open(bytes: &[u8]) -> Result<Self, KernelError> { + let (journal, state) = journal::WorldJournal::open(bytes)?; Ok(Self { state, journal }) } + fn export(&self) -> Result<Vec<u8>, KernelError> { + self.journal.export() + } + fn snapshot(&self) -> Result<WorldSnapshot, KernelError> { - self.journal.ensure_healthy()?; snapshot(&self.state) } @@ -1023,7 +966,6 @@ impl WorldKernel { command: CommandEnvelope, authenticated: &AuthenticatedCaller, ) -> Result<CommitReceipt, KernelError> { - self.journal.ensure_healthy()?; let command_id = command.id(); if command.world_id != self.state.world_id { return Err(KernelError::WorldMismatch); @@ -1062,9 +1004,10 @@ impl WorldKernel { commit.digest = commit_digest(&commit)?; candidate.last_commit_digest = Some(commit.digest.clone()); - self.journal.commit(&candidate, &commit)?; + let receipt = CommitReceipt::from(&commit); + self.journal.append(commit); self.state = candidate; - Ok(CommitReceipt::from(&commit)) + Ok(receipt) } } @@ -4669,57 +4612,63 @@ mod tests { #[test] fn create_submit_restart_and_replay_are_exact() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("world.cc"); let creation = creation("First"); let (mut kernel, creation_receipt) = - WorldKernel::create(&path, creation.clone(), &auth_principal(owner())).unwrap(); + WorldKernel::create(creation.clone(), &auth_principal(owner())).unwrap(); let active = kernel.snapshot().unwrap(); let operator = subject_by_label(&kernel.state, "The Council"); - let caller = play_caller(); let command = command( &active, - caller.clone(), + play_caller(), CommandBody::Act { actor: operator, invocation: speak(first_grant(&active, operator), "The vote carries."), }, ); kernel - .submit( - command.clone(), - &AuthenticatedCaller::fixture(caller.clone()), - ) + .submit(command.clone(), &AuthenticatedCaller::verified_play()) .unwrap(); let accepted = kernel.snapshot().unwrap(); - drop(kernel); + let exported = kernel.export().unwrap(); - let (mut reopened, retried_creation_receipt) = - WorldKernel::create(&path, creation, &auth_principal(owner())).unwrap(); - assert_eq!(retried_creation_receipt, creation_receipt); + // The same creation names the same world, with the same receipt. + let (_, retried) = WorldKernel::create(creation, &auth_principal(owner())).unwrap(); + assert_eq!(retried, creation_receipt); + + // The export is the whole world: its reopening is equal, re-exports + // byte for byte, and the applied command is stale in it. + let mut reopened = WorldKernel::open(&exported).unwrap(); assert_eq!(reopened.snapshot().unwrap(), accepted); + assert_eq!(reopened.export().unwrap(), exported); assert!(matches!( - reopened .submit(command, &AuthenticatedCaller::fixture(caller)), + reopened.submit(command, &AuthenticatedCaller::verified_play()), Err(KernelError::RevisionMismatch { .. }) )); - drop(reopened); - let reopened = WorldKernel::open(&path, accepted.world_id).unwrap(); - assert_eq!(reopened.snapshot().unwrap(), accepted); + + // The next command gives equal receipts and equal worlds on both. + let next = play_command(&accepted, tick_body(1)); + let original_receipt = kernel + .submit(next.clone(), &AuthenticatedCaller::verified_play()) + .unwrap(); + let reopened_receipt = reopened + .submit(next, &AuthenticatedCaller::verified_play()) + .unwrap(); + assert_eq!(original_receipt, reopened_receipt); + assert_eq!(kernel.snapshot().unwrap(), reopened.snapshot().unwrap()); + assert_eq!(kernel.export().unwrap(), reopened.export().unwrap()); } #[test] - fn stale_commands_do_not_commit() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("world.cc"); - let (mut kernel, _) = WorldKernel::create( - &path, - creation("Still"), + fn a_stale_command_is_a_revision_mismatch() { + let (mut kernel, _) = WorldKernel::create(creation("Still"), &auth_principal(owner()), ) .unwrap(); let genesis = kernel.snapshot().unwrap(); assert!(submit_play(&mut kernel, &genesis, tick_body(1)).resulting_revision > 0); let after = kernel.snapshot().unwrap(); + // The very command that was applied, resubmitted: there is no retry + // identity, so it is stale like any other. let stale = play_command(&genesis, tick_body(1)); assert!(matches!( kernel.submit(stale, &AuthenticatedCaller::verified_play()), @@ -4731,17 +4680,15 @@ mod tests { #[test] fn ids_are_derived_from_the_command() { - let dir = tempfile::tempdir().unwrap(); - let create = |name: &str, title: &str| { - WorldKernel::create(dir.path().join(name), creation(title), &auth_principal(owner())) - .unwrap() + let create = |title: &str| { + WorldKernel::create(creation(title), &auth_principal(owner())).unwrap() }; - let (mut kernel, receipt) = create("a.cc", "Same"); - let (twin, twin_receipt) = create("b.cc", "Same"); + let (mut kernel, receipt) = create("Same"); + let (twin, twin_receipt) = create("Same"); assert_eq!(receipt, twin_receipt); assert_eq!(kernel.state.world_id, twin.state.world_id); assert_eq!(receipt.world_id, WorldId::of(receipt.command_id)); - let (other, _) = create("c.cc", "Other"); + let (other, _) = create("Other"); assert_ne!(kernel.state.world_id, other.state.world_id); // The same patch at two revisions is two commands, so the entity it @@ -4778,12 +4725,10 @@ mod tests { #[test] fn invalid_seed_never_allocates_a_world() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("world.cc"); let mut invalid = creation("Nope"); invalid.patch.declarations[3] = invalid.patch.declarations[2].clone(); let Err(KernelError::PatchRejected(rejected)) = - WorldKernel::create(&path, invalid, &auth_principal(owner())) + WorldKernel::create(invalid, &auth_principal(owner())) else { panic!("expected a rejected creation patch"); }; @@ -4794,137 +4739,16 @@ mod tests { }] ); assert!( - WorldKernel::create( - &path, - creation("Valid"), + WorldKernel::create(creation("Valid"), &auth_principal(owner()) ) .is_ok() ); } - #[test] - fn a_second_live_owner_is_refused() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("world.cc"); - let creation = creation("Held"); - let (kernel, _) = - WorldKernel::create(&path, creation.clone(), &auth_principal(owner())).unwrap(); - let world_id = kernel.snapshot().unwrap().world_id; - assert!(matches!( - WorldKernel::open(&path, world_id), - Err(KernelError::Store(_)) - )); - assert!(matches!( - WorldKernel::create(&path, creation.clone(), &auth_principal(owner())), - Err(KernelError::Store(_)) - )); - drop(kernel); - let kernel = WorldKernel::open(&path, world_id).unwrap(); - drop(kernel); - assert!(matches!( - WorldKernel::open(&path, WorldId::of(CommandId::issue())), - Err(KernelError::OpenedWorldMismatch) - )); - } - - #[test] - fn lost_post_commit_ack_poisons_until_reopen_and_exact_retry() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("world.cc"); - let (mut kernel, _) = WorldKernel::create( - &path, - creation("Certain"), - &auth_principal(owner()), - ) - .unwrap(); - let genesis = kernel.snapshot().unwrap(); - let attempted = play_command(&genesis, tick_body(1)); - let uncertain = attempted.id(); - kernel.journal.fail_after_durable_commit_for_test(); - assert!(matches!( - kernel.submit(attempted.clone(), &AuthenticatedCaller::verified_play()), - Err(KernelError::RecoveryRequired { command_id }) if command_id == uncertain - )); - assert!(matches!( - kernel.snapshot(), - Err(KernelError::RecoveryRequired { command_id }) if command_id == uncertain - )); - drop(kernel); - - let mut reopened = WorldKernel::open(&path, genesis.world_id).unwrap(); - let durable = reopened.snapshot().unwrap(); - assert_eq!(durable.revision, 1); - assert!(matches!( - reopened .submit(attempted, &AuthenticatedCaller::verified_play()), - Err(KernelError::RevisionMismatch { .. }) - )); - } - - #[test] - fn lost_genesis_ack_reopens_as_the_same_world_and_exact_receipt() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("world.cc"); - let input = creation("Durable Genesis"); - let command_id = input.id(); - let authenticated = auth_principal(owner()); - let mut empty = match journal::WorldJournal::open_owner(&path).unwrap() { - journal::JournalOpen::Empty(empty) => empty, - journal::JournalOpen::Live { .. } => panic!("fixture store must be empty"), - }; - empty.fail_after_durable_initialize_for_test(); - let prepared = prepare_creation(input.clone(), &authenticated).unwrap(); - assert!(matches!( - WorldKernel::initialize(empty, prepared), - Err(KernelError::RecoveryRequired { command_id: uncertain }) - if uncertain == command_id - )); - - let (reopened, receipt) = WorldKernel::create(&path, input, &authenticated).unwrap(); - let snapshot = reopened.snapshot().unwrap(); - assert_eq!(receipt.command_id, command_id); - assert_eq!(receipt.world_id, snapshot.world_id); - assert_eq!(snapshot.revision, 0); - assert_eq!(snapshot.title, "Durable Genesis"); - } - - #[test] - fn replacing_the_store_path_revokes_the_live_owner() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("world.cc"); - let displaced = dir.path().join("displaced.cc"); - let (mut kernel, _) = WorldKernel::create( - &path, - creation("Pinned"), - &auth_principal(owner()), - ) - .unwrap(); - let snapshot = kernel.snapshot().unwrap(); - std::fs::rename(&path, &displaced).unwrap(); - std::fs::File::create(&path).unwrap(); - assert!(matches!(kernel.snapshot(), Err(KernelError::OwnershipLost))); - assert!(matches!( - kernel.submit( - play_command(&snapshot, tick_body(1)), - &AuthenticatedCaller::verified_play() - ), - Err(KernelError::OwnershipLost) - )); - std::fs::remove_file(&path).unwrap(); - std::fs::rename(&displaced, &path).unwrap(); - assert!(matches!(kernel.snapshot(), Err(KernelError::OwnershipLost))); - drop(kernel); - let reopened = WorldKernel::open(&path, snapshot.world_id).unwrap(); - assert_eq!(reopened.snapshot().unwrap(), snapshot); - } - #[test] fn sealed_authentication_cannot_be_replaced_by_a_command_claim() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("world.cc"); - let (mut kernel, _) = WorldKernel::create( - &path, - creation("Owned"), + let (mut kernel, _) = WorldKernel::create(creation("Owned"), &auth_principal(owner()), ) .unwrap(); @@ -4946,10 +4770,7 @@ mod tests { /// that moves the world, not a hand-edited state. #[test] fn soul_scope_components_exclude_revision_and_everything_outside_the_scope() { - let dir = tempfile::tempdir().unwrap(); - let (mut kernel, _) = WorldKernel::create( - dir.path().join("world.cc"), - creation("Preimage"), + let (mut kernel, _) = WorldKernel::create(creation("Preimage"), &auth_principal(owner()), ) .unwrap(); @@ -5068,10 +4889,7 @@ mod tests { /// one that does not. #[test] fn act_needs_the_actors_grant() { - let dir = tempfile::tempdir().unwrap(); - let (mut kernel, _) = WorldKernel::create( - dir.path().join("world.cc"), - creation("SharedCatalogIds"), + let (mut kernel, _) = WorldKernel::create(creation("SharedCatalogIds"), &auth_principal(owner()), ) .unwrap(); @@ -5130,10 +4948,7 @@ mod tests { #[test] fn a_distant_route_closing_leaves_the_actors_scope_alone_and_its_act_commits() { - let dir = tempfile::tempdir().unwrap(); - let (mut kernel, _) = WorldKernel::create( - dir.path().join("world.cc"), - creation("BindingAndAdmission"), + let (mut kernel, _) = WorldKernel::create(creation("BindingAndAdmission"), &auth_principal(owner()), ) .unwrap(); @@ -5179,8 +4994,7 @@ mod tests { /// office, not one subject with two controllers. #[test] fn an_institution_and_its_voice_are_two_subjects_joined_by_an_office() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "Two"); + let mut kernel = crate::custody_tests::custody_kernel("Two"); let (_, civic, _) = civic_world(&mut kernel); @@ -5209,8 +5023,7 @@ mod tests { /// total unchanged, and no other partition touched. #[test] fn a_levy_round_trips_from_catalog_to_conservation() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "Levy"); + let mut kernel = crate::custody_tests::custody_kernel("Levy"); let (_, civic, active) = civic_world(&mut kernel); let before_total: u64 = kernel .state @@ -5293,8 +5106,7 @@ mod tests { /// that stops the two-subject shape from collapsing back into one. #[test] fn office_admission_is_person_and_institution_shaped() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "Offices"); + let mut kernel = crate::custody_tests::custody_kernel("Offices"); let (_, civic, _) = civic_world(&mut kernel); let refuse = |kernel: &mut WorldKernel, ops: Vec<ComponentOp>| { let before = kernel.snapshot().unwrap(); @@ -5343,8 +5155,7 @@ mod tests { /// authority is refused, overlap between subjects is layered government. #[test] fn overlapping_jurisdiction_within_one_subject_is_rejected() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "Overlap"); + let mut kernel = crate::custody_tests::custody_kernel("Overlap"); let (_, civic, _) = civic_world(&mut kernel); let refuse = |kernel: &mut WorldKernel, ops: Vec<ComponentOp>| { let before = kernel.snapshot().unwrap(); @@ -5401,8 +5212,7 @@ mod tests { /// allocation, and repairing exactly those failures commits. #[test] fn civic_operations_are_rejected_with_the_complete_set() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "CivicSet"); + let mut kernel = crate::custody_tests::custody_kernel("CivicSet"); let (_, civic, _) = civic_world(&mut kernel); let before = kernel.snapshot().unwrap(); let broken = vec![ @@ -5471,9 +5281,8 @@ mod tests { /// A civic operation that changes nothing is not a canonical change. #[test] fn an_idempotent_civic_operation_is_no_change() { - let directory = tempfile::tempdir().unwrap(); let mut kernel = - crate::custody_tests::custody_kernel(directory.path(), "Idempotent"); + crate::custody_tests::custody_kernel("Idempotent"); let (_, civic, _) = civic_world(&mut kernel); for operation in [ grant_to(civic.treasury, LEVY_KIND, over_place(civic.hall)), @@ -5508,8 +5317,7 @@ mod tests { /// world the actor reaches. #[test] fn scope_components_read_authority_and_delegation_but_not_occupancy() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "Digest"); + let mut kernel = crate::custody_tests::custody_kernel("Digest"); let (topology, civic, _) = civic_world(&mut kernel); let digest_of = |kernel: &WorldKernel, subject_id| { scope_components(&kernel.state, subject_id) @@ -5597,8 +5405,7 @@ mod tests { /// grants. #[test] fn a_forum_is_visible_only_to_its_standing() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "Redress"); + let mut kernel = crate::custody_tests::custody_kernel("Redress"); let (_, civic, active) = civic_world(&mut kernel); let of = |subject_id: SubjectId| { active @@ -5648,8 +5455,7 @@ mod tests { /// cannot declare a restricted room and walk anyone into it in one batch. #[test] fn a_same_patch_destination_is_covered_by_no_grant() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "DraftDoor"); + let mut kernel = crate::custody_tests::custody_kernel("DraftDoor"); let topology = admit_topology(&mut kernel); let before = kernel.snapshot().unwrap(); let patch = WorldPatch { @@ -5707,8 +5513,7 @@ mod tests { /// the one site that turns an office into effective authority. #[test] fn a_retired_institution_lends_no_authority_to_its_office_holder() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "RetiredLends"); + let mut kernel = crate::custody_tests::custody_kernel("RetiredLends"); let (_, civic, before) = civic_world(&mut kernel); let over_hall = AuthorityGrant { kind: authority_kind(LEVY_KIND), @@ -5754,10 +5559,8 @@ mod custody_tests { }; use super::*; - pub(crate) fn custody_kernel(path: &Path, title: &str) -> WorldKernel { - WorldKernel::create( - path.join("world.cc"), - creation(title), + pub(crate) fn custody_kernel(title: &str) -> WorldKernel { + WorldKernel::create(creation(title), &auth_principal(owner()), ) .expect("a created world") @@ -5779,8 +5582,7 @@ mod custody_tests { /// the conservation equation itself is falsified directly beside it. #[test] fn a_non_conserving_transfer_effect_does_not_apply() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = custody_kernel(directory.path(), "Forged"); + let mut kernel = custody_kernel("Forged"); let (_, custody, _) = custody_world(&mut kernel); let before = kernel.state.holdings.clone(); @@ -5840,8 +5642,7 @@ mod custody_tests { /// patch's own evidence list mints nothing and allocates no ID. #[test] fn an_admit_without_evidence_is_rejected() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = custody_kernel(directory.path(), "Unevidenced"); + let mut kernel = custody_kernel("Unevidenced"); let topology = admit_topology(&mut kernel); let speak = speak_entry(&kernel); let before = kernel.snapshot().unwrap(); @@ -5890,8 +5691,7 @@ mod custody_tests { #[test] fn a_transfer_moves_the_exact_quantity_and_nothing_else() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = custody_kernel(directory.path(), "Transfer"); + let mut kernel = custody_kernel("Transfer"); let (_, custody, active) = custody_world(&mut kernel); let entities = kernel.state.entities.clone(); let edges = kernel.state.edges.clone(); @@ -5920,8 +5720,7 @@ mod custody_tests { /// resource key and emptying a holder removes the holder key. #[test] fn consume_reduces_the_holding_and_emptying_removes_the_key() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = custody_kernel(directory.path(), "Consume"); + let mut kernel = custody_kernel("Consume"); let (_, custody, active) = custody_world(&mut kernel); let after_three = submit_play( @@ -5959,8 +5758,7 @@ mod custody_tests { #[test] fn a_transform_conserves_one_for_one() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = custody_kernel(directory.path(), "Transform"); + let mut kernel = custody_kernel("Transform"); let (_, custody, active) = custody_world(&mut kernel); submit_play( @@ -5982,8 +5780,7 @@ mod custody_tests { #[test] fn spending_more_than_held_is_rejected_with_insufficient_custody() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = custody_kernel(directory.path(), "Insufficient"); + let mut kernel = custody_kernel("Insufficient"); let (_, custody, _) = custody_world(&mut kernel); let too_much = Quantity(OPENING_BALANCE + 1); let attempts = [ @@ -6023,8 +5820,7 @@ mod custody_tests { /// zero entry anywhere in the snapshot. #[test] fn an_absent_holding_is_zero() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = custody_kernel(directory.path(), "Absent"); + let mut kernel = custody_kernel("Absent"); let (_, custody, active) = custody_world(&mut kernel); let mismatches = reject_play( @@ -6052,8 +5848,7 @@ mod custody_tests { #[test] fn a_zero_quantity_operation_is_rejected() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = custody_kernel(directory.path(), "Zero"); + let mut kernel = custody_kernel("Zero"); let topology = admit_topology(&mut kernel); let custody = admit_custody(&mut kernel, &topology); @@ -6101,8 +5896,7 @@ mod custody_tests { #[test] fn dependency_bind_and_release_round_trip() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = custody_kernel(directory.path(), "Dependency"); + let mut kernel = custody_kernel("Dependency"); let (_, custody, active) = custody_world(&mut kernel); let before = kernel.state.dependencies.clone(); @@ -6136,8 +5930,7 @@ mod custody_tests { /// already owns; a subject bound to itself is `SelfDependency`. #[test] fn a_duplicate_dependency_bind_is_rejected_as_no_effect() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = custody_kernel(directory.path(), "Duplicate"); + let mut kernel = custody_kernel("Duplicate"); let (_, custody, active) = custody_world(&mut kernel); let bind = ComponentOp::Bind { @@ -6180,8 +5973,7 @@ mod custody_tests { /// components; nothing rejects it and nothing fires from it. #[test] fn a_dependency_on_a_closed_route_is_representable_and_visible() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = custody_kernel(directory.path(), "Closed"); + let mut kernel = custody_kernel("Closed"); let (topology, custody, active) = custody_world(&mut kernel); assert!(!kernel.state.edges[&topology.shutter].is_open()); @@ -6211,8 +6003,7 @@ mod custody_tests { /// only its own: a counterparty's churn does not move it. #[test] fn scope_components_read_holdings_and_dependencies() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = custody_kernel(directory.path(), "ScopeCustody"); + let mut kernel = custody_kernel("ScopeCustody"); let topology = admit_topology(&mut kernel); let custody = admit_custody(&mut kernel, &topology); let scope = custody.holder; @@ -6250,8 +6041,7 @@ mod custody_tests { /// consumed - spent`, and no third resource moves. #[test] fn soul_a_mixed_patch_conserves_every_resource_it_touches() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = custody_kernel(directory.path(), "MixedLedger"); + let mut kernel = custody_kernel("MixedLedger"); let (_, custody, active) = custody_world(&mut kernel); // The opening balance was created by `Admit` alone: before is zero, @@ -6318,8 +6108,7 @@ mod custody_tests { /// records: the apply-side call is unreachable from the current closed set. #[test] fn soul_a_forged_sequence_dies_at_the_per_operation_check_not_the_ledger() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = custody_kernel(directory.path(), "ForgedSequence"); + let mut kernel = custody_kernel("ForgedSequence"); let (_, custody, _) = custody_world(&mut kernel); let before = kernel.state.holdings.clone(); @@ -6436,8 +6225,7 @@ mod custody_tests { /// whose sum exceeds `u64::MAX` mint nothing and allocate no ID. #[test] fn soul_a_holding_cannot_overflow_silently() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = custody_kernel(directory.path(), "Overflow"); + let mut kernel = custody_kernel("Overflow"); let topology = admit_topology(&mut kernel); let speak = speak_entry(&kernel); let before = kernel.snapshot().unwrap(); @@ -6490,8 +6278,7 @@ mod custody_tests { /// no unrelated subject's, whose act still commits at the later revision. #[test] fn soul_an_incoming_transfer_changes_only_the_counterpartys_scope() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = custody_kernel(directory.path(), "IncomingScope"); + let mut kernel = custody_kernel("IncomingScope"); let (topology, custody, active) = custody_world(&mut kernel); let receiver_before = scope_components(&kernel.state, custody.counterparty); let bystander_before = scope_components(&kernel.state, topology.walker); @@ -6541,12 +6328,9 @@ mod knowledge_tests { owner, reject_play, speech_world, spoken, submit_play, }; use super::*; - use std::path::Path; - fn speech_kernel(path: &Path, title: &str) -> (WorldKernel, Speech, WorldSnapshot) { - let mut kernel = WorldKernel::create( - path.join("world.cc"), - creation(title), + fn speech_kernel(title: &str) -> (WorldKernel, Speech, WorldSnapshot) { + let mut kernel = WorldKernel::create(creation(title), &auth_principal(owner()), ) .expect("a created world") @@ -6619,8 +6403,7 @@ mod knowledge_tests { /// accessible fact, and a rejected citation allocates nothing. #[test] fn knowledge_citing_an_inaccessible_fact_is_rejected() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, speech, active) = speech_kernel(directory.path(), "Inaccessible"); + let (mut kernel, speech, active) = speech_kernel("Inaccessible"); let before = kernel.state.clone(); assert_eq!( @@ -6677,10 +6460,7 @@ mod knowledge_tests { /// canon needs its receipt in the same patch, a claim needs a live asserter. #[test] fn a_canonical_fact_needs_evidence_and_a_claim_needs_an_asserter() { - let directory = tempfile::tempdir().unwrap(); - let mut draft = WorldKernel::create( - directory.path().join("world.cc"), - creation("Standing"), + let mut draft = WorldKernel::create(creation("Standing"), &auth_principal(owner()), ) .expect("a draft world") @@ -6754,8 +6534,7 @@ mod knowledge_tests { /// never evaluated. #[test] fn evidenced_knowledge_of_a_claim_is_rejected() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, speech, _) = speech_kernel(directory.path(), "Evidenced"); + let (mut kernel, speech, _) = speech_kernel("Evidenced"); utter(&mut kernel, speech.speaker, say( speech.proclaim, @@ -6804,8 +6583,7 @@ mod knowledge_tests { /// the exact room, and the utterance lands in `facts` and nowhere else. #[test] fn speak_fans_out_to_the_audience_and_not_beyond() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, speech, active) = speech_kernel(directory.path(), "FanOut"); + let (mut kernel, speech, active) = speech_kernel("FanOut"); utter(&mut kernel, speech.speaker, say( speech.whisper, @@ -6847,8 +6625,7 @@ mod knowledge_tests { /// subtree, through the same containment walk a jurisdiction uses. #[test] fn co_location_reach_is_the_exact_place_and_a_channel_place_is_the_subtree() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, speech, _) = speech_kernel(directory.path(), "Reach"); + let (mut kernel, speech, _) = speech_kernel("Reach"); utter(&mut kernel, speech.speaker, say( speech.proclaim, @@ -6901,8 +6678,7 @@ mod knowledge_tests { /// nothing. #[test] fn speaking_into_an_empty_room_commits_the_claim_and_lands_nothing() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, speech, _) = speech_kernel(directory.path(), "EmptyRoom"); + let (mut kernel, speech, _) = speech_kernel("EmptyRoom"); let knowledge_before = kernel.state.knowledge.clone(); utter(&mut kernel, speech.bystander, say( @@ -6953,8 +6729,7 @@ mod knowledge_tests { /// and still folds its arms only before the hall. #[test] fn a_display_is_seen_by_the_room_and_by_no_one_else() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, speech, active) = speech_kernel(directory.path(), "Display"); + let (mut kernel, speech, active) = speech_kernel("Display"); utter(&mut kernel, speech.speaker, show( speech.proclaim, @@ -7009,8 +6784,7 @@ mod knowledge_tests { /// and lands nothing, as speaking alone does. #[test] fn a_silent_display_addresses_the_room_through_the_speak_entry() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, speech, active) = speech_kernel(directory.path(), "Silent"); + let (mut kernel, speech, active) = speech_kernel("Silent"); let speak = affordance_named(&active, "speak"); utter(&mut kernel, speech.speaker, show(speak, Vec::new(), None, "I nod toward the stair."), @@ -7041,8 +6815,7 @@ mod knowledge_tests { /// fails the entry's own `NoAudience`. None of them mints anything. #[test] fn a_display_is_refused_when_empty_placeless_or_when_nothing_is_addressed() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, speech, active) = speech_kernel(directory.path(), "Refused"); + let (mut kernel, speech, active) = speech_kernel("Refused"); let speak = affordance_named(&active, "speak"); let mut padded = show(speak, Vec::new(), None, "placeholder"); padded.display = Some(serde_json::from_str::<Statement>("\" \"").unwrap()); @@ -7075,12 +6848,8 @@ mod knowledge_tests { /// the journal exactly, through the same path as speech. #[test] fn restart_replay_after_a_display_is_exact() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let (speech, world_id, expected) = { - let mut kernel = WorldKernel::create( - &path, - creation("ReplayDisplay"), + let (speech, exported, expected) = { + let mut kernel = WorldKernel::create(creation("ReplayDisplay"), &auth_principal(owner()), ) .expect("a created world") @@ -7095,9 +6864,9 @@ mod knowledge_tests { show(speak, Vec::new(), None, "I look away."), ) .expect("the silent act commits"); - (speech, kernel.state.world_id, kernel.state.clone()) + (speech, kernel.export().unwrap(), kernel.state.clone()) }; - let reopened = WorldKernel::open(&path, world_id).expect("the store replays"); + let reopened = WorldKernel::open(&exported).expect("the export replays"); assert_eq!(reopened.state, expected); assert!(reopened.state.knowledge[&speech.listener] .values() @@ -7121,8 +6890,7 @@ mod knowledge_tests { /// same invocation to exactly one named failure. #[test] fn a_channel_controller_may_speak_outside_its_own_reach() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, speech, active) = speech_kernel(directory.path(), "Controller"); + let (mut kernel, speech, active) = speech_kernel("Controller"); submit_play( &mut kernel, &active, @@ -7161,8 +6929,7 @@ mod knowledge_tests { /// audience receives the telling, not only the addressed subject. #[test] fn an_addressed_subject_outside_the_audience_names_itself() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, speech, active) = speech_kernel(directory.path(), "Addressing"); + let (mut kernel, speech, active) = speech_kernel("Addressing"); let whisper = || { say( speech.whisper, @@ -7197,8 +6964,7 @@ mod knowledge_tests { /// rather than storing a zero. #[test] fn knows_fails_below_its_confidence_and_forget_removes() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, speech, active) = speech_kernel(directory.path(), "Knows"); + let (mut kernel, speech, active) = speech_kernel("Knows"); let recant = || DecisionInvocation { affordance: speech.recant, bindings: vec![binding("fact", Target::Entity(speech.flood))], @@ -7263,8 +7029,7 @@ mod knowledge_tests { /// credence. #[test] fn a_telling_never_overwrites_a_holder() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, speech, active) = speech_kernel(directory.path(), "NoOverwrite"); + let (mut kernel, speech, active) = speech_kernel("NoOverwrite"); submit_play( &mut kernel, &active, @@ -7304,8 +7069,7 @@ mod knowledge_tests { /// channel's reach, and a speaker outside it is not speaking. #[test] fn communicating_from_outside_the_audience_is_rejected() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, speech, active) = speech_kernel(directory.path(), "OutsideAudience"); + let (mut kernel, speech, active) = speech_kernel("OutsideAudience"); assert_eq!( reject_play( &mut kernel, @@ -7338,8 +7102,7 @@ mod knowledge_tests { /// directly with the recorded world, command, handle, and discriminator. #[test] fn every_canonical_id_comes_from_one_of_two_sites() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, speech, active) = speech_kernel(directory.path(), "Allocation"); + let (mut kernel, speech, active) = speech_kernel("Allocation"); let world_id = kernel.state.world_id; let caller = play_caller(); let entities_before = kernel.state.entities.len(); @@ -7385,12 +7148,8 @@ mod knowledge_tests { /// state. #[test] fn restart_replay_after_speech_is_exact() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let (speech, world_id, expected) = { - let mut kernel = WorldKernel::create( - &path, - creation("ReplaySpeech"), + let (speech, exported, expected) = { + let mut kernel = WorldKernel::create(creation("ReplaySpeech"), &auth_principal(owner()), ) .expect("a created world") @@ -7422,11 +7181,11 @@ mod knowledge_tests { to: AudienceRef::Channel(Ref::Existing(speech.horn)), }]), ); - let world_id = kernel.state.world_id; - (speech, world_id, kernel.state.clone()) + let exported = kernel.export().unwrap(); + (speech, exported, kernel.state.clone()) }; - let reopened = WorldKernel::open(&path, world_id).expect("the store replays"); + let reopened = WorldKernel::open(&exported).expect("the export replays"); assert_eq!(reopened.state.facts, expected.facts); assert_eq!(reopened.state.channels, expected.channels); assert_eq!(reopened.state.knowledge, expected.knowledge); @@ -7440,8 +7199,7 @@ mod knowledge_tests { /// recipients. #[test] fn a_forged_claim_or_forged_recipient_does_not_apply() { - let directory = tempfile::tempdir().unwrap(); - let (kernel, speech, _) = speech_kernel(directory.path(), "Forgery"); + let (kernel, speech, _) = speech_kernel("Forgery"); let command_id = CommandId::issue(); let caller = play_caller(); let invocation = say( @@ -7516,8 +7274,7 @@ mod knowledge_tests { /// alone, and a reach change moves only the controller's scope. #[test] fn a_telling_moves_only_the_listeners_scope() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, speech, _) = speech_kernel(directory.path(), "ScopeMove"); + let (mut kernel, speech, _) = speech_kernel("ScopeMove"); let digest = |kernel: &WorldKernel, subject: SubjectId| { scope_components(&kernel.state, subject) }; @@ -7556,10 +7313,7 @@ mod knowledge_tests { /// and two is unchoosable. Each rejection allocates no `AffordanceId`. #[test] fn a_speech_carrying_entry_must_declare_exactly_one_audience() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = WorldKernel::create( - directory.path().join("world.cc"), - creation("SpeechAudience"), + let mut kernel = WorldKernel::create(creation("SpeechAudience"), &auth_principal(owner()), ) .expect("a draft world") @@ -7615,11 +7369,8 @@ mod knowledge_tests { /// canonical fact and one that plainly negates it commit identically. #[test] fn the_kernel_never_compares_two_statements() { - let directory = tempfile::tempdir().unwrap(); let run = |name: &str, text: &str| { - let room = directory.path().join(name); - std::fs::create_dir_all(&room).unwrap(); - let (mut kernel, speech, _) = speech_kernel(&room, name); + let (mut kernel, speech, _) = speech_kernel(name); let receipt = utter(&mut kernel, speech.speaker, say( speech.whisper, @@ -7664,12 +7415,9 @@ mod soul_knowledge_tests { owner, speech_world, submit_play, }; use super::*; - use std::path::Path; - fn speech_kernel(path: &Path, title: &str) -> (WorldKernel, Speech, WorldSnapshot) { - let mut kernel = WorldKernel::create( - path.join("world.cc"), - creation(title), + fn speech_kernel(title: &str) -> (WorldKernel, Speech, WorldSnapshot) { + let mut kernel = WorldKernel::create(creation(title), &auth_principal(owner()), ) .expect("a created world") @@ -7733,8 +7481,7 @@ mod soul_knowledge_tests { /// its own or another subject's. #[test] fn soul_a_channel_controller_hears_what_it_is_out_of_reach_of() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, speech, active) = speech_kernel(directory.path(), "ControllerHears"); + let (mut kernel, speech, active) = speech_kernel("ControllerHears"); // The horn now reaches exactly one subject. The speaker controls it and // is not in that set. submit_play( @@ -7808,8 +7555,7 @@ mod soul_knowledge_tests { /// replay to be caught later. #[test] fn soul_a_refused_utterance_dies_at_the_gate_and_allocates_nothing() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, speech, active) = speech_kernel(directory.path(), "GateNotReplay"); + let (mut kernel, speech, active) = speech_kernel("GateNotReplay"); let speak = affordance_named(&active, "speak"); let before = kernel.state.clone(); @@ -7867,8 +7613,7 @@ mod soul_knowledge_tests { /// by `apply_effect` itself, so replay is never the first reader to notice. #[test] fn soul_a_forged_wider_audience_does_not_apply() { - let directory = tempfile::tempdir().unwrap(); - let (kernel, speech, _) = speech_kernel(directory.path(), "WiderAudience"); + let (kernel, speech, _) = speech_kernel("WiderAudience"); let command_id = CommandId::issue(); let caller = play_caller(); let invocation = say( @@ -7940,8 +7685,7 @@ mod soul_knowledge_tests { /// by a speaker who is in the room applies. #[test] fn a_telling_by_a_speaker_outside_its_audience_does_not_apply() { - let directory = tempfile::tempdir().unwrap(); - let (kernel, speech, _) = speech_kernel(directory.path(), "OutsideAudience"); + let (kernel, speech, _) = speech_kernel("OutsideAudience"); let resolves_to = kernel.state.revision + 1; let mut candidate = kernel.state.clone(); @@ -7979,8 +7723,7 @@ mod soul_knowledge_tests { /// survives an utterance nobody heard. #[test] fn soul_speech_that_lands_nothing_moves_no_digest_including_the_speakers() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, speech, active) = speech_kernel(directory.path(), "NoDigestMove"); + let (mut kernel, speech, active) = speech_kernel("NoDigestMove"); let speak = affordance_named(&active, "speak"); let everyone = [ speech.speaker, @@ -8020,8 +7763,7 @@ mod soul_knowledge_tests { /// what the subject ends up holding. #[test] fn soul_a_same_patch_telling_then_forget_fails_closed_only() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, speech, active) = speech_kernel(directory.path(), "SamePatchOrder"); + let (mut kernel, speech, active) = speech_kernel("SamePatchOrder"); let tell = ComponentOp::Communicate { speaker: Ref::Existing(speech.speaker), fact: Ref::Existing(speech.flood), @@ -8086,9 +7828,7 @@ mod soul_knowledge_tests { /// claim is a valid shape and its store reopens. #[test] fn an_orphan_claim_is_a_valid_shape_and_reopens() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let (mut kernel, speech, active) = speech_kernel(directory.path(), "OrphanClaim"); + let (mut kernel, speech, active) = speech_kernel("OrphanClaim"); // The Draft-declared fact is an orphan by construction: no event names // it. Reopening runs the shape verifier over the replayed state. assert!(kernel.state.facts.contains_key(&speech.flood)); @@ -8099,7 +7839,6 @@ mod soul_knowledge_tests { .iter() .all(|event| event.speech.is_none()) ); - let world_id = kernel.state.world_id; let before = kernel.state.clone(); let receipt = kernel @@ -8128,8 +7867,9 @@ mod soul_knowledge_tests { assert!(receipt.resulting_revision > 0); assert_eq!(kernel.state.facts.len(), before.facts.len() + 1); let facts = kernel.state.facts.clone(); + let exported = kernel.export().unwrap(); drop(kernel); - let replayed = WorldKernel::open(&path, world_id).expect("the orphan store is healthy"); + let replayed = WorldKernel::open(&exported).expect("the orphan store is healthy"); assert_eq!(replayed.state.facts, facts); } @@ -8139,10 +7879,8 @@ mod soul_knowledge_tests { /// from the journal, and reopening again reproduces the same state. #[test] fn soul_replay_is_exact_across_every_new_arm() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let (world_id, expected) = { - let (mut kernel, speech, _) = speech_kernel(directory.path(), "ReplayArms"); + let (exported, expected) = { + let (mut kernel, speech, _) = speech_kernel("ReplayArms"); utter(&mut kernel, speech.speaker, say( speech.proclaim, @@ -8188,11 +7926,11 @@ mod soul_knowledge_tests { ); assert!(!kernel.state.knowledge.is_empty()); assert!(!kernel.state.facts.is_empty()); - (kernel.state.world_id, kernel.state.clone()) + (kernel.export().unwrap(), kernel.state.clone()) }; for _ in 0..2 { - let replayed = WorldKernel::open(&path, world_id).expect("the store replays"); + let replayed = WorldKernel::open(&exported).expect("the export replays"); assert_eq!(replayed.state.facts, expected.facts); assert_eq!(replayed.state.channels, expected.channels); assert_eq!(replayed.state.knowledge, expected.knowledge); @@ -8212,8 +7950,7 @@ mod soul_knowledge_tests { /// a subject-facing surface. #[test] fn soul_the_utterance_is_stored_in_facts_and_in_the_committed_effect() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, speech, active) = speech_kernel(directory.path(), "OneHome"); + let (mut kernel, speech, active) = speech_kernel("OneHome"); let speak = affordance_named(&active, "speak"); let text = "A statement that appears nowhere else."; utter(&mut kernel, speech.speaker, @@ -8329,10 +8066,8 @@ mod witness_tests { } } - fn nesting_kernel(path: &Path, title: &str) -> (WorldKernel, Nesting, WorldSnapshot) { - let mut kernel = WorldKernel::create( - path.join("world.cc"), - creation(title), + fn nesting_kernel(title: &str) -> (WorldKernel, Nesting, WorldSnapshot) { + let mut kernel = WorldKernel::create(creation(title), &auth_principal(owner()), ) .expect("a created world") @@ -8484,8 +8219,7 @@ mod witness_tests { /// beside it, and a wider place reaches the wider set. #[test] fn a_witness_reaches_every_subject_under_the_place_and_no_other() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, world, active) = nesting_kernel(directory.path(), "Reach"); + let (mut kernel, world, active) = nesting_kernel("Reach"); submit_play( &mut kernel, &active, @@ -8545,8 +8279,7 @@ mod witness_tests { /// mind by repeating itself. #[test] fn a_witness_never_overwrites_a_holder() { - let directory = tempfile::tempdir().unwrap(); - let (kernel, world, _) = nesting_kernel(directory.path(), "Holder"); + let (kernel, world, _) = nesting_kernel("Holder"); // `Told` has exactly one writer, so the holder's row is planted at the // layer that can hold one and the witness is applied beside it. let held = Knowledge { @@ -8592,8 +8325,7 @@ mod witness_tests { /// every stander already holds the fact. #[test] fn a_witness_over_nobody_is_refused_at_resolve_and_at_apply() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, world, active) = nesting_kernel(directory.path(), "Nobody"); + let (mut kernel, world, active) = nesting_kernel("Nobody"); let forged = |place: EntityId, state: &WorldState| { let resolves_to = state.revision + 1; let mut state = state.clone(); @@ -8682,8 +8414,7 @@ mod witness_tests { /// layer and the apply layer agree on both. #[test] fn a_mid_patch_relocation_into_the_subtree_counts() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, world, active) = nesting_kernel(directory.path(), "Relocation"); + let (mut kernel, world, active) = nesting_kernel("Relocation"); // The village's own standers already hold it, so the relocated coaster // is the only candidate recipient left. submit_play( @@ -8752,8 +8483,7 @@ mod witness_tests { /// moves exactly the components of the subjects that learned something. #[test] fn a_witness_moves_every_recipients_scope_components_and_nobody_elses() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, world, active) = nesting_kernel(directory.path(), "Digest"); + let (mut kernel, world, active) = nesting_kernel("Digest"); submit_play( &mut kernel, &active, @@ -8791,8 +8521,7 @@ mod witness_tests { /// place position binds a subject is refused before it is ever declared. #[test] fn a_witness_affordance_lowers_with_no_speaker() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, world, active) = nesting_kernel(directory.path(), "Affordance"); + let (mut kernel, world, active) = nesting_kernel("Affordance"); let beacon = *active .subjects .iter() @@ -8884,8 +8613,7 @@ mod witness_tests { /// wrote pass the shape check with no clause of their own. #[test] fn a_world_with_a_witness_replays() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, world, active) = nesting_kernel(directory.path(), "Replay"); + let (mut kernel, world, active) = nesting_kernel("Replay"); submit_play( &mut kernel, &active, @@ -8896,11 +8624,11 @@ mod witness_tests { )]), ); assert!(journal::verify_state_shape(&kernel.state).is_ok()); - let world_id = kernel.state.world_id; let committed = kernel.state.clone(); + let exported = kernel.export().unwrap(); drop(kernel); let reopened = - WorldKernel::open(directory.path().join("world.cc"), world_id).expect("it replays"); + WorldKernel::open(&exported).expect("it replays"); assert_eq!(reopened.state, committed); assert_eq!( knows(&reopened, world.villager, world.asteroid), @@ -8916,8 +8644,6 @@ mod witness_tests { /// state it was written into. #[test] fn a_genesis_seeded_knowledge_row_is_acquired_at_revision_zero() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); let mut creation = creation("PAf49Genesis"); creation.patch.declarations.push(Declaration::Fact(FactDeclaration { handle: DraftHandle::new("founding"), @@ -8933,7 +8659,7 @@ mod witness_tests { source: AuthoredSource::Witnessed, confidence: Confidence::Certain, }); - let (kernel, _) = WorldKernel::create(&path, creation, &auth_principal(owner())).unwrap(); + let (kernel, _) = WorldKernel::create(creation, &auth_principal(owner())).unwrap(); assert_eq!(kernel.state.revision, 0); let human = *kernel .state @@ -8961,8 +8687,7 @@ mod witness_tests { /// resolves to, one past the state it was applied against. #[test] fn a_later_commits_knowledge_row_is_acquired_at_that_commits_revision() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, world, active) = nesting_kernel(directory.path(), "PAf49Later"); + let (mut kernel, world, active) = nesting_kernel("PAf49Later"); submit_play( &mut kernel, &active, @@ -8986,8 +8711,7 @@ mod witness_tests { /// replay silently. #[test] fn a_shape_check_refuses_a_knowledge_row_forged_ahead_of_the_world_revision() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, world, active) = nesting_kernel(directory.path(), "PAf49Shape"); + let (mut kernel, world, active) = nesting_kernel("PAf49Shape"); submit_play( &mut kernel, &active, @@ -9016,8 +8740,7 @@ mod witness_tests { /// it. #[test] fn soul_a_place_reach_fan_out_and_a_witness_select_the_same_subjects() { - let directory = tempfile::tempdir().unwrap(); - let (kernel, world, _) = nesting_kernel(directory.path(), "One owner"); + let (kernel, world, _) = nesting_kernel("One owner"); let mut state = kernel.state.clone(); // One holder, so the already-holds half of the selection is exercised // and not merely the subtree half. @@ -9069,8 +8792,7 @@ mod witness_tests { /// world's widest. #[test] fn soul_under_place_covers_itself_and_below_and_never_the_placeless() { - let directory = tempfile::tempdir().unwrap(); - let (kernel, world, _) = nesting_kernel(directory.path(), "Nesting"); + let (kernel, world, _) = nesting_kernel("Nesting"); let under = |root: EntityId| under_place(&kernel.state, root); // The village holds its two standers and nobody else. assert_eq!( @@ -9156,8 +8878,7 @@ mod witness_tests { /// by both. #[test] fn soul_a_subject_declared_and_placed_in_one_patch_is_a_recipient_at_both_layers() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, world, active) = nesting_kernel(directory.path(), "Draft stander"); + let (mut kernel, world, active) = nesting_kernel("Draft stander"); submit_play( &mut kernel, &active, @@ -9268,8 +8989,7 @@ mod witness_tests { /// reaching nobody. #[test] fn soul_a_forget_before_a_witness_agrees_at_both_layers() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, world, active) = nesting_kernel(directory.path(), "Forget first"); + let (mut kernel, world, active) = nesting_kernel("Forget first"); submit_play( &mut kernel, &active, @@ -9328,8 +9048,7 @@ mod witness_tests { /// row, so no attributable line can be built from it. #[test] fn soul_a_witness_moves_only_knows_and_writes_no_spoken_row() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, world, active) = nesting_kernel(directory.path(), "Anonymous"); + let (mut kernel, world, active) = nesting_kernel("Anonymous"); let before = scope_components(&kernel.state, world.villager); submit_play( &mut kernel, @@ -9377,7 +9096,6 @@ mod clock_tests { speech_world, submit_play, }; use super::*; - use std::path::Path; /// The canonical IDs of the clock fixture: a hall containing a yard, a /// dead end reached by exactly one route, three subjects, a resource, and @@ -9403,10 +9121,8 @@ mod clock_tests { TickMinutes::new(value).expect("a valid span") } - fn clock_kernel(path: &Path, title: &str) -> (WorldKernel, Clockwork, WorldSnapshot) { - let mut kernel = WorldKernel::create( - path.join("world.cc"), - creation(title), + fn clock_kernel(title: &str) -> (WorldKernel, Clockwork, WorldSnapshot) { + let mut kernel = WorldKernel::create(creation(title), &auth_principal(owner()), ) .expect("a created world") @@ -9713,8 +9429,7 @@ mod clock_tests { /// its subject, and the pressure grows with the next tick. #[test] fn a_defaulted_commitment_advances_pressure_one_step_per_tick() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Default"); + let (mut kernel, clockwork, _) = clock_kernel("Default"); let sourced = PressureSource::Commitment { subject: clockwork.farmer, key: clockwork.obligation, @@ -9736,8 +9451,7 @@ mod clock_tests { /// and a blocked one neither rolls nor presses. #[test] fn a_due_routine_auto_fulfils_and_a_blocked_one_does_not() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "Routine"); + let (mut kernel, clockwork, active) = clock_kernel("Routine"); let holdings = kernel.state.holdings.clone(); let positions = kernel.state.positions.clone(); let edges = kernel.state.edges.clone(); @@ -9804,8 +9518,7 @@ mod clock_tests { /// canonical change. #[test] fn a_tick_with_nothing_due_moves_only_the_clock() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, _, _) = clock_kernel(directory.path(), "Quiet"); + let (mut kernel, _, _) = clock_kernel("Quiet"); let before = kernel.state.clone(); tick(&mut kernel, 1).expect("the tick commits"); @@ -9826,8 +9539,7 @@ mod clock_tests { /// does. #[test] fn an_unavailable_dependency_presses_its_depender() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Dependency"); + let (mut kernel, clockwork, _) = clock_kernel("Dependency"); let sourced = PressureSource::Dependency(DependencyTarget::Route(clockwork.gate)); tick(&mut kernel, 1).expect("the tick commits"); @@ -9876,8 +9588,7 @@ mod clock_tests { /// The clock moves through exactly one command body. #[test] fn time_advances_only_through_advance_time() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "OnlyTick"); + let (mut kernel, clockwork, _) = clock_kernel("OnlyTick"); tick(&mut kernel, 5).expect("the tick commits"); let now = kernel.state.now; @@ -9904,10 +9615,7 @@ mod clock_tests { /// Who may tick, when, and how far. #[test] fn advance_time_negatives() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = WorldKernel::create( - directory.path().join("world.cc"), - creation("Negatives"), + let mut kernel = WorldKernel::create(creation("Negatives"), &auth_principal(owner()), ) .expect("a created world") @@ -9971,8 +9679,7 @@ mod clock_tests { /// magnitude, or clock reading is one comparison. #[test] fn a_forged_motion_does_not_apply() { - let directory = tempfile::tempdir().unwrap(); - let (kernel, clockwork, _) = clock_kernel(directory.path(), "Forged"); + let (kernel, clockwork, _) = clock_kernel("Forged"); let to = FictionalMinutes(120); let honest = clock::derive_motion(&kernel.state, to); assert!(!honest.fulfilled.is_empty() || !honest.pressed.is_empty()); @@ -10059,10 +9766,7 @@ mod clock_tests { /// Replay across a tick is exact, and every envelope is idempotent. #[test] fn restart_replay_across_a_tick_is_exact() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Replay"); - let world_id = kernel.state.world_id; + let (mut kernel, clockwork, _) = clock_kernel("Replay"); exercise( &mut kernel, @@ -10100,8 +9804,9 @@ mod clock_tests { let before = kernel.state.clone(); let before_snapshot = kernel.snapshot().unwrap(); + let exported = kernel.export().unwrap(); drop(kernel); - let mut replayed = WorldKernel::open(&path, world_id).expect("the store replays"); + let mut replayed = WorldKernel::open(&exported).expect("the export replays"); assert_eq!(replayed.state, before); assert_eq!(replayed.snapshot().unwrap(), before_snapshot); assert!(matches!( @@ -10113,8 +9818,7 @@ mod clock_tests { /// Every commitment shape check, in one complete sorted set. #[test] fn commitment_declaration_negatives() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "Shapes"); + let (mut kernel, clockwork, active) = clock_kernel("Shapes"); let before = kernel.state.clone(); let create = |kind: CommitmentKind, counterparty: Option<SubjectId>, @@ -10243,8 +9947,7 @@ mod clock_tests { /// treasury and the reeve did not. #[test] fn committed_reads_the_actors_own_commitments() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Committed"); + let (mut kernel, clockwork, _) = clock_kernel("Committed"); // The reeve promised the treasury nothing. let error = exercise( @@ -10281,8 +9984,7 @@ mod clock_tests { /// it is refused and nothing commits. #[test] fn a_discharged_commitment_refuses_the_act_that_needs_it() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "DischargeThenAct"); + let (mut kernel, clockwork, _) = clock_kernel("DischargeThenAct"); let snapshot = kernel.snapshot().unwrap(); submit_play( &mut kernel, @@ -10317,8 +10019,7 @@ mod clock_tests { /// half while the kind half holds. #[test] fn committed_requires_the_named_counterparty() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "CommittedCounterparty"); + let (mut kernel, clockwork, _) = clock_kernel("CommittedCounterparty"); let error = exercise( &mut kernel, clockwork.farmer, @@ -10338,8 +10039,7 @@ mod clock_tests { /// half fails. The farmer's own obligation to the same treasury still passes. #[test] fn committed_requires_the_named_kind() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "CommittedKind"); + let (mut kernel, clockwork, _) = clock_kernel("CommittedKind"); let snapshot = kernel.snapshot().unwrap(); submit_play( &mut kernel, @@ -10388,8 +10088,7 @@ mod clock_tests { /// that fulfils a routine moves exactly that subject's. #[test] fn a_pressure_tick_moves_no_scope_components_and_a_routine_tick_moves_one() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Digests"); + let (mut kernel, clockwork, _) = clock_kernel("Digests"); let digests = |kernel: &WorldKernel| -> BTreeMap<SubjectId, ScopeComponents> { kernel .state @@ -10446,8 +10145,7 @@ mod clock_tests { /// and zero is spelled by absence at both ends. #[test] fn soul_pressure_saturates_and_never_underflows() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Saturate"); + let (mut kernel, clockwork, _) = clock_kernel("Saturate"); let sourced = PressureSource::Commitment { subject: clockwork.farmer, key: clockwork.obligation, @@ -10513,8 +10211,7 @@ mod clock_tests { /// the clock and not one subject's components. #[test] fn soul_a_clock_only_tick_moves_no_scope_components() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, _, _) = clock_kernel(directory.path(), "ClockOnly"); + let (mut kernel, _, _) = clock_kernel("ClockOnly"); let digests = |kernel: &WorldKernel| -> BTreeMap<SubjectId, ScopeComponents> { kernel .state @@ -10540,8 +10237,6 @@ mod clock_tests { /// fact or one operation fails here. #[test] fn genesis_may_not_rule_or_mint() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); let mut input = creation("RulesAndMints"); for handle in ["first-rule", "second-rule"] { input @@ -10565,7 +10260,7 @@ mod clock_tests { qty: Quantity(4), }); } - let Err(error) = WorldKernel::create(&path, input, &auth_principal(owner())) else { + let Err(error) = WorldKernel::create(input, &auth_principal(owner())) else { panic!("a genesis patch that rules and mints was admitted"); }; let KernelError::PatchRejected(set) = error else { @@ -10581,7 +10276,6 @@ mod clock_tests { offender(patch::Site::Operation(1)), ] ); - assert!(!path.exists(), "a refused genesis wrote a world file"); } /// `prepare_creation` and `WorldState::genesis` both forbid rulings at @@ -10589,8 +10283,6 @@ mod clock_tests { /// a world is ever written. #[test] fn a_genesis_patch_carrying_a_ruled_fact_is_refused() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); let mut input = creation("RuledGenesis"); input .patch @@ -10601,7 +10293,7 @@ mod clock_tests { statement: Statement::new("Stated by the table.").unwrap(), standing: FactStandingRef::Ruled, })); - let Err(error) = WorldKernel::create(&path, input, &auth_principal(owner())) else { + let Err(error) = WorldKernel::create(input, &auth_principal(owner())) else { panic!("a genesis patch carrying a Ruled fact was admitted"); }; assert!( @@ -10611,15 +10303,12 @@ mod clock_tests { })), "{error:?}" ); - assert!(!path.exists(), "a refused genesis wrote a world file"); } /// The `Mint` half: a creation patch that carries a `Mint` is refused the /// same way. #[test] fn a_genesis_patch_carrying_a_mint_is_refused() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); let mut input = creation("MintGenesis"); input .patch @@ -10630,7 +10319,7 @@ mod clock_tests { resource: Ref::Draft(DraftHandle::new("loot")), qty: Quantity(4), }); - let Err(error) = WorldKernel::create(&path, input, &auth_principal(owner())) else { + let Err(error) = WorldKernel::create(input, &auth_principal(owner())) else { panic!("a genesis patch carrying a Mint was admitted"); }; assert!( @@ -10640,7 +10329,6 @@ mod clock_tests { })), "{error:?}" ); - assert!(!path.exists(), "a refused genesis wrote a world file"); } /// `WorldState::genesis` re-decides `forbid_rulings_at_genesis` on its own @@ -10706,8 +10394,7 @@ mod clock_tests { /// Soul falsification: a discharge names one subject's own live key. #[test] fn soul_discharging_a_foreign_or_already_discharged_commitment_is_refused() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Discharge"); + let (mut kernel, clockwork, _) = clock_kernel("Discharge"); // The farmer's obligation, claimed by the reeve. let snapshot = kernel.snapshot().unwrap(); @@ -10751,8 +10438,7 @@ mod clock_tests { /// whatever the span, and a non-routine cannot carry checks. #[test] fn soul_a_routine_re_arms_exactly_one_period_per_command() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Rearm"); + let (mut kernel, clockwork, _) = clock_kernel("Rearm"); let period = u64::from( kernel.state.commitments[&clockwork.farmer][&clockwork.routine] .period @@ -10801,8 +10487,7 @@ mod clock_tests { /// failing dependency at once. #[test] fn soul_derive_motion_is_pure_and_the_tick_replays_exactly() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Pure"); + let (mut kernel, clockwork, _) = clock_kernel("Pure"); let snapshot = kernel.snapshot().unwrap(); submit_play( &mut kernel, @@ -10888,8 +10573,7 @@ mod clock_tests { /// it because no partition holds one. #[test] fn mismatch_never_appears_in_a_world_commit() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Separation"); + let (mut kernel, clockwork, _) = clock_kernel("Separation"); submit_as( &mut kernel, play_caller(), @@ -10942,8 +10626,7 @@ mod clock_tests { /// Active with no answer. #[test] fn the_play_authority_declares_in_active_without_an_answer() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PlayDeclares"); + let (mut kernel, clockwork, _) = clock_kernel("PlayDeclares"); let receipt = submit_as( &mut kernel, play_caller(), @@ -10960,8 +10643,7 @@ mod clock_tests { /// a confined author cannot do. #[test] fn the_play_authority_is_unconfined() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PlayUnconfined"); + let (mut kernel, clockwork, _) = clock_kernel("PlayUnconfined"); submit_as( &mut kernel, play_caller(), @@ -10975,8 +10657,7 @@ mod clock_tests { /// Invariant 5: the play authority advances time, the clock's precedent. #[test] fn the_play_authority_advances_time() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, _clockwork, active) = clock_kernel(directory.path(), "PlayClock"); + let (mut kernel, _clockwork, active) = clock_kernel("PlayClock"); let receipt = submit_as( &mut kernel, play_caller(), @@ -10992,8 +10673,7 @@ mod clock_tests { /// P3.4: a ruled fact is world truth to every subject that knows it. #[test] fn the_play_authority_rules_a_fact_and_a_witness_knows_it_as_canon() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PlayRules"); + let (mut kernel, clockwork, _) = clock_kernel("PlayRules"); let mut patch = ruled_fact_patch("verdict"); patch.operations.push(ComponentOp::AcquireKnowledge { subject: Ref::Existing(clockwork.reeve), @@ -11036,10 +10716,8 @@ mod clock_tests { /// P3.5: minted quantity balances the ledger, and replay reproduces it. #[test] fn the_play_authority_mints_and_the_ledger_balances() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let (world_id, reeve, grain) = { - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PlayMints"); + let (exported, reeve, grain) = { + let (mut kernel, clockwork, _) = clock_kernel("PlayMints"); let grain = resource_named(&kernel, "Winter Grain"); let before = held(&kernel.state, clockwork.reeve, grain); assert_eq!(before, 0); @@ -11061,9 +10739,9 @@ mod clock_tests { .expect("the play authority mints"); let after = held(&kernel.state, clockwork.reeve, grain); assert_eq!(before + 7, after); - (kernel.state.world_id, clockwork.reeve, grain) + (kernel.export().unwrap(), clockwork.reeve, grain) }; - let replayed = WorldKernel::open(&path, world_id).expect("the minted store replays"); + let replayed = WorldKernel::open(&exported).expect("the minted export replays"); assert_eq!(held(&replayed.state, reeve, grain), 7); } @@ -11072,8 +10750,7 @@ mod clock_tests { /// such an assertion. #[test] fn a_ruled_fact_cannot_be_known_evidenced() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PlayEvidenced"); + let (mut kernel, clockwork, _) = clock_kernel("PlayEvidenced"); let mut patch = ruled_fact_patch("verdict"); patch.operations.push(ComponentOp::AcquireKnowledge { subject: Ref::Existing(clockwork.reeve), @@ -11101,8 +10778,7 @@ mod clock_tests { /// receipts, so its `Admit` is refused without one. #[test] fn the_evidence_gate_holds_for_play() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PlayEvidenceGate"); + let (mut kernel, clockwork, _) = clock_kernel("PlayEvidenceGate"); let grain = resource_named(&kernel, "Winter Grain"); // Without a receipt: `Play`'s `Admit` is refused exactly as anyone's. @@ -11154,10 +10830,8 @@ mod clock_tests { /// reproduces both across the digest. #[test] fn a_journal_holding_a_ruled_fact_and_a_mint_replays() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let (world_id, expected) = { - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PlayReplay"); + let (exported, expected) = { + let (mut kernel, clockwork, _) = clock_kernel("PlayReplay"); let grain = resource_named(&kernel, "Winter Grain"); let mut patch = ruled_fact_patch("verdict"); patch.operations.push(ComponentOp::Mint { @@ -11173,13 +10847,14 @@ mod clock_tests { }, ) .expect("the play authority rules and mints in one patch"); - (kernel.state.world_id, kernel.snapshot().unwrap()) + (kernel.export().unwrap(), kernel.snapshot().unwrap()) }; - let replayed = WorldKernel::open(&path, world_id).expect("the store replays"); + let replayed = WorldKernel::open(&exported).expect("the export replays"); assert_eq!(replayed.snapshot().unwrap(), expected); + let exported = replayed.export().unwrap(); drop(replayed); let replayed_again = - WorldKernel::open(&path, world_id).expect("the store replays a second time"); + WorldKernel::open(&exported).expect("the export replays a second time"); assert_eq!(replayed_again.snapshot().unwrap(), expected); } @@ -11210,10 +10885,8 @@ mod clock_tests { /// grants and `retired` both survive the round trip. #[test] fn a_retired_subject_holds_no_grants_across_a_replay() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let (world_id, reeve) = { - let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "RetireReplay"); + let (exported, reeve) = { + let (mut kernel, clockwork, active) = clock_kernel("RetireReplay"); assert!( !active .subjects @@ -11225,9 +10898,9 @@ mod clock_tests { "the reeve holds grants before retirement" ); play_retires(&mut kernel, clockwork.reeve).expect("play retires the reeve"); - (kernel.state.world_id, clockwork.reeve) + (kernel.export().unwrap(), clockwork.reeve) }; - let replayed = WorldKernel::open(&path, world_id).expect("the store replays"); + let replayed = WorldKernel::open(&exported).expect("the export replays"); let snapshot = replayed.snapshot().unwrap(); let subject = snapshot .subjects @@ -11242,8 +10915,7 @@ mod clock_tests { /// removed its grants. #[test] fn a_retired_subject_cannot_act() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RetireCannotAct"); + let (mut kernel, clockwork, _) = clock_kernel("RetireCannotAct"); play_retires(&mut kernel, clockwork.reeve).expect("play retires the reeve"); let error = exercise( &mut kernel, @@ -11260,8 +10932,7 @@ mod clock_tests { /// does. #[test] fn a_retired_subject_hears_nothing() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RetireHearsNothing"); + let (mut kernel, clockwork, _) = clock_kernel("RetireHearsNothing"); play_retires(&mut kernel, clockwork.reeve).expect("play retires the reeve"); let mut patch = ruled_fact_patch("news"); patch.operations.push(ComponentOp::Witness { @@ -11296,8 +10967,7 @@ mod clock_tests { /// retirement untouched. #[test] fn a_retired_subject_keeps_its_history() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RetireKeepsHistory"); + let (mut kernel, clockwork, _) = clock_kernel("RetireKeepsHistory"); let before_holdings = kernel.state.holdings.get(&clockwork.farmer).cloned(); let before_commitments = kernel.state.commitments.get(&clockwork.farmer).cloned(); assert!(before_holdings.is_some()); @@ -11317,8 +10987,7 @@ mod clock_tests { /// P4.1: retiring twice is `NoOperationEffect`, not a second retirement. #[test] fn retiring_twice_is_no_effect() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RetireTwice"); + let (mut kernel, clockwork, _) = clock_kernel("RetireTwice"); play_retires(&mut kernel, clockwork.reeve).expect("the first retirement commits"); let error = play_retires(&mut kernel, clockwork.reeve).unwrap_err(); assert!( @@ -11358,10 +11027,7 @@ mod clock_tests { /// verb the same way any owner-authored `GrantAffordance` does. #[test] fn the_seed_grants_the_player_a_verb_in_draft() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = WorldKernel::create( - directory.path().join("world.cc"), - creation("SeedGrantsDraft"), + let mut kernel = WorldKernel::create(creation("SeedGrantsDraft"), &auth_principal(owner()), ) .expect("a created world") @@ -11405,8 +11071,7 @@ mod clock_tests { /// P5.1: Play grants and revokes a verb in Active. #[test] fn the_play_authority_grants_and_revokes_in_active() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PlayGrantRevoke"); + let (mut kernel, clockwork, _) = clock_kernel("PlayGrantRevoke"); submit_as( &mut kernel, play_caller(), @@ -11473,14 +11138,12 @@ mod clock_tests { /// PA.f31: `verify_state_shape` no longer judges a `DecisionEvent` against /// the subject's *present* controller identity. Retiring a subject that /// has acted commits, and the history survives a full reopen-and-replay - /// (`recover` -> `verify_history` -> `verify_state_shape` for every + /// (`open` -> `verify_history` -> `verify_state_shape` for every /// commit, per the caller census in the report). #[test] fn retiring_a_subject_that_acted_survives_reopen_and_replay() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let world_id = { - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf31RetireActed"); + let exported = { + let (mut kernel, clockwork, _) = clock_kernel("PAf31RetireActed"); exercise( &mut kernel, clockwork.reeve, @@ -11490,9 +11153,9 @@ mod clock_tests { .expect("the threat commits"); play_retires(&mut kernel, clockwork.reeve) .expect("a subject with history can be retired"); - kernel.state.world_id + kernel.export().unwrap() }; - let reopened = WorldKernel::open(&path, world_id).expect("the store replays"); + let reopened = WorldKernel::open(&exported).expect("the export replays"); let retired = reopened .snapshot() .unwrap() @@ -11510,10 +11173,8 @@ mod clock_tests { /// against the present-day grant set. #[test] fn revoking_a_used_verb_survives_reopen_and_replay() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let world_id = { - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf31RevokeUsed"); + let exported = { + let (mut kernel, clockwork, _) = clock_kernel("PAf31RevokeUsed"); exercise( &mut kernel, clockwork.reeve, @@ -11530,9 +11191,9 @@ mod clock_tests { affordance: Ref::Existing(clockwork.threaten), }]), ); - kernel.state.world_id + kernel.export().unwrap() }; - let reopened = WorldKernel::open(&path, world_id).expect("the store replays"); + let reopened = WorldKernel::open(&exported).expect("the export replays"); assert_eq!(reopened.state.events.len(), 1); } @@ -11543,16 +11204,14 @@ mod clock_tests { /// controller roster in Active. #[test] fn retiring_the_human_in_active_survives_reopen_and_replay() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let (world_id, human) = { - let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "PAf32ActiveRetire"); + let (exported, human) = { + let (mut kernel, clockwork, active) = clock_kernel("PAf32ActiveRetire"); let _ = &clockwork; let human = human_subject(&active); play_retires(&mut kernel, human).expect("play retires the human subject"); - (kernel.state.world_id, human) + (kernel.export().unwrap(), human) }; - let reopened = WorldKernel::open(&path, world_id).expect("the store replays"); + let reopened = WorldKernel::open(&exported).expect("the export replays"); let retired = reopened .snapshot() .unwrap() @@ -11570,8 +11229,7 @@ mod clock_tests { /// knowledge from a telling into that channel. #[test] fn channel_audience_excludes_a_retired_member() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf33Audience"); + let (mut kernel, clockwork, _) = clock_kernel("PAf33Audience"); play_retires(&mut kernel, clockwork.reeve).expect("retire"); let mut patch = ruled_fact_patch("news"); patch.declarations.push(Declaration::Channel(ChannelDeclaration { @@ -11604,8 +11262,7 @@ mod clock_tests { /// controller. #[test] fn a_retired_subject_cannot_speak_through_a_channel() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf33RetiredSpeaks"); + let (mut kernel, clockwork, _) = clock_kernel("PAf33RetiredSpeaks"); let mut declare = ruled_fact_patch("wire-decl"); declare.declarations.push(Declaration::Channel(ChannelDeclaration { handle: DraftHandle::new("wire"), @@ -11640,10 +11297,7 @@ mod clock_tests { /// respects — one statement of reach, one fix. #[test] fn a_retired_subject_is_unreachable_through_can_reach() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = WorldKernel::create( - directory.path().join("world.cc"), - creation("PAf33CanReach"), + let mut kernel = WorldKernel::create(creation("PAf33CanReach"), &auth_principal(owner()), ) .expect("a created world") @@ -11676,8 +11330,7 @@ mod clock_tests { /// PA.f34: `AcquireKnowledge` refuses a retired subject. #[test] fn a_retired_subject_cannot_acquire_knowledge() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf34Acquire"); + let (mut kernel, clockwork, _) = clock_kernel("PAf34Acquire"); play_retires(&mut kernel, clockwork.reeve).expect("retire"); let mut patch = ruled_fact_patch("news"); patch.operations.push(ComponentOp::AcquireKnowledge { @@ -11698,8 +11351,7 @@ mod clock_tests { /// PA.f34: `Forget` refuses a retired subject. #[test] fn a_retired_subject_cannot_forget() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf34Forget"); + let (mut kernel, clockwork, _) = clock_kernel("PAf34Forget"); let mut declare = ruled_fact_patch("news"); declare.operations.push(ComponentOp::AcquireKnowledge { subject: Ref::Existing(clockwork.reeve), @@ -11726,8 +11378,7 @@ mod clock_tests { /// PA.f34: `InstallIncumbent` refuses a retired subject as incumbent. #[test] fn a_retired_subject_cannot_take_office() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf34Office"); + let (mut kernel, clockwork, _) = clock_kernel("PAf34Office"); play_retires(&mut kernel, clockwork.farmer).expect("retire"); let before = kernel.snapshot().unwrap(); let error = reject_play( @@ -11753,8 +11404,7 @@ mod clock_tests { /// still be looted after it stops acting. #[test] fn holdings_are_still_transferable_from_a_retired_holder() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf34Loot"); + let (mut kernel, clockwork, _) = clock_kernel("PAf34Loot"); play_retires(&mut kernel, clockwork.farmer).expect("retire"); let before = kernel.snapshot().unwrap(); let grain = *kernel @@ -11788,8 +11438,7 @@ mod clock_tests { /// retired subject. #[test] fn retiring_then_relocating_in_one_patch_is_rejected() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf35RetireRelocate"); + let (mut kernel, clockwork, _) = clock_kernel("PAf35RetireRelocate"); let stair = *kernel .state .edges @@ -11818,8 +11467,7 @@ mod clock_tests { /// re-resolving. #[test] fn retiring_the_same_subject_twice_in_one_patch_is_a_noop_the_second_time() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf35DoubleRetire"); + let (mut kernel, clockwork, _) = clock_kernel("PAf35DoubleRetire"); let before = kernel.snapshot().unwrap(); let error = reject_play( &mut kernel, @@ -11839,8 +11487,7 @@ mod clock_tests { /// office incumbent draws. #[test] fn a_retired_subject_cannot_be_a_promisor() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf37Promisor"); + let (mut kernel, clockwork, _) = clock_kernel("PAf37Promisor"); play_retires(&mut kernel, clockwork.farmer).expect("retire"); let before = kernel.snapshot().unwrap(); let error = reject_play( @@ -11868,8 +11515,7 @@ mod clock_tests { /// they were the moment it retired. #[test] fn after_retirement_a_tick_moves_none_of_the_retired_subjects_commitments() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf37Frozen"); + let (mut kernel, clockwork, _) = clock_kernel("PAf37Frozen"); let snapshot = kernel.snapshot().unwrap(); submit_play( &mut kernel, @@ -11937,8 +11583,7 @@ mod clock_tests { /// exercises, since the farmer it retires holds no dependency. #[test] fn after_retirement_a_tick_moves_none_of_the_retired_subjects_goal_or_dependency() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf37FrozenDep"); + let (mut kernel, clockwork, _) = clock_kernel("PAf37FrozenDep"); let snapshot = kernel.snapshot().unwrap(); submit_play( &mut kernel, @@ -11993,20 +11638,18 @@ mod clock_tests { /// every other retirement effect in this batch does. #[test] fn a_retired_subjects_frozen_commitments_survive_reopen_and_replay() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let (world_id, farmer, routine, obligation) = { - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf37Replay"); + let (exported, farmer, routine, obligation) = { + let (mut kernel, clockwork, _) = clock_kernel("PAf37Replay"); play_retires(&mut kernel, clockwork.farmer).expect("retire the farmer"); tick(&mut kernel, ROUTINE_DUE as u32 + LATE_DUE as u32).expect("the tick commits"); ( - kernel.state.world_id, + kernel.export().unwrap(), clockwork.farmer, clockwork.routine, clockwork.obligation, ) }; - let reopened = WorldKernel::open(&path, world_id).expect("the store replays"); + let reopened = WorldKernel::open(&exported).expect("the export replays"); assert_eq!( due(&reopened, farmer, routine), FictionalMinutes(ROUTINE_DUE), @@ -12036,8 +11679,7 @@ mod clock_tests { /// too. #[test] fn a_retired_subject_cannot_acquire_evidenced_knowledge() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf39Evidenced"); + let (mut kernel, clockwork, _) = clock_kernel("PAf39Evidenced"); play_retires(&mut kernel, clockwork.farmer).expect("retire"); let patch = WorldPatch { declarations: vec![Declaration::Fact(FactDeclaration { @@ -12077,8 +11719,7 @@ mod clock_tests { /// and kills a mutation that removes `audience()`'s retired filter. #[test] fn a_retired_placeless_subject_is_unreachable_through_a_subjects_channel() { - let directory = tempfile::tempdir().unwrap(); - let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf39S2"); + let (mut kernel, clockwork, _) = clock_kernel("PAf39S2"); let speak = super::tests::speak_entry(&kernel); submit_as( &mut kernel, @@ -12198,16 +11839,12 @@ mod agency_tests { }; use super::*; - fn world(title: &str) -> (tempfile::TempDir, std::path::PathBuf, WorldKernel) { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let (kernel, _) = WorldKernel::create( - &path, - creation(title), + fn world(title: &str) -> WorldKernel { + let (kernel, _) = WorldKernel::create(creation(title), &auth_principal(owner()), ) .unwrap(); - (directory, path, kernel) + kernel } fn declare_place_patch(handle: &str) -> WorldPatch { @@ -12225,7 +11862,7 @@ mod agency_tests { #[test] fn after_genesis_only_play_writes() { - let (_directory, _path, mut kernel) = world("PlayOnly"); + let mut kernel = world("PlayOnly"); let snapshot = kernel.snapshot().unwrap(); let human = subject_by_label(&kernel.state, "The Human"); let persona = subject_by_label(&kernel.state, "The Witness"); @@ -12302,7 +11939,7 @@ mod agency_tests { #[test] fn apply_effect_re_decides_play() { - let (_directory, _path, kernel) = world("ReDecide"); + let kernel = world("ReDecide"); let state = &kernel.state; let command_id = CommandId::issue(); let human = subject_by_label(state, "The Human"); @@ -12357,7 +11994,7 @@ mod agency_tests { /// grant for, both come back Unauthorized. #[test] fn a_non_play_caller_is_refused_before_the_world_is_read() { - let (_directory, _path, mut kernel) = world("Blind"); + let mut kernel = world("Blind"); let snapshot = kernel.snapshot().unwrap(); let persona = subject_by_label(&kernel.state, "The Witness"); let ungranted = affordance_named(&snapshot, "convene"); @@ -12391,18 +12028,19 @@ mod agency_tests { #[test] fn a_world_is_born_active() { - let (_directory, path, mut kernel) = world("BornActive"); + let mut kernel = world("BornActive"); let snapshot = kernel.snapshot().unwrap(); assert_eq!(snapshot.revision, 0); let human = subject_by_label(&kernel.state, "The Human"); act(&mut kernel, human, speak(first_grant(&snapshot, human), "At once.")).unwrap(); let accepted = kernel.snapshot().unwrap(); assert_eq!(accepted.revision, 1); + let exported = kernel.export().unwrap(); drop(kernel); - let reopened = WorldKernel::open(&path, accepted.world_id).unwrap(); + let reopened = WorldKernel::open(&exported).unwrap(); assert_eq!(reopened.snapshot().unwrap(), accepted); - let (_other, _path, mut kernel) = world("BornActiveClock"); + let mut kernel = world("BornActiveClock"); let genesis = kernel.snapshot().unwrap(); submit_play(&mut kernel, &genesis, tick_body(1)); assert_eq!(kernel.snapshot().unwrap().revision, 1); @@ -12443,7 +12081,7 @@ mod agency_tests { /// Retire sets the flag `is_retired` reads, and nothing else retires. #[test] fn retirement_lives_on_the_subject() { - let (_directory, path, mut kernel) = world("RetireFlag"); + let mut kernel = world("RetireFlag"); let snapshot = kernel.snapshot().unwrap(); let persona = subject_by_label(&kernel.state, "The Witness"); assert!(!is_retired(&kernel.state, persona)); @@ -12460,8 +12098,9 @@ mod agency_tests { assert!(!kernel.state.affordance_grants.contains_key(&persona)); let after = kernel.snapshot().unwrap(); assert!(after.subjects.iter().find(|s| s.id == persona).unwrap().retired); + let exported = kernel.export().unwrap(); drop(kernel); - let reopened = WorldKernel::open(&path, after.world_id).unwrap(); + let reopened = WorldKernel::open(&exported).unwrap(); assert!(is_retired(&reopened.state, persona)); assert_eq!(reopened.snapshot().unwrap(), after); } @@ -12490,7 +12129,7 @@ mod agency_tests { #[test] fn a_revoke_may_leave_a_subject_with_no_verbs() { - let (_directory, path, mut kernel) = world("Mute"); + let mut kernel = world("Mute"); let snapshot = kernel.snapshot().unwrap(); let persona = subject_by_label(&kernel.state, "The Witness"); let only = first_grant(&snapshot, persona); @@ -12513,9 +12152,10 @@ mod agency_tests { assert!(matches!(error, KernelError::AffordanceDenied), "{error:?}"); journal::verify_state_shape(&kernel.state).expect("a mute subject is a legal shape"); let accepted = kernel.snapshot().unwrap(); + let exported = kernel.export().unwrap(); drop(kernel); assert_eq!( - WorldKernel::open(&path, accepted.world_id) + WorldKernel::open(&exported) .unwrap() .snapshot() .unwrap(), @@ -12535,12 +12175,9 @@ mod agency_tests { import_key: None, }) }; - let directory = tempfile::tempdir().unwrap(); let mut input = creation("Mutes"); input.patch.declarations.push(mute("born-mute")); - let (mut kernel, _) = WorldKernel::create( - directory.path().join("world.cc"), - input, + let (mut kernel, _) = WorldKernel::create(input, &auth_principal(owner()), ) .unwrap(); @@ -12585,7 +12222,7 @@ mod agency_tests { #[test] fn a_retired_subject_takes_no_grant() { - let (_directory, _path, mut kernel) = world("RetiredGrants"); + let mut kernel = world("RetiredGrants"); let snapshot = kernel.snapshot().unwrap(); let persona = subject_by_label(&kernel.state, "The Witness"); let convene = affordance_named(&snapshot, "convene"); @@ -12622,7 +12259,7 @@ mod agency_tests { #[test] fn retire_applies_to_every_subject() { - let (_directory, path, mut kernel) = world("RetireAll"); + let mut kernel = world("RetireAll"); let snapshot = kernel.snapshot().unwrap(); let everyone = ["The Human", "The Witness", "The Council"] .map(|label| subject_by_label(&kernel.state, label)); @@ -12646,9 +12283,10 @@ mod agency_tests { assert!(subject.position.is_none()); } assert!(kernel.state.affordance_grants.is_empty()); + let exported = kernel.export().unwrap(); drop(kernel); assert_eq!( - WorldKernel::open(&path, after.world_id) + WorldKernel::open(&exported) .unwrap() .snapshot() .unwrap(), @@ -12661,7 +12299,7 @@ mod agency_tests { /// at apply rather than leaving a grant row the shape check calls corrupt. #[test] fn apply_refuses_a_grant_to_a_retired_subject() { - let (_directory, _path, mut kernel) = world("ForgedGrant"); + let mut kernel = world("ForgedGrant"); let snapshot = kernel.snapshot().unwrap(); let persona = subject_by_label(&kernel.state, "The Witness"); let convene = affordance_named(&snapshot, "convene"); diff --git a/native/aetherlight/src/patch.rs b/native/aetherlight/src/patch.rs index cbdc5477d..7e585682e 100644 --- a/native/aetherlight/src/patch.rs +++ b/native/aetherlight/src/patch.rs @@ -2382,7 +2382,7 @@ pub(super) fn kernel_speak_entry() -> Affordance { /// Whether a stored catalog entry would still be admitted by the declaration /// validator. One validator, two readers: the resolver rejects a bad entry, and -/// journal recovery refuses a store that already holds one. +/// opening an export refuses a chain that already holds one. pub(super) fn entry_is_admissible(entry: &Affordance) -> bool { let mut mismatches = Vec::new(); validate_affordance( @@ -5810,8 +5810,7 @@ mod tests { #[test] fn a_catalog_entry_with_a_dangling_or_noncanonical_band_is_rejected() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = draft_world(directory.path()); + let mut kernel = draft_world(); let before = kernel.snapshot().unwrap(); let slots = vec![ transfer_slot(vec!["from", "to", "goods"], Bounds::Quantity(Quantity(2))), @@ -5883,8 +5882,7 @@ mod tests { #[test] fn a_slot_whose_roles_do_not_match_its_operation_is_rejected() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = draft_world(directory.path()); + let mut kernel = draft_world(); let before = kernel.snapshot().unwrap(); let handle = DraftHandle::new("verb"); @@ -5980,8 +5978,7 @@ mod tests { #[test] fn a_grant_naming_an_undeclared_affordance_is_rejected_and_the_same_patch_commits() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = draft_world(directory.path()); + let mut kernel = draft_world(); let before = kernel.snapshot().unwrap(); let entries_before = kernel.state.affordance_catalog.len(); let subjects_before = kernel.state.subjects.len(); @@ -6048,8 +6045,7 @@ mod tests { #[test] fn two_entries_cannot_share_one_kind_name() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = draft_world(directory.path()); + let mut kernel = draft_world(); let before = kernel.snapshot().unwrap(); let slot = transfer_slot(vec!["from", "to", "goods"], Bounds::Quantity(Quantity(2))); let rejected = reject_play( @@ -6103,10 +6099,8 @@ mod tests { ); } - fn draft_world(directory: &std::path::Path) -> WorldKernel { - WorldKernel::create( - directory.join("world.cc"), - creation("Kharad"), + fn draft_world() -> WorldKernel { + WorldKernel::create(creation("Kharad"), &auth_principal(owner()), ) .expect("draft world") @@ -6117,8 +6111,7 @@ mod tests { /// provides. Nothing commits and nothing is allocated. #[test] fn a_subject_declared_at_an_undeclared_place_is_rejected_and_allocates_nothing() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = draft_world(directory.path()); + let mut kernel = draft_world(); let before = kernel.snapshot().unwrap(); let commits_before = kernel.journal.commit_count(); @@ -6159,8 +6152,7 @@ mod tests { /// commit: every reference resolves to an ID the same patch allocated. #[test] fn a_declared_place_and_its_dependents_commit_atomically() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = draft_world(directory.path()); + let mut kernel = draft_world(); let before = kernel.snapshot().unwrap(); let commits_before = kernel.journal.commit_count(); @@ -6226,8 +6218,7 @@ mod tests { /// conversion between them and no public `Uuid` constructor. #[test] fn a_draft_handle_of_the_wrong_kind_is_rejected() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = draft_world(directory.path()); + let mut kernel = draft_world(); let before = kernel.snapshot().unwrap(); let commits_before = kernel.journal.commit_count(); @@ -6270,8 +6261,7 @@ mod tests { /// and repairing exactly that set is enough to commit. #[test] fn rejection_returns_every_failed_check_and_repairing_exactly_those_commits() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = draft_world(directory.path()); + let mut kernel = draft_world(); let before = kernel.snapshot().unwrap(); let broken = patch_of(vec![ @@ -6339,8 +6329,7 @@ mod tests { #[test] fn an_empty_patch_is_no_canonical_change() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = draft_world(directory.path()); + let mut kernel = draft_world(); let before = kernel.snapshot().unwrap(); let error = kernel @@ -6365,8 +6354,7 @@ mod tests { /// unrelated empty label joins the same complete set. #[test] fn a_containment_cycle_is_rejected_with_the_complete_set() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = draft_world(directory.path()); + let mut kernel = draft_world(); let before = kernel.snapshot().unwrap(); let error = kernel @@ -6409,8 +6397,7 @@ mod tests { #[test] fn a_route_endpoint_that_is_not_a_place_is_rejected() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = draft_world(directory.path()); + let mut kernel = draft_world(); let before = kernel.snapshot().unwrap(); let error = kernel @@ -6447,8 +6434,7 @@ mod tests { /// or in an operation. #[test] fn an_invalid_route_cost_is_rejected_from_declaration_and_from_alter_cost() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = draft_world(directory.path()); + let mut kernel = draft_world(); let topology = admit_topology(&mut kernel); let before = kernel.snapshot().unwrap(); @@ -6496,8 +6482,7 @@ mod tests { /// a route that does not start where the subject stands. #[test] fn relocate_without_an_open_public_route_is_rejected() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = draft_world(directory.path()); + let mut kernel = draft_world(); let topology = admit_topology(&mut kernel); let active = kernel.snapshot().unwrap(); let commits_before = kernel.journal.commit_count(); @@ -6545,8 +6530,7 @@ mod tests { /// not be read as an overlap with a lend the retirement already killed. #[test] fn a_grant_after_retiring_the_lending_institution_is_admitted() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = draft_world(directory.path()); + let mut kernel = draft_world(); let (_, civic, before) = civic_world(&mut kernel); // The office lends levy over the whole hall; grant the reeve levy @@ -6577,8 +6561,7 @@ mod tests { /// gone, and refuses the already-applied `Retire`'s sibling operation. #[test] fn a_relocate_relying_only_on_a_retiring_institutions_authority_is_refused_by_the_resolver() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = draft_world(directory.path()); + let mut kernel = draft_world(); let (topology, civic, before) = civic_world(&mut kernel); // `topology.walker` already exists and already stands at `yard`, so @@ -6631,8 +6614,7 @@ mod tests { #[test] fn relocate_moves_the_subject_and_nothing_else() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = draft_world(directory.path()); + let mut kernel = draft_world(); let topology = admit_topology(&mut kernel); let active = kernel.snapshot().unwrap(); let entities_before = kernel.state.entities.clone(); @@ -6669,11 +6651,7 @@ mod tests { #[test] fn restart_replay_after_a_relocate_is_exact() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let (mut kernel, _) = WorldKernel::create( - &path, - creation("Kharad"), + let (mut kernel, _) = WorldKernel::create(creation("Kharad"), &auth_principal(owner()), ) .unwrap(); @@ -6691,10 +6669,10 @@ mod tests { .submit(envelope.clone(), &AuthenticatedCaller::verified_play()) .unwrap(); let committed = kernel.snapshot().unwrap(); - let world_id = committed.world_id; + let exported = kernel.export().unwrap(); drop(kernel); - let mut reopened = WorldKernel::open(&path, world_id).unwrap(); + let mut reopened = WorldKernel::open(&exported).unwrap(); assert_eq!(reopened.snapshot().unwrap(), committed); assert_eq!( reopened.state.positions.get(&topology.walker), @@ -6710,8 +6688,7 @@ mod tests { #[test] fn the_snapshot_exposes_places_routes_and_positions_deterministically() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = draft_world(directory.path()); + let mut kernel = draft_world(); let topology = admit_topology(&mut kernel); let snapshot = kernel.snapshot().unwrap(); assert_eq!(snapshot, kernel.snapshot().unwrap()); @@ -6751,11 +6728,7 @@ mod tests { #[test] fn restart_replay_after_a_committed_patch_is_exact() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let (mut kernel, _) = WorldKernel::create( - &path, - creation("Kharad"), + let (mut kernel, _) = WorldKernel::create(creation("Kharad"), &auth_principal(owner()), ) .unwrap(); @@ -6777,10 +6750,10 @@ mod tests { .submit(envelope.clone(), &AuthenticatedCaller::verified_play()) .unwrap(); let committed = kernel.snapshot().unwrap(); - let world_id = committed.world_id; + let exported = kernel.export().unwrap(); drop(kernel); - let mut reopened = WorldKernel::open(&path, world_id).unwrap(); + let mut reopened = WorldKernel::open(&exported).unwrap(); assert_eq!(reopened.snapshot().unwrap(), committed); assert!(matches!( reopened.submit(envelope, &AuthenticatedCaller::verified_play()), @@ -6793,8 +6766,7 @@ mod tests { /// re-resolved gets the same ones. #[test] fn genesis_and_admit_patch_share_one_allocator() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = draft_world(directory.path()); + let mut kernel = draft_world(); let before = kernel.snapshot().unwrap(); let genesis_human = before .subjects @@ -6827,16 +6799,12 @@ mod tests { assert_eq!(first, second); } - /// The durable half of "a rejected patch mints nothing": the store on disk, - /// not just the in-memory head, carries no row and no byte of any ID the + /// The durable half of "a rejected patch mints nothing": the export, not + /// just the in-memory head, carries no commit and no byte of any ID the /// rejected patch would have allocated. #[test] - fn a_rejected_patch_leaves_no_row_and_no_id_in_the_store() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("world.cc"); - let (mut kernel, _) = WorldKernel::create( - &path, - creation("Kharad"), + fn a_rejected_patch_leaves_no_commit_and_no_id_in_the_export() { + let (mut kernel, _) = WorldKernel::create(creation("Kharad"), &auth_principal(owner()), ) .unwrap(); @@ -6877,16 +6845,17 @@ mod tests { ), ]; + let exported = kernel.export().unwrap(); drop(kernel); - let raw = std::fs::read(&path).unwrap(); + let raw = &exported; for id in would_be { assert!( !raw.windows(16).any(|window| window == id.as_bytes()), - "a rejected patch left {id} in the store" + "a rejected patch left {id} in the export" ); } - let reopened = WorldKernel::open(&path, before.world_id).unwrap(); + let reopened = WorldKernel::open(&exported).unwrap(); assert_eq!(reopened.snapshot().unwrap(), before); assert_eq!(reopened.journal.commit_count(), 1); assert_eq!(reopened.state.entities.len(), FIXTURE_ENTITIES); @@ -6904,9 +6873,7 @@ mod tests { /// otherwise concatenate to the same string. #[test] fn derive_id_does_not_collide_some_empty_discriminator_with_none() { - let directory = tempfile::tempdir().unwrap(); let (kernel, _) = WorldKernel::create( - &directory.path().join("world.cc"), creation("DeriveId"), &auth_principal(owner()), ) @@ -6944,8 +6911,7 @@ mod tests { /// without the journal's reduce-equality check running. #[test] fn apply_effect_rejects_a_forged_stale_or_unauthorized_patch_effect() { - let directory = tempfile::tempdir().unwrap(); - let kernel = draft_world(directory.path()); + let kernel = draft_world(); let patch = patch_of(vec![ entity("rhythm-road", "The Rhythm Road", EntityKind::Place), institution( @@ -7014,8 +6980,7 @@ mod tests { /// test names are each reachable from a real patch. #[test] fn soul_self_loop_unplaced_subject_and_no_effect_are_each_reachable() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = draft_world(directory.path()); + let mut kernel = draft_world(); let before = kernel.snapshot().unwrap(); // A route whose two endpoints resolve to one place. @@ -7131,8 +7096,7 @@ mod tests { /// stand on, a closed route, or a restricted one dies at apply time. #[test] fn soul_a_forged_relocate_effect_is_refused_at_apply_time() { - let directory = tempfile::tempdir().unwrap(); - let mut kernel = draft_world(directory.path()); + let mut kernel = draft_world(); let topology = admit_topology(&mut kernel); for edge_id in [topology.span, topology.shutter, topology.toll] { let forged = super::super::WorldEffect::PatchAdmitted { From d3a1caa01bb676be4a19bf26f17e9f025dcba3ce Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 02:40:09 +0100 Subject: [PATCH 146/190] aetherlight: golden session digests, clockwork commit-cost harness, provenance fixtures/golden.digests pins every committed revision's state and commit digest and the export digest for one scripted session: speech (Told), a display, a routine placed and rolled by a thirty-minute tick, and a refused convene. The round-trip test reopens the export and checks the next command gives equal receipts on both worlds. clockwork_commit_cost is an ignored harness that prints mean tick and speech submit times at 100, 400 and 1600 persons. PROVENANCE.md records the id, journal and dependency changes. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/PROVENANCE.md | 61 +++-- native/aetherlight/fixtures/golden.digests | 6 + native/aetherlight/src/golden_tests.rs | 274 +++++++++++++++++++++ native/aetherlight/src/lib.rs | 2 + 4 files changed, 327 insertions(+), 16 deletions(-) create mode 100644 native/aetherlight/fixtures/golden.digests create mode 100644 native/aetherlight/src/golden_tests.rs diff --git a/native/aetherlight/PROVENANCE.md b/native/aetherlight/PROVENANCE.md index 447f1ad70..2f0b14bda 100644 --- a/native/aetherlight/PROVENANCE.md +++ b/native/aetherlight/PROVENANCE.md @@ -30,8 +30,8 @@ fixture (removed in AL2a) was binary and no newline rule touched it. Line ranges | `Cargo.lock` | `Cargo.lock` | all | pruned by cargo to the dependencies below | `Cargo.toml` is new: package `aetherlight`, its own `[workspace]`, no features, -dependencies chrono, cultcache-rs, rmp-serde, serde, serde_json, sha2, thiserror, -unicode-normalization, unicode-properties, uuid; dev tempfile. +dependencies rmp-serde, serde, serde_json, sha2, thiserror, unicode-normalization, +unicode-properties, uuid (serde only); dev uuid with v4 (AL3a). ## Edits @@ -76,14 +76,8 @@ unicode-normalization, unicode-properties, uuid; dev tempfile. `patch.rs`, `journal.rs`, `action.rs`, `grammar/tests.rs` and `import_key_tests.rs` lose the symbols and tests listed there. -Not renamed: the `ghostlight.*` schema ids and namespaces in the code -(`STATE_SCHEMA`, `COMMIT_SCHEMA`, journal schema rows, `ghostlight.speech`). They -enter derived ids and digests. No test pins their digests since AL2a removed the -golden replay (see below); AL3/AL5 add Aetherlight's own once ids are derived -(follow-up `aetherlight-golden-replay-dialogue`). AL2a bumped `STATE_SCHEMA` and -`COMMIT_SCHEMA` from `consumer.v6` to `consumer.v7` because the state shape lost -fields, so a pre-cut store is refused at the schema gate (tested with v6 rows). -AL3 owns the format rename. +The `ghostlight.*` schema ids were renamed in AL3a (see the last section). The +golden replay AL2a removed is back as `fixtures/golden.digests` (AL3a). ## Left behind @@ -111,10 +105,9 @@ binding, preconditions, audience, band selection and lowering (`action.rs`); ## Dependency pin -`cultcache-rs` is pinned at Ghostlight's rev -`85f7024a35ea42cf9f0a0199a064526427150191`, the rev that wrote -Ghostlight's recorded-world fixture (removed in AL2a), not Aetheria's C# CultLib pin. The fork -reproduces Ghostlight first; AL3 removes cultcache-rs. +The crate no longer pins CultLib: `cultcache-rs` (Ghostlight's rev +`85f7024a35ea42cf9f0a0199a064526427150191`) left the manifest in AL3a with the +redb store it served. ## Pulling a later Ghostlight fix @@ -182,8 +175,7 @@ Kept untouched for AL2b: controllers and `ControllerMode`, consumers What the cut deletes is gone; what remains is part B's: - Authenticated-caller vocabulary: `AuthenticatedCaller::fixture`, - `verified_principal`, `verified_play`, and - `requires_owner_restart`; id helpers `text` and `nil_for_test`; + `verified_principal` and `verified_play`; id helpers `text` and `nil_for_test`; `commits_for_test`; grammar `verbs`. AL4's ABI decides which of these it needs. - Patch ingress: `decode_patch`, `check_patch_caps`, `PatchDecodeError` and @@ -322,3 +314,40 @@ Not this cut's, and kept: the channel controller (`ChannelRecord.controller`, `SetController`, `resolve_controller`), which is dialogue (`dialogue-is-world-action`). An earlier version of this file listed `resolve_controller` and `controller_key` as AL2b-2b's; that was wrong. + +## Cut AL3a: the journal is in memory; ids are derived + +Authority: cut `aetherlight-journal-a` r1 of campaign `aetheria-release`; rulings +`aetherlight-narrative-state-owner`, `cultnet-scale-is-not-negotiable`, +`dialogue-is-world-action`. Base `09a1c3256` (spec base `39c50acfc`; no `native/` +change between them). + +Ids. `CommandEnvelope::id()` is the first 16 bytes of sha256 over +`aetherlight.command.v1`, the world id, the big-endian expected revision and the +named messagepack of caller and body. `CreateWorld::id()` is the same over +`aetherlight.create.v1` and the whole creation. `WorldId::of(creation id)` is the +same over `aetherlight.world.v1`; a genesis commit whose world id is not that is +refused at open. The `id` fields on `CreateWorld` and `CommandEnvelope`, +`CommandId::new`/`parse_uuid` and `WorldId::issue` are gone; `CommandId::issue` +is a test fixture. Retry identity went with them: `SubmitReceipt` collapsed into +`CommitReceipt`, and a resubmitted applied command is a `RevisionMismatch`. +`WorldCommit.committed_at` is gone: wall time is the C# store's `stored_at`. + +Journal. `WorldJournal { commits }` is the only record of a world. `export()` is +canonical named messagepack of `{ schema: aetherlight.journal.v1, commits }`; +`open(bytes)` decodes canonically and replays through `verify_history`, which +reads the revision-ordered slice and returns the head state it derives. There is +no state row, no expected world id, no health or ownership check and no +`verify_append`. `STATE_SCHEMA` and `COMMIT_SCHEMA` are +`aetherlight.world_state.v1` and `aetherlight.world_commit.v1`; any `ghostlight.*` +schema is refused at the schema gate and at the commit chain. + +Dependencies. chrono, cultcache-rs (and with it redb) and tempfile left the +manifest; uuid keeps `serde` in `[dependencies]` and `v4` only in +`[dev-dependencies]`, so no shipped path draws a random id (`cargo build --lib` +compiles without it). + +Not taken from the spec's text: the spec's negative pattern `id: CommandId` +matches the `command_id: CommandId` parameters of the band draw and derivation +(the per-command term the spec keeps); the doc comment said `synchronous`, which +`chrono` matches, and now says `single-threaded`. diff --git a/native/aetherlight/fixtures/golden.digests b/native/aetherlight/fixtures/golden.digests new file mode 100644 index 000000000..610f26d9f --- /dev/null +++ b/native/aetherlight/fixtures/golden.digests @@ -0,0 +1,6 @@ +0 sha256:b3a1da45714cfed622b118ac441f562dcf2c1f45637baff335f08a3efa562e55 sha256:e0e30c081917a00f88268916784d55e0e3ee187b8733a6da5953f9864dbc41cd +1 sha256:6315946e2cac6d49e24aae623bb92cdf9c68ac50382c1d27ffec34f78e2ebbb5 sha256:14fa8cbdee9f94944dbc91c9158fb6009c5310e11f57d682a3c17ae3ba4a476e +2 sha256:3bc0ba23bdb8afe6782b08f3223e9a501e17a8cfbbfed3b8c0a94cab20d2de64 sha256:e962a73db29fb48e0b303ac2746f85c88e9eca43e70cb3b5efb5527a885516a7 +3 sha256:cd5930ff97930832f59fb4ad954b0fd9ca94167767a15033011de8ca2b51581d sha256:3c6277ff11415a18376e8c86f1aa742ed8529b216a13492b66e0843dffffdcb4 +4 sha256:735182443e82f4b21d7b88c82aaca27987266653e6d839ab16556ac10b27d7e4 sha256:b138a16729c1f232c11f0b1a2bc692025856d2803820b05084cefd581af1b001 +export sha256:bc412d52ed96520d74bc06faead7c7b735573d268a51e2b4ea7d3f31ff4e8ac4 diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs new file mode 100644 index 000000000..84ef74555 --- /dev/null +++ b/native/aetherlight/src/golden_tests.rs @@ -0,0 +1,274 @@ +//! The pinned replay of one scripted session, and the commit-cost harness. +//! +//! The golden file is the determinism contract in its smallest form: every +//! committed revision's state digest and commit digest, and the digest of the +//! export, for a session that touches speech, display, a routine and a refusal. +//! A change to any id derivation, schema, encoding or reducer arm moves a line. + +use crate::tests::{ + affordance_named, auth_principal, command, creation, first_grant, operations, owner, + play_caller, play_command, speak, subject_by_label, submit_play, tick_body, +}; +use crate::{ + AuthenticatedCaller, CommandBody, CommitmentKind, ComponentOp, DecisionInvocation, + FictionalMinutes, KernelError, KnowledgeSource, Ref, Statement, TickMinutes, WorldEffect, + WorldKernel, +}; +use sha2::{Digest, Sha256}; +use std::time::Instant; + +/// The script: The Human speaks to The Witness, The Human shows a gesture, a +/// Routine is placed on The Witness, thirty minutes roll it, and The Human +/// invokes `convene`, which it does not hold. +fn golden_session() -> (WorldKernel, String) { + let (mut kernel, _) = WorldKernel::create(creation("Golden"), &auth_principal(owner())) + .expect("the fixture world is created"); + let human = subject_by_label(&kernel.state, "The Human"); + let witness = subject_by_label(&kernel.state, "The Witness"); + + let snapshot = kernel.snapshot().unwrap(); + let speak_entry = first_grant(&snapshot, human); + submit_play( + &mut kernel, + &snapshot, + CommandBody::Act { + actor: human, + invocation: speak(speak_entry, "The vote carries."), + }, + ); + let heard = kernel.snapshot().unwrap(); + let witness_knowledge = &heard + .subjects + .iter() + .find(|subject| subject.id == witness) + .expect("the witness is a subject") + .knowledge; + assert!( + witness_knowledge.iter().any(|held| matches!( + held.source, + KnowledgeSource::Told { by, .. } if by == human + )), + "the witness holds what the human said as Told" + ); + + submit_play( + &mut kernel, + &heard, + CommandBody::Act { + actor: human, + invocation: DecisionInvocation { + affordance: speak_entry, + bindings: Vec::new(), + proposed: Vec::new(), + speech: None, + display: Some(Statement::new("The Human raises one finger.").unwrap()), + }, + }, + ); + + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CreateCommitment { + subject: Ref::Existing(witness), + counterparty: None, + kind: CommitmentKind::Routine, + due: FictionalMinutes(10), + period: Some(TickMinutes::new(10).unwrap()), + checks: Vec::new(), + statement: Statement::new("The Witness keeps the lamp.").unwrap(), + }]), + ); + + let snapshot = kernel.snapshot().unwrap(); + submit_play(&mut kernel, &snapshot, tick_body(30)); + let ticked = kernel.journal.commits_for_test(); + let WorldEffect::TimeAdvanced { motion, .. } = + &ticked.last().expect("the tick committed").effect + else { + panic!("the last commit is the tick"); + }; + assert!(!motion.fulfilled.is_empty(), "the routine rolled"); + + // The refusal changes nothing: not the revision, not either digest. + let before = kernel.snapshot().unwrap(); + let convene = affordance_named(&before, "convene"); + let refused = kernel.submit( + command( + &before, + play_caller(), + CommandBody::Act { + actor: human, + invocation: speak(convene, "A meeting is called."), + }, + ), + &AuthenticatedCaller::verified_play(), + ); + assert!(matches!(refused, Err(KernelError::AffordanceDenied)), "{refused:?}"); + assert_eq!(kernel.snapshot().unwrap(), before); + assert_eq!(kernel.journal.commit_count(), 5); + + let mut file = String::new(); + for commit in kernel.journal.commits_for_test() { + file.push_str(&format!( + "{} {} {}\n", + commit.resulting_revision, commit.resulting_state_digest, commit.digest + )); + } + let export = kernel.export().unwrap(); + file.push_str(&format!("export sha256:{:x}\n", Sha256::digest(&export))); + (kernel, file) +} + +#[test] +fn golden_session_digests_are_fixed() { + let (_, computed) = golden_session(); + let (_, again) = golden_session(); + assert_eq!(computed, again, "one session, two runs, one file"); + let fixture: Vec<&str> = include_str!("../fixtures/golden.digests").lines().collect(); + let computed_lines: Vec<&str> = computed.lines().collect(); + assert!( + fixture == computed_lines, + "the golden digests moved; the computed file is:\n{computed}" + ); +} + +#[test] +fn export_open_round_trip_is_exact() { + let (mut original, _) = golden_session(); + let exported = original.export().unwrap(); + let mut reopened = WorldKernel::open(&exported).expect("the golden export opens"); + assert_eq!(reopened.state, original.state); + assert_eq!(reopened.snapshot().unwrap(), original.snapshot().unwrap()); + assert_eq!(reopened.export().unwrap(), exported); + + let human = subject_by_label(&original.state, "The Human"); + let snapshot = original.snapshot().unwrap(); + let next = play_command( + &snapshot, + CommandBody::Act { + actor: human, + invocation: speak(first_grant(&snapshot, human), "Order, please."), + }, + ); + let play = AuthenticatedCaller::verified_play(); + let original_receipt = original.submit(next.clone(), &play).unwrap(); + let reopened_receipt = reopened.submit(next, &play).unwrap(); + assert_eq!(original_receipt, reopened_receipt); + assert_eq!(original.export().unwrap(), reopened.export().unwrap()); +} + +/// What one tick and one speech cost to commit as the world grows: ten persons +/// to a place, one Routine each with period 60, due staggered over the hour. +/// Run on its own, in release, to read the numbers; no threshold is asserted. +/// +/// `cargo test --release --lib clockwork_commit_cost -- --ignored --nocapture` +#[test] +#[ignore] +fn clockwork_commit_cost() { + use crate::patch::kernel_speak_grant; + use crate::patch::{Declaration, DraftHandle, EntityDeclaration, SubjectDeclaration}; + use crate::{CallerId, CommandEnvelope, CreateWorld, EntityKind, SubjectKind, WorldPatch}; + + println!("persons places create_ms tick_mean_ms speech_mean_ms revision_after"); + for persons in [100usize, 400, 1600] { + let places = persons / 10; + let mut declarations = Vec::new(); + for place in 0..places { + declarations.push(Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(format!("place-{place}")), + label: format!("Place {place}"), + kind: EntityKind::Place, + container: None, + })); + } + for person in 0..persons { + declarations.push(Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(format!("person-{person}")), + label: format!("Person {person}"), + kind: SubjectKind::Person, + affordances: kernel_speak_grant(), + position: Some(Ref::Draft(DraftHandle::new(format!("place-{}", person / 10)))), + import_key: None, + })); + } + let started = Instant::now(); + let (mut kernel, _) = WorldKernel::create( + CreateWorld { + owner: owner(), + title: "Clockwork".into(), + patch: WorldPatch { + declarations, + operations: Vec::new(), + evidence: Vec::new(), + }, + grammar: None, + }, + &auth_principal(owner()), + ) + .expect("the clockwork world is created"); + let create_ms = started.elapsed().as_secs_f64() * 1e3; + + let people: Vec<_> = (0..persons) + .map(|person| subject_by_label(&kernel.state, &format!("Person {person}"))) + .collect(); + let routines = people + .iter() + .enumerate() + .map(|(index, subject)| ComponentOp::CreateCommitment { + subject: Ref::Existing(*subject), + counterparty: None, + kind: CommitmentKind::Routine, + due: FictionalMinutes(1 + (index % 60) as u64), + period: Some(TickMinutes::new(60).unwrap()), + checks: Vec::new(), + statement: Statement::new("Keeps the hour.").unwrap(), + }) + .collect(); + let play = AuthenticatedCaller::verified_play(); + let envelope = |kernel: &WorldKernel, body: CommandBody| CommandEnvelope { + world_id: kernel.state.world_id, + expected_revision: kernel.state.revision, + caller: CallerId::Play, + body, + }; + let placing = envelope(&kernel, operations(routines)); + kernel.submit(placing, &play).expect("the routines are placed"); + + let speak_entry = *kernel + .state + .affordance_catalog + .iter() + .find(|(_, entry)| entry.kind.0 == "speak") + .map(|(id, _)| id) + .expect("genesis admits Speak"); + + let mut ticks = 0.0; + for _ in 0..30 { + let tick = envelope(&kernel, tick_body(1)); + let started = Instant::now(); + kernel.submit(tick, &play).expect("the tick commits"); + ticks += started.elapsed().as_secs_f64() * 1e3; + } + let mut speeches = 0.0; + for index in 0..30 { + let act = envelope( + &kernel, + CommandBody::Act { + actor: people[index], + invocation: speak(speak_entry, &format!("Speech {index}.")), + }, + ); + let started = Instant::now(); + kernel.submit(act, &play).expect("the speech commits"); + speeches += started.elapsed().as_secs_f64() * 1e3; + } + println!( + "{persons:>7} {places:>6} {create_ms:>9.1} {:>12.2} {:>14.2} {:>14}", + ticks / 30.0, + speeches / 30.0, + kernel.state.revision + ); + } +} diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index 0647e8db3..ee80dc982 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -58,6 +58,8 @@ mod action; mod clock; +#[cfg(test)] +mod golden_tests; mod grammar; #[cfg(test)] mod import_key_tests; From 7b7d12ea83d6283ced4f2a9cece281afd909066b Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 02:45:26 +0100 Subject: [PATCH 147/190] aetherlight: pin the world-id derivation, revision position and chain-resealed schema refusal Mutants that survived the first pass: dropping the genesis world-id check, dropping the resulting-revision contiguity check, and a ghostlight commit schema check (the old fixture left the next commit's previous digest stale, so the chain refused it for the wrong reason). Each now has a test that fails without the rule; all eleven named mutants are killed. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/journal.rs | 56 ++++++++++++++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index e8ba77c70..e017095a5 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -922,9 +922,15 @@ mod tests { refused("reordered commits", &[honest[0].clone(), honest[2].clone(), honest[1].clone()]); refused("no commits", &[]); + // Re-sealed down the chain, so the schema is the only thing wrong. let mut ghostlight = honest.clone(); ghostlight[1].schema = "ghostlight.world_commit.consumer.v10".into(); - ghostlight[1].digest = commit_digest(&ghostlight[1]).unwrap(); + for index in 1..ghostlight.len() { + if index > 1 { + ghostlight[index].previous_commit_digest = Some(ghostlight[index - 1].digest.clone()); + } + ghostlight[index].digest = commit_digest(&ghostlight[index]).unwrap(); + } refused("a ghostlight commit schema", &ghostlight); let foreign = rmp_serde::to_vec_named(&ExportRef { @@ -952,6 +958,54 @@ mod tests { )); } + /// Position `i` holds resulting revision `i`: a commit that names a later + /// revision than its place, with a state digest honestly computed for that + /// revision, is still not the chain's next commit. + #[test] + fn a_chain_that_skips_a_revision_is_refused() { + let kernel = clock_history(); + let honest = kernel.journal.commits.clone(); + let mut state = reopen(&honest[..2]).expect("genesis and the patch open"); + state.revision = 7; + let mut forged = vec![honest[0].clone(), honest[1].clone()]; + forged[1].resulting_revision = 7; + forged[1].resulting_state_digest = crate::state_digest(&state).unwrap(); + forged[1].digest = commit_digest(&forged[1]).unwrap(); + assert!(matches!(reopen(&forged), Err(JournalError::Corrupt(_)))); + } + + /// A world is named by its creation: a genesis whose world id is any other + /// is refused, however consistently every id under it was derived. + #[test] + fn a_world_id_not_derived_from_its_creation_is_refused() { + use crate::patch::resolve_patch; + use crate::tests::{auth_principal, creation, owner}; + use crate::{CommandId, PreparedCreation}; + + let input = creation("Misnamed"); + let honest = crate::prepare_creation(input.clone(), &auth_principal(owner())).unwrap(); + let other = WorldId::of(CommandId::issue()); + assert_ne!(other, honest.world_id); + let resolved = resolve_patch( + &WorldState::empty(other, input.owner.clone(), honest.title.clone(), None), + input.id(), + &input.patch, + ) + .unwrap(); + let (kernel, _) = WorldKernel::initialize(PreparedCreation { + command: input, + world_id: other, + owner: honest.owner, + title: honest.title, + resolved, + }) + .unwrap(); + assert!(matches!( + reopen(&kernel.journal.commits), + Err(JournalError::Corrupt(_)) + )); + } + /// A stored command is not believed about who made it. The forgery re-seals /// the commit around its rewrite and the head's last commit digest names the /// re-sealed commit, so no digest can answer for the check; the control, the From 36d1d2507dac40815d2f521d2feac16e7b2e2e67 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 03:06:59 +0100 Subject: [PATCH 148/190] aetherlight: pin the digest and genesis clauses, record a band draw in the golden, document host contracts A stored digest flipped without re-sealing, and each genesis clause rewritten and re-sealed on a lone genesis, are now refused by tests that only that clause can satisfy. The golden session declares a two-band toss and uses it three times, so band selection is pinned (golden.digests regenerated). The BandPreimage doc no longer claims the payload cannot reach the draw; WorldId byte-equality, and truncation or rollback of an export, are documented as host contracts in the code and PROVENANCE. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/PROVENANCE.md | 13 +++++ native/aetherlight/fixtures/golden.digests | 10 ++-- native/aetherlight/src/action.rs | 12 +++-- native/aetherlight/src/golden_tests.rs | 59 +++++++++++++++++++-- native/aetherlight/src/journal.rs | 60 ++++++++++++++++++++++ native/aetherlight/src/lib.rs | 3 ++ 6 files changed, 147 insertions(+), 10 deletions(-) diff --git a/native/aetherlight/PROVENANCE.md b/native/aetherlight/PROVENANCE.md index 2f0b14bda..fb203c0ec 100644 --- a/native/aetherlight/PROVENANCE.md +++ b/native/aetherlight/PROVENANCE.md @@ -351,3 +351,16 @@ Not taken from the spec's text: the spec's negative pattern `id: CommandId` matches the `command_id: CommandId` parameters of the band draw and derivation (the per-command term the spec keeps); the doc comment said `synchronous`, which `chrono` matches, and now says `single-threaded`. + +Host contracts (AL3a, from Soul's pass): + +- Two byte-equal creations share a `WorldId` and every id under it. A host that + wants distinct worlds salts each run or profile into the creation, for example + a run seed in the patch. +- Truncation and rollback open: a chain verifies as a prefix, so an export with + its tail dropped, or an older export, opens as a valid shorter world. The + holder of the bytes keeps the head (revision and state digest from `snapshot()` + at export time) and compares after `open`. AL5's C# store owns this. +- The band draw is grindable through the command id (it hashes the body, so the + text, a magnitude or the revision re-roll it). Only Play submits acts after + genesis and Play is trusted, so it is not an authority hole. diff --git a/native/aetherlight/fixtures/golden.digests b/native/aetherlight/fixtures/golden.digests index 610f26d9f..2e43d097f 100644 --- a/native/aetherlight/fixtures/golden.digests +++ b/native/aetherlight/fixtures/golden.digests @@ -1,6 +1,10 @@ 0 sha256:b3a1da45714cfed622b118ac441f562dcf2c1f45637baff335f08a3efa562e55 sha256:e0e30c081917a00f88268916784d55e0e3ee187b8733a6da5953f9864dbc41cd 1 sha256:6315946e2cac6d49e24aae623bb92cdf9c68ac50382c1d27ffec34f78e2ebbb5 sha256:14fa8cbdee9f94944dbc91c9158fb6009c5310e11f57d682a3c17ae3ba4a476e 2 sha256:3bc0ba23bdb8afe6782b08f3223e9a501e17a8cfbbfed3b8c0a94cab20d2de64 sha256:e962a73db29fb48e0b303ac2746f85c88e9eca43e70cb3b5efb5527a885516a7 -3 sha256:cd5930ff97930832f59fb4ad954b0fd9ca94167767a15033011de8ca2b51581d sha256:3c6277ff11415a18376e8c86f1aa742ed8529b216a13492b66e0843dffffdcb4 -4 sha256:735182443e82f4b21d7b88c82aaca27987266653e6d839ab16556ac10b27d7e4 sha256:b138a16729c1f232c11f0b1a2bc692025856d2803820b05084cefd581af1b001 -export sha256:bc412d52ed96520d74bc06faead7c7b735573d268a51e2b4ea7d3f31ff4e8ac4 +3 sha256:1e6fa2e6104ad2cdde11db5f4643a0881f88cdda2cf049e445774ea9a2f36b65 sha256:1e8047a55a7857a19c05e07c9978a8656423de4c1c7fc49151a71abf399e2e2c +4 sha256:777d7f85b0c342ba44f51aacc03a615038cc243aa8930adf9c5e5ef7200a4325 sha256:f5ce5f59d767866fb02c76948f6693cda954d712efb6b2ac624b6dfe816cdd4f +5 sha256:f08db5b927a98b741cec0aec4d566f376ea283e1057e8a6f5abbff3f5983acb1 sha256:07889d5e1c2958e51b37087acf9784d2274c47a8cf854aadf3ed809a02b5af6e +6 sha256:0edc5712426bb23a2773fe7c804c0cccddff5f23d733679c2cd3857f2009dc6b sha256:8cebfbdbf217aad91e76301188095a04fc0cef488e6367eb3fc8a7b3f93e7f77 +7 sha256:3fdf073544f807ef4ca9928e7c95aaec58982ecb37fdcc758f3bf916914dd215 sha256:c04c37fcc192f208869f396bc2287db76e08527e5d179ffae0ec07a513964cee +8 sha256:18c5a5b61bfb8d039f9e38b5ac3a8353024de84c572d019a8af94a9508462e04 sha256:85449a2d63f3383dff2a0813071a76f665d208a77aa954d65b308c2b57657301 +export sha256:4ba94ec8ee6036e74b2fb28b9cbef97cb5386fea4c3063cf38a08ff47de28910 diff --git a/native/aetherlight/src/action.rs b/native/aetherlight/src/action.rs index 8f61aebac..0c9ac33a2 100644 --- a/native/aetherlight/src/action.rs +++ b/native/aetherlight/src/action.rs @@ -113,10 +113,14 @@ pub enum ActionMismatch { }, } -/// The band draw's whole preimage. Five fields, none of them from the -/// invocation's payload: the proposer varies the attempt and cannot vary the -/// draw. `affordance` is the id carried by the kernel-verified grant, so the -/// draw cannot be steered by an affordance the actor does not hold. +/// The band draw's whole preimage. Five fields. `command_id` is derived from +/// the world, the expected revision, the caller and the whole body, so the +/// payload does reach the draw through it: changing the speech or display text, +/// a magnitude or the revision re-rolls the band, and a proposer who can vary +/// those can grind for a band. That is not an authority hole: only Play submits +/// an act after genesis, and Play is trusted. `affordance` is the id carried by +/// the kernel-verified grant, so the draw cannot be steered by an affordance the +/// actor does not hold. #[derive(Serialize)] struct BandPreimage { world_id: WorldId, diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs index 84ef74555..fef93ba24 100644 --- a/native/aetherlight/src/golden_tests.rs +++ b/native/aetherlight/src/golden_tests.rs @@ -9,16 +9,21 @@ use crate::tests::{ affordance_named, auth_principal, command, creation, first_grant, operations, owner, play_caller, play_command, speak, subject_by_label, submit_play, tick_body, }; +use crate::patch::{ + AffordanceDeclaration, AffordanceKindName, AudienceSpec, Declaration, DraftHandle, + OutcomeBand, Precondition, +}; use crate::{ AuthenticatedCaller, CommandBody, CommitmentKind, ComponentOp, DecisionInvocation, FictionalMinutes, KernelError, KnowledgeSource, Ref, Statement, TickMinutes, WorldEffect, - WorldKernel, + WorldKernel, WorldPatch, }; use sha2::{Digest, Sha256}; use std::time::Instant; /// The script: The Human speaks to The Witness, The Human shows a gesture, a -/// Routine is placed on The Witness, thirty minutes roll it, and The Human +/// two-band `toss` is declared, granted to The Human and used three times (so +/// the band draw is recorded), a Routine is placed on The Witness, thirty minutes roll it, and The Human /// invokes `convene`, which it does not hold. fn golden_session() -> (WorldKernel, String) { let (mut kernel, _) = WorldKernel::create(creation("Golden"), &auth_principal(owner())) @@ -66,6 +71,54 @@ fn golden_session() -> (WorldKernel, String) { }, ); + // A two-band entry: the one place the golden records a band draw. + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: vec![Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("toss"), + kind: AffordanceKindName("toss".into()), + roles: Vec::new(), + preconditions: vec![Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }], + effect_slots: Vec::new(), + outcome_bands: vec![ + OutcomeBand { weight: 1, effects: Vec::new() }, + OutcomeBand { weight: 1, effects: Vec::new() }, + ], + carries_speech: true, + })], + operations: vec![ComponentOp::GrantAffordance { + subject: Ref::Existing(human), + affordance: Ref::Draft(DraftHandle::new("toss")), + }], + evidence: Vec::new(), + }, + }, + ); + for _ in 0..3 { + let snapshot = kernel.snapshot().unwrap(); + let toss = affordance_named(&snapshot, "toss"); + submit_play( + &mut kernel, + &snapshot, + CommandBody::Act { + actor: human, + invocation: DecisionInvocation { + affordance: toss, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("Heads or tails.").unwrap()), + display: None, + }, + }, + ); + } + let snapshot = kernel.snapshot().unwrap(); submit_play( &mut kernel, @@ -107,7 +160,7 @@ fn golden_session() -> (WorldKernel, String) { ); assert!(matches!(refused, Err(KernelError::AffordanceDenied)), "{refused:?}"); assert_eq!(kernel.snapshot().unwrap(), before); - assert_eq!(kernel.journal.commit_count(), 5); + assert_eq!(kernel.journal.commit_count(), 9); let mut file = String::new(); for commit in kernel.journal.commits_for_test() { diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index e017095a5..f3414e4fe 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -55,6 +55,11 @@ impl WorldJournal { /// Decode canonically, then replay: the head state is whatever the chain /// derives, and a chain that does not verify is not a world. + /// + /// A chain verifies as a prefix, so an export with its tail dropped, or an + /// older export, opens as a valid shorter world. The holder of the bytes + /// owns the head: it keeps the revision and state digest from `snapshot()` + /// at export time and compares them after `open` (AL5's C# store). pub(super) fn open(bytes: &[u8]) -> Result<(Self, WorldState), JournalError> { let export: Export = decode(bytes)?; if export.schema != JOURNAL_SCHEMA { @@ -958,6 +963,61 @@ mod tests { )); } + /// A stored digest is checked against the commit it seals, on its own: + /// flipping one character of any commit's digest, with nothing re-sealed, + /// leaves only the digest clause to refuse it (the last commit and a lone + /// genesis have no successor whose previous-digest could). + #[test] + fn a_stored_digest_flipped_without_resealing_is_refused() { + let kernel = clock_history(); + let honest = kernel.journal.commits.clone(); + let flip = |digest: &str| { + let mut flipped = digest.to_owned(); + let last = flipped.pop().unwrap(); + flipped.push(if last == '0' { '1' } else { '0' }); + flipped + }; + for upto in 1..=honest.len() { + let mut chain = honest[..upto].to_vec(); + let tail = chain.last_mut().unwrap(); + tail.digest = flip(&tail.digest); + assert!( + matches!(reopen(&chain), Err(JournalError::Corrupt(_))), + "a flipped digest on commit {} of {upto} was admitted", + upto - 1 + ); + } + } + + /// Each clause of the genesis condition refuses alone: a lone genesis, + /// re-sealed after one field is rewritten, so nothing else can object. + #[test] + fn each_genesis_clause_refuses_on_its_own() { + let kernel = clock_history(); + let genesis = kernel.journal.commits[0].clone(); + let forgeries: [(&str, &dyn Fn(&mut WorldCommit)); 5] = [ + ("schema", &|commit| commit.schema = "ghostlight.world_commit.consumer.v10".into()), + ("a previous revision", &|commit| commit.previous_revision = Some(0)), + ("a nonzero revision", &|commit| commit.resulting_revision = 1), + ("a previous state digest", &|commit| { + commit.previous_state_digest = Some("sha256:00".into()) + }), + ("a previous commit digest", &|commit| { + commit.previous_commit_digest = Some("sha256:00".into()) + }), + ]; + reopen(std::slice::from_ref(&genesis)).expect("a lone honest genesis opens"); + for (what, forge) in forgeries { + let mut forged = genesis.clone(); + forge(&mut forged); + forged.digest = commit_digest(&forged).unwrap(); + assert!( + matches!(reopen(&[forged]), Err(JournalError::Corrupt(_))), + "a genesis with {what} was admitted" + ); + } + } + /// Position `i` holds resulting revision `i`: a commit that names a later /// revision than its place, with a state digest honestly computed for that /// revision, is still not the chain's next commit. diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index ee80dc982..b173dc6a6 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -245,6 +245,9 @@ struct CreateWorld { impl CreateWorld { /// The creation is named by its own bytes: equal creations are one command. + /// Host contract: two byte-equal creations share a `WorldId` and every id + /// derived under it, so a host that wants distinct worlds salts each run or + /// profile into the creation (for example a run seed in the patch). fn id(&self) -> CommandId { let mut hasher = Sha256::new(); hasher.update(CREATE_DOMAIN); From 993b7a2948c1d6e1ba2db01cef1ebe844125de1b Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 03:28:03 +0100 Subject: [PATCH 149/190] aetherlight: partitions become tracked documents, submit applies in place under an undo log Docs and Tracked<WorldHeader> record the first-touch value of every written key. submit applies to the live state between begin and finish and rolls back on any error, so the world is no longer cloned per commit; replay reads the commitments subjects finish() reports instead of cloning the partition. The encoding is unchanged: golden.digests is byte-identical. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/action.rs | 23 +- native/aetherlight/src/docs.rs | 185 ++++++++++ native/aetherlight/src/golden_tests.rs | 2 +- native/aetherlight/src/grammar/tests.rs | 6 +- native/aetherlight/src/import_key_tests.rs | 17 +- native/aetherlight/src/journal.rs | 48 +-- native/aetherlight/src/lib.rs | 382 +++++++++++++++------ native/aetherlight/src/patch.rs | 8 +- 8 files changed, 507 insertions(+), 164 deletions(-) create mode 100644 native/aetherlight/src/docs.rs diff --git a/native/aetherlight/src/action.rs b/native/aetherlight/src/action.rs index 0c9ac33a2..93758bac8 100644 --- a/native/aetherlight/src/action.rs +++ b/native/aetherlight/src/action.rs @@ -160,7 +160,7 @@ pub(super) fn exercise( } let band = select_band(state, command_id, granted.id, entry)?; - let operations = lower(entry, band, actor, state.now, invocation, &bindings)?; + let operations = lower(entry, band, actor, state.header.now, invocation, &bindings)?; let mut effects = if operations.is_empty() { Vec::new() } else { @@ -188,7 +188,7 @@ pub(super) fn exercise( (Some(statement), true) => { let fact = EntityId(patch::derive_id( patch::ENTITY_NAMESPACE, - state.world_id, + state.header.world_id, command_id, &patch::DraftHandle::new(SPEECH_HANDLE), Some(SPEECH_INDEX), @@ -221,7 +221,7 @@ pub(super) fn exercise( let display = invocation.display.as_ref().map(|statement| { let fact = EntityId(patch::derive_id( patch::ENTITY_NAMESPACE, - state.world_id, + state.header.world_id, command_id, &patch::DraftHandle::new(SPEECH_HANDLE), Some(DISPLAY_INDEX), @@ -780,7 +780,7 @@ fn select_band( entry: &Affordance, ) -> Result<usize, KernelError> { let draw = digest(&BandPreimage { - world_id: state.world_id, + world_id: state.header.world_id, revision: state.revision, command_id, affordance, @@ -1637,14 +1637,13 @@ mod tests { .any(|spec| spec.kind == RefKind::Subject(None)) ); - // The state row encoder and the digest owner are the same `to_vec_named` - // path the store writes through. - let encoded = rmp_serde::to_vec_named(&bench.kernel.state).expect("the state encodes"); - let decoded: WorldState = rmp_serde::from_slice(&encoded).expect("the state decodes"); - assert_eq!( - decoded.affordance_catalog, - bench.kernel.state.affordance_catalog - ); + // The affordance document round-trips through the `to_vec_named` path the + // state digest hashes. + let catalog = rmp_serde::to_vec_named(&bench.kernel.state.affordance_catalog) + .expect("the affordance document encodes"); + let decoded: std::collections::BTreeMap<_, crate::Affordance> = + rmp_serde::from_slice(&catalog).expect("the affordance document decodes"); + assert_eq!(decoded, *bench.kernel.state.affordance_catalog); assert!(digest(&bench.kernel.state).is_ok()); } diff --git a/native/aetherlight/src/docs.rs b/native/aetherlight/src/docs.rs new file mode 100644 index 000000000..ef873c47d --- /dev/null +++ b/native/aetherlight/src/docs.rs @@ -0,0 +1,185 @@ +//! Tracked documents: the one writer of a partition and the one recorder of +//! what a transaction changed. +//! +//! A `Docs` is a map whose every write goes through a method that remembers the +//! key's value as it stood before the transaction (first touch wins). `finish` +//! turns that record into the keys whose value really changed, with their old +//! values; `rollback` puts every touched key back. Reads see the plain map +//! through `Deref`, and there is no `DerefMut`, so a write cannot skip the log. +//! The fields are private to this module for the same reason. + +use serde::{Serialize, Serializer}; +use std::collections::BTreeMap; +use std::collections::btree_map::Entry; +use std::ops::Deref; + +/// A key whose value changed in a transaction, with the value it had before +/// (`None` when the key was absent). The new value is whatever the map holds. +pub(crate) type Changed<K, V> = (K, Option<V>); + +#[derive(Clone, Debug)] +pub(crate) struct Docs<K: Ord + Clone, V: Clone + PartialEq> { + map: BTreeMap<K, V>, + touched: BTreeMap<K, Option<V>>, +} + +impl<K: Ord + Clone, V: Clone + PartialEq> Default for Docs<K, V> { + fn default() -> Self { + Self { + map: BTreeMap::new(), + touched: BTreeMap::new(), + } + } +} + +/// Equality is the documents, never the log: two worlds with the same content +/// are equal whatever transaction state they are in. +impl<K: Ord + Clone, V: Clone + PartialEq> PartialEq for Docs<K, V> { + fn eq(&self, other: &Self) -> bool { + self.map == other.map + } +} + +impl<K: Ord + Clone, V: Clone + PartialEq + Eq> Eq for Docs<K, V> {} + +impl<K: Ord + Clone, V: Clone + PartialEq> Deref for Docs<K, V> { + type Target = BTreeMap<K, V>; + fn deref(&self) -> &BTreeMap<K, V> { + &self.map + } +} + +impl<'a, K: Ord + Clone, V: Clone + PartialEq> IntoIterator for &'a Docs<K, V> { + type Item = (&'a K, &'a V); + type IntoIter = std::collections::btree_map::Iter<'a, K, V>; + fn into_iter(self) -> Self::IntoIter { + self.map.iter() + } +} + +/// A partition encodes as its map, so the encoded world is what it was before +/// the partitions were tracked. +impl<K: Ord + Clone + Serialize, V: Clone + PartialEq + Serialize> Serialize for Docs<K, V> { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + self.map.serialize(serializer) + } +} + +impl<K: Ord + Clone, V: Clone + PartialEq> Docs<K, V> { + fn touch(&mut self, key: &K) { + if !self.touched.contains_key(key) { + self.touched.insert(key.clone(), self.map.get(key).cloned()); + } + } + + pub(crate) fn insert(&mut self, key: K, value: V) -> Option<V> { + self.touch(&key); + self.map.insert(key, value) + } + + pub(crate) fn remove(&mut self, key: &K) -> Option<V> { + self.touch(key); + self.map.remove(key) + } + + /// Touches only a key that is present: a miss writes nothing. + pub(crate) fn get_mut(&mut self, key: &K) -> Option<&mut V> { + if self.map.contains_key(key) { + self.touch(key); + } + self.map.get_mut(key) + } + + pub(crate) fn entry(&mut self, key: K) -> Entry<'_, K, V> { + self.touch(&key); + self.map.entry(key) + } + + /// The keys whose value differs from the start of the transaction, with the + /// value they had then. A key written back to what it was is not reported. + /// The log is empty afterwards. + pub(crate) fn finish(&mut self) -> Vec<Changed<K, V>> { + std::mem::take(&mut self.touched) + .into_iter() + .filter(|(key, old)| self.map.get(key) != old.as_ref()) + .collect() + } + + /// Puts every touched key back as it was and empties the log. + pub(crate) fn rollback(&mut self) { + for (key, old) in std::mem::take(&mut self.touched) { + match old { + Some(value) => { + self.map.insert(key, value); + } + None => { + self.map.remove(&key); + } + } + } + } + + pub(crate) fn is_clean(&self) -> bool { + self.touched.is_empty() + } +} + +/// One tracked value: the same first-touch rule as a `Docs` key, for the +/// world's own fields. +#[derive(Clone, Debug)] +pub(crate) struct Tracked<T: Clone + PartialEq> { + value: T, + /// `None` untouched; `Some(None)` logged as absent (genesis), so `finish` + /// reports it as added. + old: Option<Option<T>>, +} + +impl<T: Clone + PartialEq> PartialEq for Tracked<T> { + fn eq(&self, other: &Self) -> bool { + self.value == other.value + } +} + +impl<T: Clone + PartialEq + Eq> Eq for Tracked<T> {} + +impl<T: Clone + PartialEq> Deref for Tracked<T> { + type Target = T; + fn deref(&self) -> &T { + &self.value + } +} + +impl<T: Clone + PartialEq> Tracked<T> { + /// A value that did not exist before this transaction. + pub(crate) fn absent(value: T) -> Self { + Self { + value, + old: Some(None), + } + } + + pub(crate) fn get_mut(&mut self) -> &mut T { + if self.old.is_none() { + self.old = Some(Some(self.value.clone())); + } + &mut self.value + } + + /// The old value when the value changed (`Some(None)`: it was absent). + pub(crate) fn finish(&mut self) -> Option<Option<T>> { + match self.old.take() { + Some(old) if old.as_ref() != Some(&self.value) => Some(old), + _ => None, + } + } + + pub(crate) fn rollback(&mut self) { + if let Some(Some(old)) = self.old.take() { + self.value = old; + } + } + + pub(crate) fn is_clean(&self) -> bool { + self.old.is_none() + } +} diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs index fef93ba24..e1138bd39 100644 --- a/native/aetherlight/src/golden_tests.rs +++ b/native/aetherlight/src/golden_tests.rs @@ -281,7 +281,7 @@ fn clockwork_commit_cost() { .collect(); let play = AuthenticatedCaller::verified_play(); let envelope = |kernel: &WorldKernel, body: CommandBody| CommandEnvelope { - world_id: kernel.state.world_id, + world_id: kernel.state.header.world_id, expected_revision: kernel.state.revision, caller: CallerId::Play, body, diff --git a/native/aetherlight/src/grammar/tests.rs b/native/aetherlight/src/grammar/tests.rs index c7486841e..e59df991c 100644 --- a/native/aetherlight/src/grammar/tests.rs +++ b/native/aetherlight/src/grammar/tests.rs @@ -352,9 +352,9 @@ fn the_bound_grammar_is_part_of_the_world_state_digest() { let kernel = kernel.unwrap(); let bound_digest = crate::state_digest(&kernel.state).unwrap(); let mut state = kernel.state.clone(); - state.grammar = None; + state.header.get_mut().grammar = None; let open_digest = crate::state_digest(&state).unwrap(); - state.grammar = Some(grammar_with(&[("dock", verb(RenderPath::ShipAction, &[]))])); + state.header.get_mut().grammar = Some(grammar_with(&[("dock", verb(RenderPath::ShipAction, &[]))])); let other_digest = crate::state_digest(&state).unwrap(); assert_ne!(bound_digest, open_digest); assert_ne!(bound_digest, other_digest); @@ -621,7 +621,7 @@ fn an_effect_resolved_elsewhere_cannot_install_an_entry_outside_the_grammar() { let kernel = create(bound(Some(grammar_with(&extra)), "Forged")); let kernel = kernel.unwrap(); let mut twin = kernel.state.clone(); - twin.grammar = None; + twin.header.get_mut().grammar = None; let resolve = |kind: &str, roles: &[(&str, RefKind)]| { crate::patch::resolve_patch( &twin, diff --git a/native/aetherlight/src/import_key_tests.rs b/native/aetherlight/src/import_key_tests.rs index 4d217c586..40914edc3 100644 --- a/native/aetherlight/src/import_key_tests.rs +++ b/native/aetherlight/src/import_key_tests.rs @@ -450,22 +450,16 @@ fn keyless_world_digests_unchanged() { !contains(&state, b"import_key"), "a keyless world grew a field" ); - // A keyed world carries it, round-trips, and digests differently. + // A keyed world carries it and digests differently. let keyed = keyed_world(); let keyed_state = rmp_serde::to_vec_named(&keyed.state).unwrap(); assert!(contains(&keyed_state, b"import_key")); - let back: crate::WorldState = rmp_serde::from_slice(&keyed_state).unwrap(); - assert_eq!( - crate::state_digest(&back).unwrap(), - crate::state_digest(&keyed.state).unwrap() - ); assert_ne!( crate::state_digest(&keyed.state).unwrap(), crate::state_digest(&kernel.state).unwrap() ); - // And a pre-key state deserialises with every key absent. - let stripped: crate::WorldState = rmp_serde::from_slice(&state).unwrap(); - assert!(stripped.subjects.values().all(|s| s.import_key.is_none())); + // And a world nobody imported into holds every key absent. + assert!(kernel.state.subjects.values().all(|s| s.import_key.is_none())); } #[test] @@ -571,8 +565,9 @@ fn a_loaded_state_with_a_bad_import_key_is_refused() { assert!(crate::journal::verify_state_shape(&kernel.state).is_ok()); let corrupt = |edit: &dyn Fn(&mut ImportKey)| { let mut state = kernel.state.clone(); - for subject in state.subjects.values_mut() { - if let Some(held) = subject.import_key.as_mut() { + let ids: Vec<_> = state.subjects.keys().copied().collect(); + for id in ids { + if let Some(held) = state.subjects.get_mut(&id).and_then(|s| s.import_key.as_mut()) { edit(held); } } diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index f3414e4fe..aea378de6 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -1,7 +1,8 @@ use super::{ - COMMIT_SCHEMA, CommittedCommand, KernelError, STATE_SCHEMA, WorldCommit, WorldEffect, + COMMIT_SCHEMA, CommittedCommand, KernelError, WorldCommit, WorldEffect, WorldId, WorldState, apply_effect, commit_digest, reduce, state_digest, }; +use crate::docs::Changed; use serde::{Deserialize, Serialize, de::DeserializeOwned}; use std::collections::{BTreeMap, BTreeSet}; use thiserror::Error; @@ -121,7 +122,8 @@ pub(super) fn verify_history(commits: &[WorldCommit]) -> Result<WorldState, Jour let mut replay = WorldState::genesis(genesis.world_id, genesis_command, &genesis.effect) .map_err(kernel_error)?; verify_state_shape(&replay)?; - verify_commitments_are_future(&replay, &BTreeMap::new())?; + let born: Vec<_> = replay.commitments.keys().map(|subject| (*subject, None)).collect(); + verify_commitments_are_future(&replay, &born)?; if replay.state_digest != genesis.resulting_state_digest { return Err(JournalError::Corrupt( "genesis resulting state digest is invalid".into(), @@ -131,7 +133,7 @@ pub(super) fn verify_history(commits: &[WorldCommit]) -> Result<WorldState, Jour for commit in &commits[1..] { if commit.schema != COMMIT_SCHEMA - || commit.world_id != replay.world_id + || commit.world_id != replay.header.world_id || commit.previous_revision != Some(replay.revision) || commit.resulting_revision != replay.revision.saturating_add(1) || commit.previous_state_digest.as_deref() != Some(replay.state_digest.as_str()) @@ -142,8 +144,7 @@ pub(super) fn verify_history(commits: &[WorldCommit]) -> Result<WorldState, Jour "commit chain is not contiguous or verifiable".into(), )); } - let previous_now = replay.now; - let previous_commitments = replay.commitments.clone(); + let previous_now = replay.header.now; // Authority is re-decided here for free: `apply_committed_command` // re-runs `reduce` against the pre-commit state and requires effect // equality, then `apply_effect`, and both of those call @@ -151,16 +152,18 @@ pub(super) fn verify_history(commits: &[WorldCommit]) -> Result<WorldState, Jour // a post-genesis command fails replay rather than being admitted by a // reducer that trusts the recorded caller. A third statement of the same rule here would be a // third owner of one decision. + replay.begin(); apply_committed_command(&mut replay, commit)?; // Two chain checks one state cannot make: the clock never runs // backwards, and it advances only on a tick. let advanced = matches!(commit.effect, WorldEffect::TimeAdvanced { .. }); - if replay.now < previous_now || (replay.now > previous_now) != advanced { + if replay.header.now < previous_now || (replay.header.now > previous_now) != advanced { return Err(JournalError::Corrupt( "the world clock moved without a time-advanced commit, or ran backwards".into(), )); } - verify_commitments_are_future(&replay, &previous_commitments)?; + let touched = replay.finish(); + verify_commitments_are_future(&replay, &touched)?; replay.revision = commit.resulting_revision; replay.state_digest = state_digest(&replay).map_err(kernel_error)?; if replay.state_digest != commit.resulting_state_digest { @@ -176,17 +179,21 @@ pub(super) fn verify_history(commits: &[WorldCommit]) -> Result<WorldState, Jour /// The replay-side twin of `Mismatch::CommitmentDueInThePast`: every commitment /// key this commit introduced is due after the post-commit clock. Replay already -/// reconstructs both sides, so this is a set difference over one partition. +/// reconstructs both sides, and the transaction's change set names the only subjects +/// that can hold a new key, with what each held before. fn verify_commitments_are_future( state: &WorldState, - before: &BTreeMap<super::SubjectId, BTreeMap<super::CommitmentKey, super::Commitment>>, + touched: &[Changed<super::SubjectId, BTreeMap<super::CommitmentKey, super::Commitment>>], ) -> Result<(), JournalError> { - for (subject_id, held) in &state.commitments { + for (subject_id, before) in touched { + let Some(held) = state.commitments.get(subject_id) else { + continue; + }; for (key, commitment) in held { let existed = before - .get(subject_id) + .as_ref() .is_some_and(|previous| previous.contains_key(key)); - if !existed && commitment.due <= state.now { + if !existed && commitment.due <= state.header.now { return Err(JournalError::Corrupt( "a commitment was born at or after its own due date".into(), )); @@ -197,15 +204,12 @@ fn verify_commitments_are_future( } pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> { - if state.schema != STATE_SCHEMA { - return Err(JournalError::Corrupt("invalid state schema".into())); - } - if state.title.trim().is_empty() || state.title.trim() != state.title { + if state.header.title.trim().is_empty() || state.header.title.trim() != state.header.title { return Err(JournalError::Corrupt( "world title is empty or noncanonical".into(), )); } - super::validate_principal(&state.owner).map_err(kernel_error)?; + super::validate_principal(&state.header.owner).map_err(kernel_error)?; if state.subjects.is_empty() { return Err(JournalError::Corrupt("world ontology is empty".into())); } @@ -613,7 +617,7 @@ fn apply_committed_command( "creation command appears after world genesis".into(), )); }; - if command.world_id != state.world_id || command.expected_revision != state.revision { + if command.world_id != state.header.world_id || command.expected_revision != state.revision { return Err(JournalError::Corrupt( "committed command does not target the exact replay state".into(), )); @@ -894,14 +898,14 @@ mod tests { let kernel = clock_history(); let replayed = reopen(&kernel.journal.commits).expect("the honest history replays"); assert_eq!(replayed.state_digest, kernel.state.state_digest); - assert_eq!(replayed.now, kernel.state.now); + assert_eq!(replayed.header.now, kernel.state.header.now); - let (digest, now) = (kernel.state.state_digest.clone(), kernel.state.now); + let (digest, now) = (kernel.state.state_digest.clone(), kernel.state.header.now); let exported = kernel.export().unwrap(); drop(kernel); let reopened = WorldKernel::open(&exported).unwrap(); assert_eq!(reopened.state.state_digest, digest); - assert_eq!(reopened.state.now, now); + assert_eq!(reopened.state.header.now, now); } /// An export is a claim about a chain, and `open` believes none of it that @@ -1806,7 +1810,7 @@ mod custody_tests { verify_state_shape(&kernel.state).expect("a canonical title passes"); for title in ["", " ", " Titled", "Titled "] { let mut forged = kernel.state.clone(); - forged.title = title.into(); + forged.header.get_mut().title = title.into(); assert!( matches!(verify_state_shape(&forged), Err(JournalError::Corrupt(_))), "title {title:?} passed the shape check" diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index b173dc6a6..f6bc8b3ea 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -58,6 +58,7 @@ mod action; mod clock; +mod docs; #[cfg(test)] mod golden_tests; mod grammar; @@ -98,6 +99,7 @@ pub(crate) use patch::{ }; use patch::{EdgeRecord, EntityRecord, LedgerDelta, ResolvedOp, ResolvedPatch}; +use docs::{Changed, Docs, Tracked}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet}; @@ -426,70 +428,76 @@ pub(crate) struct DecisionEvent { pub(crate) effects: Vec<ResolvedOp>, } -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -struct WorldState { - schema: String, +/// The world's own fields: the one document that is not a map row. Tracked like +/// a partition key, so a tick that advances the clock is one changed document. +#[derive(Clone, Debug, PartialEq, Eq)] +struct WorldHeader { world_id: WorldId, - revision: u64, owner: PrincipalId, title: String, /// Bound by genesis and never written again; absent from a world with no /// grammar, so such a world's state and digests are what they were before /// grammars existed. - #[serde(default, skip_serializing_if = "Option::is_none")] grammar: Option<GrammarBinding>, - subjects: BTreeMap<SubjectId, SubjectState>, - entities: BTreeMap<EntityId, EntityRecord>, - edges: BTreeMap<EdgeId, EdgeRecord>, - positions: BTreeMap<SubjectId, Position>, + /// Minutes since genesis. The world's only clock, advanced by exactly one + /// command body and read by no wall clock. It is world truth, and it is + /// read by no precondition. + now: FictionalMinutes, +} + +/// Every partition is a `Docs`: reads see the map, every write is logged, and +/// `submit` applies in place and either finishes or rolls the log back. +#[derive(Clone, Debug, PartialEq, Eq)] +struct WorldState { + header: Tracked<WorldHeader>, + revision: u64, + subjects: Docs<SubjectId, SubjectState>, + entities: Docs<EntityId, EntityRecord>, + edges: Docs<EdgeId, EdgeRecord>, + positions: Docs<SubjectId, Position>, /// What each subject holds. Absence is zero at both levels: no stored /// `Quantity(0)` and no empty inner map, so a duplicate holding is /// unrepresentable and "nothing" has one shape. - holdings: BTreeMap<SubjectId, BTreeMap<EntityId, Quantity>>, + holdings: Docs<SubjectId, BTreeMap<EntityId, Quantity>>, /// What each subject depends on. Never empty for a present key. - dependencies: BTreeMap<SubjectId, BTreeSet<DependencyTarget>>, + dependencies: Docs<SubjectId, BTreeSet<DependencyTarget>>, /// One row per `EntityKind::Fact` entity, and no orphan either way. Facts /// are write-once: declaration and `AssertClaim` are the only writers, and /// standing never changes after admission. - facts: BTreeMap<EntityId, FactRecord>, + facts: Docs<EntityId, FactRecord>, /// One row per `EntityKind::Channel` entity, and no orphan either way. - channels: BTreeMap<EntityId, ChannelRecord>, + channels: Docs<EntityId, ChannelRecord>, /// What each subject knows. The sole owner of who-heard-what: `events` /// records what was done, and this decides what a subject may act on and /// what its projection may contain. Never empty for a present key, and /// absence is "knows nothing of it" — forgetting removes the key. - knowledge: BTreeMap<SubjectId, BTreeMap<EntityId, Knowledge>>, + knowledge: Docs<SubjectId, BTreeMap<EntityId, Knowledge>>, /// What ground each subject has jurisdiction over, and under which /// world-declared kind. Never empty for a present key. No subject holds two /// grants of one kind over overlapping ground, so nothing ever arbitrates /// between two sources of one permission. - authority: BTreeMap<SubjectId, BTreeSet<AuthorityGrant>>, + authority: Docs<SubjectId, BTreeSet<AuthorityGrant>>, /// The offices each institution constitutes, and who sits in them. An /// incumbent never acts as its institution: an office answers what its /// incumbent has jurisdiction over, not who the actor is. - selection: BTreeMap<SubjectId, BTreeMap<OfficeName, Office>>, + selection: Docs<SubjectId, BTreeMap<OfficeName, Office>>, /// Where each kind of grievance goes, and who may bring it. Keyed by /// neither a subject nor a referent, so it enters no scope components and /// is admission-only state. - redress: BTreeMap<GrievanceKindName, Forum>, + redress: Docs<GrievanceKindName, Forum>, /// What each subject has promised. Never empty for a present key. - commitments: BTreeMap<SubjectId, BTreeMap<CommitmentKey, Commitment>>, - /// Lived meaning per subject. Read by projection and by nothing that - /// decides, so it enters `state_digest` and no scope. + commitments: Docs<SubjectId, BTreeMap<CommitmentKey, Commitment>>, /// Pressure *on* each subject, keyed target-major then source. Never empty - /// for a present key; no stored zero magnitude. - pressures: BTreeMap<SubjectId, BTreeMap<PressureSource, PressureMagnitude>>, - /// Minutes since genesis. The world's only clock, advanced by exactly one - /// command body and read by no wall clock. It enters `state_digest` and no - /// scope: it is world truth, and it is read by no precondition. - now: FictionalMinutes, + /// for a present key; no stored zero magnitude. Lived meaning: read by + /// projection and by nothing that decides. + pressures: Docs<SubjectId, BTreeMap<PressureSource, PressureMagnitude>>, /// What an affordance *is*. World-authored and written by `admit_resolved` /// alone. - affordance_catalog: BTreeMap<AffordanceId, Affordance>, + affordance_catalog: Docs<AffordanceId, Affordance>, /// Who may exercise which entry: a row exists if and only if the subject /// holds at least one verb. A grant carries no payload, so a duplicate /// grant is unrepresentable rather than checked. - affordance_grants: BTreeMap<SubjectId, BTreeSet<AffordanceId>>, + affordance_grants: Docs<SubjectId, BTreeSet<AffordanceId>>, events: Vec<DecisionEvent>, state_digest: String, last_commit_digest: Option<String>, @@ -972,7 +980,7 @@ impl WorldKernel { authenticated: &AuthenticatedCaller, ) -> Result<CommitReceipt, KernelError> { let command_id = command.id(); - if command.world_id != self.state.world_id { + if command.world_id != self.state.header.world_id { return Err(KernelError::WorldMismatch); } if command.caller != authenticated.caller { @@ -986,32 +994,47 @@ impl WorldKernel { } let effect = reduce(&self.state, &command)?; - let mut candidate = self.state.clone(); - apply_effect(&mut candidate, command_id, &command.caller, &effect)?; - candidate.revision = candidate - .revision - .checked_add(1) - .ok_or_else(|| KernelError::Serialization("world revision overflow".into()))?; - candidate.state_digest = state_digest(&candidate)?; - - let mut commit = WorldCommit { - schema: COMMIT_SCHEMA.into(), - world_id: self.state.world_id, - command: CommittedCommand::WorldCommand(command), - previous_revision: Some(self.state.revision), - resulting_revision: candidate.revision, - previous_state_digest: Some(self.state.state_digest.clone()), - resulting_state_digest: candidate.state_digest.clone(), - previous_commit_digest: self.state.last_commit_digest.clone(), - effect, - digest: String::new(), + let previous_revision = self.state.revision; + let previous_state_digest = self.state.state_digest.clone(); + let previous_commit_digest = self.state.last_commit_digest.clone(); + // Applied in place under the partitions' undo logs: the world is never + // cloned, and any failure up to the sealed commit puts it back. + self.state.begin(); + let sealed = (|| -> Result<WorldCommit, KernelError> { + apply_effect(&mut self.state, command_id, &command.caller, &effect)?; + self.state.revision = previous_revision + .checked_add(1) + .ok_or_else(|| KernelError::Serialization("world revision overflow".into()))?; + self.state.state_digest = state_digest(&self.state)?; + let mut commit = WorldCommit { + schema: COMMIT_SCHEMA.into(), + world_id: self.state.header.world_id, + command: CommittedCommand::WorldCommand(command), + previous_revision: Some(previous_revision), + resulting_revision: self.state.revision, + previous_state_digest: Some(previous_state_digest.clone()), + resulting_state_digest: self.state.state_digest.clone(), + previous_commit_digest, + effect, + digest: String::new(), + }; + commit.digest = commit_digest(&commit)?; + Ok(commit) + })(); + let commit = match sealed { + Ok(commit) => commit, + Err(error) => { + self.state.rollback(); + self.state.revision = previous_revision; + self.state.state_digest = previous_state_digest; + return Err(error); + } }; - commit.digest = commit_digest(&commit)?; - candidate.last_commit_digest = Some(commit.digest.clone()); + self.state.finish(); + self.state.last_commit_digest = Some(commit.digest.clone()); let receipt = CommitReceipt::from(&commit); self.journal.append(commit); - self.state = candidate; Ok(receipt) } @@ -1034,7 +1057,7 @@ fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result<WorldEffect, } CommandBody::AdvanceTime { minutes } => { let to = state - .now + .header.now .checked_add(*minutes) .ok_or_else(|| KernelError::Serialization("world clock overflow".into()))?; // A tick with an empty motion is still a commit: the clock moved, @@ -1073,6 +1096,129 @@ fn is_genesis(revision: u64, subjects: &BTreeMap<SubjectId, SubjectState>) -> bo revision == 0 && subjects.is_empty() } +impl WorldState { + /// The encoding the state digest has always hashed: every partition as its + /// map, in this order. `sealed` false writes the chain head (the two digest + /// fields) as blank, the form the state digest is taken over. + fn write_encoded<S: serde::Serializer>( + &self, + serializer: S, + sealed: bool, + ) -> Result<S::Ok, S::Error> { + use serde::ser::SerializeStruct; + let header = &*self.header; + let fields = if header.grammar.is_some() { 26 } else { 25 }; + let mut out = serializer.serialize_struct("WorldState", fields)?; + out.serialize_field("schema", STATE_SCHEMA)?; + out.serialize_field("world_id", &header.world_id)?; + out.serialize_field("revision", &self.revision)?; + out.serialize_field("owner", &header.owner)?; + out.serialize_field("title", &header.title)?; + if header.grammar.is_some() { + out.serialize_field("grammar", &header.grammar)?; + } + out.serialize_field("subjects", &self.subjects)?; + out.serialize_field("entities", &self.entities)?; + out.serialize_field("edges", &self.edges)?; + out.serialize_field("positions", &self.positions)?; + out.serialize_field("holdings", &self.holdings)?; + out.serialize_field("dependencies", &self.dependencies)?; + out.serialize_field("facts", &self.facts)?; + out.serialize_field("channels", &self.channels)?; + out.serialize_field("knowledge", &self.knowledge)?; + out.serialize_field("authority", &self.authority)?; + out.serialize_field("selection", &self.selection)?; + out.serialize_field("redress", &self.redress)?; + out.serialize_field("commitments", &self.commitments)?; + out.serialize_field("pressures", &self.pressures)?; + out.serialize_field("now", &header.now)?; + out.serialize_field("affordance_catalog", &self.affordance_catalog)?; + out.serialize_field("affordance_grants", &self.affordance_grants)?; + out.serialize_field("events", &self.events)?; + if sealed { + out.serialize_field("state_digest", &self.state_digest)?; + out.serialize_field("last_commit_digest", &self.last_commit_digest)?; + } else { + out.serialize_field("state_digest", "")?; + out.serialize_field("last_commit_digest", &None::<String>)?; + } + out.end() + } + + /// Opens a transaction. Every log must be empty: a write outside a + /// transaction, or a transaction left open, is a bug here and not state. + fn begin(&self) { + debug_assert!(self.header.is_clean(), "a transaction is open"); + debug_assert!(self.subjects.is_clean() && self.entities.is_clean()); + debug_assert!(self.edges.is_clean() && self.positions.is_clean()); + debug_assert!(self.holdings.is_clean() && self.dependencies.is_clean()); + debug_assert!(self.facts.is_clean() && self.channels.is_clean()); + debug_assert!(self.knowledge.is_clean() && self.authority.is_clean()); + debug_assert!(self.selection.is_clean() && self.redress.is_clean()); + debug_assert!(self.commitments.is_clean() && self.pressures.is_clean()); + debug_assert!(self.affordance_catalog.is_clean() && self.affordance_grants.is_clean()); + } + + /// Closes the transaction, keeping its writes. Returns the commitments + /// subjects that changed, with their old promises, for replay's check that + /// every commitment stays in the future. + fn finish(&mut self) -> Vec<Changed<SubjectId, BTreeMap<CommitmentKey, Commitment>>> { + self.header.finish(); + self.subjects.finish(); + self.entities.finish(); + self.edges.finish(); + self.positions.finish(); + self.holdings.finish(); + self.dependencies.finish(); + self.facts.finish(); + self.channels.finish(); + self.knowledge.finish(); + self.authority.finish(); + self.selection.finish(); + self.redress.finish(); + self.pressures.finish(); + self.affordance_catalog.finish(); + self.affordance_grants.finish(); + self.commitments.finish() + } + + /// Closes the transaction, undoing every write in it. + fn rollback(&mut self) { + self.header.rollback(); + self.subjects.rollback(); + self.entities.rollback(); + self.edges.rollback(); + self.positions.rollback(); + self.holdings.rollback(); + self.dependencies.rollback(); + self.facts.rollback(); + self.channels.rollback(); + self.knowledge.rollback(); + self.authority.rollback(); + self.selection.rollback(); + self.redress.rollback(); + self.commitments.rollback(); + self.pressures.rollback(); + self.affordance_catalog.rollback(); + self.affordance_grants.rollback(); + } +} + +impl Serialize for WorldState { + fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + self.write_encoded(serializer, true) + } +} + +/// The state with its chain head blanked: what `state_digest` hashes. +struct Unsealed<'a>(&'a WorldState); + +impl Serialize for Unsealed<'_> { + fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + self.0.write_encoded(serializer, false) + } +} + impl WorldState { /// The world before any structure. Genesis resolves its own patch against /// this value, so the genesis lane and `AdmitPatch` share one resolver @@ -1084,29 +1230,30 @@ impl WorldState { grammar: Option<GrammarBinding>, ) -> Self { Self { - schema: STATE_SCHEMA.into(), - world_id, + header: Tracked::absent(WorldHeader { + world_id, + owner, + title, + grammar, + now: FictionalMinutes::default(), + }), revision: 0, - owner, - title, - grammar, - subjects: BTreeMap::new(), - entities: BTreeMap::new(), - edges: BTreeMap::new(), - positions: BTreeMap::new(), - holdings: BTreeMap::new(), - dependencies: BTreeMap::new(), - facts: BTreeMap::new(), - channels: BTreeMap::new(), - knowledge: BTreeMap::new(), - authority: BTreeMap::new(), - selection: BTreeMap::new(), - redress: BTreeMap::new(), - commitments: BTreeMap::new(), - pressures: BTreeMap::new(), - now: FictionalMinutes::default(), - affordance_catalog: BTreeMap::new(), - affordance_grants: BTreeMap::new(), + subjects: Docs::default(), + entities: Docs::default(), + edges: Docs::default(), + positions: Docs::default(), + holdings: Docs::default(), + dependencies: Docs::default(), + facts: Docs::default(), + channels: Docs::default(), + knowledge: Docs::default(), + authority: Docs::default(), + selection: Docs::default(), + redress: Docs::default(), + commitments: Docs::default(), + pressures: Docs::default(), + affordance_catalog: Docs::default(), + affordance_grants: Docs::default(), events: Vec::new(), state_digest: String::new(), last_commit_digest: None, @@ -1158,6 +1305,7 @@ impl WorldState { // unlike every later commit, which resolves to `state.revision + 1`. let genesis_revision = state.revision; admit_resolved(&mut state, resolved, genesis_revision)?; + state.finish(); state.state_digest = state_digest(&state)?; Ok(state) } @@ -1239,7 +1387,7 @@ fn admit_resolved( // The catalog's only writer holds the same grammar check the resolver // runs, so an effect resolved elsewhere cannot install an entry the // bound grammar refuses. - if state.grammar.as_ref().is_some_and(|grammar| { + if state.header.grammar.as_ref().is_some_and(|grammar| { grammar .refusal(&entry.affordance.kind, &entry.affordance.roles) .is_some() @@ -2188,10 +2336,21 @@ fn apply_operation( subject: *subject, key: *key, }; - state.pressures.retain(|_, held| { - held.remove(&sourced); - !held.is_empty() - }); + let holding: Vec<SubjectId> = state + .pressures + .iter() + .filter(|(_, held)| held.contains_key(&sourced)) + .map(|(target, _)| *target) + .collect(); + for target in holding { + let emptied = state.pressures.get_mut(&target).is_some_and(|held| { + held.remove(&sourced); + held.is_empty() + }); + if emptied { + state.pressures.remove(&target); + } + } } ResolvedOp::AdvancePressure { source, target, by } | ResolvedOp::ReducePressure { source, target, by } => { @@ -2315,7 +2474,7 @@ fn commitment_is_live(state: &WorldState, subject: SubjectId, commitment: &Commi counterparty_is_live && (commitment.kind == CommitmentKind::Routine) == commitment.period.is_some() && (commitment.kind == CommitmentKind::Routine || commitment.checks.is_empty()) - && commitment.due > state.now + && commitment.due > state.header.now && commitment .checks .iter() @@ -2900,7 +3059,7 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> { due: commitment.due, period: commitment.period, statement: commitment.statement.clone(), - past_due: commitment.due <= state.now, + past_due: commitment.due <= state.header.now, }) .collect(), dependencies: components.dependencies.iter().copied().collect(), @@ -2987,11 +3146,11 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> { }) .collect(); Ok(WorldSnapshot { - world_id: state.world_id, + world_id: state.header.world_id, revision: state.revision, - owner: state.owner.clone(), - title: state.title.clone(), - grammar: state.grammar.as_ref().map(GrammarBinding::identity), + owner: state.header.owner.clone(), + title: state.header.title.clone(), + grammar: state.header.grammar.as_ref().map(GrammarBinding::identity), subjects, affordances: state .affordance_catalog @@ -3000,7 +3159,7 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> { id: *affordance_id, entry: entry.clone(), render_path: state - .grammar + .header.grammar .as_ref() .and_then(|grammar| grammar.verb(&entry.kind.0)) .map(|verb| verb.render_path), @@ -3011,7 +3170,7 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> { routes, channels, facts, - now: state.now, + now: state.header.now, state_digest: state.state_digest.clone(), last_commit_digest: state.last_commit_digest.clone(), }) @@ -3140,13 +3299,14 @@ fn apply_effect( "acted effect does not derive from the actor's grants".into(), )); } - state.events.push(event.clone()); if !event.effects.is_empty() { // `derived != *event` above already proved `event.revision` is // exactly what `resolution_revision(state)` would compute right // now; read it back rather than computing it a second time. apply_operations(state, &event.effects, &[], event.revision)?; } + // After the writes, so a failed apply leaves nothing to undo here. + state.events.push(event.clone()); } WorldEffect::TimeAdvanced { minutes, @@ -3154,7 +3314,7 @@ fn apply_effect( motion, } => { let derived_to = state - .now + .header.now .checked_add(*minutes) .ok_or_else(|| KernelError::Serialization("world clock overflow".into()))?; // The whole motion is re-derived rather than trusted field by @@ -3165,7 +3325,7 @@ fn apply_effect( "time effect does not derive from the world clock".into(), )); } - state.now = *to; + state.header.get_mut().now = *to; for rolled in &motion.fulfilled { let commitment = state .commitments @@ -3197,10 +3357,7 @@ fn digest<T: Serialize>(value: &T) -> Result<String, KernelError> { } fn state_digest(state: &WorldState) -> Result<String, KernelError> { - let mut value = state.clone(); - value.state_digest.clear(); - value.last_commit_digest = None; - digest(&value) + digest(&Unsealed(state)) } fn commit_digest(commit: &WorldCommit) -> Result<String, KernelError> { @@ -4691,10 +4848,10 @@ mod tests { let (mut kernel, receipt) = create("Same"); let (twin, twin_receipt) = create("Same"); assert_eq!(receipt, twin_receipt); - assert_eq!(kernel.state.world_id, twin.state.world_id); + assert_eq!(kernel.state.header.world_id, twin.state.header.world_id); assert_eq!(receipt.world_id, WorldId::of(receipt.command_id)); let (other, _) = create("Other"); - assert_ne!(kernel.state.world_id, other.state.world_id); + assert_ne!(kernel.state.header.world_id, other.state.header.world_id); // The same patch at two revisions is two commands, so the entity it // declares is minted twice under two ids. @@ -7108,7 +7265,7 @@ mod knowledge_tests { #[test] fn every_canonical_id_comes_from_one_of_two_sites() { let (mut kernel, speech, active) = speech_kernel("Allocation"); - let world_id = kernel.state.world_id; + let world_id = kernel.state.header.world_id; let caller = play_caller(); let entities_before = kernel.state.entities.len(); let whisper = command( @@ -7986,7 +8143,10 @@ mod soul_knowledge_tests { // Those two are the whole of it: strip `facts` and `events` and the // rest of the state is silent. let mut stripped = kernel.state.clone(); - stripped.facts.clear(); + let facts: Vec<_> = stripped.facts.keys().copied().collect(); + for fact in facts { + stripped.facts.remove(&fact); + } stripped.events.clear(); let encoded = rmp_serde::to_vec_named(&stripped).unwrap(); assert!( @@ -9527,7 +9687,7 @@ mod clock_tests { let before = kernel.state.clone(); tick(&mut kernel, 1).expect("the tick commits"); - assert_eq!(kernel.state.now, FictionalMinutes(1)); + assert_eq!(kernel.state.header.now, FictionalMinutes(1)); assert_eq!(kernel.state.revision, before.revision + 1); assert!(kernel.state.pressures.is_empty()); assert_eq!(kernel.state.commitments, before.commitments); @@ -9536,7 +9696,7 @@ mod clock_tests { assert_eq!(kernel.state.events, before.events); tick(&mut kernel, 2).expect("the tick commits"); - assert_eq!(kernel.state.now, FictionalMinutes(3)); + assert_eq!(kernel.state.header.now, FictionalMinutes(3)); } /// A closed route in one place becomes political pressure in another without @@ -9595,7 +9755,7 @@ mod clock_tests { fn time_advances_only_through_advance_time() { let (mut kernel, clockwork, _) = clock_kernel("OnlyTick"); tick(&mut kernel, 5).expect("the tick commits"); - let now = kernel.state.now; + let now = kernel.state.header.now; exercise( &mut kernel, @@ -9604,7 +9764,7 @@ mod clock_tests { vec![binding("target", Target::Subject(clockwork.farmer))], ) .expect("the threat commits"); - assert_eq!(kernel.state.now, now); + assert_eq!(kernel.state.header.now, now); let snapshot = kernel.snapshot().unwrap(); submit_play( @@ -9614,7 +9774,7 @@ mod clock_tests { route: Ref::Existing(clockwork.gate), }]), ); - assert_eq!(kernel.state.now, now); + assert_eq!(kernel.state.header.now, now); } /// Who may tick, when, and how far. @@ -9659,11 +9819,11 @@ mod clock_tests { minutes: minutes(7), }, ); - assert_eq!(kernel.state.now, FictionalMinutes(7)); + assert_eq!(kernel.state.header.now, FictionalMinutes(7)); // And a span that would overflow the clock is refused rather than // wrapping. - kernel.state.now = FictionalMinutes(u64::MAX); + kernel.state.header.get_mut().now = FictionalMinutes(u64::MAX); let snapshot = kernel.snapshot().unwrap(); let error = kernel .submit( @@ -9765,7 +9925,7 @@ mod clock_tests { }, ) .expect("the honest motion applies"); - assert_eq!(candidate.now, to); + assert_eq!(candidate.header.now, to); } /// Replay across a tick is exact, and every envelope is idempotent. @@ -10226,11 +10386,11 @@ mod clock_tests { .collect() }; let before = digests(&kernel); - let before_now = kernel.state.now; + let before_now = kernel.state.header.now; // Short of every due date in the fixture. tick(&mut kernel, 10).expect("the tick commits"); - assert_eq!(kernel.state.now, FictionalMinutes(before_now.0 + 10)); + assert_eq!(kernel.state.header.now, FictionalMinutes(before_now.0 + 10)); assert!(kernel.state.pressures.is_empty()); assert_eq!(digests(&kernel), before, "the clock entered a scope"); } @@ -10541,7 +10701,7 @@ mod clock_tests { kernel .submit(ticking, &AuthenticatedCaller::fixture(CallerId::Play)) .expect("the tick commits"); - assert_eq!(replayed.now, kernel.state.now); + assert_eq!(replayed.header.now, kernel.state.header.now); assert_eq!(replayed.commitments, kernel.state.commitments); assert_eq!(replayed.pressures, kernel.state.pressures); } @@ -10672,7 +10832,7 @@ mod clock_tests { ) .expect("the play authority advances time"); assert!(receipt.resulting_revision > 0); - assert!(kernel.state.now > active.now); + assert!(kernel.state.header.now > active.now); } /// P3.4: a ruled fact is world truth to every subject that knows it. @@ -11953,7 +12113,7 @@ mod agency_tests { let granted = require_granted(state, human, affordance).unwrap(); let event = action::exercise(state, command_id, human, &granted, &invocation).unwrap(); let minutes = TickMinutes::new(9).unwrap(); - let to = state.now.checked_add(minutes).unwrap(); + let to = state.header.now.checked_add(minutes).unwrap(); let effects = [ ( "patch", diff --git a/native/aetherlight/src/patch.rs b/native/aetherlight/src/patch.rs index 7e585682e..a8e19aa23 100644 --- a/native/aetherlight/src/patch.rs +++ b/native/aetherlight/src/patch.rs @@ -3035,7 +3035,7 @@ fn check_against_grammar( roles: &[RoleSpec], mismatches: &mut Vec<Mismatch>, ) { - let Some(grammar) = &state.grammar else { + let Some(grammar) = &state.header.grammar else { return; }; let handle = handle.clone(); @@ -3057,7 +3057,7 @@ pub(super) fn resolve_patch( command_id: CommandId, patch: &WorldPatch, ) -> Result<ResolvedPatch, Vec<Mismatch>> { - let world_id = state.world_id; + let world_id = state.header.world_id; let genesis = super::is_genesis(state.revision, &state.subjects); let mut mismatches = Vec::new(); let mut index: BTreeMap<DraftHandle, RefKind> = BTreeMap::new(); @@ -3651,7 +3651,7 @@ pub(super) fn resolve_patch( } // A promise cannot be born past due: it would press on its // subject on the very next tick with no chance to act. - if *due <= state.now { + if *due <= state.header.now { mismatches.push(Mismatch::CommitmentDueInThePast { operation: position, }); @@ -6878,7 +6878,7 @@ mod tests { &auth_principal(owner()), ) .unwrap(); - let world_id = kernel.state.world_id; + let world_id = kernel.state.header.world_id; let command_id = CommandId::issue(); let handle = DraftHandle::new("a-handle"); assert_ne!( From 5445e5daf9cf790dc6ed9ac9600e256c0f10247b Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 03:36:55 +0100 Subject: [PATCH 150/190] aetherlight: the state digest is an LtHash16 set digest, events leave the state The world digest is now a homomorphic set hash over per-document digests (sha256 of schema, key and the named encoding of the value), updated by the documents a commit changed, sealed with the revision. WorldState is no longer an encoded value and loses Serialize; events live once, in the Acted commit that applied them, and snapshot folds minted_at and last_acted_at over the journal; knowledge is one document per (subject, fact). Schemas become world_state.v2 and world_commit.v2, so every digest and the export hash move and golden.digests is regenerated. verify_state_shape no longer judges events: replay re-derives each through action::exercise. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/fixtures/golden.digests | 20 +- native/aetherlight/src/action.rs | 44 +- native/aetherlight/src/digest.rs | 183 ++++++++ native/aetherlight/src/docs.rs | 28 ++ native/aetherlight/src/grammar/tests.rs | 8 +- native/aetherlight/src/import_key_tests.rs | 8 +- native/aetherlight/src/journal.rs | 172 ++------ native/aetherlight/src/lib.rs | 468 ++++++++++----------- native/aetherlight/src/patch.rs | 15 +- 9 files changed, 506 insertions(+), 440 deletions(-) create mode 100644 native/aetherlight/src/digest.rs diff --git a/native/aetherlight/fixtures/golden.digests b/native/aetherlight/fixtures/golden.digests index 2e43d097f..cd2c826c8 100644 --- a/native/aetherlight/fixtures/golden.digests +++ b/native/aetherlight/fixtures/golden.digests @@ -1,10 +1,10 @@ -0 sha256:b3a1da45714cfed622b118ac441f562dcf2c1f45637baff335f08a3efa562e55 sha256:e0e30c081917a00f88268916784d55e0e3ee187b8733a6da5953f9864dbc41cd -1 sha256:6315946e2cac6d49e24aae623bb92cdf9c68ac50382c1d27ffec34f78e2ebbb5 sha256:14fa8cbdee9f94944dbc91c9158fb6009c5310e11f57d682a3c17ae3ba4a476e -2 sha256:3bc0ba23bdb8afe6782b08f3223e9a501e17a8cfbbfed3b8c0a94cab20d2de64 sha256:e962a73db29fb48e0b303ac2746f85c88e9eca43e70cb3b5efb5527a885516a7 -3 sha256:1e6fa2e6104ad2cdde11db5f4643a0881f88cdda2cf049e445774ea9a2f36b65 sha256:1e8047a55a7857a19c05e07c9978a8656423de4c1c7fc49151a71abf399e2e2c -4 sha256:777d7f85b0c342ba44f51aacc03a615038cc243aa8930adf9c5e5ef7200a4325 sha256:f5ce5f59d767866fb02c76948f6693cda954d712efb6b2ac624b6dfe816cdd4f -5 sha256:f08db5b927a98b741cec0aec4d566f376ea283e1057e8a6f5abbff3f5983acb1 sha256:07889d5e1c2958e51b37087acf9784d2274c47a8cf854aadf3ed809a02b5af6e -6 sha256:0edc5712426bb23a2773fe7c804c0cccddff5f23d733679c2cd3857f2009dc6b sha256:8cebfbdbf217aad91e76301188095a04fc0cef488e6367eb3fc8a7b3f93e7f77 -7 sha256:3fdf073544f807ef4ca9928e7c95aaec58982ecb37fdcc758f3bf916914dd215 sha256:c04c37fcc192f208869f396bc2287db76e08527e5d179ffae0ec07a513964cee -8 sha256:18c5a5b61bfb8d039f9e38b5ac3a8353024de84c572d019a8af94a9508462e04 sha256:85449a2d63f3383dff2a0813071a76f665d208a77aa954d65b308c2b57657301 -export sha256:4ba94ec8ee6036e74b2fb28b9cbef97cb5386fea4c3063cf38a08ff47de28910 +0 sha256:2ca3c099943ec537cd4dad9eef0b79b7368daa5b2dbd93baac0cb57cba3dcabe sha256:a94b938beddc671d28803581c9c3711fc520603f2dc8ac192b7cb54e73b3ff14 +1 sha256:cc421710aaa5d92b07abe0d7c4d0506fd6f9b66d1c806e863942e8a0113c7620 sha256:1abfc74079a3894ad21923f6d195f5e067adf58c5806f6cfc6bf08094f72ce9f +2 sha256:c2c2c2631caa85f9a0721778a7a05515a6687dda65af71f916a6565314f20f1b sha256:58a46e1def214cba12ed5d6ba1e991fa43d6927f6467fe10c276c0bc5ec38691 +3 sha256:5326e779106a076a35b26deb2d1116813accd9c8ad7da32569d240d4631de85c sha256:1cb8fd189c2c64c7ebf8708ae7db856b020b156c5660ac9178a27b50421ddbd4 +4 sha256:8b6e54464a24af395e8f5c0149aab8993355fa79994c09c4be53eabc5688d23a sha256:c78021e910c535f333fa4fdf97742a1329c5eb788b874c5c6302613abeef639b +5 sha256:78af2b889c301251919c6d68cf397d2befdf9b4fc012d73887c7d56894e86ecf sha256:3ab475b3e27f2e4d0afabd973ff69fff3523182216aa1f4ff3331de1747e1482 +6 sha256:2ce1eee99f2a650d9ef212ec04c2042b5e63005c5c263063d4e53b79d7ba7214 sha256:575b25743bc6d1673a71d9d0dc7be3825bec261f485bae13984065028601fb98 +7 sha256:fd5454f623359764bb4afaae6305a9ca41bca8670c36fd1f4f1c38779add4aa4 sha256:ba97a6d5c09e018c6abe91f782ab8bc5e618d0d8a45ac22cb637f40ad01755ef +8 sha256:7762f695b8205cba054d957e9a9242399320683d6d34c30ee9612dc89844ff2f sha256:b531e0d1afdb4f11033fc19e5280f7b46fc2b27911194e5c34dcbe8d57fae10e +export sha256:ef186452fd00de5b85a44e4a623489264e649810ab95847a45f25d82a0ae36fd diff --git a/native/aetherlight/src/action.rs b/native/aetherlight/src/action.rs index 93758bac8..582de0623 100644 --- a/native/aetherlight/src/action.rs +++ b/native/aetherlight/src/action.rs @@ -519,8 +519,7 @@ fn evaluate( BoundPrecondition::Knows { fact, at_least } => { return (!state .knowledge - .get(&actor) - .and_then(|held| held.get(fact)) + .get(&(actor, *fact)) .is_some_and(|held| held.confidence >= *at_least)) .then_some(ActionMismatch::FactUnknown { precondition: index, @@ -1190,6 +1189,7 @@ mod tests { fn a_missing_present_precondition_names_itself() { let bench = bench("Present"); let before = bench.kernel.state.clone(); + let before_events = bench.kernel.events(); // The clerk stands in the yard, so a Carry bound to the gate fails the // first precondition and nothing else. @@ -1199,7 +1199,7 @@ mod tests { ); assert_eq!(bench.kernel.state.revision, before.revision); assert_eq!(bench.kernel.state.holdings, before.holdings); - assert_eq!(bench.kernel.state.events, before.events); + assert_eq!(bench.kernel.events(), before_events); } #[test] @@ -1500,7 +1500,7 @@ mod tests { assert_eq!(bench.kernel.state.holdings, holdings); assert_eq!(bench.kernel.state.positions, positions); assert_eq!(bench.kernel.state.edges, edges); - assert_eq!(bench.kernel.state.events.len(), 1); + assert_eq!(bench.kernel.events().len(), 1); assert_eq!(bench.kernel.state.revision, revision + 1); } @@ -1509,12 +1509,8 @@ mod tests { let mut bench = bench("Lowering"); let receipt = bench.commit(bench.carry(2, bench.yard)); assert!(receipt.resulting_revision > 0); - let event = bench - .kernel - .state - .events - .last() - .expect("the committed event"); + let events = bench.kernel.events(); + let event = events.last().expect("the committed event"); assert_eq!( event.effects, vec![ResolvedOp::Transfer { @@ -1572,8 +1568,7 @@ mod tests { bench.refresh(); let event = bench .kernel - .state - .events + .events() .last() .expect("the committed event") .clone(); @@ -1644,7 +1639,7 @@ mod tests { let decoded: std::collections::BTreeMap<_, crate::Affordance> = rmp_serde::from_slice(&catalog).expect("the affordance document decodes"); assert_eq!(decoded, *bench.kernel.state.affordance_catalog); - assert!(digest(&bench.kernel.state).is_ok()); + assert!(bench.kernel.state.full_state_digest().is_ok()); } #[test] @@ -1746,7 +1741,8 @@ mod tests { ) .expect("the Speak entry commits"); assert!(receipt.resulting_revision > 0); - let event = kernel.state.events.last().unwrap(); + let events = kernel.events(); + let event = events.last().unwrap(); assert_eq!(event.band, 0); // The two the speech lowering prepends, and nothing from a slot. assert_eq!(event.effects.len(), 2); @@ -1917,13 +1913,14 @@ mod tests { fn an_unauthorized_actor_names_the_failed_precondition() { let bench = civics("Unauthorized"); let before = bench.kernel.state.clone(); + let before_events = bench.kernel.events(); assert_eq!( bench.rejected_as(bench.civic.farmer, &bench.levy(bench.civic.reeve, 1)), vec![ActionMismatch::NotAuthorized { precondition: 0 }] ); assert_eq!(bench.kernel.state.revision, before.revision); assert_eq!(bench.kernel.state.holdings, before.holdings); - assert_eq!(bench.kernel.state.events, before.events); + assert_eq!(bench.kernel.events(), before_events); } /// A place jurisdiction reaches everything under it and nothing else, and @@ -2219,12 +2216,8 @@ mod tests { let farmer = bench.civic.farmer; assert!(bench.commit_as(farmer, petition.clone()).resulting_revision > 0); - let event = bench - .kernel - .state - .events - .last() - .expect("the committed event"); + let events = bench.kernel.events(); + let event = events.last().expect("the committed event"); assert_eq!(event.effects.len(), 2); assert_eq!( crate::tests::spoken(&bench.kernel.state, event), @@ -2378,6 +2371,7 @@ mod tests { bench.admit(vec![grant_to(treasury, COMMAND_KIND, over_place(road))]); let invocation = bench.delegate(outsider, road); let before = bench.kernel.state.clone(); + let before_events = bench.kernel.events(); let error = soul_submit(&mut bench, treasury, invocation).unwrap_err(); let KernelError::ActionRejected(rejected) = error else { panic!("an over-wide delegation is an action rejection"); @@ -2388,7 +2382,7 @@ mod tests { ); assert_eq!(bench.kernel.state.revision, before.revision); assert_eq!(bench.kernel.state.authority, before.authority); - assert_eq!(bench.kernel.state.events.len(), before.events.len()); + assert_eq!(bench.kernel.events().len(), before_events.len()); } /// The `Restricted` rule is enforced by the component writer, not only by @@ -2449,13 +2443,13 @@ mod tests { holder: PatchRef::Existing(treasury), grant: crate::tests::grant_of(LEVY_KIND, over_place(hall)), }]); - let events = bench.kernel.state.events.len(); + let events = bench.kernel.events().len(); let error = act(&mut bench.kernel, reeve, invocation).unwrap_err(); assert!( matches!(error, KernelError::ActionRejected(_)), "a revoked lend is a rejection: {error:?}" ); - assert_eq!(bench.kernel.state.events.len(), events); + assert_eq!(bench.kernel.events().len(), events); } /// Structural overlap alone does not see a `Subject` grant sitting inside @@ -2560,7 +2554,7 @@ mod tests { panic!("an acted effect"); }; assert_eq!( - bench.kernel.state.events.last().expect("a committed event"), + bench.kernel.events().last().expect("a committed event"), &event, "the committed event is not what reduce produced" ); diff --git a/native/aetherlight/src/digest.rs b/native/aetherlight/src/digest.rs new file mode 100644 index 000000000..ce709dcfd --- /dev/null +++ b/native/aetherlight/src/digest.rs @@ -0,0 +1,183 @@ +//! The state digest: a homomorphic set hash over per-document digests. +//! +//! Each document (one row of a partition, or the world header) has a digest +//! `sha256(len schema, schema, len key, key, rmp named value)`. The world's +//! accumulator is LtHash16 (Lewi et al. 2019): a document digest is expanded to +//! 2048 bytes and added lane-wise as 1024 wrapping `u16`; removing a document +//! subtracts it, and updating one subtracts the old and adds the new. So the +//! digest of a commit costs what the commit changed, not the size of the world, +//! and it depends on the set of documents alone, never on the order they were +//! written. `state_digest` seals the accumulator with the revision. + +use crate::docs::{DocKey, Docs, Tracked}; +use crate::{KernelError, STATE_SCHEMA}; +use serde::Serialize; +use sha2::{Digest, Sha256}; + +const LANES: usize = 1024; +/// 64 blocks of 32 bytes: 2048 bytes, 1024 lanes. +const BLOCKS: u8 = 64; + +pub(crate) type DocDigest = [u8; 32]; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct LtHash16(Box<[u16; LANES]>); + +impl Default for LtHash16 { + fn default() -> Self { + Self(Box::new([0; LANES])) + } +} + +impl LtHash16 { + fn lanes(doc: &DocDigest) -> impl Iterator<Item = u16> + '_ { + (0..BLOCKS).flat_map(move |block| { + let mut hasher = Sha256::new(); + hasher.update(doc); + hasher.update([block]); + let expanded: [u8; 32] = hasher.finalize().into(); + (0..16).map(move |lane| u16::from_le_bytes([expanded[2 * lane], expanded[2 * lane + 1]])) + }) + } + + pub(crate) fn add(&mut self, doc: &DocDigest) { + for (slot, lane) in self.0.iter_mut().zip(Self::lanes(doc)) { + *slot = slot.wrapping_add(lane); + } + } + + pub(crate) fn subtract(&mut self, doc: &DocDigest) { + for (slot, lane) in self.0.iter_mut().zip(Self::lanes(doc)) { + *slot = slot.wrapping_sub(lane); + } + } + + /// The commit-facing digest: the accumulator sealed with the revision. + pub(crate) fn state_digest(&self, revision: u64) -> String { + let mut hasher = Sha256::new(); + hasher.update(STATE_SCHEMA.as_bytes()); + hasher.update(revision.to_be_bytes()); + for lane in self.0.iter() { + hasher.update(lane.to_le_bytes()); + } + format!("sha256:{:x}", hasher.finalize()) + } +} + +#[cfg(test)] +thread_local! { + /// Document digests computed on this thread, for the work-bound test. + pub(crate) static DOC_DIGESTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; +} + +pub(crate) fn doc_digest<V: Serialize>( + schema: &str, + key: &str, + value: &V, +) -> Result<DocDigest, KernelError> { + #[cfg(test)] + DOC_DIGESTS.with(|count| count.set(count.get() + 1)); + let bytes = rmp_serde::to_vec_named(value) + .map_err(|error| KernelError::Serialization(error.to_string()))?; + let mut hasher = Sha256::new(); + hasher.update((schema.len() as u64).to_be_bytes()); + hasher.update(schema.as_bytes()); + hasher.update((key.len() as u64).to_be_bytes()); + hasher.update(key.as_bytes()); + hasher.update(bytes); + Ok(hasher.finalize().into()) +} + +/// One change of one document: subtract the old, add the new. +pub(crate) fn fold_change<V: Serialize>( + acc: &mut LtHash16, + schema: &str, + key: &str, + old: Option<&V>, + new: Option<&V>, +) -> Result<(), KernelError> { + if let Some(old) = old { + acc.subtract(&doc_digest(schema, key, old)?); + } + if let Some(new) = new { + acc.add(&doc_digest(schema, key, new)?); + } + Ok(()) +} + +/// What `WorldState` needs of a partition, whatever its key and value types. +pub(crate) trait Partition { + fn is_clean(&self) -> bool; + fn rollback(&mut self); + fn finish_log(&mut self); + /// Folds the open transaction's changes into `acc`. + fn fold_changes(&self, schema: &str, acc: &mut LtHash16) -> Result<(), KernelError>; + /// Every document's digest, by (schema, key): the full enumeration the + /// incremental digest is checked against. + #[cfg(test)] + fn documents( + &self, + schema: &str, + out: &mut std::collections::BTreeMap<(String, String), DocDigest>, + ) -> Result<(), KernelError>; + /// The partition as encoded: the bytes a test scans for what must never appear. + #[cfg(test)] + fn encoded(&self) -> Vec<u8>; +} + +impl<K, V> Partition for Docs<K, V> +where + K: Ord + Clone + DocKey + Serialize, + V: Clone + PartialEq + Serialize, +{ + fn is_clean(&self) -> bool { + Docs::is_clean(self) + } + + fn rollback(&mut self) { + Docs::rollback(self); + } + + fn finish_log(&mut self) { + self.finish(); + } + + fn fold_changes(&self, schema: &str, acc: &mut LtHash16) -> Result<(), KernelError> { + for (key, old, new) in self.changes() { + fold_change(acc, schema, &key.key_text(), old, new)?; + } + Ok(()) + } + + #[cfg(test)] + fn documents( + &self, + schema: &str, + out: &mut std::collections::BTreeMap<(String, String), DocDigest>, + ) -> Result<(), KernelError> { + for (key, value) in self.iter() { + let key = key.key_text(); + let digest = doc_digest(schema, &key, value)?; + out.insert((schema.to_owned(), key), digest); + } + Ok(()) + } + + #[cfg(test)] + fn encoded(&self) -> Vec<u8> { + rmp_serde::to_vec_named(self).expect("a partition encodes") + } +} + +/// The header's one change, keyed by its own world id. +pub(crate) fn fold_header<T: Clone + PartialEq + Serialize>( + acc: &mut LtHash16, + schema: &str, + key: &str, + header: &Tracked<T>, +) -> Result<(), KernelError> { + if let Some((old, new)) = header.change() { + fold_change(acc, schema, key, old, Some(new))?; + } + Ok(()) +} diff --git a/native/aetherlight/src/docs.rs b/native/aetherlight/src/docs.rs index ef873c47d..916311504 100644 --- a/native/aetherlight/src/docs.rs +++ b/native/aetherlight/src/docs.rs @@ -95,6 +95,14 @@ impl<K: Ord + Clone, V: Clone + PartialEq> Docs<K, V> { self.map.entry(key) } + /// The open transaction's changed keys as (key, old, new), without closing it. + pub(crate) fn changes(&self) -> impl Iterator<Item = (&K, Option<&V>, Option<&V>)> + '_ { + self.touched.iter().filter_map(|(key, old)| { + let new = self.map.get(key); + (new != old.as_ref()).then_some((key, old.as_ref(), new)) + }) + } + /// The keys whose value differs from the start of the transaction, with the /// value they had then. A key written back to what it was is not reported. /// The log is empty afterwards. @@ -173,6 +181,14 @@ impl<T: Clone + PartialEq> Tracked<T> { } } + /// (old, new) when the value changed in the open transaction. + pub(crate) fn change(&self) -> Option<(Option<&T>, &T)> { + match &self.old { + Some(old) if old.as_ref() != Some(&self.value) => Some((old.as_ref(), &self.value)), + _ => None, + } + } + pub(crate) fn rollback(&mut self) { if let Some(Some(old)) = self.old.take() { self.value = old; @@ -183,3 +199,15 @@ impl<T: Clone + PartialEq> Tracked<T> { self.old.is_none() } } + +/// The text a document is keyed by in its digest: stable, canonical, one per +/// key. An id is its uuid as `Display` prints it. +pub(crate) trait DocKey { + fn key_text(&self) -> String; +} + +impl<A: DocKey, B: DocKey> DocKey for (A, B) { + fn key_text(&self) -> String { + format!("{}/{}", self.0.key_text(), self.1.key_text()) + } +} diff --git a/native/aetherlight/src/grammar/tests.rs b/native/aetherlight/src/grammar/tests.rs index e59df991c..817668d73 100644 --- a/native/aetherlight/src/grammar/tests.rs +++ b/native/aetherlight/src/grammar/tests.rs @@ -297,7 +297,7 @@ fn unbound_world_keeps_the_open_catalog() { // The state row of a world with no grammar carries no grammar key, so its // bytes and digests are those of a world written before grammars existed. - let encoded = rmp_serde::to_vec_named(&kernel.state).unwrap(); + let encoded = rmp_serde::to_vec_named(&*kernel.state.header).unwrap(); let keys: std::collections::BTreeMap<String, serde::de::IgnoredAny> = rmp_serde::from_slice(&encoded).unwrap(); assert!(!keys.contains_key("grammar")); @@ -350,12 +350,12 @@ fn a_reopened_grammar_world_still_holds_its_grammar() { fn the_bound_grammar_is_part_of_the_world_state_digest() { let kernel = create(bound(Some(grammar_with(&[])), "Digested")); let kernel = kernel.unwrap(); - let bound_digest = crate::state_digest(&kernel.state).unwrap(); + let bound_digest = kernel.state.full_state_digest().unwrap(); let mut state = kernel.state.clone(); state.header.get_mut().grammar = None; - let open_digest = crate::state_digest(&state).unwrap(); + let open_digest = state.full_state_digest().unwrap(); state.header.get_mut().grammar = Some(grammar_with(&[("dock", verb(RenderPath::ShipAction, &[]))])); - let other_digest = crate::state_digest(&state).unwrap(); + let other_digest = state.full_state_digest().unwrap(); assert_ne!(bound_digest, open_digest); assert_ne!(bound_digest, other_digest); } diff --git a/native/aetherlight/src/import_key_tests.rs b/native/aetherlight/src/import_key_tests.rs index 40914edc3..150da6960 100644 --- a/native/aetherlight/src/import_key_tests.rs +++ b/native/aetherlight/src/import_key_tests.rs @@ -445,18 +445,18 @@ fn keyless_world_digests_unchanged() { // digest written before keys existed is the digest of the same bytes. let kernel = create(creation("Keyless")); let kernel = kernel.unwrap(); - let state = rmp_serde::to_vec_named(&kernel.state).unwrap(); + let state = kernel.state.encoded_documents(); assert!( !contains(&state, b"import_key"), "a keyless world grew a field" ); // A keyed world carries it and digests differently. let keyed = keyed_world(); - let keyed_state = rmp_serde::to_vec_named(&keyed.state).unwrap(); + let keyed_state = keyed.state.encoded_documents(); assert!(contains(&keyed_state, b"import_key")); assert_ne!( - crate::state_digest(&keyed.state).unwrap(), - crate::state_digest(&kernel.state).unwrap() + keyed.state.full_state_digest().unwrap(), + kernel.state.full_state_digest().unwrap() ); // And a world nobody imported into holds every key absent. assert!(kernel.state.subjects.values().all(|s| s.import_key.is_none())); diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index aea378de6..1296329f1 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -1,6 +1,6 @@ use super::{ COMMIT_SCHEMA, CommittedCommand, KernelError, WorldCommit, WorldEffect, - WorldId, WorldState, apply_effect, commit_digest, reduce, state_digest, + WorldId, WorldState, apply_effect, commit_digest, reduce, }; use crate::docs::Changed; use serde::{Deserialize, Serialize, de::DeserializeOwned}; @@ -46,6 +46,15 @@ impl WorldJournal { self.commits.push(commit); } + /// Every decision the world has acted on, oldest first: the one place an + /// event lives, in the commit that applied it. + pub(super) fn acted_events(&self) -> impl Iterator<Item = &super::DecisionEvent> { + self.commits.iter().filter_map(|commit| match &commit.effect { + WorldEffect::Acted { event, .. } => Some(event), + _ => None, + }) + } + pub(super) fn export(&self) -> Result<Vec<u8>, KernelError> { rmp_serde::to_vec_named(&ExportRef { schema: JOURNAL_SCHEMA, @@ -162,15 +171,16 @@ pub(super) fn verify_history(commits: &[WorldCommit]) -> Result<WorldState, Jour "the world clock moved without a time-advanced commit, or ran backwards".into(), )); } - let touched = replay.finish(); - verify_commitments_are_future(&replay, &touched)?; replay.revision = commit.resulting_revision; - replay.state_digest = state_digest(&replay).map_err(kernel_error)?; + let accumulator = replay.folded().map_err(kernel_error)?; + replay.state_digest = accumulator.state_digest(replay.revision); if replay.state_digest != commit.resulting_state_digest { return Err(JournalError::Corrupt( "commit resulting state digest is invalid".into(), )); } + let touched = replay.finish(accumulator); + verify_commitments_are_future(&replay, &touched)?; replay.last_commit_digest = Some(commit.digest.clone()); } verify_state_shape(&replay)?; @@ -351,7 +361,7 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> )); } } - for (subject_id, held) in &state.knowledge { + for ((subject_id, fact), entry) in &state.knowledge { let entry_is_live = |entry: &super::Knowledge| { entry.acquired_at <= state.revision && match entry.source { @@ -364,10 +374,8 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> } }; if !state.subjects.contains_key(subject_id) - || held.is_empty() - || held - .iter() - .any(|(fact, entry)| !state.facts.contains_key(fact) || !entry_is_live(entry)) + || !state.facts.contains_key(fact) + || !entry_is_live(entry) { return Err(JournalError::Corrupt( "knowledge does not name a canonical subject, fact, and source, or was acquired ahead of the world's revision" @@ -544,67 +552,6 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> )); } } - let mut event_ids = BTreeSet::new(); - let mut claimed = BTreeSet::new(); - let mut previous_event_revision = 0; - for event in &state.events { - if !state.subjects.contains_key(&event.actor) { - return Err(JournalError::Corrupt( - "event references an unknown actor".into(), - )); - } - let entry = state - .affordance_catalog - .get(&event.affordance) - .ok_or_else(|| JournalError::Corrupt("event uses an unknown affordance".into()))?; - // A speech or display event names the claim it minted, and that claim - // is asserted by the acting subject and by no other event. - let mut minted_is_canonical = |fact: Option<super::EntityId>| { - fact.is_none_or(|fact| { - claimed.insert(fact) - && state.facts.get(&fact).is_some_and(|record| { - record.standing - == super::FactStanding::Claimed { - by: event.actor, - } - }) - }) - }; - let speech_is_canonical = minted_is_canonical(event.speech); - let display_is_canonical = minted_is_canonical(event.display); - if !event_ids.insert(event.id) - || event.revision == 0 - || event.revision > state.revision - || event.revision <= previous_event_revision - // Present-tense affordance grants are not judged here: retiring a - // subject or revoking a verb it once used must not corrupt the - // history of that use. Authority at commit time is judged once, by - // `reduce`, and after that by replay (`verify_history` re-runs - // `reduce` for every commit) and by the digest chain. This shape - // check only holds time-invariant facts: the event's actor is a - // subject (checked above) and its affordance is a catalog entry - // (checked above). - || event.band >= entry.outcome_bands.len() - // Speech rides only a speech-carrying entry; such an entry always - // addresses someone, by words or by a visible act; a display may - // accompany any entry. - || (event.speech.is_some() && !entry.carries_speech) - || (entry.carries_speech && event.speech.is_none() && event.display.is_none()) - // One lowered operation per band effect, plus the two the speech - // lowering prepends and the two the display lowering adds. - || entry.outcome_bands[event.band].effects.len() - + if event.speech.is_some() { 2 } else { 0 } - + if event.display.is_some() { 2 } else { 0 } - != event.effects.len() - || !speech_is_canonical - || !display_is_canonical - { - return Err(JournalError::Corrupt( - "decision event is noncanonical".into(), - )); - } - previous_event_revision = event.revision; - } Ok(()) } @@ -1033,7 +980,7 @@ mod tests { state.revision = 7; let mut forged = vec![honest[0].clone(), honest[1].clone()]; forged[1].resulting_revision = 7; - forged[1].resulting_state_digest = crate::state_digest(&state).unwrap(); + forged[1].resulting_state_digest = state.full_state_digest().unwrap(); forged[1].digest = commit_digest(&forged[1]).unwrap(); assert!(matches!(reopen(&forged), Err(JournalError::Corrupt(_)))); } @@ -1476,13 +1423,15 @@ mod tests { ) .unwrap(); let committed = kernel.snapshot().unwrap(); - let event = kernel.state.events.last().expect("the levy event").clone(); + let events = kernel.events(); + let event = events.last().expect("the levy event").clone(); let exported = kernel.export().unwrap(); drop(kernel); let mut reopened = WorldKernel::open(&exported).unwrap(); assert_eq!(reopened.snapshot().unwrap(), committed); - let replayed = reopened.state.events.last().expect("the replayed event"); + let events = reopened.events(); + let replayed = events.last().expect("the replayed event"); assert_eq!(replayed.band, event.band); assert_eq!(replayed.effects, event.effects); assert!(matches!( @@ -1776,8 +1725,7 @@ mod custody_tests { .unwrap(); let accepted = kernel.snapshot().unwrap(); let committed = kernel - .state - .events + .events() .last() .expect("the committed event") .clone(); @@ -1788,7 +1736,7 @@ mod custody_tests { let mut reopened = WorldKernel::open(&exported).unwrap(); assert_eq!(reopened.snapshot().unwrap(), accepted); assert_eq!( - reopened.state.events.last().expect("the replayed event"), + reopened.events().last().expect("the replayed event"), &committed ); assert!(matches!( @@ -1860,10 +1808,9 @@ mod custody_tests { }); } - /// A chain holding `Acted` commits recovers and verifies on reopen, and an - /// event whose actor is no subject is corrupt at the shape check. + /// A chain holding `Acted` commits recovers and verifies on reopen. #[test] - fn an_acted_chain_reopens_and_a_foreign_actor_is_corrupt() { + fn an_acted_chain_reopens() { use crate::tests::{ act, auth_principal, creation, first_grant, owner, speak, }; @@ -1892,73 +1839,6 @@ mod custody_tests { let reopened = WorldKernel::open(&exported).expect("the acted chain recovers"); assert_eq!(reopened.snapshot().unwrap(), accepted); verify_state_shape(&reopened.state).expect("an honest event passes the shape check"); - - let mut forged = reopened.state.clone(); - forged.events[0].actor = crate::SubjectId::issue(); - assert!( - matches!(verify_state_shape(&forged), Err(JournalError::Corrupt(_))), - "an event naming no subject passed the shape check" - ); - - let mut reordered = reopened.state.clone(); - reordered.events.swap(0, 1); - assert!( - matches!(verify_state_shape(&reordered), Err(JournalError::Corrupt(_))), - "events out of revision order passed the shape check" - ); - } - - /// The event shape check holds for a silent act too: a non-speech event - /// whose actor is no subject is corrupt, with no minted claim to catch it. - #[test] - fn a_non_speech_event_with_a_foreign_actor_is_corrupt() { - use crate::tests::{ - act, admit_custody, admit_topology, affordance_named, auth_principal, - creation, owner, - }; - use crate::{DecisionInvocation, Magnitude, ProposedEffect, Quantity, Role, RoleBinding, Target}; - - let (mut kernel, _) = WorldKernel::create(creation("SilentForgery"), - &auth_principal(owner()), - ) - .unwrap(); - let topology = admit_topology(&mut kernel); - let custody = admit_custody(&mut kernel, &topology); - let active = kernel.snapshot().unwrap(); - let role = |name: &str, target| RoleBinding { - role: Role(name.into()), - target, - }; - act( - &mut kernel, - custody.holder, - DecisionInvocation { - affordance: affordance_named(&active, "carry"), - bindings: vec![ - role("from", Target::Subject(custody.holder)), - role("recipient", Target::Subject(custody.counterparty)), - role("place", Target::Entity(topology.yard)), - role("resource", Target::Entity(custody.tithe)), - ], - proposed: vec![ProposedEffect { - slot: 0, - magnitude: Magnitude::Quantity(Quantity(1)), - }], - speech: None, - display: None, - }, - ) - .unwrap(); - let event = kernel.state.events.last().unwrap(); - assert!(event.speech.is_none() && event.display.is_none()); - verify_state_shape(&kernel.state).expect("the honest silent event passes"); - - let mut forged = kernel.state.clone(); - forged.events.last_mut().unwrap().actor = crate::SubjectId::issue(); - assert!( - matches!(verify_state_shape(&forged), Err(JournalError::Corrupt(_))), - "a silent event naming no subject passed the shape check" - ); } /// Absence is zero and one slot holds one pair, so a stored zero, an empty diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index f6bc8b3ea..75cc8a108 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -58,6 +58,7 @@ mod action; mod clock; +mod digest; mod docs; #[cfg(test)] mod golden_tests; @@ -99,15 +100,16 @@ pub(crate) use patch::{ }; use patch::{EdgeRecord, EntityRecord, LedgerDelta, ResolvedOp, ResolvedPatch}; -use docs::{Changed, Docs, Tracked}; +use digest::{LtHash16, Partition}; +use docs::{Changed, DocKey, Docs, Tracked}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet}; use thiserror::Error; use uuid::Uuid; -pub const STATE_SCHEMA: &str = "aetherlight.world_state.v1"; -pub(crate) const COMMIT_SCHEMA: &str = "aetherlight.world_commit.v1"; +pub const STATE_SCHEMA: &str = "aetherlight.world_state.v2"; +pub(crate) const COMMIT_SCHEMA: &str = "aetherlight.world_commit.v2"; /// Domain strings of the three content-derived identities. A command is named /// by what it says, so no caller draws an id and no retry needs one. @@ -132,6 +134,12 @@ macro_rules! opaque_uuid { )] #[serde(transparent)] $vis struct $name(Uuid); + + impl DocKey for $name { + fn key_text(&self) -> String { + self.0.to_string() + } + } }; ($name:ident) => { opaque_uuid!($name, pub(crate)); @@ -430,7 +438,7 @@ pub(crate) struct DecisionEvent { /// The world's own fields: the one document that is not a map row. Tracked like /// a partition key, so a tick that advances the clock is one changed document. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] struct WorldHeader { world_id: WorldId, owner: PrincipalId, @@ -438,6 +446,7 @@ struct WorldHeader { /// Bound by genesis and never written again; absent from a world with no /// grammar, so such a world's state and digests are what they were before /// grammars existed. + #[serde(skip_serializing_if = "Option::is_none")] grammar: Option<GrammarBinding>, /// Minutes since genesis. The world's only clock, advanced by exactly one /// command body and read by no wall clock. It is world truth, and it is @@ -469,9 +478,9 @@ struct WorldState { channels: Docs<EntityId, ChannelRecord>, /// What each subject knows. The sole owner of who-heard-what: `events` /// records what was done, and this decides what a subject may act on and - /// what its projection may contain. Never empty for a present key, and + /// what its projection may contain. One document per (subject, fact), and /// absence is "knows nothing of it" — forgetting removes the key. - knowledge: Docs<SubjectId, BTreeMap<EntityId, Knowledge>>, + knowledge: Docs<(SubjectId, EntityId), Knowledge>, /// What ground each subject has jurisdiction over, and under which /// world-declared kind. Never empty for a present key. No subject holds two /// grants of one kind over overlapping ground, so nothing ever arbitrates @@ -498,7 +507,8 @@ struct WorldState { /// holds at least one verb. A grant carries no payload, so a duplicate /// grant is unrepresentable rather than checked. affordance_grants: Docs<SubjectId, BTreeSet<AffordanceId>>, - events: Vec<DecisionEvent>, + // The chain head: outside every document. + accumulator: LtHash16, state_digest: String, last_commit_digest: Option<String>, } @@ -622,7 +632,7 @@ pub struct SubjectSnapshot { /// itself. View-only: it is already carried by `components`. pub(crate) dependencies: Vec<DependencyTarget>, /// The greatest `DecisionEvent.revision` whose actor is this subject, or - /// `None` if the subject never acted. Derived from `state.events` alone: + /// `None` if the subject never acted. Derived from the journal's acted events alone: /// no new state, no schema change. The recency marker `projector_knowledge` /// stamps onto each knowledge row is `acquired_at > last_acted_at`. pub(crate) last_acted_at: Option<u64>, @@ -971,7 +981,13 @@ impl WorldKernel { } fn snapshot(&self) -> Result<WorldSnapshot, KernelError> { - snapshot(&self.state) + snapshot(&self.state, &self.journal) + } + + /// The decisions the world has acted on, for the tests that read them. + #[cfg(test)] + fn events(&self) -> Vec<DecisionEvent> { + self.journal.acted_events().cloned().collect() } fn submit( @@ -1000,12 +1016,13 @@ impl WorldKernel { // Applied in place under the partitions' undo logs: the world is never // cloned, and any failure up to the sealed commit puts it back. self.state.begin(); - let sealed = (|| -> Result<WorldCommit, KernelError> { + let sealed = (|| -> Result<(WorldCommit, LtHash16), KernelError> { apply_effect(&mut self.state, command_id, &command.caller, &effect)?; self.state.revision = previous_revision .checked_add(1) .ok_or_else(|| KernelError::Serialization("world revision overflow".into()))?; - self.state.state_digest = state_digest(&self.state)?; + let accumulator = self.state.folded()?; + self.state.state_digest = accumulator.state_digest(self.state.revision); let mut commit = WorldCommit { schema: COMMIT_SCHEMA.into(), world_id: self.state.header.world_id, @@ -1019,10 +1036,10 @@ impl WorldKernel { digest: String::new(), }; commit.digest = commit_digest(&commit)?; - Ok(commit) + Ok((commit, accumulator)) })(); - let commit = match sealed { - Ok(commit) => commit, + let (commit, accumulator) = match sealed { + Ok(sealed) => sealed, Err(error) => { self.state.rollback(); self.state.revision = previous_revision; @@ -1030,7 +1047,7 @@ impl WorldKernel { return Err(error); } }; - self.state.finish(); + self.state.finish(accumulator); self.state.last_commit_digest = Some(commit.digest.clone()); let receipt = CommitReceipt::from(&commit); @@ -1096,126 +1113,126 @@ fn is_genesis(revision: u64, subjects: &BTreeMap<SubjectId, SubjectState>) -> bo revision == 0 && subjects.is_empty() } -impl WorldState { - /// The encoding the state digest has always hashed: every partition as its - /// map, in this order. `sealed` false writes the chain head (the two digest - /// fields) as blank, the form the state digest is taken over. - fn write_encoded<S: serde::Serializer>( - &self, - serializer: S, - sealed: bool, - ) -> Result<S::Ok, S::Error> { - use serde::ser::SerializeStruct; - let header = &*self.header; - let fields = if header.grammar.is_some() { 26 } else { 25 }; - let mut out = serializer.serialize_struct("WorldState", fields)?; - out.serialize_field("schema", STATE_SCHEMA)?; - out.serialize_field("world_id", &header.world_id)?; - out.serialize_field("revision", &self.revision)?; - out.serialize_field("owner", &header.owner)?; - out.serialize_field("title", &header.title)?; - if header.grammar.is_some() { - out.serialize_field("grammar", &header.grammar)?; - } - out.serialize_field("subjects", &self.subjects)?; - out.serialize_field("entities", &self.entities)?; - out.serialize_field("edges", &self.edges)?; - out.serialize_field("positions", &self.positions)?; - out.serialize_field("holdings", &self.holdings)?; - out.serialize_field("dependencies", &self.dependencies)?; - out.serialize_field("facts", &self.facts)?; - out.serialize_field("channels", &self.channels)?; - out.serialize_field("knowledge", &self.knowledge)?; - out.serialize_field("authority", &self.authority)?; - out.serialize_field("selection", &self.selection)?; - out.serialize_field("redress", &self.redress)?; - out.serialize_field("commitments", &self.commitments)?; - out.serialize_field("pressures", &self.pressures)?; - out.serialize_field("now", &header.now)?; - out.serialize_field("affordance_catalog", &self.affordance_catalog)?; - out.serialize_field("affordance_grants", &self.affordance_grants)?; - out.serialize_field("events", &self.events)?; - if sealed { - out.serialize_field("state_digest", &self.state_digest)?; - out.serialize_field("last_commit_digest", &self.last_commit_digest)?; - } else { - out.serialize_field("state_digest", "")?; - out.serialize_field("last_commit_digest", &None::<String>)?; - } - out.end() - } +/// The partition table: each partition under the schema its documents are +/// digested with. The one list `begin`, `folded`, `finish`, `rollback` and the +/// test oracle all walk. +macro_rules! partitions { + ($state:expr, $($borrow:tt)+) => { + [ + ("aetherlight.subject.v1", $($borrow)+ $state.subjects as $($borrow)+ dyn Partition), + ("aetherlight.entity.v1", $($borrow)+ $state.entities as $($borrow)+ dyn Partition), + ("aetherlight.edge.v1", $($borrow)+ $state.edges as $($borrow)+ dyn Partition), + ("aetherlight.position.v1", $($borrow)+ $state.positions as $($borrow)+ dyn Partition), + ("aetherlight.holdings.v1", $($borrow)+ $state.holdings as $($borrow)+ dyn Partition), + ("aetherlight.dependencies.v1", $($borrow)+ $state.dependencies as $($borrow)+ dyn Partition), + ("aetherlight.fact.v1", $($borrow)+ $state.facts as $($borrow)+ dyn Partition), + ("aetherlight.channel.v1", $($borrow)+ $state.channels as $($borrow)+ dyn Partition), + ("aetherlight.knowledge.v1", $($borrow)+ $state.knowledge as $($borrow)+ dyn Partition), + ("aetherlight.authority.v1", $($borrow)+ $state.authority as $($borrow)+ dyn Partition), + ("aetherlight.selection.v1", $($borrow)+ $state.selection as $($borrow)+ dyn Partition), + ("aetherlight.redress.v1", $($borrow)+ $state.redress as $($borrow)+ dyn Partition), + ("aetherlight.commitments.v1", $($borrow)+ $state.commitments as $($borrow)+ dyn Partition), + ("aetherlight.pressures.v1", $($borrow)+ $state.pressures as $($borrow)+ dyn Partition), + ("aetherlight.affordance.v1", $($borrow)+ $state.affordance_catalog as $($borrow)+ dyn Partition), + ( + "aetherlight.affordance_grants.v1", + $($borrow)+ $state.affordance_grants as $($borrow)+ dyn Partition, + ), + ] + }; +} +const WORLD_DOC_SCHEMA: &str = "aetherlight.world.v1"; + +impl WorldState { /// Opens a transaction. Every log must be empty: a write outside a /// transaction, or a transaction left open, is a bug here and not state. fn begin(&self) { debug_assert!(self.header.is_clean(), "a transaction is open"); - debug_assert!(self.subjects.is_clean() && self.entities.is_clean()); - debug_assert!(self.edges.is_clean() && self.positions.is_clean()); - debug_assert!(self.holdings.is_clean() && self.dependencies.is_clean()); - debug_assert!(self.facts.is_clean() && self.channels.is_clean()); - debug_assert!(self.knowledge.is_clean() && self.authority.is_clean()); - debug_assert!(self.selection.is_clean() && self.redress.is_clean()); - debug_assert!(self.commitments.is_clean() && self.pressures.is_clean()); - debug_assert!(self.affordance_catalog.is_clean() && self.affordance_grants.is_clean()); + debug_assert!(partitions!(self, &).iter().all(|(_, docs)| docs.is_clean())); } - /// Closes the transaction, keeping its writes. Returns the commitments - /// subjects that changed, with their old promises, for replay's check that - /// every commitment stays in the future. - fn finish(&mut self) -> Vec<Changed<SubjectId, BTreeMap<CommitmentKey, Commitment>>> { + /// What `subject` knows: its rows of the flat knowledge partition, by fact. + fn knowledge_of(&self, subject: SubjectId) -> impl Iterator<Item = (&EntityId, &Knowledge)> { + self.knowledge + .range((subject, EntityId(Uuid::nil()))..=(subject, EntityId(Uuid::max()))) + .map(|((_, fact), held)| (fact, held)) + } + + /// The accumulator the open transaction's writes lead to. Reads the logs and + /// changes nothing, so a failure after it can still roll back. + fn folded(&self) -> Result<LtHash16, KernelError> { + let mut acc = self.accumulator.clone(); + digest::fold_header(&mut acc, WORLD_DOC_SCHEMA, &self.header.world_id.key(), &self.header)?; + for (schema, docs) in partitions!(self, &) { + docs.fold_changes(schema, &mut acc)?; + } + Ok(acc) + } + + /// Closes the transaction, keeping its writes and the accumulator `folded` + /// computed for them. Returns the commitments subjects that changed, with + /// their old promises, for replay's check that every commitment stays in the + /// future. + fn finish( + &mut self, + accumulator: LtHash16, + ) -> Vec<Changed<SubjectId, BTreeMap<CommitmentKey, Commitment>>> { + self.accumulator = accumulator; self.header.finish(); - self.subjects.finish(); - self.entities.finish(); - self.edges.finish(); - self.positions.finish(); - self.holdings.finish(); - self.dependencies.finish(); - self.facts.finish(); - self.channels.finish(); - self.knowledge.finish(); - self.authority.finish(); - self.selection.finish(); - self.redress.finish(); - self.pressures.finish(); - self.affordance_catalog.finish(); - self.affordance_grants.finish(); - self.commitments.finish() + let commitments = self.commitments.finish(); + for (_, docs) in partitions!(self, &mut) { + docs.finish_log(); + } + commitments } /// Closes the transaction, undoing every write in it. fn rollback(&mut self) { self.header.rollback(); - self.subjects.rollback(); - self.entities.rollback(); - self.edges.rollback(); - self.positions.rollback(); - self.holdings.rollback(); - self.dependencies.rollback(); - self.facts.rollback(); - self.channels.rollback(); - self.knowledge.rollback(); - self.authority.rollback(); - self.selection.rollback(); - self.redress.rollback(); - self.commitments.rollback(); - self.pressures.rollback(); - self.affordance_catalog.rollback(); - self.affordance_grants.rollback(); + for (_, docs) in partitions!(self, &mut) { + docs.rollback(); + } } -} -impl Serialize for WorldState { - fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { - self.write_encoded(serializer, true) + /// Every document's digest by (schema, key), enumerated from the maps and + /// ignoring the logs. + #[cfg(test)] + fn documents( + &self, + ) -> Result<std::collections::BTreeMap<(String, String), digest::DocDigest>, KernelError> { + let mut out = std::collections::BTreeMap::new(); + let header = &*self.header; + let key = header.world_id.key(); + out.insert( + (WORLD_DOC_SCHEMA.to_owned(), key.clone()), + digest::doc_digest(WORLD_DOC_SCHEMA, &key, header)?, + ); + for (schema, docs) in partitions!(self, &) { + docs.documents(schema, &mut out)?; + } + Ok(out) } -} -/// The state with its chain head blanked: what `state_digest` hashes. -struct Unsealed<'a>(&'a WorldState); + /// The accumulator recomputed from every document: the oracle the + /// incremental digest is checked against. + #[cfg(test)] + fn full_state_digest(&self) -> Result<String, KernelError> { + let mut acc = LtHash16::default(); + for doc in self.documents()?.values() { + acc.add(doc); + } + Ok(acc.state_digest(self.revision)) + } -impl Serialize for Unsealed<'_> { - fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { - self.0.write_encoded(serializer, false) + /// Every document as encoded, header first: the bytes a test scans. + #[cfg(test)] + fn encoded_documents(&self) -> Vec<u8> { + let mut bytes = rmp_serde::to_vec_named(&*self.header).expect("the header encodes"); + for (_, docs) in partitions!(self, &) { + bytes.extend(docs.encoded()); + } + bytes } } @@ -1254,7 +1271,7 @@ impl WorldState { pressures: Docs::default(), affordance_catalog: Docs::default(), affordance_grants: Docs::default(), - events: Vec::new(), + accumulator: LtHash16::default(), state_digest: String::new(), last_commit_digest: None, } @@ -1305,8 +1322,9 @@ impl WorldState { // unlike every later commit, which resolves to `state.revision + 1`. let genesis_revision = state.revision; admit_resolved(&mut state, resolved, genesis_revision)?; - state.finish(); - state.state_digest = state_digest(&state)?; + let accumulator = state.folded()?; + state.state_digest = accumulator.state_digest(state.revision); + state.finish(accumulator); Ok(state) } } @@ -2102,8 +2120,7 @@ fn apply_operation( // `acquired_at`. if state .knowledge - .get(subject) - .and_then(|held| held.get(fact)) + .get(&(*subject, *fact)) .is_some_and(|held| held.confidence == *confidence && held.source == source) { return Err(KernelError::Invariant( @@ -2124,29 +2141,14 @@ fn apply_operation( source, acquired_at, }; - state - .knowledge - .entry(*subject) - .or_default() - .insert(*fact, entry); + state.knowledge.insert((*subject, *fact), entry); } ResolvedOp::Forget { subject, fact } => { - let (removed, emptied) = state - .knowledge - .get_mut(subject) - .map(|held| { - let removed = held.remove(fact).is_some(); - (removed, held.is_empty()) - }) - .unwrap_or((false, false)); - if !removed { + if state.knowledge.remove(&(*subject, *fact)).is_none() { return Err(KernelError::Invariant( "knowledge operation changes nothing".into(), )); } - if emptied { - state.knowledge.remove(subject); - } } ResolvedOp::Communicate { speaker, fact, to } => { if !state.subjects.contains_key(speaker) || !state.facts.contains_key(fact) { @@ -2168,8 +2170,8 @@ fn apply_operation( // otherwise. let acquired_at = resolves_to; for listener in fan_out(state, *speaker, *fact, to) { - state.knowledge.entry(listener).or_default().insert( - *fact, + state.knowledge.insert( + (listener, *fact), Knowledge { confidence: Confidence::Believed, source: KnowledgeSource::Told { @@ -2207,8 +2209,8 @@ fn apply_operation( // revision ahead of the state it was written into. let acquired_at = resolves_to; for viewer in fan_out(state, *actor, *fact, &room) { - state.knowledge.entry(viewer).or_default().insert( - *fact, + state.knowledge.insert( + (viewer, *fact), Knowledge { confidence: Confidence::Believed, source: KnowledgeSource::Seen { by: *actor }, @@ -2251,8 +2253,8 @@ fn apply_operation( // revision ahead of the state it was written into. let acquired_at = resolves_to; for witness in recipients { - state.knowledge.entry(witness).or_default().insert( - *fact, + state.knowledge.insert( + (witness, *fact), Knowledge { confidence: *confidence, source: KnowledgeSource::Witnessed, @@ -2653,10 +2655,7 @@ fn unheld( listeners .into_iter() .filter(|listener| { - !state - .knowledge - .get(listener) - .is_some_and(|held| held.contains_key(&fact)) + !state.knowledge.contains_key(&(*listener, fact)) }) .collect() } @@ -2909,11 +2908,8 @@ fn scope_components(state: &WorldState, subject_id: SubjectId) -> ScopeComponent .unwrap_or_default(), delegated: delegated_authority(state, subject_id), knows: state - .knowledge - .get(&subject_id) - .into_iter() - .flat_map(BTreeMap::keys) - .copied() + .knowledge_of(subject_id) + .map(|(fact, _)| *fact) .collect(), controls: state .channels @@ -2929,12 +2925,14 @@ fn scope_components(state: &WorldState, subject_id: SubjectId) -> ScopeComponent } } -fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> { +fn snapshot( + state: &WorldState, + journal: &journal::WorldJournal, +) -> Result<WorldSnapshot, KernelError> { // One pass over the causal record so each subject's own knowledge map can be // stamped with the revision that minted each claim it holds. - let minted_at: BTreeMap<EntityId, u64> = state - .events - .iter() + let minted_at: BTreeMap<EntityId, u64> = journal + .acted_events() .flat_map(|event| { event .speech @@ -2947,9 +2945,8 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> { // revision of its own last exercised decision. `None` for a subject that // never acted. let last_acted_at: BTreeMap<SubjectId, u64> = - state - .events - .iter() + journal + .acted_events() .fold(BTreeMap::new(), |mut acc, event| { let entry = acc.entry(event.actor).or_insert(event.revision); if event.revision > *entry { @@ -3013,10 +3010,7 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> { // controller: a controller that recomputed perception would be a // second answer to who heard what. let mut knowledge: Vec<KnowledgeSnapshot> = state - .knowledge - .get(subject_id) - .into_iter() - .flatten() + .knowledge_of(*subject_id) .map(|(fact, held)| { let record = state.facts.get(fact).ok_or_else(|| { KernelError::Invariant("knowledge names no canonical fact".into()) @@ -3139,8 +3133,8 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> { }, known_by: state .knowledge - .iter() - .filter(|(_, held)| held.contains_key(fact_id)) + .keys() + .filter(|(_, fact)| fact == fact_id) .map(|(subject_id, _)| *subject_id) .collect(), }) @@ -3305,8 +3299,6 @@ fn apply_effect( // now; read it back rather than computing it a second time. apply_operations(state, &event.effects, &[], event.revision)?; } - // After the writes, so a failed apply leaves nothing to undo here. - state.events.push(event.clone()); } WorldEffect::TimeAdvanced { minutes, @@ -3356,10 +3348,6 @@ fn digest<T: Serialize>(value: &T) -> Result<String, KernelError> { Ok(format!("sha256:{:x}", Sha256::digest(bytes))) } -fn state_digest(state: &WorldState) -> Result<String, KernelError> { - digest(&Unsealed(state)) -} - fn commit_digest(commit: &WorldCommit) -> Result<String, KernelError> { let mut value = commit.clone(); value.digest.clear(); @@ -5251,7 +5239,7 @@ mod tests { .sum(); assert_eq!(before_total, after_total); assert_eq!( - kernel.state.events.last().unwrap().effects, + kernel.events().last().unwrap().effects, vec![ResolvedOp::Transfer { from: civic.farmer, to: civic.treasury, @@ -6537,8 +6525,7 @@ mod knowledge_tests { kernel .state .knowledge - .get(&subject) - .and_then(|held| held.get(&fact)) + .get(&(subject, fact)) .copied() } @@ -6553,8 +6540,7 @@ mod knowledge_tests { fn minted_claim(kernel: &WorldKernel) -> EntityId { kernel - .state - .events + .events() .last() .expect("the committed event") .speech @@ -6755,7 +6741,8 @@ mod knowledge_tests { ) .expect("the whisper commits"); - let event = kernel.state.events.last().expect("the committed event"); + let events = kernel.events(); + let event = events.last().expect("the committed event"); let claim = event.speech.expect("a speech act names its claim"); assert_eq!(spoken(&kernel.state, event), Some("Mind the hinge.")); assert_eq!( @@ -6852,9 +6839,9 @@ mod knowledge_tests { .expect("speech into an empty room commits"); assert_eq!(kernel.state.knowledge, knowledge_before); - assert_eq!(kernel.state.events.len(), 1); + assert_eq!(kernel.events().len(), 1); assert_eq!( - spoken(&kernel.state, kernel.state.events.last().unwrap()), + spoken(&kernel.state, kernel.events().last().unwrap()), Some("Nobody is here.") ); assert_eq!( @@ -6902,7 +6889,8 @@ mod knowledge_tests { ) .expect("the proclamation with a display commits"); - let event = kernel.state.events.last().expect("the committed event"); + let events = kernel.events(); + let event = events.last().expect("the committed event"); let said = event.speech.expect("the utterance names its claim"); let seen = event.display.expect("the display names its claim"); assert_ne!(said, seen); @@ -6952,7 +6940,8 @@ mod knowledge_tests { show(speak, Vec::new(), None, "I nod toward the stair."), ) .expect("a silent act commits"); - let event = kernel.state.events.last().unwrap(); + let events = kernel.events(); + let event = events.last().unwrap(); assert!(event.speech.is_none()); let seen = event.display.expect("the display names its claim"); assert_eq!( @@ -6967,7 +6956,7 @@ mod knowledge_tests { ) .expect("a display into an empty room commits"); assert_eq!(kernel.state.knowledge, knowledge_before); - assert_eq!(kernel.state.events.len(), 2); + assert_eq!(kernel.events().len(), 2); assert_eq!(claimed(&kernel), 2); } @@ -7002,7 +6991,7 @@ mod knowledge_tests { )), vec![ActionMismatch::NoAudience { precondition: 0 }] ); - assert!(kernel.state.events.is_empty()); + assert!(kernel.events().is_empty()); assert_eq!(claimed(&kernel), 0); } @@ -7030,12 +7019,14 @@ mod knowledge_tests { }; let reopened = WorldKernel::open(&exported).expect("the export replays"); assert_eq!(reopened.state, expected); - assert!(reopened.state.knowledge[&speech.listener] - .values() - .any(|held| held.source == KnowledgeSource::Seen { by: speech.speaker })); - assert!(reopened.state.knowledge[&speech.speaker] - .values() - .any(|held| held.source == KnowledgeSource::Seen { by: speech.listener })); + assert!(reopened + .state + .knowledge_of(speech.listener) + .any(|(_, held)| held.source == KnowledgeSource::Seen { by: speech.speaker })); + assert!(reopened + .state + .knowledge_of(speech.speaker) + .any(|(_, held)| held.source == KnowledgeSource::Seen { by: speech.listener })); } fn claimed(kernel: &WorldKernel) -> usize { @@ -7170,8 +7161,8 @@ mod knowledge_tests { ); utter(&mut kernel, speech.listener, recant()) .expect("certainty admits the recant"); - // Absence is the one shape of knowing nothing: no empty inner map. - assert!(!kernel.state.knowledge.contains_key(&speech.listener)); + // Absence is the one shape of knowing nothing: no row. + assert!(kernel.state.knowledge_of(speech.listener).next().is_none()); let active = kernel.snapshot().unwrap(); assert_eq!( @@ -7310,7 +7301,7 @@ mod knowledge_tests { /// state. #[test] fn restart_replay_after_speech_is_exact() { - let (speech, exported, expected) = { + let (speech, exported, expected, expected_events) = { let mut kernel = WorldKernel::create(creation("ReplaySpeech"), &auth_principal(owner()), ) @@ -7344,16 +7335,16 @@ mod knowledge_tests { }]), ); let exported = kernel.export().unwrap(); - (speech, exported, kernel.state.clone()) + (speech, exported, kernel.state.clone(), kernel.events()) }; let reopened = WorldKernel::open(&exported).expect("the export replays"); assert_eq!(reopened.state.facts, expected.facts); assert_eq!(reopened.state.channels, expected.channels); assert_eq!(reopened.state.knowledge, expected.knowledge); - assert_eq!(reopened.state.events, expected.events); + assert_eq!(reopened.events(), expected_events); assert_eq!(reopened.state, expected); - assert!(!reopened.state.knowledge[&speech.bystander].is_empty()); + assert!(reopened.state.knowledge_of(speech.bystander).next().is_some()); } /// A forged claim does not apply, and a forged recipient list is @@ -7429,7 +7420,7 @@ mod knowledge_tests { }, ) .expect("the honest event applies"); - assert!(candidate.knowledge.contains_key(&speech.listener)); + assert!(candidate.knowledge_of(speech.listener).next().is_some()); } /// The scope table: a telling moves its listener's scope and leaves a bystander @@ -7542,7 +7533,8 @@ mod knowledge_tests { ) .expect("both statements commit identically"); assert!(receipt.resulting_revision > 0); - let event = kernel.state.events.last().unwrap().clone(); + let events = kernel.events(); + let event = events.last().unwrap().clone(); (kernel, speech, event) }; let (agreeing, agreeing_speech, agreeing_event) = run("agree", FLOOD_STATEMENT); @@ -7617,8 +7609,7 @@ mod soul_knowledge_tests { kernel .state .knowledge - .get(&subject) - .and_then(|held| held.get(&fact)) + .get(&(subject, fact)) .copied() } @@ -7628,8 +7619,7 @@ mod soul_knowledge_tests { fn minted_claim(kernel: &WorldKernel) -> EntityId { kernel - .state - .events + .events() .last() .expect("the committed event") .speech @@ -7906,7 +7896,7 @@ mod soul_knowledge_tests { .expect("speaking into an empty room commits"); assert_eq!(kernel.state.facts.len(), facts_before + 1); - assert_eq!(kernel.state.events.len(), 1); + assert_eq!(kernel.events().len(), 1); assert!(kernel.state.knowledge.is_empty()); for (subject, digest) in everyone.iter().zip(before) { assert_eq!( @@ -7996,8 +7986,7 @@ mod soul_knowledge_tests { assert!(kernel.state.facts.contains_key(&speech.flood)); assert!( kernel - .state - .events + .events() .iter() .all(|event| event.speech.is_none()) ); @@ -8041,7 +8030,7 @@ mod soul_knowledge_tests { /// from the journal, and reopening again reproduces the same state. #[test] fn soul_replay_is_exact_across_every_new_arm() { - let (exported, expected) = { + let (exported, expected, expected_events) = { let (mut kernel, speech, _) = speech_kernel("ReplayArms"); utter(&mut kernel, speech.speaker, say( @@ -8088,7 +8077,7 @@ mod soul_knowledge_tests { ); assert!(!kernel.state.knowledge.is_empty()); assert!(!kernel.state.facts.is_empty()); - (kernel.export().unwrap(), kernel.state.clone()) + (kernel.export().unwrap(), kernel.state.clone(), kernel.events()) }; for _ in 0..2 { @@ -8097,7 +8086,7 @@ mod soul_knowledge_tests { assert_eq!(replayed.state.channels, expected.channels); assert_eq!(replayed.state.knowledge, expected.knowledge); assert_eq!(replayed.state.entities, expected.entities); - assert_eq!(replayed.state.events, expected.events); + assert_eq!(replayed.events(), expected_events); assert_eq!(replayed.state, expected); } } @@ -8129,7 +8118,8 @@ mod soul_knowledge_tests { // The event no longer embeds the invocation, and its `speech` field is // the fact id. The bytes still appear in the event, inside the committed // `AssertClaim` effect. - let event = kernel.state.events.last().unwrap(); + let events = kernel.events(); + let event = events.last().unwrap(); assert_eq!(event.speech, Some(claim)); assert_eq!( event.effects[0], @@ -8140,15 +8130,14 @@ mod soul_knowledge_tests { }, "the event carries the statement as a replay witness, not a second read surface" ); - // Those two are the whole of it: strip `facts` and `events` and the + // The facts are the whole of it: strip them and the // rest of the state is silent. let mut stripped = kernel.state.clone(); let facts: Vec<_> = stripped.facts.keys().copied().collect(); for fact in facts { stripped.facts.remove(&fact); } - stripped.events.clear(); - let encoded = rmp_serde::to_vec_named(&stripped).unwrap(); + let encoded = stripped.encoded_documents(); assert!( !encoded .windows(text.len()) @@ -8367,8 +8356,7 @@ mod witness_tests { kernel .state .knowledge - .get(&subject) - .and_then(|held| held.get(&fact)) + .get(&(subject, fact)) .copied() } @@ -8433,7 +8421,6 @@ mod witness_tests { .state .knowledge .values() - .flat_map(|held| held.values()) .all(|entry| !matches!(entry.source, KnowledgeSource::Told { .. })), "a witness wrote a told row" ); @@ -8457,11 +8444,7 @@ mod witness_tests { }; let mut state = kernel.state.clone(); let state_revision = state.revision; - state - .knowledge - .entry(world.villager) - .or_default() - .insert(world.asteroid, held); + state.knowledge.insert((world.villager, world.asteroid), held); apply_operation( &mut state, &ResolvedOp::Witness { @@ -8473,9 +8456,9 @@ mod witness_tests { state_revision + 1, ) .expect("the witness lands"); - assert_eq!(state.knowledge[&world.villager][&world.asteroid], held); + assert_eq!(state.knowledge[&(world.villager, world.asteroid)], held); assert_eq!( - state.knowledge[&world.neighbour][&world.asteroid], + state.knowledge[&(world.neighbour, world.asteroid)], Knowledge { confidence: Confidence::Certain, source: KnowledgeSource::Witnessed, @@ -8735,8 +8718,7 @@ mod witness_tests { .expect("the beacon lands"); assert_eq!( kernel - .state - .events + .events() .last() .expect("a committed event") .effects, @@ -8841,7 +8823,7 @@ mod witness_tests { .expect("genesis admits the declared fact") .0; assert_eq!( - kernel.state.knowledge[&human][&fact].acquired_at, + kernel.state.knowledge[&(human, fact)].acquired_at, 0, "a genesis-seeded row landed one revision ahead of the state it was written into" ); @@ -8865,7 +8847,7 @@ mod witness_tests { ); assert_eq!(kernel.state.revision, active.revision + 1); assert_eq!( - kernel.state.knowledge[&world.villager][&world.asteroid].acquired_at, + kernel.state.knowledge[&(world.villager, world.asteroid)].acquired_at, active.revision + 1 ); } @@ -8890,8 +8872,7 @@ mod witness_tests { let mut forged = kernel.state.clone(); let entry = forged .knowledge - .get_mut(&world.villager) - .and_then(|held| held.get_mut(&world.asteroid)) + .get_mut(&(world.villager, world.asteroid)) .expect("the witness landed on the villager"); entry.acquired_at = forged.revision + 1; assert!(journal::verify_state_shape(&forged).is_err()); @@ -8909,8 +8890,8 @@ mod witness_tests { let mut state = kernel.state.clone(); // One holder, so the already-holds half of the selection is exercised // and not merely the subtree half. - state.knowledge.entry(world.neighbour).or_default().insert( - world.asteroid, + state.knowledge.insert( + (world.neighbour, world.asteroid), Knowledge { confidence: Confidence::Doubted, source: KnowledgeSource::Witnessed, @@ -9017,13 +8998,12 @@ mod witness_tests { assert!( !adrift .knowledge - .get(&world.drifter) - .is_some_and(|held| held.contains_key(&world.moon)), + .contains_key(&(world.drifter, world.moon)), "a placeless subject witnessed the widest event in the world" ); for subject in [world.villager, world.neighbour, world.coaster] { assert_eq!( - adrift.knowledge[&subject][&world.moon], + adrift.knowledge[&(subject, world.moon)], Knowledge { confidence: Confidence::Certain, source: KnowledgeSource::Witnessed, @@ -9685,6 +9665,7 @@ mod clock_tests { fn a_tick_with_nothing_due_moves_only_the_clock() { let (mut kernel, _, _) = clock_kernel("Quiet"); let before = kernel.state.clone(); + let before_events = kernel.events(); tick(&mut kernel, 1).expect("the tick commits"); assert_eq!(kernel.state.header.now, FictionalMinutes(1)); @@ -9693,7 +9674,7 @@ mod clock_tests { assert_eq!(kernel.state.commitments, before.commitments); assert_eq!(kernel.state.holdings, before.holdings); assert_eq!(kernel.state.positions, before.positions); - assert_eq!(kernel.state.events, before.events); + assert_eq!(kernel.events(), before_events); tick(&mut kernel, 2).expect("the tick commits"); assert_eq!(kernel.state.header.now, FictionalMinutes(3)); @@ -10159,7 +10140,7 @@ mod clock_tests { key: clockwork.obligation, }]), ); - let events = kernel.state.events.len(); + let events = kernel.events().len(); let error = exercise( &mut kernel, clockwork.farmer, @@ -10175,7 +10156,7 @@ mod clock_tests { ), "{error:?}" ); - assert_eq!(kernel.state.events.len(), events); + assert_eq!(kernel.events().len(), events); } /// `Committed` is a conjunction: the actor holds a commitment to this very @@ -10748,7 +10729,7 @@ mod clock_tests { ) .expect("the play table's patch commits"); - let bytes = rmp_serde::to_vec_named(&kernel.state).expect("state encodes"); + let bytes = kernel.state.encoded_documents(); let text = String::from_utf8_lossy(&bytes); for tag in [ "outside_jurisdiction", @@ -11359,7 +11340,7 @@ mod clock_tests { kernel.export().unwrap() }; let reopened = WorldKernel::open(&exported).expect("the export replays"); - assert_eq!(reopened.state.events.len(), 1); + assert_eq!(reopened.events().len(), 1); } /// PA.f32(b, c): once the world is Active, the human's Draft approval is @@ -11413,12 +11394,7 @@ mod clock_tests { }); submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { patch }) .expect("admitted"); - let reeve_knows = kernel - .state - .knowledge - .get(&clockwork.reeve) - .map(BTreeMap::len) - .unwrap_or(0); + let reeve_knows = kernel.state.knowledge_of(clockwork.reeve).count(); assert_eq!(reeve_knows, 0, "a retired subject was an audience"); } @@ -11526,7 +11502,7 @@ mod clock_tests { }); submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { patch: declare }) .expect("the reeve learns the fact"); - let fact = *kernel.state.knowledge[&clockwork.reeve].keys().next().unwrap(); + let fact = *kernel.state.knowledge_of(clockwork.reeve).next().unwrap().0; play_retires(&mut kernel, clockwork.reeve).expect("retire"); let before = kernel.snapshot().unwrap(); let error = reject_play( diff --git a/native/aetherlight/src/patch.rs b/native/aetherlight/src/patch.rs index a8e19aa23..884590815 100644 --- a/native/aetherlight/src/patch.rs +++ b/native/aetherlight/src/patch.rs @@ -129,6 +129,13 @@ pub(crate) struct Office { #[serde(transparent)] pub(crate) struct GrievanceKindName(pub(crate) String); + +impl crate::docs::DocKey for GrievanceKindName { + fn key_text(&self) -> String { + self.0.clone() + } +} + /// Where one kind of grievance goes, and who may bring it. One forum per /// grievance kind, world-wide; per-jurisdiction forums would key this on /// `(GrievanceKindName, AuthorityTarget)`, and that key has no consumer yet. @@ -3371,9 +3378,8 @@ pub(super) fn resolve_patch( let mut knowledge: BTreeMap<(Key<SubjectId>, Key<EntityId>), KnowledgeCandidate> = state .knowledge .iter() - .flat_map(|(subject_id, held)| { - held.iter().map(move |(fact, entry)| { - ( + .map(|((subject_id, fact), entry)| { + ( (Key::Existing(*subject_id), Key::Existing(*fact)), KnowledgeCandidate { confidence: entry.confidence, @@ -3389,8 +3395,7 @@ pub(super) fn resolve_patch( }, }, }, - ) - }) + ) }) .collect(); // Presence is all a discharge asks, and a create cannot collide: the key is From 8ce1e7e23b2b189457e342c6b40b00b39b907ef2 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 03:45:03 +0100 Subject: [PATCH 151/190] aetherlight: pin the set digest, the rollback and the digest work bound Incremental digest equals a full recompute at every revision of the golden session and across a removal; LtHash16 add then subtract returns to zero in any order and wraps; digest work per tick and per speech is equal at 100 and 1600 persons and equals Added + Removed + 2 x Updated; a failed apply rolls every partition back; a v1 commit chain is refused. The clockwork harness takes period N/2 and prints digests per submit beside the times. PROVENANCE records the cut. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/PROVENANCE.md | 56 +++++ native/aetherlight/src/digest.rs | 75 ++++++ native/aetherlight/src/docs.rs | 107 ++++++++ native/aetherlight/src/golden_tests.rs | 325 +++++++++++++++++++------ native/aetherlight/src/journal.rs | 17 ++ 5 files changed, 499 insertions(+), 81 deletions(-) diff --git a/native/aetherlight/PROVENANCE.md b/native/aetherlight/PROVENANCE.md index fb203c0ec..01c8fa801 100644 --- a/native/aetherlight/PROVENANCE.md +++ b/native/aetherlight/PROVENANCE.md @@ -364,3 +364,59 @@ Host contracts (AL3a, from Soul's pass): - The band draw is grindable through the command id (it hashes the body, so the text, a magnitude or the revision re-roll it). Only Play submits acts after genesis and Play is trusted, so it is not an authority hole. + +## Cut AL3b: partitions are tracked documents, the state digest is a set digest + +Authority: cut `aetherlight-journal-b` r1 of campaign `aetheria-release`; rulings +`aetherlight-narrative-state-owner`, `cultnet-scale-is-not-negotiable`, +`terminus-clockwork-world`. Base `36d1d2507`. + +Tracked documents. Each partition of `WorldState` is a `Docs<K, V>` (`docs.rs`): +a map whose every write method records the key's value as it stood when the +transaction first touched it. `finish` reports the keys whose value really +changed with their old value; `rollback` puts the touched keys back. The world's +own fields (id, owner, title, grammar, clock) are one `Tracked<WorldHeader>`. +`revision`, the accumulator, `state_digest` and `last_commit_digest` are the +chain head, outside every document. `submit` checks, reduces, opens a +transaction, applies to the live state, then folds the change set and seals the +commit; any error before the commit is sealed rolls the state back. There is no +candidate clone, and replay uses the same begin, apply, finish path, so opening +a world costs what its commits touched. + +Set digest. A document digest is sha256 over `u64be len(schema)`, schema, +`u64be len(key)`, key and the named messagepack of the value. The accumulator is +LtHash16 (Lewi et al. 2019): a document digest is expanded to 2048 bytes by +sha256(digest, block) for blocks 0 to 63, read as 1024 little-endian `u16` +lanes, and added (or subtracted) with wrapping. An updated document subtracts +its old digest and adds its new one. `state_digest` is `sha256:` plus the hex of +sha256 over `aetherlight.world_state.v2`, `u64be revision` and the lanes. It +depends on the set of documents alone, never on write order. + +Document names are `aetherlight.<name>.v1` for world, subject, entity, edge, +position, holdings, dependencies, fact, channel, knowledge, authority, +selection, redress, commitments, pressures, affordance and affordance_grants. +Keys are the id's uuid text; redress is keyed by the grievance name and knowledge +by `subject/fact`. These schema ids exist only as digest input. + +Schemas. `aetherlight.world_state.v2` and `aetherlight.world_commit.v2`. An +export whose commits carry v1 is refused. Every state digest, every commit +digest and the export hash moved; `fixtures/golden.digests` was regenerated and +reproduces on Linux. + +Events and knowledge. `WorldState` no longer holds events: an event lives once, +in the `Acted` effect of the commit that applied it. `snapshot` folds +`minted_at` and `last_acted_at` over the journal (still one O(history) pass; an +index is the follow-up's). `verify_state_shape` no longer judges events; replay +re-derives each through `action::exercise` in `apply_effect`. Knowledge is one +document per (subject, fact), so a subject's knowledge is a range over the key +and forgetting removes one key. `WorldState` has no `Serialize` or `Deserialize`: +only documents are encoded, one at a time. + +The change set is transient here. AL3c records it through the CultLib type. + +Timing. The ratio of 1600 to 100 persons is not gated by this cut: the world +reads a commit makes (`audience`, `derive_motion`, the snapshot) are still +O(world), and follow-up `aetherlight-read-indexes-timing-gate` owns the gate. What +this cut owns is the work it does for the digest, which +`golden_tests::digest_work_is_equal_at_100_and_1600` pins: document digests per +commit equal at both sizes and equal to Added + Removed + 2 x Updated. diff --git a/native/aetherlight/src/digest.rs b/native/aetherlight/src/digest.rs index ce709dcfd..8958f61a2 100644 --- a/native/aetherlight/src/digest.rs +++ b/native/aetherlight/src/digest.rs @@ -181,3 +181,78 @@ pub(crate) fn fold_header<T: Clone + PartialEq + Serialize>( } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + fn documents(count: u32) -> Vec<DocDigest> { + (0..count) + .map(|index| doc_digest("aetherlight.test.v1", &index.to_string(), &index).unwrap()) + .collect() + } + + /// Order never matters and a subtraction undoes an addition, so the digest + /// is a function of the set of documents alone. + #[test] + fn lthash_add_then_subtract_is_zero() { + let docs = documents(300); + let mut acc = LtHash16::default(); + for doc in &docs { + acc.add(doc); + } + assert_ne!(acc, LtHash16::default()); + + let mut backwards = LtHash16::default(); + for doc in docs.iter().rev() { + backwards.add(doc); + } + assert_eq!(acc, backwards, "equal sets in two orders differ"); + + let mut strided = LtHash16::default(); + for index in (0..docs.len()).map(|step| (step * 7) % docs.len()) { + strided.add(&docs[index]); + } + assert_eq!(acc, strided, "equal sets in a third order differ"); + + for index in (0..docs.len()).map(|step| (step * 11) % docs.len()) { + acc.subtract(&docs[index]); + } + assert_eq!(acc, LtHash16::default(), "add then subtract left a residue"); + } + + /// A lane that carries must wrap: 40 additions of one document overflow + /// nearly every lane of a `u16`, and the subtractions still return to zero. + #[test] + fn lanes_wrap_instead_of_saturating() { + let doc = documents(1)[0]; + let mut acc = LtHash16::default(); + for _ in 0..40 { + acc.add(&doc); + } + for _ in 0..40 { + acc.subtract(&doc); + } + assert_eq!(acc, LtHash16::default()); + } + + #[test] + fn the_state_digest_seals_the_revision_and_every_lane() { + let docs = documents(3); + let mut acc = LtHash16::default(); + docs.iter().for_each(|doc| acc.add(doc)); + assert_ne!(acc.state_digest(1), acc.state_digest(2), "the revision is not sealed"); + let mut other = acc.clone(); + other.0[1023] = other.0[1023].wrapping_add(1); + assert_ne!(acc.state_digest(1), other.state_digest(1), "the last lane is not hashed"); + } + + #[test] + fn a_document_digest_separates_schema_key_and_value() { + let one = doc_digest("ab", "c", &1u8).unwrap(); + assert_ne!(one, doc_digest("a", "bc", &1u8).unwrap(), "schema and key run together"); + assert_ne!(one, doc_digest("ab", "c", &2u8).unwrap()); + assert_ne!(one, doc_digest("ab", "d", &1u8).unwrap()); + assert_eq!(one, doc_digest("ab", "c", &1u8).unwrap()); + } +} diff --git a/native/aetherlight/src/docs.rs b/native/aetherlight/src/docs.rs index 916311504..fff61f099 100644 --- a/native/aetherlight/src/docs.rs +++ b/native/aetherlight/src/docs.rs @@ -211,3 +211,110 @@ impl<A: DocKey, B: DocKey> DocKey for (A, B) { format!("{}/{}", self.0.key_text(), self.1.key_text()) } } + +#[cfg(test)] +mod tests { + use super::*; + + type Rows = Docs<u8, u8>; + + fn rows(held: &[(u8, u8)]) -> Rows { + let mut docs = Rows::default(); + for (key, value) in held { + docs.insert(*key, *value); + } + docs.finish(); + docs + } + + fn contents(docs: &Rows) -> Vec<(u8, u8)> { + docs.iter().map(|(key, value)| (*key, *value)).collect() + } + + #[test] + fn a_write_is_reported_with_the_value_the_transaction_began_with() { + let mut docs = rows(&[(1, 10), (2, 20)]); + docs.insert(1, 11); + docs.insert(1, 12); + docs.insert(3, 30); + docs.remove(&2); + let mut changed = docs.finish(); + changed.sort(); + assert_eq!(changed, vec![(1, Some(10)), (2, Some(20)), (3, None)]); + assert!(docs.finish().is_empty(), "finish empties the log"); + assert!(docs.is_clean()); + } + + #[test] + fn a_key_written_back_to_what_it_was_is_not_a_change() { + let mut docs = rows(&[(1, 10), (2, 20)]); + docs.insert(1, 11); + docs.insert(1, 10); + docs.insert(3, 30); + docs.remove(&3); + *docs.get_mut(&2).unwrap() = 20; + *docs.entry(2).or_insert(0) = 20; + assert!(docs.changes().next().is_none()); + assert!(docs.finish().is_empty()); + } + + #[test] + fn a_get_mut_that_misses_touches_nothing() { + let mut docs = rows(&[(1, 10)]); + assert!(docs.get_mut(&9).is_none()); + assert!(docs.is_clean()); + *docs.get_mut(&1).unwrap() += 1; + assert!(!docs.is_clean()); + assert_eq!(docs.finish(), vec![(1, Some(10))]); + } + + #[test] + fn an_entry_that_adds_a_row_is_a_change_and_one_that_finds_it_is_not() { + let mut docs = rows(&[(1, 10)]); + docs.entry(1).or_insert(99); + docs.entry(2).or_insert(20); + assert_eq!(docs.finish(), vec![(2, None)]); + assert_eq!(contents(&docs), vec![(1, 10), (2, 20)]); + } + + #[test] + fn rollback_restores_every_touched_key_and_empties_the_log() { + let mut docs = rows(&[(1, 10), (2, 20), (3, 30)]); + docs.insert(1, 11); + docs.insert(4, 40); + docs.remove(&2); + *docs.get_mut(&3).unwrap() = 31; + *docs.entry(5).or_insert(0) = 50; + docs.rollback(); + assert_eq!(contents(&docs), vec![(1, 10), (2, 20), (3, 30)]); + assert!(docs.is_clean()); + } + + #[test] + fn equality_is_the_documents_and_not_the_log() { + let mut open = rows(&[(1, 10)]); + open.insert(1, 11); + open.insert(1, 10); + assert_eq!(open, rows(&[(1, 10)])); + } + + #[test] + fn the_header_is_logged_once_and_a_genesis_value_is_an_addition() { + let mut header = Tracked::absent(5u8); + assert_eq!(header.finish(), Some(None), "genesis adds the header"); + + *header.get_mut() = 6; + *header.get_mut() = 7; + assert_eq!(header.finish(), Some(Some(5))); + assert!(header.is_clean()); + + *header.get_mut() = 8; + *header.get_mut() = 7; + assert_eq!(header.finish(), None, "written back is not a change"); + + *header.get_mut() = 9; + header.rollback(); + assert_eq!(*header, 7); + assert!(header.is_clean()); + } +} diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs index e1138bd39..e6a7a8208 100644 --- a/native/aetherlight/src/golden_tests.rs +++ b/native/aetherlight/src/golden_tests.rs @@ -212,116 +212,279 @@ fn export_open_round_trip_is_exact() { assert_eq!(original.export().unwrap(), reopened.export().unwrap()); } -/// What one tick and one speech cost to commit as the world grows: ten persons -/// to a place, one Routine each with period 60, due staggered over the hour. -/// Run on its own, in release, to read the numbers; no threshold is asserted. +/// The digest is what a replay or a fresh recompute would derive, at every +/// revision of the golden session and after reopening it, and also across a +/// removal, which the session itself never makes. +#[test] +fn incremental_digest_equals_full_recompute() { + let (mut kernel, _) = golden_session(); + let commits = kernel.journal.commits_for_test(); + for (index, commit) in commits.iter().enumerate() { + let replayed = crate::journal::verify_history(&commits[..=index]).unwrap(); + assert_eq!( + replayed.full_state_digest().unwrap(), + commit.resulting_state_digest, + "revision {index}: the incremental digest left the full recompute" + ); + } + assert_eq!(kernel.state.full_state_digest().unwrap(), kernel.state.state_digest); + + // A removal: the witness forgets what it was told. + let witness = subject_by_label(&kernel.state, "The Witness"); + let (fact, _) = kernel + .state + .knowledge_of(witness) + .next() + .expect("the witness knows something"); + let fact = *fact; + let rows = kernel.state.knowledge.len(); + let snapshot = kernel.snapshot().unwrap(); + submit_play( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::Forget { + subject: Ref::Existing(witness), + fact: Ref::Existing(fact), + }]), + ); + assert_eq!(kernel.state.knowledge.len(), rows - 1, "a row was removed"); + assert_eq!(kernel.state.full_state_digest().unwrap(), kernel.state.state_digest); + + let reopened = WorldKernel::open(&kernel.export().unwrap()).unwrap(); + assert_eq!(reopened.state.full_state_digest().unwrap(), reopened.state.state_digest); + assert_eq!(reopened.state.accumulator, kernel.state.accumulator); +} + +/// The clockwork world: `persons` persons, ten to a place, one Routine each +/// with period `persons / 2`, due `1 + i mod (persons / 2)`, so a one-minute +/// tick rolls two routines at every size and a speech reaches the same nine +/// listeners. +fn clockwork_world(persons: usize) -> (WorldKernel, Vec<crate::SubjectId>, crate::AffordanceId) { + use crate::patch::kernel_speak_grant; + use crate::patch::{EntityDeclaration, SubjectDeclaration}; + use crate::{CallerId, CommandEnvelope, CreateWorld, EntityKind, SubjectKind}; + + let places = persons / 10; + let mut declarations = Vec::new(); + for place in 0..places { + declarations.push(Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(format!("place-{place}")), + label: format!("Place {place}"), + kind: EntityKind::Place, + container: None, + })); + } + for person in 0..persons { + declarations.push(Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(format!("person-{person}")), + label: format!("Person {person}"), + kind: SubjectKind::Person, + affordances: kernel_speak_grant(), + position: Some(Ref::Draft(DraftHandle::new(format!("place-{}", person / 10)))), + import_key: None, + })); + } + let (mut kernel, _) = WorldKernel::create( + CreateWorld { + owner: owner(), + title: "Clockwork".into(), + patch: WorldPatch { + declarations, + operations: Vec::new(), + evidence: Vec::new(), + }, + grammar: None, + }, + &auth_principal(owner()), + ) + .expect("the clockwork world is created"); + let people: Vec<_> = (0..persons) + .map(|person| subject_by_label(&kernel.state, &format!("Person {person}"))) + .collect(); + let period = (persons / 2) as u64; + let routines = people + .iter() + .enumerate() + .map(|(index, subject)| ComponentOp::CreateCommitment { + subject: Ref::Existing(*subject), + counterparty: None, + kind: CommitmentKind::Routine, + due: FictionalMinutes(1 + index as u64 % period), + period: Some(TickMinutes::new(period as u32).unwrap()), + checks: Vec::new(), + statement: Statement::new("Keeps the hour.").unwrap(), + }) + .collect(); + let placing = CommandEnvelope { + world_id: kernel.state.header.world_id, + expected_revision: kernel.state.revision, + caller: CallerId::Play, + body: operations(routines), + }; + kernel + .submit(placing, &AuthenticatedCaller::verified_play()) + .expect("the routines are placed"); + let speak_entry = *kernel + .state + .affordance_catalog + .iter() + .find(|(_, entry)| entry.kind.0 == "speak") + .map(|(id, _)| id) + .expect("genesis admits Speak"); + (kernel, people, speak_entry) +} + +fn clockwork_envelope(kernel: &WorldKernel, body: CommandBody) -> crate::CommandEnvelope { + crate::CommandEnvelope { + world_id: kernel.state.header.world_id, + expected_revision: kernel.state.revision, + caller: crate::CallerId::Play, + body, + } +} + +/// Submits and reports the document digests the commit computed beside the +/// ones its change set implies: added + removed + 2 x updated, counted by +/// enumerating every document before and after. +fn submit_counting_digests(kernel: &mut WorldKernel, body: CommandBody) -> (usize, usize) { + let before = kernel.state.documents().unwrap(); + let envelope = clockwork_envelope(kernel, body); + crate::digest::DOC_DIGESTS.with(|count| count.set(0)); + kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .expect("the commit lands"); + let computed = crate::digest::DOC_DIGESTS.with(|count| count.get()); + let after = kernel.state.documents().unwrap(); + let added = after.keys().filter(|key| !before.contains_key(*key)).count(); + let removed = before.keys().filter(|key| !after.contains_key(*key)).count(); + let updated = after + .iter() + .filter(|(key, digest)| before.get(*key).is_some_and(|old| old != *digest)) + .count(); + (computed, added + removed + 2 * updated) +} + +/// A commit's digest work is what it changed, not what the world holds: a tick +/// and a speech cost the same number of document digests at 100 persons and at +/// 1600, and exactly Added + Removed + 2 x Updated of that commit. +#[test] +fn digest_work_is_equal_at_100_and_1600() { + let mut worked = Vec::new(); + for persons in [100usize, 1600] { + let (mut kernel, people, speak_entry) = clockwork_world(persons); + let mut counts = Vec::new(); + for _ in 0..3 { + counts.push(submit_counting_digests(&mut kernel, tick_body(1))); + } + for index in 0..3 { + let speech = CommandBody::Act { + actor: people[index], + invocation: speak(speak_entry, &format!("Speech {index}.")), + }; + counts.push(submit_counting_digests(&mut kernel, speech)); + } + for (computed, implied) in &counts { + assert!(*computed > 0, "a commit changed documents and digested none"); + assert_eq!( + computed, implied, + "{persons} persons: digests != Added + Removed + 2 x Updated" + ); + } + worked.push(counts); + } + assert_eq!(worked[0], worked[1], "digest work grew with the world"); +} + +/// A failed apply leaves nothing behind: state, accumulator and digest equal +/// to before, no transaction open, and the next honest command commits. The +/// failure is the revision overflow a tick meets after it has written the +/// clock, a routine and its pressure. +#[test] +fn a_failed_apply_rolls_back() { + let (mut kernel, _, _) = clockwork_world(20); + let honest_revision = kernel.state.revision; + kernel.state.revision = u64::MAX; + let before = kernel.state.clone(); + let commits = kernel.journal.commit_count(); + + let tick = clockwork_envelope(&kernel, tick_body(1)); + let error = kernel + .submit(tick, &AuthenticatedCaller::verified_play()) + .unwrap_err(); + assert!(matches!(error, KernelError::Serialization(_)), "{error:?}"); + assert_eq!(kernel.state, before, "the failed tick left writes behind"); + assert_eq!(kernel.journal.commit_count(), commits); + kernel.state.begin(); + assert_eq!(kernel.state.folded().unwrap(), kernel.state.accumulator); + assert_eq!( + kernel.state.accumulator.state_digest(u64::MAX), + kernel.state.full_state_digest().unwrap(), + "the accumulator no longer matches the documents" + ); + + kernel.state.revision = honest_revision; + let tick = clockwork_envelope(&kernel, tick_body(1)); + kernel + .submit(tick, &AuthenticatedCaller::verified_play()) + .expect("the next honest command commits"); + assert_eq!(kernel.state.full_state_digest().unwrap(), kernel.state.state_digest); +} + +/// What one tick and one speech cost to commit as the world grows, by the +/// clockwork world above. Run on its own, in release, to read the numbers; no +/// time is asserted here. The timing gate belongs to the follow-up +/// `aetherlight-read-indexes-timing-gate`, because the world reads a commit +/// makes (`audience`, `derive_motion`) are still O(world) and bound the ratio. +/// `digest_work_is_equal_at_100_and_1600` is the gate on what this commit owns. /// /// `cargo test --release --lib clockwork_commit_cost -- --ignored --nocapture` #[test] #[ignore] fn clockwork_commit_cost() { - use crate::patch::kernel_speak_grant; - use crate::patch::{Declaration, DraftHandle, EntityDeclaration, SubjectDeclaration}; - use crate::{CallerId, CommandEnvelope, CreateWorld, EntityKind, SubjectKind, WorldPatch}; - - println!("persons places create_ms tick_mean_ms speech_mean_ms revision_after"); + println!("persons create_ms tick_ms tick_digests speech_ms speech_digests"); + let mut ticks_ms = Vec::new(); + let mut speeches_ms = Vec::new(); for persons in [100usize, 400, 1600] { - let places = persons / 10; - let mut declarations = Vec::new(); - for place in 0..places { - declarations.push(Declaration::Entity(EntityDeclaration { - handle: DraftHandle::new(format!("place-{place}")), - label: format!("Place {place}"), - kind: EntityKind::Place, - container: None, - })); - } - for person in 0..persons { - declarations.push(Declaration::Subject(SubjectDeclaration { - handle: DraftHandle::new(format!("person-{person}")), - label: format!("Person {person}"), - kind: SubjectKind::Person, - affordances: kernel_speak_grant(), - position: Some(Ref::Draft(DraftHandle::new(format!("place-{}", person / 10)))), - import_key: None, - })); - } let started = Instant::now(); - let (mut kernel, _) = WorldKernel::create( - CreateWorld { - owner: owner(), - title: "Clockwork".into(), - patch: WorldPatch { - declarations, - operations: Vec::new(), - evidence: Vec::new(), - }, - grammar: None, - }, - &auth_principal(owner()), - ) - .expect("the clockwork world is created"); + let (mut kernel, people, speak_entry) = clockwork_world(persons); let create_ms = started.elapsed().as_secs_f64() * 1e3; - - let people: Vec<_> = (0..persons) - .map(|person| subject_by_label(&kernel.state, &format!("Person {person}"))) - .collect(); - let routines = people - .iter() - .enumerate() - .map(|(index, subject)| ComponentOp::CreateCommitment { - subject: Ref::Existing(*subject), - counterparty: None, - kind: CommitmentKind::Routine, - due: FictionalMinutes(1 + (index % 60) as u64), - period: Some(TickMinutes::new(60).unwrap()), - checks: Vec::new(), - statement: Statement::new("Keeps the hour.").unwrap(), - }) - .collect(); let play = AuthenticatedCaller::verified_play(); - let envelope = |kernel: &WorldKernel, body: CommandBody| CommandEnvelope { - world_id: kernel.state.header.world_id, - expected_revision: kernel.state.revision, - caller: CallerId::Play, - body, - }; - let placing = envelope(&kernel, operations(routines)); - kernel.submit(placing, &play).expect("the routines are placed"); - let speak_entry = *kernel - .state - .affordance_catalog - .iter() - .find(|(_, entry)| entry.kind.0 == "speak") - .map(|(id, _)| id) - .expect("genesis admits Speak"); - - let mut ticks = 0.0; + let (mut ticks, mut tick_digests) = (0.0, 0); for _ in 0..30 { - let tick = envelope(&kernel, tick_body(1)); + let tick = clockwork_envelope(&kernel, tick_body(1)); + crate::digest::DOC_DIGESTS.with(|count| count.set(0)); let started = Instant::now(); kernel.submit(tick, &play).expect("the tick commits"); ticks += started.elapsed().as_secs_f64() * 1e3; + tick_digests = crate::digest::DOC_DIGESTS.with(|count| count.get()); } - let mut speeches = 0.0; + let (mut speeches, mut speech_digests) = (0.0, 0); for index in 0..30 { - let act = envelope( + let act = clockwork_envelope( &kernel, CommandBody::Act { actor: people[index], invocation: speak(speak_entry, &format!("Speech {index}.")), }, ); + crate::digest::DOC_DIGESTS.with(|count| count.set(0)); let started = Instant::now(); kernel.submit(act, &play).expect("the speech commits"); speeches += started.elapsed().as_secs_f64() * 1e3; + speech_digests = crate::digest::DOC_DIGESTS.with(|count| count.get()); } println!( - "{persons:>7} {places:>6} {create_ms:>9.1} {:>12.2} {:>14.2} {:>14}", + "{persons:>7} {create_ms:>9.1} {:>7.3} {tick_digests:>12} {:>9.3} {speech_digests:>14}", ticks / 30.0, speeches / 30.0, - kernel.state.revision ); + ticks_ms.push(ticks / 30.0); + speeches_ms.push(speeches / 30.0); } + println!( + "ratio 1600/100: tick {:.2} speech {:.2}", + ticks_ms[2] / ticks_ms[0], + speeches_ms[2] / speeches_ms[0] + ); } diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index 1296329f1..59a27a917 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -914,6 +914,23 @@ mod tests { )); } + /// A chain written under the whole-state digest is refused: its commits carry + /// the v1 schema, re-sealed end to end so the schema is the only thing wrong. + #[test] + fn a_v1_commit_is_refused() { + let kernel = clock_history(); + let mut v1 = kernel.journal.commits.clone(); + reopen(&v1).expect("the honest chain opens"); + for index in 0..v1.len() { + v1[index].schema = "aetherlight.world_commit.v1".into(); + if index > 0 { + v1[index].previous_commit_digest = Some(v1[index - 1].digest.clone()); + } + v1[index].digest = commit_digest(&v1[index]).unwrap(); + } + assert!(matches!(reopen(&v1), Err(JournalError::Corrupt(_)))); + } + /// A stored digest is checked against the commit it seals, on its own: /// flipping one character of any commit's digest, with nothing re-sealed, /// leaves only the digest clause to refuse it (the last commit and a lone From 30c65cdef5ae7c86ba89f0834b6777dd6c5e2756 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 04:05:51 +0100 Subject: [PATCH 152/190] aetherlight: kill the surviving mutants of the digest and replay rewrite An unchanged touched document costs no digest, begin refuses an open log, known_by is the knowledge partition read the other way, each arm of the knowledge shape check and of the committed-command target check is judged alone, the replay future check reads only touched new keys, and document keys are canonical text. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/golden_tests.rs | 103 ++++++++++++++++++++++++- native/aetherlight/src/journal.rs | 52 +++++++++++++ 2 files changed, 154 insertions(+), 1 deletion(-) diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs index e6a7a8208..fdf118edc 100644 --- a/native/aetherlight/src/golden_tests.rs +++ b/native/aetherlight/src/golden_tests.rs @@ -25,7 +25,7 @@ use std::time::Instant; /// two-band `toss` is declared, granted to The Human and used three times (so /// the band draw is recorded), a Routine is placed on The Witness, thirty minutes roll it, and The Human /// invokes `convene`, which it does not hold. -fn golden_session() -> (WorldKernel, String) { +pub(super) fn golden_session() -> (WorldKernel, String) { let (mut kernel, _) = WorldKernel::create(creation("Golden"), &auth_principal(owner())) .expect("the fixture world is created"); let human = subject_by_label(&kernel.state, "The Human"); @@ -488,3 +488,104 @@ fn clockwork_commit_cost() { speeches_ms[2] / speeches_ms[0] ); } + +/// A document written back to what it was costs no digest: the transaction +/// logged it, and folding finds nothing changed. A real change costs two (the +/// old, subtracted, and the new, added) and moves the accumulator. +#[test] +fn a_touched_document_written_back_costs_no_digest() { + let (mut kernel, _) = golden_session(); + let witness = subject_by_label(&kernel.state, "The Witness"); + let before = kernel.state.accumulator.clone(); + let digests = || crate::digest::DOC_DIGESTS.with(|count| count.get()); + + kernel.state.begin(); + let now = kernel.state.header.now; + kernel.state.header.get_mut().now = now; + kernel.state.commitments.get_mut(&witness).expect("the witness holds a routine"); + crate::digest::DOC_DIGESTS.with(|count| count.set(0)); + assert_eq!(kernel.state.folded().unwrap(), before); + assert_eq!(digests(), 0, "an unchanged document was digested"); + + kernel.state.header.get_mut().now = FictionalMinutes(now.0 + 1); + crate::digest::DOC_DIGESTS.with(|count| count.set(0)); + assert_ne!(kernel.state.folded().unwrap(), before); + assert_eq!(digests(), 2, "an updated document is its old digest and its new"); + kernel.state.rollback(); + assert_eq!(kernel.state.header.now, now); +} + +/// A transaction is never opened over an open one, nor over a stray write. +#[cfg(debug_assertions)] +#[test] +#[should_panic(expected = "a transaction is open")] +fn begin_refuses_an_open_header_log() { + let (mut kernel, _) = golden_session(); + kernel.state.header.get_mut(); + kernel.state.begin(); +} + +#[cfg(debug_assertions)] +#[test] +#[should_panic] +fn begin_refuses_an_open_partition_log() { + let (mut kernel, _) = golden_session(); + let witness = subject_by_label(&kernel.state, "The Witness"); + kernel.state.commitments.get_mut(&witness); + kernel.state.begin(); +} + +/// The snapshot's `known_by` is the knowledge partition read the other way: +/// exactly the subjects holding a row for the fact. +#[test] +fn a_fact_is_known_by_exactly_the_subjects_holding_a_row() { + let (kernel, _) = golden_session(); + let snapshot = kernel.snapshot().unwrap(); + assert!(snapshot.facts.iter().any(|fact| !fact.known_by.is_empty())); + for fact in &snapshot.facts { + let holders: Vec<_> = kernel + .state + .subjects + .keys() + .filter(|subject| kernel.state.knowledge.contains_key(&(**subject, fact.id))) + .copied() + .collect(); + assert_eq!(fact.known_by, holders); + } +} + +/// A knowledge row names a live subject and a canonical fact, each judged on +/// its own. +#[test] +fn a_knowledge_row_without_a_subject_or_a_fact_is_corrupt() { + use crate::tests::subject_by_label; + let (kernel, _) = golden_session(); + let witness = subject_by_label(&kernel.state, "The Witness"); + let (fact, held) = kernel + .state + .knowledge_of(witness) + .next() + .map(|(fact, held)| (*fact, *held)) + .expect("the witness knows something"); + crate::journal::verify_state_shape(&kernel.state).expect("the honest state passes"); + + let mut no_subject = kernel.state.clone(); + no_subject.knowledge.insert((crate::SubjectId::issue(), fact), held); + assert!(crate::journal::verify_state_shape(&no_subject).is_err()); + + let mut no_fact = kernel.state.clone(); + no_fact.knowledge.insert((witness, crate::EntityId::issue()), held); + assert!(crate::journal::verify_state_shape(&no_fact).is_err()); +} + +/// The text a document is keyed by is the contract the digest hashes: an id's +/// uuid, a pair's two joined by a slash, a grievance kind's name. +#[test] +fn document_keys_are_canonical_text() { + use crate::docs::DocKey; + let subject = crate::SubjectId::issue(); + let fact = crate::EntityId::issue(); + assert_eq!(subject.key_text(), subject.0.to_string()); + assert_eq!((subject, fact).key_text(), format!("{}/{}", subject.0, fact.0)); + assert_eq!(crate::patch::GrievanceKindName("theft".into()).key_text(), "theft"); +} diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index 59a27a917..de93b50ea 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -931,6 +931,58 @@ mod tests { assert!(matches!(reopen(&v1), Err(JournalError::Corrupt(_)))); } + /// The replay-side future check reads only the subjects the transaction + /// touched, and a key a subject already held is not newly born. + #[test] + fn a_commitment_born_due_is_corrupt_only_for_a_touched_new_key() { + use crate::tests::subject_by_label; + let (kernel, _) = crate::golden_tests::golden_session(); + let witness = subject_by_label(&kernel.state, "The Witness"); + let held = kernel + .state + .commitments + .get(&witness) + .cloned() + .expect("the witness holds a routine"); + let mut early = kernel.state.clone(); + early.header.get_mut().now = crate::FictionalMinutes(0); + let mut late = kernel.state.clone(); + late.header.get_mut().now = crate::FictionalMinutes(u64::MAX); + + assert!(verify_commitments_are_future(&early, &[(witness, None)]).is_ok()); + assert!(matches!( + verify_commitments_are_future(&late, &[(witness, None)]), + Err(JournalError::Corrupt(_)) + )); + assert!(verify_commitments_are_future(&late, &[(witness, Some(held))]).is_ok()); + assert!(verify_commitments_are_future(&late, &[]).is_ok()); + } + + /// A committed command names the exact world and revision it applies to; + /// each is judged on its own. + #[test] + fn a_command_aimed_at_another_world_or_revision_is_corrupt() { + let kernel = clock_history(); + for aim_at_world in [true, false] { + let mut forged = kernel.journal.commits.clone(); + let last = forged.last_mut().unwrap(); + let CommittedCommand::WorldCommand(command) = &mut last.command else { + panic!("the last commit is a world command"); + }; + if aim_at_world { + command.world_id = WorldId::nil_for_test(); + } else { + command.expected_revision += 1; + } + last.digest = commit_digest(last).unwrap(); + assert!( + matches!(reopen(&forged), Err(JournalError::Corrupt(_))), + "a command aimed at another {} was admitted", + if aim_at_world { "world" } else { "revision" } + ); + } + } + /// A stored digest is checked against the commit it seals, on its own: /// flipping one character of any commit's digest, with nothing re-sealed, /// leaves only the digest clause to refuse it (the last commit and a lone From 412084d3085e5c19bb1af355aed95ee8f32bb05c Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 04:09:02 +0100 Subject: [PATCH 153/190] aetherlight: pin the snapshot's past_due against the clock Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/golden_tests.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs index fdf118edc..02e30ef37 100644 --- a/native/aetherlight/src/golden_tests.rs +++ b/native/aetherlight/src/golden_tests.rs @@ -589,3 +589,26 @@ fn document_keys_are_canonical_text() { assert_eq!((subject, fact).key_text(), format!("{}/{}", subject.0, fact.0)); assert_eq!(crate::patch::GrievanceKindName("theft".into()).key_text(), "theft"); } + +/// The snapshot says a commitment is past due exactly when its due minute has +/// been reached: the golden's routine rolled once by a thirty-minute tick and +/// is due again at or before the clock. +#[test] +fn a_commitment_due_at_or_before_the_clock_reads_past_due() { + let (kernel, _) = golden_session(); + let witness = subject_by_label(&kernel.state, "The Witness"); + let snapshot = kernel.snapshot().unwrap(); + let subject = snapshot + .subjects + .iter() + .find(|subject| subject.id == witness) + .expect("the witness is a subject"); + assert!(!subject.commitments.is_empty()); + for commitment in &subject.commitments { + assert_eq!(commitment.past_due, commitment.due <= kernel.state.header.now); + } + assert!( + subject.commitments.iter().any(|commitment| commitment.past_due), + "the routine fell due behind the clock" + ); +} From 6896553a5b1971202f3c4a0cca5ccf23de9301a2 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 04:44:41 +0100 Subject: [PATCH 154/190] aetherlight: the partitions are declared once, the table is generated The WorldState partition fields, the table begin/folded/finish/rollback and the test oracle walk, and the empty world all come from one world_state! row list. A partition cannot be a field without being in the digest and under the undo log, and a field added to the generated struct without a row fails to compile (missing field in with_header). Addresses partition-table-second-authority. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/lib.rs | 166 ++++++++++++++++------------------ 1 file changed, 78 insertions(+), 88 deletions(-) diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index 75cc8a108..30a3c8a12 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -454,63 +454,104 @@ struct WorldHeader { now: FictionalMinutes, } +/// The world's partitions, declared once. Each row names a partition, its +/// key and value types and the schema its documents are digested with; the +/// struct, the table `begin`, `folded`, `finish`, `rollback` and the test +/// oracle walk, and the empty world are all generated from these rows, so a +/// partition is in the digest and under the undo log because it exists, and +/// there is no second list to forget it from. +/// /// Every partition is a `Docs`: reads see the map, every write is logged, and /// `submit` applies in place and either finishes or rolls the log back. -#[derive(Clone, Debug, PartialEq, Eq)] -struct WorldState { - header: Tracked<WorldHeader>, - revision: u64, - subjects: Docs<SubjectId, SubjectState>, - entities: Docs<EntityId, EntityRecord>, - edges: Docs<EdgeId, EdgeRecord>, - positions: Docs<SubjectId, Position>, +macro_rules! world_state { + ($($(#[$meta:meta])* $field:ident: Docs<$key:ty, $value:ty> = $schema:literal;)*) => { + #[derive(Clone, Debug, PartialEq, Eq)] + struct WorldState { + header: Tracked<WorldHeader>, + revision: u64, + $($(#[$meta])* $field: Docs<$key, $value>,)* + // The chain head: outside every document. + accumulator: LtHash16, + state_digest: String, + last_commit_digest: Option<String>, + } + + impl WorldState { + /// The number of partitions. + const PARTITIONS: usize = [$($schema),*].len(); + + /// Every partition under the schema its documents are digested with. + fn partitions(&self) -> [(&'static str, &dyn Partition); Self::PARTITIONS] { + [$(($schema, &self.$field as &dyn Partition)),*] + } + + fn partitions_mut(&mut self) -> [(&'static str, &mut dyn Partition); Self::PARTITIONS] { + [$(($schema, &mut self.$field as &mut dyn Partition)),*] + } + + /// A world with this header, revision 0 and no documents. + fn with_header(header: Tracked<WorldHeader>) -> Self { + Self { + header, + revision: 0, + $($field: Docs::default(),)* + accumulator: LtHash16::default(), + state_digest: String::new(), + last_commit_digest: None, + } + } + } + }; +} + +world_state! { + subjects: Docs<SubjectId, SubjectState> = "aetherlight.subject.v1"; + entities: Docs<EntityId, EntityRecord> = "aetherlight.entity.v1"; + edges: Docs<EdgeId, EdgeRecord> = "aetherlight.edge.v1"; + positions: Docs<SubjectId, Position> = "aetherlight.position.v1"; /// What each subject holds. Absence is zero at both levels: no stored /// `Quantity(0)` and no empty inner map, so a duplicate holding is /// unrepresentable and "nothing" has one shape. - holdings: Docs<SubjectId, BTreeMap<EntityId, Quantity>>, + holdings: Docs<SubjectId, BTreeMap<EntityId, Quantity>> = "aetherlight.holdings.v1"; /// What each subject depends on. Never empty for a present key. - dependencies: Docs<SubjectId, BTreeSet<DependencyTarget>>, + dependencies: Docs<SubjectId, BTreeSet<DependencyTarget>> = "aetherlight.dependencies.v1"; /// One row per `EntityKind::Fact` entity, and no orphan either way. Facts /// are write-once: declaration and `AssertClaim` are the only writers, and /// standing never changes after admission. - facts: Docs<EntityId, FactRecord>, + facts: Docs<EntityId, FactRecord> = "aetherlight.fact.v1"; /// One row per `EntityKind::Channel` entity, and no orphan either way. - channels: Docs<EntityId, ChannelRecord>, + channels: Docs<EntityId, ChannelRecord> = "aetherlight.channel.v1"; /// What each subject knows. The sole owner of who-heard-what: `events` /// records what was done, and this decides what a subject may act on and /// what its projection may contain. One document per (subject, fact), and /// absence is "knows nothing of it" — forgetting removes the key. - knowledge: Docs<(SubjectId, EntityId), Knowledge>, + knowledge: Docs<(SubjectId, EntityId), Knowledge> = "aetherlight.knowledge.v1"; /// What ground each subject has jurisdiction over, and under which /// world-declared kind. Never empty for a present key. No subject holds two /// grants of one kind over overlapping ground, so nothing ever arbitrates /// between two sources of one permission. - authority: Docs<SubjectId, BTreeSet<AuthorityGrant>>, + authority: Docs<SubjectId, BTreeSet<AuthorityGrant>> = "aetherlight.authority.v1"; /// The offices each institution constitutes, and who sits in them. An /// incumbent never acts as its institution: an office answers what its /// incumbent has jurisdiction over, not who the actor is. - selection: Docs<SubjectId, BTreeMap<OfficeName, Office>>, + selection: Docs<SubjectId, BTreeMap<OfficeName, Office>> = "aetherlight.selection.v1"; /// Where each kind of grievance goes, and who may bring it. Keyed by /// neither a subject nor a referent, so it enters no scope components and /// is admission-only state. - redress: Docs<GrievanceKindName, Forum>, + redress: Docs<GrievanceKindName, Forum> = "aetherlight.redress.v1"; /// What each subject has promised. Never empty for a present key. - commitments: Docs<SubjectId, BTreeMap<CommitmentKey, Commitment>>, + commitments: Docs<SubjectId, BTreeMap<CommitmentKey, Commitment>> = "aetherlight.commitments.v1"; /// Pressure *on* each subject, keyed target-major then source. Never empty /// for a present key; no stored zero magnitude. Lived meaning: read by /// projection and by nothing that decides. - pressures: Docs<SubjectId, BTreeMap<PressureSource, PressureMagnitude>>, + pressures: Docs<SubjectId, BTreeMap<PressureSource, PressureMagnitude>> = "aetherlight.pressures.v1"; /// What an affordance *is*. World-authored and written by `admit_resolved` /// alone. - affordance_catalog: Docs<AffordanceId, Affordance>, + affordance_catalog: Docs<AffordanceId, Affordance> = "aetherlight.affordance.v1"; /// Who may exercise which entry: a row exists if and only if the subject /// holds at least one verb. A grant carries no payload, so a duplicate /// grant is unrepresentable rather than checked. - affordance_grants: Docs<SubjectId, BTreeSet<AffordanceId>>, - // The chain head: outside every document. - accumulator: LtHash16, - state_digest: String, - last_commit_digest: Option<String>, + affordance_grants: Docs<SubjectId, BTreeSet<AffordanceId>> = "aetherlight.affordance_grants.v1"; } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] @@ -1113,35 +1154,6 @@ fn is_genesis(revision: u64, subjects: &BTreeMap<SubjectId, SubjectState>) -> bo revision == 0 && subjects.is_empty() } -/// The partition table: each partition under the schema its documents are -/// digested with. The one list `begin`, `folded`, `finish`, `rollback` and the -/// test oracle all walk. -macro_rules! partitions { - ($state:expr, $($borrow:tt)+) => { - [ - ("aetherlight.subject.v1", $($borrow)+ $state.subjects as $($borrow)+ dyn Partition), - ("aetherlight.entity.v1", $($borrow)+ $state.entities as $($borrow)+ dyn Partition), - ("aetherlight.edge.v1", $($borrow)+ $state.edges as $($borrow)+ dyn Partition), - ("aetherlight.position.v1", $($borrow)+ $state.positions as $($borrow)+ dyn Partition), - ("aetherlight.holdings.v1", $($borrow)+ $state.holdings as $($borrow)+ dyn Partition), - ("aetherlight.dependencies.v1", $($borrow)+ $state.dependencies as $($borrow)+ dyn Partition), - ("aetherlight.fact.v1", $($borrow)+ $state.facts as $($borrow)+ dyn Partition), - ("aetherlight.channel.v1", $($borrow)+ $state.channels as $($borrow)+ dyn Partition), - ("aetherlight.knowledge.v1", $($borrow)+ $state.knowledge as $($borrow)+ dyn Partition), - ("aetherlight.authority.v1", $($borrow)+ $state.authority as $($borrow)+ dyn Partition), - ("aetherlight.selection.v1", $($borrow)+ $state.selection as $($borrow)+ dyn Partition), - ("aetherlight.redress.v1", $($borrow)+ $state.redress as $($borrow)+ dyn Partition), - ("aetherlight.commitments.v1", $($borrow)+ $state.commitments as $($borrow)+ dyn Partition), - ("aetherlight.pressures.v1", $($borrow)+ $state.pressures as $($borrow)+ dyn Partition), - ("aetherlight.affordance.v1", $($borrow)+ $state.affordance_catalog as $($borrow)+ dyn Partition), - ( - "aetherlight.affordance_grants.v1", - $($borrow)+ $state.affordance_grants as $($borrow)+ dyn Partition, - ), - ] - }; -} - const WORLD_DOC_SCHEMA: &str = "aetherlight.world.v1"; impl WorldState { @@ -1149,7 +1161,7 @@ impl WorldState { /// transaction, or a transaction left open, is a bug here and not state. fn begin(&self) { debug_assert!(self.header.is_clean(), "a transaction is open"); - debug_assert!(partitions!(self, &).iter().all(|(_, docs)| docs.is_clean())); + debug_assert!(self.partitions().iter().all(|(_, docs)| docs.is_clean())); } /// What `subject` knows: its rows of the flat knowledge partition, by fact. @@ -1164,7 +1176,7 @@ impl WorldState { fn folded(&self) -> Result<LtHash16, KernelError> { let mut acc = self.accumulator.clone(); digest::fold_header(&mut acc, WORLD_DOC_SCHEMA, &self.header.world_id.key(), &self.header)?; - for (schema, docs) in partitions!(self, &) { + for (schema, docs) in self.partitions() { docs.fold_changes(schema, &mut acc)?; } Ok(acc) @@ -1181,7 +1193,7 @@ impl WorldState { self.accumulator = accumulator; self.header.finish(); let commitments = self.commitments.finish(); - for (_, docs) in partitions!(self, &mut) { + for (_, docs) in self.partitions_mut() { docs.finish_log(); } commitments @@ -1190,7 +1202,7 @@ impl WorldState { /// Closes the transaction, undoing every write in it. fn rollback(&mut self) { self.header.rollback(); - for (_, docs) in partitions!(self, &mut) { + for (_, docs) in self.partitions_mut() { docs.rollback(); } } @@ -1208,7 +1220,7 @@ impl WorldState { (WORLD_DOC_SCHEMA.to_owned(), key.clone()), digest::doc_digest(WORLD_DOC_SCHEMA, &key, header)?, ); - for (schema, docs) in partitions!(self, &) { + for (schema, docs) in self.partitions() { docs.documents(schema, &mut out)?; } Ok(out) @@ -1229,7 +1241,7 @@ impl WorldState { #[cfg(test)] fn encoded_documents(&self) -> Vec<u8> { let mut bytes = rmp_serde::to_vec_named(&*self.header).expect("the header encodes"); - for (_, docs) in partitions!(self, &) { + for (_, docs) in self.partitions() { bytes.extend(docs.encoded()); } bytes @@ -1246,35 +1258,13 @@ impl WorldState { title: String, grammar: Option<GrammarBinding>, ) -> Self { - Self { - header: Tracked::absent(WorldHeader { - world_id, - owner, - title, - grammar, - now: FictionalMinutes::default(), - }), - revision: 0, - subjects: Docs::default(), - entities: Docs::default(), - edges: Docs::default(), - positions: Docs::default(), - holdings: Docs::default(), - dependencies: Docs::default(), - facts: Docs::default(), - channels: Docs::default(), - knowledge: Docs::default(), - authority: Docs::default(), - selection: Docs::default(), - redress: Docs::default(), - commitments: Docs::default(), - pressures: Docs::default(), - affordance_catalog: Docs::default(), - affordance_grants: Docs::default(), - accumulator: LtHash16::default(), - state_digest: String::new(), - last_commit_digest: None, - } + Self::with_header(Tracked::absent(WorldHeader { + world_id, + owner, + title, + grammar, + now: FictionalMinutes::default(), + })) } fn genesis( From 415ac9208b836a9ba2530e4e591a43dc4e49e5cf Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 04:48:56 +0100 Subject: [PATCH 155/190] aetherlight: a commit of another schema generation is refused by name A v1 export is well-formed, so it is not corruption: open now returns UnsupportedSchema{found, supported} from the one schema judge, asked of every commit before its other fields are believed, instead of CorruptJournal at genesis. The test asserts the version in the error for a v1 chain and a later commit of another generation. Addresses v1-refusal-unnamed. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/journal.rs | 46 +++++++++++++++++++++++++------ native/aetherlight/src/lib.rs | 12 ++++++-- 2 files changed, 48 insertions(+), 10 deletions(-) diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index de93b50ea..c4ce73c75 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -13,6 +13,23 @@ pub(super) const JOURNAL_SCHEMA: &str = "aetherlight.journal.v1"; pub(super) enum JournalError { #[error("world journal is corrupt: {0}")] Corrupt(String), + /// A well-formed commit of another schema generation: not damage, a world + /// this build cannot read. Named apart so a store can tell an old save from + /// a corrupt one. + #[error("commit schema {found} is not the supported {supported}")] + UnsupportedSchema { found: String, supported: &'static str }, +} + +/// The one judge of the schema generation, asked of every commit before any of +/// its other fields is believed. +fn require_commit_schema(commit: &WorldCommit) -> Result<(), JournalError> { + if commit.schema == COMMIT_SCHEMA { + return Ok(()); + } + Err(JournalError::UnsupportedSchema { + found: commit.schema.clone(), + supported: COMMIT_SCHEMA, + }) } /// What an export carries: the schema that names the format, and the commits in @@ -106,6 +123,7 @@ pub(super) fn verify_history(commits: &[WorldCommit]) -> Result<WorldState, Jour let genesis = commits .first() .ok_or_else(|| JournalError::Corrupt("world has no genesis commit".into()))?; + require_commit_schema(genesis)?; let CommittedCommand::CreateWorld(genesis_command) = &genesis.command else { return Err(JournalError::Corrupt( "first commit does not contain the immutable creation command".into(), @@ -116,8 +134,7 @@ pub(super) fn verify_history(commits: &[WorldCommit]) -> Result<WorldState, Jour "first commit is not immutable world genesis".into(), )); }; - if genesis.schema != COMMIT_SCHEMA - || genesis.previous_revision.is_some() + if genesis.previous_revision.is_some() || genesis.resulting_revision != 0 || genesis.world_id != WorldId::of(genesis_command.id()) || genesis.previous_state_digest.is_some() @@ -141,8 +158,8 @@ pub(super) fn verify_history(commits: &[WorldCommit]) -> Result<WorldState, Jour replay.last_commit_digest = Some(genesis.digest.clone()); for commit in &commits[1..] { - if commit.schema != COMMIT_SCHEMA - || commit.world_id != replay.header.world_id + require_commit_schema(commit)?; + if commit.world_id != replay.header.world_id || commit.previous_revision != Some(replay.revision) || commit.resulting_revision != replay.revision.saturating_add(1) || commit.previous_state_digest.as_deref() != Some(replay.state_digest.as_str()) @@ -867,7 +884,7 @@ mod tests { reopen(&honest).expect("the honest chain opens"); let refused = |what: &str, commits: &[WorldCommit]| { assert!( - matches!(reopen(commits), Err(JournalError::Corrupt(_))), + reopen(commits).is_err(), "{what} was admitted" ); }; @@ -928,7 +945,20 @@ mod tests { } v1[index].digest = commit_digest(&v1[index]).unwrap(); } - assert!(matches!(reopen(&v1), Err(JournalError::Corrupt(_)))); + match reopen(&v1) { + Err(JournalError::UnsupportedSchema { found, supported }) => { + assert_eq!(found, "aetherlight.world_commit.v1"); + assert_eq!(supported, COMMIT_SCHEMA); + } + other => panic!("a v1 chain must be refused by name, got {other:?}"), + } + // A later commit of another generation is refused the same way. + let mut mixed = kernel.journal.commits.clone(); + last_commit(&mut mixed).schema = "aetherlight.world_commit.v3".into(); + assert!(matches!( + reopen(&mixed), + Err(JournalError::UnsupportedSchema { .. }) + )); } /// The replay-side future check reads only the subjects the transaction @@ -1032,7 +1062,7 @@ mod tests { forge(&mut forged); forged.digest = commit_digest(&forged).unwrap(); assert!( - matches!(reopen(&[forged]), Err(JournalError::Corrupt(_))), + reopen(&[forged]).is_err(), "a genesis with {what} was admitted" ); } @@ -1134,7 +1164,7 @@ mod tests { }); let error = reopen(&forged) .expect_err("a commit forged to the owner replayed"); - let JournalError::Corrupt(_) = error; + assert!(matches!(error, JournalError::Corrupt(_)), "{error:?}"); } } diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index 30a3c8a12..3918dba55 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -916,14 +916,22 @@ pub enum KernelError { Serialization(String), #[error("world journal is corrupt: {0}")] CorruptJournal(String), + /// A well-formed export written under another commit schema generation + /// (a v1 save): not corrupt, but not readable by this build. + #[error("export commit schema {found} is not the supported {supported}")] + UnsupportedSchema { found: String, supported: &'static str }, #[error("private reducer invariant failed: {0}")] Invariant(String), } impl From<journal::JournalError> for KernelError { fn from(error: journal::JournalError) -> Self { - let journal::JournalError::Corrupt(detail) = error; - Self::CorruptJournal(detail) + match error { + journal::JournalError::Corrupt(detail) => Self::CorruptJournal(detail), + journal::JournalError::UnsupportedSchema { found, supported } => { + Self::UnsupportedSchema { found, supported } + } + } } } From 9c8ab5ec851164b02167a4b41fa4f1b3319490ec Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 04:49:28 +0100 Subject: [PATCH 156/190] aetherlight: TickMinutes owns its bound at decode, replay's clock clause goes TickMinutes was serde(transparent): a stored zero-minute tick (or a span above MAX_ROUTE_COST, which submit cannot build) decoded, and replay's clock clause alone judged it. The type now decodes through TryFrom<u32> (1..=MAX_ROUTE_COST), so a command, a routine period or a stored tick outside the bound cannot be read. With that the clock clause in verify_history is unreachable (only TimeAdvanced writes the clock, and a tick's span is at least one minute), so it is deleted rather than defended; so is the period clause in verify_state_shape. Tests: bounds at decode, and an export whose tick span is rewritten to 0 or over the bound does not open. Addresses clock-clause-not-redundant. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/clock.rs | 29 +++++++-- native/aetherlight/src/journal.rs | 100 ++++++++++++++++-------------- 2 files changed, 79 insertions(+), 50 deletions(-) diff --git a/native/aetherlight/src/clock.rs b/native/aetherlight/src/clock.rs index a1ba08f94..bde23bb79 100644 --- a/native/aetherlight/src/clock.rs +++ b/native/aetherlight/src/clock.rs @@ -26,14 +26,33 @@ impl FictionalMinutes { } } -/// The span one `AdvanceTime` names. Constructor-checked `1..=MAX_ROUTE_COST` -/// (one year of minutes), reusing pass 2's constant as a span bound rather than -/// an edge bound: an unbounded span lets one command jump the clock past every -/// due date in the world and makes the size of a commit a caller-chosen number. +/// The span one `AdvanceTime` names, `1..=MAX_ROUTE_COST` (one year of +/// minutes), reusing pass 2's constant as a span bound rather than an edge +/// bound: an unbounded span lets one command jump the clock past every due date +/// in the world and makes the size of a commit a caller-chosen number. +/// +/// The type owns its bound at every door: `new` and decoding both go through +/// it, so a command, a routine's period or a stored commit that names a span +/// outside the bound cannot be read at all, and no reducer or replay clause +/// re-checks it. #[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[serde(transparent)] +#[serde(try_from = "u32", into = "u32")] pub struct TickMinutes(u32); +impl TryFrom<u32> for TickMinutes { + type Error = &'static str; + + fn try_from(minutes: u32) -> Result<Self, Self::Error> { + Self::new(minutes).ok_or("a tick span is 1..=525600 minutes") + } +} + +impl From<TickMinutes> for u32 { + fn from(span: TickMinutes) -> u32 { + span.0 + } +} + impl TickMinutes { pub fn new(minutes: u32) -> Option<Self> { (1..=MAX_ROUTE_COST) diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index c4ce73c75..09e7ca7b9 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -170,7 +170,6 @@ pub(super) fn verify_history(commits: &[WorldCommit]) -> Result<WorldState, Jour "commit chain is not contiguous or verifiable".into(), )); } - let previous_now = replay.header.now; // Authority is re-decided here for free: `apply_committed_command` // re-runs `reduce` against the pre-commit state and requires effect // equality, then `apply_effect`, and both of those call @@ -180,14 +179,10 @@ pub(super) fn verify_history(commits: &[WorldCommit]) -> Result<WorldState, Jour // third owner of one decision. replay.begin(); apply_committed_command(&mut replay, commit)?; - // Two chain checks one state cannot make: the clock never runs - // backwards, and it advances only on a tick. - let advanced = matches!(commit.effect, WorldEffect::TimeAdvanced { .. }); - if replay.header.now < previous_now || (replay.header.now > previous_now) != advanced { - return Err(JournalError::Corrupt( - "the world clock moved without a time-advanced commit, or ran backwards".into(), - )); - } + // The clock needs no chain check of its own: only `TimeAdvanced` writes + // it, `apply_effect` re-derives `to` from a `TickMinutes` that cannot + // be read outside `1..=MAX_ROUTE_COST`, so every tick moves it forward + // and nothing else moves it. replay.revision = commit.resulting_revision; let accumulator = replay.folded().map_err(kernel_error)?; replay.state_digest = accumulator.state_digest(replay.revision); @@ -407,9 +402,6 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> for (subject_id, held) in &state.commitments { let commitment_is_canonical = |commitment: &super::Commitment| { (commitment.kind == super::CommitmentKind::Routine) == commitment.period.is_some() - && commitment.period.is_none_or(|period| { - (1..=super::patch::MAX_ROUTE_COST).contains(&period.minutes()) - }) && (commitment.kind == super::CommitmentKind::Routine || commitment.checks.is_empty()) && match commitment.counterparty { @@ -961,6 +953,38 @@ mod tests { )); } + /// A stored tick whose span is zero or above the bound is not a world: the + /// export does not decode. This is the door the clock needs no check behind: + /// a zero-minute tick would be a commit that moves nothing, and an oversize + /// one a commit no `submit` could have built. + #[test] + fn a_stored_tick_with_a_span_outside_the_bound_does_not_open() { + let kernel = clock_history(); + let honest = export_of(&kernel.journal.commits); + // MessagePack names the span `minutes` and encodes the honest ones + // (1, 2, 30) as a single positive fixint byte, so each is rewritten in + // place, in the command and again in the effect. + let key = b"\xa7minutes"; + let at: Vec<usize> = (0..honest.len() - key.len()) + .filter(|&at| &honest[at..at + key.len()] == key) + .collect(); + assert!(at.len() >= 2, "a tick carries its span in the command and its effect"); + for forged_span in [vec![0x00], [&[0xce][..], &(crate::patch::MAX_ROUTE_COST + 1).to_be_bytes()].concat()] { + let mut bytes = honest.clone(); + for &start in at.iter().rev() { + let value = start + key.len(); + assert!(honest[value] < 0x80, "an honest span is a fixint"); + bytes.splice(value..=value, forged_span.iter().copied()); + } + let error = WorldJournal::open(&bytes).err().expect("a forged span opened"); + assert!( + error.to_string().contains("could not decode the export") + && error.to_string().contains("tick span"), + "{forged_span:?}: {error}" + ); + } + } + /// The replay-side future check reads only the subjects the transaction /// touched, and a key a subject already held is not newly born. #[test] @@ -2243,40 +2267,26 @@ mod custody_tests { let _ = subject; } - /// `TickMinutes` is `#[serde(transparent)]`, so a hand-written store row - /// can carry a period of zero — a routine that re-arms on the same minute - /// forever — without ever passing through `TickMinutes::new`. The shape - /// check now enforces the same `1..=MAX_ROUTE_COST` span bound the - /// constructor enforces, so the forged row is refused directly. + /// `TickMinutes` owns its bound at decode, so a span outside + /// `1..=MAX_ROUTE_COST` cannot be read in any position: a routine's period, + /// a command, or a tick's own effect. #[test] - fn soul_a_zero_period_is_refused_by_the_shape_check() { - let (kernel, subject) = ticking_world(); - - // The forgery an in-crate caller cannot write: `TickMinutes::new` - // refuses zero, and the field is private, so the only door is serde. - assert!(crate::TickMinutes::new(0).is_none()); - let zero: crate::TickMinutes = - rmp_serde::from_slice(&rmp_serde::to_vec(&0u32).unwrap()).expect("a transparent span"); - - let mut forged = kernel.state.clone(); - let key = *forged.commitments[&subject] - .iter() - .find(|(_, commitment)| commitment.period.is_some()) - .expect("the routine") - .0; - forged - .commitments - .get_mut(&subject) - .unwrap() - .get_mut(&key) - .unwrap() - .period = Some(zero); - - // The shape check refuses the forged span bound directly. - assert!( - matches!(verify_state_shape(&forged), Err(JournalError::Corrupt(_))), - "verify_state_shape admitted a period outside 1..=MAX_ROUTE_COST" - ); + fn a_span_outside_the_bound_cannot_be_decoded() { + for minutes in [0u32, crate::patch::MAX_ROUTE_COST + 1, u32::MAX] { + let raw = rmp_serde::to_vec(&minutes).unwrap(); + assert!( + rmp_serde::from_slice::<crate::TickMinutes>(&raw).is_err(), + "{minutes} decoded as a span" + ); + assert!(serde_json::from_value::<crate::TickMinutes>(minutes.into()).is_err()); + } + for minutes in [1u32, crate::patch::MAX_ROUTE_COST] { + let raw = rmp_serde::to_vec(&minutes).unwrap(); + assert_eq!( + rmp_serde::from_slice::<crate::TickMinutes>(&raw).unwrap().minutes(), + minutes + ); + } } } From 28db7e2197c26ce0871643169f8fb43fcddec5f3 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 04:56:03 +0100 Subject: [PATCH 157/190] aetherlight: pin every partition's digest, undo and finish, and the failure after the digest every_partition_is_digested_undone_and_finished iterates the declaration: for each partition one written document must be in the folded digest and agree with the full recompute, be put back by rollback (state, bytes, logs), and leave the logs empty and the accumulator at the full recompute on finish; a partition no fixture world populates fails loudly. a_failed_apply_rolls_back now runs a tick that rolls routines, a tick that writes pressure rows (the old tick wrote none, contrary to its doc), a speech and a forget, each under the revision overflow and under an injected failure after the digest is folded and the commit sealed (test-only thread-local seam in submit). Addresses table-rows-undefended. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/digest.rs | 19 +++ native/aetherlight/src/golden_tests.rs | 204 +++++++++++++++++++++---- native/aetherlight/src/lib.rs | 13 +- 3 files changed, 206 insertions(+), 30 deletions(-) diff --git a/native/aetherlight/src/digest.rs b/native/aetherlight/src/digest.rs index 8958f61a2..d9be5bff6 100644 --- a/native/aetherlight/src/digest.rs +++ b/native/aetherlight/src/digest.rs @@ -123,6 +123,12 @@ pub(crate) trait Partition { /// The partition as encoded: the bytes a test scans for what must never appear. #[cfg(test)] fn encoded(&self) -> Vec<u8>; + /// How many documents the partition holds. + #[cfg(test)] + fn rows(&self) -> usize; + /// Removes the first document, logged like any write; false when empty. + #[cfg(test)] + fn remove_first(&mut self) -> bool; } impl<K, V> Partition for Docs<K, V> @@ -167,6 +173,19 @@ where fn encoded(&self) -> Vec<u8> { rmp_serde::to_vec_named(self).expect("a partition encodes") } + + #[cfg(test)] + fn rows(&self) -> usize { + self.len() + } + + #[cfg(test)] + fn remove_first(&mut self) -> bool { + let Some(key) = self.keys().next().cloned() else { + return false; + }; + self.remove(&key).is_some() + } } /// The header's one change, keyed by its own world id. diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs index 02e30ef37..f8d632b81 100644 --- a/native/aetherlight/src/golden_tests.rs +++ b/native/aetherlight/src/golden_tests.rs @@ -395,39 +395,185 @@ fn digest_work_is_equal_at_100_and_1600() { assert_eq!(worked[0], worked[1], "digest work grew with the world"); } -/// A failed apply leaves nothing behind: state, accumulator and digest equal -/// to before, no transaction open, and the next honest command commits. The -/// failure is the revision overflow a tick meets after it has written the -/// clock, a routine and its pressure. +/// The ways a failed apply is injected: the revision overflow a tick meets after +/// it has written its documents, and the failure after the digest is folded and +/// the commit sealed, the last point before the world is kept. +#[derive(Clone, Copy, Debug)] +enum Failure { + RevisionOverflow, + AfterDigest, +} + +/// One command to fail, and the world to fail it in. +struct FailureCase { + name: &'static str, + kernel: WorldKernel, + body: CommandBody, +} + +/// Each case writes what its name says: the two ticks are checked against the +/// motion the clock derives for them, so a case cannot quietly stop writing. +fn failure_cases() -> Vec<FailureCase> { + let mut cases = Vec::new(); + + let (kernel, _, _) = clockwork_world(20); + let to = kernel.state.header.now.checked_add(TickMinutes::new(1).unwrap()).unwrap(); + assert!(!crate::clock::derive_motion(&kernel.state, to).fulfilled.is_empty()); + cases.push(FailureCase { name: "a tick that rolls routines", kernel, body: tick_body(1) }); + + let (kernel, _, _) = crate::clock_tests::clock_kernel("Pressure"); + let to = kernel.state.header.now.checked_add(TickMinutes::new(200).unwrap()).unwrap(); + assert!(!crate::clock::derive_motion(&kernel.state, to).pressed.is_empty()); + cases.push(FailureCase { name: "a tick that writes pressure rows", kernel, body: tick_body(200) }); + + let (kernel, _) = golden_session(); + let human = subject_by_label(&kernel.state, "The Human"); + let snapshot = kernel.snapshot().unwrap(); + let body = CommandBody::Act { + actor: human, + invocation: speak(first_grant(&snapshot, human), "Order, please."), + }; + cases.push(FailureCase { name: "a speech", kernel, body }); + + let (kernel, _) = golden_session(); + let witness = subject_by_label(&kernel.state, "The Witness"); + let (fact, _) = kernel.state.knowledge_of(witness).next().expect("the witness knows"); + let body = operations(vec![ComponentOp::Forget { + subject: Ref::Existing(witness), + fact: Ref::Existing(*fact), + }]); + cases.push(FailureCase { name: "a forget", kernel, body }); + cases +} + +/// A failed apply leaves nothing behind: state, accumulator, digest, every +/// partition's bytes, every log and the journal as before, and the next honest +/// command commits. Each case is failed twice: by the revision overflow a tick +/// meets after it has written its documents, and by a failure after the digest +/// is folded and the commit sealed, the last point before the world is kept. #[test] fn a_failed_apply_rolls_back() { - let (mut kernel, _, _) = clockwork_world(20); - let honest_revision = kernel.state.revision; - kernel.state.revision = u64::MAX; - let before = kernel.state.clone(); - let commits = kernel.journal.commit_count(); + for failure in [Failure::RevisionOverflow, Failure::AfterDigest] { + for FailureCase { name, mut kernel, body } in failure_cases() { + let label = format!("{name}, {failure:?}"); + let honest_revision = kernel.state.revision; + let before = kernel.state.clone(); + let bytes = before.encoded_documents(); + let commits = kernel.journal.commit_count(); + match failure { + Failure::RevisionOverflow => kernel.state.revision = u64::MAX, + Failure::AfterDigest => crate::INJECT_FAILURE_AFTER_DIGEST.set(true), + } + let envelope = clockwork_envelope(&kernel, body.clone()); + let error = kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .unwrap_err(); + crate::INJECT_FAILURE_AFTER_DIGEST.set(false); + match failure { + Failure::RevisionOverflow => { + assert!(matches!(error, KernelError::Serialization(_)), "{label}: {error:?}"); + } + Failure::AfterDigest => { + assert!(matches!(error, KernelError::Invariant(_)), "{label}: {error:?}"); + } + } + kernel.state.revision = honest_revision; + assert_eq!(kernel.state, before, "{label}: the failure left writes behind"); + assert_eq!(kernel.state.encoded_documents(), bytes, "{label}"); + assert_eq!(kernel.journal.commit_count(), commits, "{label}"); + assert!(kernel.state.header.is_clean(), "{label}: header log open"); + for (schema, docs) in kernel.state.partitions() { + assert!(docs.is_clean(), "{label}: {schema} log open"); + } + assert_eq!( + kernel.state.full_state_digest().unwrap(), + kernel.state.state_digest, + "{label}: the accumulator no longer matches the documents" + ); - let tick = clockwork_envelope(&kernel, tick_body(1)); - let error = kernel - .submit(tick, &AuthenticatedCaller::verified_play()) - .unwrap_err(); - assert!(matches!(error, KernelError::Serialization(_)), "{error:?}"); - assert_eq!(kernel.state, before, "the failed tick left writes behind"); - assert_eq!(kernel.journal.commit_count(), commits); - kernel.state.begin(); - assert_eq!(kernel.state.folded().unwrap(), kernel.state.accumulator); - assert_eq!( - kernel.state.accumulator.state_digest(u64::MAX), - kernel.state.full_state_digest().unwrap(), - "the accumulator no longer matches the documents" - ); + let envelope = clockwork_envelope(&kernel, body); + kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .unwrap_or_else(|error| panic!("{label}: the next honest command: {error:?}")); + assert_eq!(kernel.state.full_state_digest().unwrap(), kernel.state.state_digest); + } + } +} - kernel.state.revision = honest_revision; - let tick = clockwork_envelope(&kernel, tick_body(1)); - kernel - .submit(tick, &AuthenticatedCaller::verified_play()) - .expect("the next honest command commits"); - assert_eq!(kernel.state.full_state_digest().unwrap(), kernel.state.state_digest); +/// Worlds that between them hold a document in every partition: the golden +/// session, the civic, custody and speech benches and the ticked clock bench. +fn populated_worlds() -> Vec<crate::WorldState> { + use crate::tests::{auth_principal, civic_world, creation, custody_world, owner, speech_world}; + let created = |title: &str| { + WorldKernel::create(creation(title), &auth_principal(owner())).unwrap().0 + }; + let mut worlds = vec![golden_session().0.state]; + let mut kernel = created("Civic"); + civic_world(&mut kernel); + worlds.push(kernel.state); + let mut kernel = created("Custody"); + custody_world(&mut kernel); + worlds.push(kernel.state); + let mut kernel = created("Speech"); + speech_world(&mut kernel); + worlds.push(kernel.state); + let (mut kernel, _, _) = crate::clock_tests::clock_kernel("Pressure"); + let tick = clockwork_envelope(&kernel, tick_body(200)); + kernel.submit(tick, &AuthenticatedCaller::verified_play()).unwrap(); + worlds.push(kernel.state); + worlds +} + +/// Membership of the partition table is behaviour: for every partition the +/// declaration names, one written document is in the folded digest and agrees +/// with the full recompute, is put back by a rollback, and leaves the log empty +/// and the accumulator at the full recompute when the transaction finishes. The +/// loop runs over the declaration, so a partition added to it is covered, and a +/// partition no fixture populates fails here rather than going untested. +#[test] +fn every_partition_is_digested_undone_and_finished() { + let worlds = populated_worlds(); + for index in 0..crate::WorldState::PARTITIONS { + let schema = worlds[0].partitions()[index].0; + let base = worlds + .iter() + .find(|world| world.partitions()[index].1.rows() > 0) + .unwrap_or_else(|| panic!("no fixture world holds a document in {schema}")); + let written = |state: &mut crate::WorldState| { + state.begin(); + assert!(state.partitions_mut()[index].1.remove_first(), "{schema}: nothing to write"); + let folded = state.folded().unwrap(); + assert_ne!(folded, state.accumulator, "{schema}: the write is not in the digest"); + assert_eq!( + folded.state_digest(state.revision), + state.full_state_digest().unwrap(), + "{schema}: the folded digest left the full recompute" + ); + folded + }; + let clean = |state: &crate::WorldState| { + state.header.is_clean() && state.partitions().iter().all(|(_, docs)| docs.is_clean()) + }; + + let mut state = base.clone(); + written(&mut state); + assert!(!state.partitions()[index].1.is_clean(), "{schema}: the write is not logged"); + state.rollback(); + assert_eq!(&state, base, "{schema}: rollback left the write behind"); + assert_eq!(state.encoded_documents(), base.encoded_documents(), "{schema}"); + assert!(clean(&state), "{schema}: rollback left a log open"); + + let mut state = base.clone(); + let folded = written(&mut state); + state.finish(folded); + assert!(clean(&state), "{schema}: finish left a log open"); + assert_ne!(&state, base, "{schema}: finish dropped the write"); + assert_eq!( + state.accumulator.state_digest(state.revision), + state.full_state_digest().unwrap(), + "{schema}: the finished accumulator left the full recompute" + ); + } } /// What one tick and one speech cost to commit as the world grows, by the diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index 3918dba55..cde56ab16 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -935,6 +935,13 @@ impl From<journal::JournalError> for KernelError { } } +// Test seam: when set on this thread, `submit` fails after it has folded the +// digest and sealed the commit, the last point before the world is kept. +#[cfg(test)] +thread_local! { + static INJECT_FAILURE_AFTER_DIGEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + struct WorldKernel { state: WorldState, journal: journal::WorldJournal, @@ -1085,6 +1092,10 @@ impl WorldKernel { digest: String::new(), }; commit.digest = commit_digest(&commit)?; + #[cfg(test)] + if INJECT_FAILURE_AFTER_DIGEST.get() { + return Err(KernelError::Invariant("injected failure after the digest".into())); + } Ok((commit, accumulator)) })(); let (commit, accumulator) = match sealed { @@ -9264,7 +9275,7 @@ mod clock_tests { TickMinutes::new(value).expect("a valid span") } - fn clock_kernel(title: &str) -> (WorldKernel, Clockwork, WorldSnapshot) { + pub(crate) fn clock_kernel(title: &str) -> (WorldKernel, Clockwork, WorldSnapshot) { let mut kernel = WorldKernel::create(creation(title), &auth_principal(owner()), ) From 576605c7b044c3941d5e4bb836ed8ea1117379f2 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 05:16:01 +0100 Subject: [PATCH 158/190] aetherlight: pin that a non-routine commitment cannot carry a check A live check from a Routine is put on an obligation or goal and verify_state_shape must refuse it; the honest world is the control. Kills the survivor of && to || on the routine-or-no-checks conjunction (shape-conjunction-survivor). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/journal.rs | 38 +++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index 09e7ca7b9..1d795e086 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -2267,6 +2267,44 @@ mod custody_tests { let _ = subject; } + /// A commitment that is not a Routine and carries a check is not canonical: + /// nothing would ever evaluate the check. The check is a live one, taken + /// from a Routine, so no other clause can be what refuses it; the control + /// is the honest world. + #[test] + fn a_non_routine_commitment_carrying_a_check_is_corrupt() { + let (kernel, _, _) = crate::clock_tests::clock_kernel("Checks"); + verify_state_shape(&kernel.state).expect("the honest world is canonical"); + let check = kernel + .state + .commitments + .values() + .flat_map(|held| held.values()) + .find_map(|commitment| commitment.checks.first().cloned()) + .expect("the clock bench's routine carries a check"); + let (subject, key) = kernel + .state + .commitments + .iter() + .flat_map(|(subject, held)| held.iter().map(move |(key, c)| (*subject, *key, c))) + .find(|(_, _, commitment)| commitment.kind != crate::CommitmentKind::Routine) + .map(|(subject, key, _)| (subject, key)) + .expect("the clock bench holds an obligation or a goal"); + + let mut forged = kernel.state.clone(); + forged + .commitments + .get_mut(&subject) + .unwrap() + .get_mut(&key) + .unwrap() + .checks = vec![check]; + assert!( + matches!(verify_state_shape(&forged), Err(JournalError::Corrupt(_))), + "a non-routine commitment with a check was admitted" + ); + } + /// `TickMinutes` owns its bound at decode, so a span outside /// `1..=MAX_ROUTE_COST` cannot be read in any position: a routine's period, /// a command, or a tick's own effect. From 436c6d59caf80b55845bf4cdf4e55315bf5dff6e Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 05:51:57 +0100 Subject: [PATCH 159/190] aetherlight: Docs loses Deref; reads are inherent methods and every row an iterator yields is counted No behaviour change. Reads of a partition go through get, contains_key, len, is_empty, iter, keys, values, range, Index and IntoIterator, so no reader can bypass the test-build row counter by coercing to BTreeMap. Resolver and is_genesis parameters take &Docs. golden.digests untouched. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/action.rs | 2 +- native/aetherlight/src/docs.rs | 127 ++++++++++++++++++++++++++++--- native/aetherlight/src/lib.rs | 2 +- native/aetherlight/src/patch.rs | 15 ++-- 4 files changed, 127 insertions(+), 19 deletions(-) diff --git a/native/aetherlight/src/action.rs b/native/aetherlight/src/action.rs index 582de0623..fb6fb9347 100644 --- a/native/aetherlight/src/action.rs +++ b/native/aetherlight/src/action.rs @@ -1638,7 +1638,7 @@ mod tests { .expect("the affordance document encodes"); let decoded: std::collections::BTreeMap<_, crate::Affordance> = rmp_serde::from_slice(&catalog).expect("the affordance document decodes"); - assert_eq!(decoded, *bench.kernel.state.affordance_catalog); + assert_eq!(decoded, *bench.kernel.state.affordance_catalog.as_map()); assert!(bench.kernel.state.full_state_digest().is_ok()); } diff --git a/native/aetherlight/src/docs.rs b/native/aetherlight/src/docs.rs index fff61f099..7ef189406 100644 --- a/native/aetherlight/src/docs.rs +++ b/native/aetherlight/src/docs.rs @@ -5,7 +5,7 @@ //! key's value as it stood before the transaction (first touch wins). `finish` //! turns that record into the keys whose value really changed, with their old //! values; `rollback` puts every touched key back. Reads see the plain map -//! through `Deref`, and there is no `DerefMut`, so a write cannot skip the log. +//! through inherent methods, and no method hands out the map, so a write cannot skip the log. //! The fields are private to this module for the same reason. use serde::{Serialize, Serializer}; @@ -13,6 +13,55 @@ use std::collections::BTreeMap; use std::collections::btree_map::Entry; use std::ops::Deref; +#[cfg(test)] +thread_local! { + /// Rows any `Docs` iterator has yielded on this thread, and entries any + /// `indexed` read has returned: the work a read did, counted where the + /// reads are owned so no reader can skip it. + static ROWS_READ: std::cell::Cell<u64> = const { std::cell::Cell::new(0) }; +} + +/// The rows read on this thread so far (test builds only). +#[cfg(test)] +pub(crate) fn rows_read() -> u64 { + ROWS_READ.with(|rows| rows.get()) +} + +#[cfg(test)] +fn count_rows(rows: u64) { + ROWS_READ.with(|count| count.set(count.get() + rows)); +} + +/// A partition iterator that counts every row it yields (test builds); in a +/// shipped build it is the map's own iterator. +pub(crate) struct Counted<I>(I); + +impl<I: Iterator> Iterator for Counted<I> { + type Item = I::Item; + fn next(&mut self) -> Option<I::Item> { + let item = self.0.next(); + #[cfg(test)] + if item.is_some() { + count_rows(1); + } + item + } + fn size_hint(&self) -> (usize, Option<usize>) { + self.0.size_hint() + } +} + +impl<I: DoubleEndedIterator> DoubleEndedIterator for Counted<I> { + fn next_back(&mut self) -> Option<I::Item> { + let item = self.0.next_back(); + #[cfg(test)] + if item.is_some() { + count_rows(1); + } + item + } +} + /// A key whose value changed in a transaction, with the value it had before /// (`None` when the key was absent). The new value is whatever the map holds. pub(crate) type Changed<K, V> = (K, Option<V>); @@ -42,18 +91,11 @@ impl<K: Ord + Clone, V: Clone + PartialEq> PartialEq for Docs<K, V> { impl<K: Ord + Clone, V: Clone + PartialEq + Eq> Eq for Docs<K, V> {} -impl<K: Ord + Clone, V: Clone + PartialEq> Deref for Docs<K, V> { - type Target = BTreeMap<K, V>; - fn deref(&self) -> &BTreeMap<K, V> { - &self.map - } -} - impl<'a, K: Ord + Clone, V: Clone + PartialEq> IntoIterator for &'a Docs<K, V> { type Item = (&'a K, &'a V); - type IntoIter = std::collections::btree_map::Iter<'a, K, V>; + type IntoIter = Counted<std::collections::btree_map::Iter<'a, K, V>>; fn into_iter(self) -> Self::IntoIter { - self.map.iter() + self.iter() } } @@ -65,7 +107,55 @@ impl<K: Ord + Clone + Serialize, V: Clone + PartialEq + Serialize> Serialize for } } +impl<K: Ord + Clone, V: Clone + PartialEq> std::ops::Index<&K> for Docs<K, V> { + type Output = V; + fn index(&self, key: &K) -> &V { + &self.map[key] + } +} + impl<K: Ord + Clone, V: Clone + PartialEq> Docs<K, V> { + pub(crate) fn get(&self, key: &K) -> Option<&V> { + self.map.get(key) + } + + pub(crate) fn contains_key(&self, key: &K) -> bool { + self.map.contains_key(key) + } + + pub(crate) fn len(&self) -> usize { + self.map.len() + } + + pub(crate) fn is_empty(&self) -> bool { + self.map.is_empty() + } + + pub(crate) fn iter(&self) -> Counted<std::collections::btree_map::Iter<'_, K, V>> { + Counted(self.map.iter()) + } + + pub(crate) fn keys(&self) -> Counted<std::collections::btree_map::Keys<'_, K, V>> { + Counted(self.map.keys()) + } + + pub(crate) fn values(&self) -> Counted<std::collections::btree_map::Values<'_, K, V>> { + Counted(self.map.values()) + } + + pub(crate) fn range<R: std::ops::RangeBounds<K>>( + &self, + range: R, + ) -> Counted<std::collections::btree_map::Range<'_, K, V>> { + Counted(self.map.range(range)) + } + + /// The plain map, for a test that compares a decoded partition to it. + #[cfg(test)] + pub(crate) fn as_map(&self) -> &BTreeMap<K, V> { + &self.map + } + fn touch(&mut self, key: &K) { if !self.touched.contains_key(key) { self.touched.insert(key.clone(), self.map.get(key).cloned()); @@ -290,6 +380,23 @@ mod tests { assert!(docs.is_clean()); } + #[test] + fn every_row_an_iterator_yields_is_counted_and_point_reads_are_not() { + let docs = rows(&[(1, 10), (2, 20), (3, 30), (4, 40)]); + let before = rows_read(); + assert_eq!(docs.iter().count(), 4); + assert_eq!(rows_read() - before, 4); + assert_eq!(docs.keys().count() + docs.values().count(), 8); + assert_eq!(docs.range(2..4).count(), 2); + assert_eq!((&docs).into_iter().rev().take(1).count(), 1); + assert_eq!(rows_read() - before, 4 + 8 + 2 + 1); + let before = rows_read(); + assert_eq!(docs.get(&2), Some(&20)); + assert!(docs.contains_key(&3) && docs[&4] == 40); + assert_eq!(docs.len(), 4); + assert_eq!(rows_read(), before); + } + #[test] fn equality_is_the_documents_and_not_the_log() { let mut open = rows(&[(1, 10)]); diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index cde56ab16..cbc5b94f9 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -1169,7 +1169,7 @@ fn require_play(caller: &CallerId) -> Result<(), KernelError> { /// `WorldState` so the genesis lane, which resolves declarations before any /// `WorldState` exists, can call the same owner instead of hand-copying the /// literal it would otherwise always evaluate to. -fn is_genesis(revision: u64, subjects: &BTreeMap<SubjectId, SubjectState>) -> bool { +fn is_genesis(revision: u64, subjects: &Docs<SubjectId, SubjectState>) -> bool { revision == 0 && subjects.is_empty() } diff --git a/native/aetherlight/src/patch.rs b/native/aetherlight/src/patch.rs index 884590815..21dcd0374 100644 --- a/native/aetherlight/src/patch.rs +++ b/native/aetherlight/src/patch.rs @@ -13,6 +13,7 @@ use super::clock::{FictionalMinutes, TickMinutes}; use super::grammar::GrammarRefusal; +use super::docs::Docs; use super::{ AffordanceId, CommandId, EdgeId, EntityId, SubjectId, SubjectKind, SubjectState, WorldId, }; @@ -2412,7 +2413,7 @@ fn resolve_affordance( site: Site, reference: &Ref<AffordanceId>, index: &BTreeMap<DraftHandle, RefKind>, - catalog: &BTreeMap<AffordanceId, Affordance>, + catalog: &Docs<AffordanceId, Affordance>, mismatches: &mut Vec<Mismatch>, ) -> Option<Key<AffordanceId>> { match reference { @@ -2676,7 +2677,7 @@ fn resolve_entity( expected_kind: EntityKind, reference: &Ref<EntityId>, index: &BTreeMap<DraftHandle, RefKind>, - entities: &BTreeMap<EntityId, EntityRecord>, + entities: &Docs<EntityId, EntityRecord>, mismatches: &mut Vec<Mismatch>, ) -> Option<Key<EntityId>> { let expected = RefKind::Entity(expected_kind); @@ -2724,7 +2725,7 @@ fn resolve_subject( site: Site, reference: &Ref<SubjectId>, index: &BTreeMap<DraftHandle, RefKind>, - subjects: &BTreeMap<SubjectId, SubjectState>, + subjects: &Docs<SubjectId, SubjectState>, mismatches: &mut Vec<Mismatch>, ) -> Option<Key<SubjectId>> { match reference { @@ -2766,7 +2767,7 @@ fn resolve_route( site: Site, reference: &Ref<EdgeId>, index: &BTreeMap<DraftHandle, RefKind>, - edges: &BTreeMap<EdgeId, EdgeRecord>, + edges: &Docs<EdgeId, EdgeRecord>, mismatches: &mut Vec<Mismatch>, ) -> Option<Key<EdgeId>> { match reference { @@ -5606,7 +5607,7 @@ fn contains_itself( /// downward enumeration and no child index: every jurisdictional question this /// kernel asks is "is this target inside my ground". pub(super) fn covers_place( - entities: &BTreeMap<EntityId, EntityRecord>, + entities: &Docs<EntityId, EntityRecord>, root: EntityId, place: EntityId, ) -> bool { @@ -5624,7 +5625,7 @@ pub(super) fn covers_place( /// The canonical twin of the candidate graph's `candidate_targets_overlap`: whether two /// jurisdictions of one kind cover common ground. pub(super) fn targets_overlap( - entities: &BTreeMap<EntityId, EntityRecord>, + entities: &Docs<EntityId, EntityRecord>, left: AuthorityTarget, right: AuthorityTarget, ) -> bool { @@ -5663,7 +5664,7 @@ pub(super) fn route_admits( /// chain that never terminates dies before the partition keeps it. pub(super) fn containment_terminates( start: EntityId, - entities: &BTreeMap<EntityId, EntityRecord>, + entities: &Docs<EntityId, EntityRecord>, ) -> bool { let mut current = entities.get(&start).and_then(|record| record.container); for _ in 0..=entities.len() { From edeea42f5e5a0bf0c798ebafcee5955287e9f325 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 05:58:09 +0100 Subject: [PATCH 160/190] aetherlight: partition read indexes owned by Docs; eight whole-partition scans become index reads A Docs may carry a Projection: a pure function of one document's value. Docs::finish folds each changed key (old points out, new points in) from the list the digest folds; Docs::indexed returns (point, key) in order, corrected by the open log so it is true mid-transaction; rollback never touches the index. Seven projections: DueAt, StandsAt, ChildOf, BySource, ByEndpoint, ByController, ByIncumbent. under_place, audience Colocated, DischargeCommitment holders, scope_components routes and controls, delegated_authority, derive_motion's commitments and reachable's outbound edges now read the index; each old scan is kept as a cfg(test) *_by_scan reference. golden.digests byte-identical. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/action.rs | 6 +- native/aetherlight/src/clock.rs | 13 +- native/aetherlight/src/digest.rs | 20 +- native/aetherlight/src/docs.rs | 265 +++++++++++++++++++++++-- native/aetherlight/src/lib.rs | 319 +++++++++++++++++++++++++------ native/aetherlight/src/patch.rs | 22 ++- 6 files changed, 558 insertions(+), 87 deletions(-) diff --git a/native/aetherlight/src/action.rs b/native/aetherlight/src/action.rs index fb6fb9347..2ad319e79 100644 --- a/native/aetherlight/src/action.rs +++ b/native/aetherlight/src/action.rs @@ -663,7 +663,9 @@ fn reachable( settled.insert(place); let outbound: Vec<(EdgeId, EntityId, u64)> = state .edges - .iter() + .indexed(place..=place) + .into_iter() + .map(|(_, edge_id)| (edge_id, &state.edges[&edge_id])) .filter(|(_, record)| record.is_open()) .filter_map(|(edge_id, record)| { let (from, to) = record.endpoints(); @@ -675,7 +677,7 @@ fn reachable( return None; }; patch::route_admits(state, authority, record.access(), next) - .then(|| (*edge_id, next, u64::from(record.cost().0))) + .then(|| (edge_id, next, u64::from(record.cost().0))) }) .collect(); for (_, next, step) in outbound { diff --git a/native/aetherlight/src/clock.rs b/native/aetherlight/src/clock.rs index bde23bb79..3fe6c8a5d 100644 --- a/native/aetherlight/src/clock.rs +++ b/native/aetherlight/src/clock.rs @@ -114,7 +114,18 @@ pub(super) fn derive_motion(state: &WorldState, to: FictionalMinutes) -> Motion let mut fulfilled = Vec::new(); let mut pressed: BTreeMap<(SubjectId, PressureSource), u32> = BTreeMap::new(); - for (subject, held) in &state.commitments { + // Only subjects with something due: the commitments index answers it + // without walking every promise in the world. The dependencies walk below + // is still one row per subject holding a dependency: follow-up + // aetherlight-cross-partition-views. + let due: std::collections::BTreeSet<SubjectId> = state + .commitments + .indexed(..=to) + .into_iter() + .map(|(_, subject)| subject) + .collect(); + for subject in &due { + let held = &state.commitments[subject]; // A retired subject cannot act, and neither fulfilling a routine nor // pressing an obligation or goal is anything but that subject acting: // its commitments stay in history, un-discharged and un-deleted, but diff --git a/native/aetherlight/src/digest.rs b/native/aetherlight/src/digest.rs index d9be5bff6..1cf891244 100644 --- a/native/aetherlight/src/digest.rs +++ b/native/aetherlight/src/digest.rs @@ -129,12 +129,20 @@ pub(crate) trait Partition { /// Removes the first document, logged like any write; false when empty. #[cfg(test)] fn remove_first(&mut self) -> bool; + /// Whether the read index is exactly the projection of the documents. + #[cfg(test)] + fn index_is_derived(&self) -> bool; + /// Damages the read index in one place (a stray entry, else a missing one); + /// false when there is nothing to damage. + #[cfg(test)] + fn corrupt_index_first(&mut self, stray: bool) -> bool; } -impl<K, V> Partition for Docs<K, V> +impl<K, V, P> Partition for Docs<K, V, P> where K: Ord + Clone + DocKey + Serialize, V: Clone + PartialEq + Serialize, + P: crate::docs::Projection<V>, { fn is_clean(&self) -> bool { Docs::is_clean(self) @@ -186,6 +194,16 @@ where }; self.remove(&key).is_some() } + + #[cfg(test)] + fn index_is_derived(&self) -> bool { + Docs::index_is_derived(self) + } + + #[cfg(test)] + fn corrupt_index_first(&mut self, stray: bool) -> bool { + self.corrupt_index_for_test(stray) + } } /// The header's one change, keyed by its own world id. diff --git a/native/aetherlight/src/docs.rs b/native/aetherlight/src/docs.rs index 7ef189406..bb05fd192 100644 --- a/native/aetherlight/src/docs.rs +++ b/native/aetherlight/src/docs.rs @@ -9,7 +9,7 @@ //! The fields are private to this module for the same reason. use serde::{Serialize, Serializer}; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::collections::btree_map::Entry; use std::ops::Deref; @@ -66,32 +66,55 @@ impl<I: DoubleEndedIterator> DoubleEndedIterator for Counted<I> { /// (`None` when the key was absent). The new value is whatever the map holds. pub(crate) type Changed<K, V> = (K, Option<V>); -#[derive(Clone, Debug)] -pub(crate) struct Docs<K: Ord + Clone, V: Clone + PartialEq> { - map: BTreeMap<K, V>, - touched: BTreeMap<K, Option<V>>, +/// Where a document sits in a partition's read index: a pure function of one +/// document's value, so the index can always be rebuilt from the map and never +/// disagrees with it. +pub(crate) trait Projection<V> { + type Point: Ord + Clone + std::fmt::Debug; + /// Appends every point `value` sits at (duplicates allowed). + fn points(value: &V, out: &mut Vec<Self::Point>); } -impl<K: Ord + Clone, V: Clone + PartialEq> Default for Docs<K, V> { +/// The projection of a partition nothing reads by value. +#[derive(Clone, Debug, Default)] +pub(crate) struct NoIndex; + +impl<V> Projection<V> for NoIndex { + type Point = (); + fn points(_: &V, _: &mut Vec<()>) {} +} + +/// A partition: its documents, the log of the open transaction, and the read +/// index (the projection of the documents as of the last `finish`). The index +/// is derived state: it is not digested, not encoded, and ignored by equality. +#[derive(Clone, Debug)] +pub(crate) struct Docs<K: Ord + Clone, V: Clone + PartialEq, P: Projection<V> = NoIndex> { + map: BTreeMap<K, V>, + touched: BTreeMap<K, Option<V>>, + index: BTreeMap<P::Point, BTreeSet<K>>, +} + +impl<K: Ord + Clone, V: Clone + PartialEq, P: Projection<V>> Default for Docs<K, V, P> { fn default() -> Self { Self { map: BTreeMap::new(), touched: BTreeMap::new(), + index: BTreeMap::new(), } } } /// Equality is the documents, never the log: two worlds with the same content /// are equal whatever transaction state they are in. -impl<K: Ord + Clone, V: Clone + PartialEq> PartialEq for Docs<K, V> { +impl<K: Ord + Clone, V: Clone + PartialEq, P: Projection<V>> PartialEq for Docs<K, V, P> { fn eq(&self, other: &Self) -> bool { self.map == other.map } } -impl<K: Ord + Clone, V: Clone + PartialEq + Eq> Eq for Docs<K, V> {} +impl<K: Ord + Clone, V: Clone + PartialEq + Eq, P: Projection<V>> Eq for Docs<K, V, P> {} -impl<'a, K: Ord + Clone, V: Clone + PartialEq> IntoIterator for &'a Docs<K, V> { +impl<'a, K: Ord + Clone, V: Clone + PartialEq, P: Projection<V>> IntoIterator for &'a Docs<K, V, P> { type Item = (&'a K, &'a V); type IntoIter = Counted<std::collections::btree_map::Iter<'a, K, V>>; fn into_iter(self) -> Self::IntoIter { @@ -101,20 +124,20 @@ impl<'a, K: Ord + Clone, V: Clone + PartialEq> IntoIterator for &'a Docs<K, V> { /// A partition encodes as its map, so the encoded world is what it was before /// the partitions were tracked. -impl<K: Ord + Clone + Serialize, V: Clone + PartialEq + Serialize> Serialize for Docs<K, V> { +impl<K: Ord + Clone + Serialize, V: Clone + PartialEq + Serialize, P: Projection<V>> Serialize for Docs<K, V, P> { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { self.map.serialize(serializer) } } -impl<K: Ord + Clone, V: Clone + PartialEq> std::ops::Index<&K> for Docs<K, V> { +impl<K: Ord + Clone, V: Clone + PartialEq, P: Projection<V>> std::ops::Index<&K> for Docs<K, V, P> { type Output = V; fn index(&self, key: &K) -> &V { &self.map[key] } } -impl<K: Ord + Clone, V: Clone + PartialEq> Docs<K, V> { +impl<K: Ord + Clone, V: Clone + PartialEq, P: Projection<V>> Docs<K, V, P> { pub(crate) fn get(&self, key: &K) -> Option<&V> { self.map.get(key) } @@ -197,10 +220,112 @@ impl<K: Ord + Clone, V: Clone + PartialEq> Docs<K, V> { /// value they had then. A key written back to what it was is not reported. /// The log is empty afterwards. pub(crate) fn finish(&mut self) -> Vec<Changed<K, V>> { - std::mem::take(&mut self.touched) + let changed: Vec<Changed<K, V>> = std::mem::take(&mut self.touched) .into_iter() .filter(|(key, old)| self.map.get(key) != old.as_ref()) - .collect() + .collect(); + for (key, old) in &changed { + self.fold_index(key, old.as_ref()); + } + changed + } + + /// Moves one changed key's entries: its old points out, its current points in. + fn fold_index(&mut self, key: &K, old: Option<&V>) { + let mut points = Vec::new(); + if let Some(old) = old { + P::points(old, &mut points); + for point in points.drain(..) { + if let Some(keys) = self.index.get_mut(&point) { + keys.remove(key); + if keys.is_empty() { + self.index.remove(&point); + } + } + } + } + if let Some(new) = self.map.get(key) { + P::points(new, &mut points); + for point in points { + self.index.entry(point).or_default().insert(key.clone()); + } + } + } + + /// Every (point, key) inside `range`, in order, true at this moment: the + /// committed index, corrected by the open log. A logged key's committed + /// entries are dropped and its current value's points are read from the + /// map, so a read inside a transaction sees what the transaction wrote and + /// the index itself never saw it (which is why `rollback` leaves it alone). + pub(crate) fn indexed<R: std::ops::RangeBounds<P::Point>>( + &self, + range: R, + ) -> Vec<(P::Point, K)> { + let mut found: Vec<(P::Point, K)> = self + .index + .range((range.start_bound(), range.end_bound())) + .flat_map(|(point, keys)| keys.iter().map(move |key| (point, key))) + .filter(|(_, key)| !self.touched.contains_key(*key)) + .map(|(point, key)| (point.clone(), key.clone())) + .collect(); + if !self.touched.is_empty() { + let mut points = Vec::new(); + for key in self.touched.keys() { + if let Some(value) = self.map.get(key) { + P::points(value, &mut points); + for point in points.drain(..) { + if range.contains(&point) { + found.push((point, key.clone())); + } + } + } + } + found.sort(); + found.dedup(); + } + #[cfg(test)] + count_rows(found.len() as u64); + found + } + + /// Whether the index is exactly the projection of the map (test builds). + #[cfg(test)] + pub(crate) fn index_is_derived(&self) -> bool { + let mut rebuilt: BTreeMap<P::Point, BTreeSet<K>> = BTreeMap::new(); + let mut points = Vec::new(); + for (key, value) in &self.map { + P::points(value, &mut points); + for point in points.drain(..) { + rebuilt.entry(point).or_default().insert(key.clone()); + } + } + rebuilt == self.index + } + + /// Makes the index disagree with the map in one place: a stray entry (a + /// document listed at a point it does not sit at) or a missing one. False + /// when this partition has no such place to damage (test builds). + #[cfg(test)] + pub(crate) fn corrupt_index_for_test(&mut self, stray: bool) -> bool { + if !stray { + let Some(point) = self.index.keys().next().cloned() else { + return false; + }; + let keys = self.index.get_mut(&point).expect("the point is present"); + let key = keys.iter().next().cloned().expect("a point holds a key"); + keys.remove(&key); + if keys.is_empty() { + self.index.remove(&point); + } + return true; + } + for keys in self.index.values_mut() { + if let Some(key) = self.map.keys().find(|key| !keys.contains(*key)) { + keys.insert(key.clone()); + return true; + } + } + false } /// Puts every touched key back as it was and empties the log. @@ -317,6 +442,118 @@ mod tests { docs } + /// A value sits at its tens digit and its units digit (one point when they + /// agree), so a document has several points and two documents can share one. + #[derive(Clone, Debug)] + struct Digits; + + impl Projection<u8> for Digits { + type Point = u8; + fn points(value: &u8, out: &mut Vec<u8>) { + out.push(value / 10); + out.push(value % 10); + } + } + + type Spread = Docs<u8, u8, Digits>; + + fn spread(held: &[(u8, u8)]) -> Spread { + let mut docs = Spread::default(); + for (key, value) in held { + docs.insert(*key, *value); + } + docs.finish(); + docs + } + + /// The projection of the map, computed from scratch: what `indexed(..)` must + /// return at every moment. + fn truth(docs: &Spread) -> Vec<(u8, u8)> { + let mut out = Vec::new(); + for (key, value) in docs.iter() { + out.push((value / 10, *key)); + out.push((value % 10, *key)); + } + out.sort(); + out.dedup(); + out + } + + #[test] + fn a_committed_index_is_the_projection_and_follows_every_finish() { + let mut docs = spread(&[(1, 10), (2, 21), (3, 33)]); + assert!(docs.index_is_derived()); + assert_eq!(docs.indexed(..), truth(&docs)); + assert_eq!(docs.indexed(1..=1), vec![(1, 1), (1, 2)]); + + docs.insert(1, 32); + docs.remove(&2); + docs.insert(4, 44); + docs.finish(); + assert!(docs.index_is_derived(), "old points leave, new points arrive"); + assert_eq!(docs.indexed(..), truth(&docs)); + assert!(docs.indexed(0..=0).is_empty() && docs.indexed(1..=1).is_empty()); + } + + #[test] + fn a_read_inside_a_transaction_sees_the_log_and_the_index_does_not() { + let mut docs = spread(&[(1, 10), (2, 21), (3, 33)]); + docs.insert(1, 55); + docs.remove(&2); + docs.insert(7, 12); + assert_eq!(docs.indexed(..), truth(&docs), "the read is true mid-transaction"); + assert!(!docs.indexed(0..=0).iter().any(|(_, key)| *key == 1), "an overwritten value leaves its old points"); + assert!(docs.indexed(5..=5).contains(&(5, 1)), "a new value is seen at once"); + assert!(docs.indexed(..).iter().all(|(_, key)| *key != 2), "a removed document is gone"); + for point in 0..=9 { + assert_eq!( + docs.indexed(point..=point), + truth(&docs).into_iter().filter(|(p, _)| *p == point).collect::<Vec<_>>() + ); + } + assert!(!docs.index_is_derived(), "the open log has not reached the index"); + + docs.insert(1, 10); + docs.insert(7, 12); + docs.remove(&7); + assert_eq!(docs.indexed(..), truth(&docs), "a key written back or added and removed adds nothing"); + } + + #[test] + fn rollback_leaves_the_index_as_it_was_because_it_never_saw_the_transaction() { + let mut docs = spread(&[(1, 10), (2, 21)]); + let before = docs.indexed(..); + docs.insert(1, 99); + docs.insert(5, 35); + docs.remove(&2); + docs.rollback(); + assert!(docs.index_is_derived()); + assert_eq!(docs.indexed(..), before); + assert_eq!(docs.indexed(..), truth(&docs)); + } + + #[test] + fn an_index_read_counts_the_entries_it_returns() { + let docs = spread(&[(1, 10), (2, 21), (3, 33)]); + let before = rows_read(); + let found = docs.indexed(..); + assert_eq!(rows_read() - before, found.len() as u64); + let before = rows_read(); + assert_eq!(docs.indexed(1..=1).len(), 2); + assert_eq!(rows_read() - before, 2); + } + + #[test] + fn a_damaged_index_is_seen_as_not_derived() { + for stray in [true, false] { + let mut docs = spread(&[(1, 10), (2, 21), (3, 33)]); + assert!(docs.corrupt_index_for_test(stray)); + assert!(!docs.index_is_derived(), "stray={stray}"); + } + let mut empty = Spread::default(); + assert!(!empty.corrupt_index_for_test(true) && !empty.corrupt_index_for_test(false)); + } + fn contents(docs: &Rows) -> Vec<(u8, u8)> { docs.iter().map(|(key, value)| (*key, *value)).collect() } diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index cbc5b94f9..91766348e 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -462,14 +462,16 @@ struct WorldHeader { /// there is no second list to forget it from. /// /// Every partition is a `Docs`: reads see the map, every write is logged, and -/// `submit` applies in place and either finishes or rolls the log back. +/// `submit` applies in place and either finishes or rolls the log back. A row +/// may name a [`docs::Projection`] as a third type: that partition then keeps a +/// read index, and the projections sit just above this macro. macro_rules! world_state { - ($($(#[$meta:meta])* $field:ident: Docs<$key:ty, $value:ty> = $schema:literal;)*) => { + ($($(#[$meta:meta])* $field:ident: Docs<$key:ty, $value:ty $(, $proj:ty)?> = $schema:literal;)*) => { #[derive(Clone, Debug, PartialEq, Eq)] struct WorldState { header: Tracked<WorldHeader>, revision: u64, - $($(#[$meta])* $field: Docs<$key, $value>,)* + $($(#[$meta])* $field: Docs<$key, $value $(, $proj)?>,)* // The chain head: outside every document. accumulator: LtHash16, state_digest: String, @@ -504,11 +506,106 @@ macro_rules! world_state { }; } +/// The read indexes. Each is a pure function of one document's value, held by +/// its partition's `Docs` and read only through `Docs::indexed`; none is state +/// of its own, so none is digested or encoded. +/// +/// `ChildOf`: the places directly inside a place. +#[derive(Clone, Debug)] +struct ChildOf; + +impl docs::Projection<EntityRecord> for ChildOf { + type Point = EntityId; + fn points(value: &EntityRecord, out: &mut Vec<EntityId>) { + out.extend(value.container); + } +} + +/// `StandsAt`: who stands in a place. A position holds only its place, so two +/// positions are equal exactly when their places are. +#[derive(Clone, Debug)] +struct StandsAt; + +impl docs::Projection<Position> for StandsAt { + type Point = EntityId; + fn points(value: &Position, out: &mut Vec<EntityId>) { + out.push(value.place); + } +} + +/// `DueAt`: when a subject's commitments fall due, one entry per distinct due. +#[derive(Clone, Debug)] +struct DueAt; + +impl docs::Projection<BTreeMap<CommitmentKey, Commitment>> for DueAt { + type Point = FictionalMinutes; + fn points(value: &BTreeMap<CommitmentKey, Commitment>, out: &mut Vec<FictionalMinutes>) { + let first = out.len(); + out.extend(value.values().map(|commitment| commitment.due)); + out[first..].sort(); + out.dedup(); + } +} + +/// `BySource`: which pressure sources press on a subject. +#[derive(Clone, Debug)] +struct BySource; + +impl docs::Projection<BTreeMap<PressureSource, PressureMagnitude>> for BySource { + type Point = PressureSource; + fn points( + value: &BTreeMap<PressureSource, PressureMagnitude>, + out: &mut Vec<PressureSource>, + ) { + out.extend(value.keys().copied()); + } +} + +/// `ByEndpoint`: the routes touching a place, at either end. +#[derive(Clone, Debug)] +struct ByEndpoint; + +impl docs::Projection<EdgeRecord> for ByEndpoint { + type Point = EntityId; + fn points(value: &EdgeRecord, out: &mut Vec<EntityId>) { + let (from, to) = value.endpoints(); + out.push(from); + if to != from { + out.push(to); + } + } +} + +/// `ByController`: the channels a subject controls. +#[derive(Clone, Debug)] +struct ByController; + +impl docs::Projection<ChannelRecord> for ByController { + type Point = SubjectId; + fn points(value: &ChannelRecord, out: &mut Vec<SubjectId>) { + out.extend(value.controller); + } +} + +/// `ByIncumbent`: the institutions in which a subject holds an office. +#[derive(Clone, Debug)] +struct ByIncumbent; + +impl docs::Projection<BTreeMap<OfficeName, Office>> for ByIncumbent { + type Point = SubjectId; + fn points(value: &BTreeMap<OfficeName, Office>, out: &mut Vec<SubjectId>) { + let first = out.len(); + out.extend(value.values().filter_map(|office| office.incumbent)); + out[first..].sort(); + out.dedup(); + } +} + world_state! { subjects: Docs<SubjectId, SubjectState> = "aetherlight.subject.v1"; - entities: Docs<EntityId, EntityRecord> = "aetherlight.entity.v1"; - edges: Docs<EdgeId, EdgeRecord> = "aetherlight.edge.v1"; - positions: Docs<SubjectId, Position> = "aetherlight.position.v1"; + entities: Docs<EntityId, EntityRecord, ChildOf> = "aetherlight.entity.v1"; + edges: Docs<EdgeId, EdgeRecord, ByEndpoint> = "aetherlight.edge.v1"; + positions: Docs<SubjectId, Position, StandsAt> = "aetherlight.position.v1"; /// What each subject holds. Absence is zero at both levels: no stored /// `Quantity(0)` and no empty inner map, so a duplicate holding is /// unrepresentable and "nothing" has one shape. @@ -520,7 +617,7 @@ world_state! { /// standing never changes after admission. facts: Docs<EntityId, FactRecord> = "aetherlight.fact.v1"; /// One row per `EntityKind::Channel` entity, and no orphan either way. - channels: Docs<EntityId, ChannelRecord> = "aetherlight.channel.v1"; + channels: Docs<EntityId, ChannelRecord, ByController> = "aetherlight.channel.v1"; /// What each subject knows. The sole owner of who-heard-what: `events` /// records what was done, and this decides what a subject may act on and /// what its projection may contain. One document per (subject, fact), and @@ -534,17 +631,17 @@ world_state! { /// The offices each institution constitutes, and who sits in them. An /// incumbent never acts as its institution: an office answers what its /// incumbent has jurisdiction over, not who the actor is. - selection: Docs<SubjectId, BTreeMap<OfficeName, Office>> = "aetherlight.selection.v1"; + selection: Docs<SubjectId, BTreeMap<OfficeName, Office>, ByIncumbent> = "aetherlight.selection.v1"; /// Where each kind of grievance goes, and who may bring it. Keyed by /// neither a subject nor a referent, so it enters no scope components and /// is admission-only state. redress: Docs<GrievanceKindName, Forum> = "aetherlight.redress.v1"; /// What each subject has promised. Never empty for a present key. - commitments: Docs<SubjectId, BTreeMap<CommitmentKey, Commitment>> = "aetherlight.commitments.v1"; + commitments: Docs<SubjectId, BTreeMap<CommitmentKey, Commitment>, DueAt> = "aetherlight.commitments.v1"; /// Pressure *on* each subject, keyed target-major then source. Never empty /// for a present key; no stored zero magnitude. Lived meaning: read by /// projection and by nothing that decides. - pressures: Docs<SubjectId, BTreeMap<PressureSource, PressureMagnitude>> = "aetherlight.pressures.v1"; + pressures: Docs<SubjectId, BTreeMap<PressureSource, PressureMagnitude>, BySource> = "aetherlight.pressures.v1"; /// What an affordance *is*. World-authored and written by `admit_resolved` /// alone. affordance_catalog: Docs<AffordanceId, Affordance> = "aetherlight.affordance.v1"; @@ -2347,13 +2444,7 @@ fn apply_operation( subject: *subject, key: *key, }; - let holding: Vec<SubjectId> = state - .pressures - .iter() - .filter(|(_, held)| held.contains_key(&sourced)) - .map(|(target, _)| *target) - .collect(); - for target in holding { + for target in pressure_holders(state, sourced) { let emptied = state.pressures.get_mut(&target).is_some_and(|held| { held.remove(&sourced); held.is_empty() @@ -2581,6 +2672,38 @@ pub(crate) fn is_retired(state: &WorldState, subject_id: SubjectId) -> bool { /// declared broadcast area and a witnessed event. A subject with no position is /// under nothing. fn under_place(state: &WorldState, root: EntityId) -> BTreeSet<SubjectId> { + // The subtree by `ChildOf`, collecting who stands in each place. Containment + // is acyclic (`admit_resolved` refuses a chain that does not terminate); the + // visited set keeps the walk total regardless. + let mut under = BTreeSet::new(); + let mut seen = BTreeSet::new(); + let mut frontier = vec![root]; + while let Some(place) = frontier.pop() { + if !seen.insert(place) { + continue; + } + under.extend( + state + .positions + .indexed(place..=place) + .into_iter() + .map(|(_, subject_id)| subject_id), + ); + frontier.extend( + state + .entities + .indexed(place..=place) + .into_iter() + .map(|(_, child)| child), + ); + } + under +} + +/// What `under_place` was before the index: every position, asked whether its +/// place is covered. The index read must equal it. +#[cfg(test)] +fn under_place_by_scan(state: &WorldState, root: EntityId) -> BTreeSet<SubjectId> { state .positions .iter() @@ -2604,9 +2727,9 @@ fn audience(state: &WorldState, actor: SubjectId, of: &Audience) -> BTreeSet<Sub }; state .positions - .iter() - .filter(|(_, position)| **position == here) - .map(|(subject_id, _)| *subject_id) + .indexed(here.place..=here.place) + .into_iter() + .map(|(_, subject_id)| subject_id) .collect() } Audience::Channel(channel) => { @@ -2848,30 +2971,54 @@ fn delegated_authority( ) -> BTreeMap<SubjectId, BTreeMap<OfficeName, BTreeSet<AuthorityGrant>>> { let mut held: BTreeMap<SubjectId, BTreeMap<OfficeName, BTreeSet<AuthorityGrant>>> = BTreeMap::new(); - for (institution, offices) in &state.selection { - // A retired institution lends nothing: `Retire` does not vacate - // offices, so the incumbency stays on record, but a dissolved - // institution's grants stop reaching its office-holders here, the one - // site that turns an office into effective authority. - if is_retired(state, *institution) { + for (_, institution) in state.selection.indexed(subject_id..=subject_id) { + lend_offices(state, subject_id, institution, &state.selection[&institution], &mut held); + } + held +} + +/// What one institution's offices lend `subject_id`, added to `held`. +fn lend_offices( + state: &WorldState, + subject_id: SubjectId, + institution: SubjectId, + offices: &BTreeMap<OfficeName, Office>, + held: &mut BTreeMap<SubjectId, BTreeMap<OfficeName, BTreeSet<AuthorityGrant>>>, +) { + // A retired institution lends nothing: `Retire` does not vacate + // offices, so the incumbency stays on record, but a dissolved + // institution's grants stop reaching its office-holders here, the one + // site that turns an office into effective authority. + if is_retired(state, institution) { + return; + } + for (name, office) in offices { + if office.incumbent != Some(subject_id) { continue; } - for (name, office) in offices { - if office.incumbent != Some(subject_id) { - continue; - } - let lent: BTreeSet<AuthorityGrant> = state - .authority - .get(institution) - .into_iter() - .flatten() - .filter(|grant| office.delegated.contains(&grant.kind)) - .cloned() - .collect(); - held.entry(*institution) - .or_default() - .insert(name.clone(), lent); - } + let lent: BTreeSet<AuthorityGrant> = state + .authority + .get(&institution) + .into_iter() + .flatten() + .filter(|grant| office.delegated.contains(&grant.kind)) + .cloned() + .collect(); + held.entry(institution) + .or_default() + .insert(name.clone(), lent); + } +} + +/// What `delegated_authority` was before the index: every institution. +#[cfg(test)] +fn delegated_authority_by_scan( + state: &WorldState, + subject_id: SubjectId, +) -> BTreeMap<SubjectId, BTreeMap<OfficeName, BTreeSet<AuthorityGrant>>> { + let mut held = BTreeMap::new(); + for (institution, offices) in &state.selection { + lend_offices(state, subject_id, *institution, offices, &mut held); } held } @@ -2886,20 +3033,79 @@ fn subject_authority(state: &WorldState, subject_id: SubjectId) -> BTreeSet<Auth ) } +/// The routes with an end at `place`, keyed by edge. +fn routes_at(state: &WorldState, place: EntityId) -> BTreeMap<EdgeId, EdgeRecord> { + state + .edges + .indexed(place..=place) + .into_iter() + .map(|(_, edge_id)| (edge_id, state.edges[&edge_id].clone())) + .collect() +} + +#[cfg(test)] +fn routes_at_by_scan(state: &WorldState, place: EntityId) -> BTreeMap<EdgeId, EdgeRecord> { + state + .edges + .iter() + .filter(|(_, record)| { + let (from, to) = record.endpoints(); + from == place || to == place + }) + .map(|(edge_id, record)| (*edge_id, record.clone())) + .collect() +} + +/// The channels `subject_id` controls, with their records. +fn channels_controlled_by( + state: &WorldState, + subject_id: SubjectId, +) -> BTreeMap<EntityId, ChannelRecord> { + state + .channels + .indexed(subject_id..=subject_id) + .into_iter() + .map(|(_, entity_id)| (entity_id, state.channels[&entity_id].clone())) + .collect() +} + +#[cfg(test)] +fn channels_controlled_by_by_scan( + state: &WorldState, + subject_id: SubjectId, +) -> BTreeMap<EntityId, ChannelRecord> { + state + .channels + .iter() + .filter(|(_, record)| record.controller == Some(subject_id)) + .map(|(entity_id, record)| (*entity_id, record.clone())) + .collect() +} + +/// The subjects with a pressure row from `source`. +fn pressure_holders(state: &WorldState, source: PressureSource) -> Vec<SubjectId> { + state + .pressures + .indexed(source..=source) + .into_iter() + .map(|(_, target)| target) + .collect() +} + +#[cfg(test)] +fn pressure_holders_by_scan(state: &WorldState, source: PressureSource) -> Vec<SubjectId> { + state + .pressures + .iter() + .filter(|(_, held)| held.contains_key(&source)) + .map(|(target, _)| *target) + .collect() +} + fn scope_components(state: &WorldState, subject_id: SubjectId) -> ScopeComponents { let position = state.positions.get(&subject_id).copied(); let routes = position - .map(|position| { - state - .edges - .iter() - .filter(|(_, record)| { - let (from, to) = record.endpoints(); - from == position.place || to == position.place - }) - .map(|(edge_id, record)| (*edge_id, record.clone())) - .collect() - }) + .map(|position| routes_at(state, position.place)) .unwrap_or_default(); ScopeComponents { position, @@ -2920,12 +3126,7 @@ fn scope_components(state: &WorldState, subject_id: SubjectId) -> ScopeComponent .knowledge_of(subject_id) .map(|(fact, _)| *fact) .collect(), - controls: state - .channels - .iter() - .filter(|(_, record)| record.controller == Some(subject_id)) - .map(|(entity_id, record)| (*entity_id, record.clone())) - .collect(), + controls: channels_controlled_by(state, subject_id), commitments: state .commitments .get(&subject_id) diff --git a/native/aetherlight/src/patch.rs b/native/aetherlight/src/patch.rs index 21dcd0374..7bf53d956 100644 --- a/native/aetherlight/src/patch.rs +++ b/native/aetherlight/src/patch.rs @@ -12,10 +12,11 @@ //! after that set is empty, so a rejected patch never mints an ID. use super::clock::{FictionalMinutes, TickMinutes}; -use super::grammar::GrammarRefusal; use super::docs::Docs; +use super::grammar::GrammarRefusal; use super::{ - AffordanceId, CommandId, EdgeId, EntityId, SubjectId, SubjectKind, SubjectState, WorldId, + AffordanceId, ByEndpoint, ChildOf, CommandId, EdgeId, EntityId, SubjectId, SubjectKind, + SubjectState, WorldId, }; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; @@ -2677,7 +2678,7 @@ fn resolve_entity( expected_kind: EntityKind, reference: &Ref<EntityId>, index: &BTreeMap<DraftHandle, RefKind>, - entities: &Docs<EntityId, EntityRecord>, + entities: &Docs<EntityId, EntityRecord, ChildOf>, mismatches: &mut Vec<Mismatch>, ) -> Option<Key<EntityId>> { let expected = RefKind::Entity(expected_kind); @@ -2767,7 +2768,7 @@ fn resolve_route( site: Site, reference: &Ref<EdgeId>, index: &BTreeMap<DraftHandle, RefKind>, - edges: &Docs<EdgeId, EdgeRecord>, + edges: &Docs<EdgeId, EdgeRecord, ByEndpoint>, mismatches: &mut Vec<Mismatch>, ) -> Option<Key<EdgeId>> { match reference { @@ -5603,11 +5604,12 @@ fn contains_itself( /// Whether `place` is `root` or is contained in it, over canonical state: one /// upward walk in the shape of [`containment_terminates`], bounded by the graph /// size. It is total because `admit_resolved` refuses a non-terminating chain, -/// so the bound is belt-and-braces rather than a repair loop. There is no -/// downward enumeration and no child index: every jurisdictional question this -/// kernel asks is "is this target inside my ground". +/// so the bound is belt-and-braces rather than a repair loop. The question it +/// answers is "is this target inside my ground". Enumerating who stands under a +/// place is the other direction and has its own owner: `under_place` walks the +/// subtree by the entities partition's `ChildOf` index. pub(super) fn covers_place( - entities: &Docs<EntityId, EntityRecord>, + entities: &Docs<EntityId, EntityRecord, ChildOf>, root: EntityId, place: EntityId, ) -> bool { @@ -5625,7 +5627,7 @@ pub(super) fn covers_place( /// The canonical twin of the candidate graph's `candidate_targets_overlap`: whether two /// jurisdictions of one kind cover common ground. pub(super) fn targets_overlap( - entities: &Docs<EntityId, EntityRecord>, + entities: &Docs<EntityId, EntityRecord, ChildOf>, left: AuthorityTarget, right: AuthorityTarget, ) -> bool { @@ -5664,7 +5666,7 @@ pub(super) fn route_admits( /// chain that never terminates dies before the partition keeps it. pub(super) fn containment_terminates( start: EntityId, - entities: &Docs<EntityId, EntityRecord>, + entities: &Docs<EntityId, EntityRecord, ChildOf>, ) -> bool { let mut current = entities.get(&start).and_then(|record| record.container); for _ in 0..=entities.len() { From 3aeea1749d98e070b6455c109bfb4fa778212a33 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 06:05:31 +0100 Subject: [PATCH 161/190] aetherlight: the read-work gate, the gate world and the index oracles The clockwork world now holds a route per consecutive place, a Reach::Place channel per place, an institution with a warden office per place and two past-due obligations, so no partition a read index serves is empty. read_work_is_equal_at_100_and_1600 and operation_reads_are_equal_at_100_and_1600 gate the rows a commit and a set of otherwise unreached reads touch; indexes_are_derived, index_reads_equal_reference_scans, an_index_read_mid_transaction_sees_the_log and a_corrupted_index_is_detected hold the index to its map and to the scans it replaced. The harness prints rows read beside time and digests and asserts nothing. golden.digests byte-identical. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/PROVENANCE.md | 48 +++ native/aetherlight/src/action.rs | 50 ++- native/aetherlight/src/clock.rs | 30 +- native/aetherlight/src/golden_tests.rs | 458 ++++++++++++++++++++++++- native/aetherlight/src/lib.rs | 24 ++ 5 files changed, 584 insertions(+), 26 deletions(-) diff --git a/native/aetherlight/PROVENANCE.md b/native/aetherlight/PROVENANCE.md index 01c8fa801..63ab68646 100644 --- a/native/aetherlight/PROVENANCE.md +++ b/native/aetherlight/PROVENANCE.md @@ -420,3 +420,51 @@ O(world), and follow-up `aetherlight-read-indexes-timing-gate` owns the gate. Wh this cut owns is the work it does for the digest, which `golden_tests::digest_work_is_equal_at_100_and_1600` pins: document digests per commit equal at both sizes and equal to Added + Removed + 2 x Updated. + +## Cut AL3b-2: partition read indexes, and the read-work gate + +Authority: cut `aetherlight-read-indexes` r1 of campaign `aetheria-release`; +rulings `aetherlight-narrative-state-owner`, `cultnet-scale-is-not-negotiable`, +`terminus-clockwork-world`. Base `576605c7b`. No digested byte moves: +`fixtures/golden.digests` is identical at every commit of the cut. + +Read indexes are derived state. A `Docs` may carry a `Projection`, a pure function +of one document's value (`DueAt`, `StandsAt`, `ChildOf`, `BySource`, `ByEndpoint`, +`ByController`, `ByIncumbent`, in `lib.rs` beside `world_state!`). The index is the +projection of the map as of the last `finish`, folded by `Docs::finish` from the +same changed-key list the digest folds. It is not a partition: not digested, not +encoded, ignored by equality, never exported. Opening a world builds it by replay, +since genesis and every replayed commit close through `finish`; there is no rebuild +path. `Docs::indexed(range)` returns (point, key) in order and is corrected by the +open log (a logged key's committed entries are dropped and its current points are +read from the map), so it is true mid-transaction; `rollback` never touches the +index because the index never saw the transaction. `Docs` no longer derefs to its +map: every read is an inherent method, so no reader can step around the counter. + +Read work is counted where reads are owned. In test builds `docs::rows_read()` is +the number of rows any `Docs` iterator has yielded plus the entries every `indexed` +call returned. `golden_tests::read_work_is_equal_at_100_and_1600` asserts that a +tick (two routines rolled, two obligations pressed) and a colocated speech read +the same number of rows at 100 and 1600 persons; `operation_reads_are_equal_at_100_and_1600` +does the same for the reads no submit shape reaches (a two-level `under_place`, a +`DischargeCommitment` among N pressure rows, one incumbent's `delegated_authority`, +a three-route `reachable`). Wall time is reported by `clockwork_commit_cost` and +asserted nowhere: it is noise at this scale. The gate world holds a route, a +`Reach::Place` channel and an institution with an office per place, because an +empty partition hides its scan. + +Eight scans became index reads: `under_place`, `audience` (colocated), the pressure +holders of `DischargeCommitment`, `scope_components`' routes and controls, +`delegated_authority`, `derive_motion`'s commitment walk and `reachable`'s outbound +edges. Each old scan is kept as a `cfg(test)` `*_by_scan` reference, and +`index_reads_equal_reference_scans` compares them over every revision of the golden +session, the populated worlds and forty clockwork commits. `indexes_are_derived` +rebuilds every index from its map after each commit, after reopen and after each +failed apply; `a_corrupted_index_is_detected` damages each index both ways. + +Reads that still scan, each with its owner: `derive_motion`'s dependencies loop and +`snapshot` (the host's whole-world projection, never on the commit path); the +resolver's reads of the whole world in `AdmitPatch` +(`aetherlight-resolver-reads-world`); `aetherlight-cross-partition-views`. The +"Timing" paragraph of AL3b above is superseded: the gate it deferred is +`read_work_is_equal_at_100_and_1600`. diff --git a/native/aetherlight/src/action.rs b/native/aetherlight/src/action.rs index 2ad319e79..4d3b3edad 100644 --- a/native/aetherlight/src/action.rs +++ b/native/aetherlight/src/action.rs @@ -635,12 +635,54 @@ fn authority_target_of(target: Target) -> Option<AuthorityTarget> { /// Admission runs at commit against live state, so a route that closed while /// the proposal was in flight makes this fail rather than letting a stale path /// commit. -fn reachable( +pub(super) fn reachable( state: &WorldState, actor: SubjectId, authority: &BTreeSet<AuthorityGrant>, destination: EntityId, within: Cost, +) -> bool { + reach(state, actor, authority, destination, within, |place| { + state + .edges + .indexed(place..=place) + .into_iter() + .map(|(_, edge_id)| edge_id) + .collect() + }) +} + +/// What `reachable` was before the index: every edge asked at every settled place. +#[cfg(test)] +pub(super) fn reachable_by_scan( + state: &WorldState, + actor: SubjectId, + authority: &BTreeSet<AuthorityGrant>, + destination: EntityId, + within: Cost, +) -> bool { + reach(state, actor, authority, destination, within, |place| { + state + .edges + .iter() + .filter(|(_, record)| { + let (from, to) = record.endpoints(); + from == place || to == place + }) + .map(|(edge_id, _)| *edge_id) + .collect() + }) +} + +/// The search, given how the routes touching a place are found, in `EdgeId` +/// order. +fn reach( + state: &WorldState, + actor: SubjectId, + authority: &BTreeSet<AuthorityGrant>, + destination: EntityId, + within: Cost, + routes_at: impl Fn(EntityId) -> Vec<EdgeId>, ) -> bool { let Some(origin) = state.positions.get(&actor).map(|position| position.place) else { return false; @@ -661,11 +703,9 @@ fn reachable( return true; } settled.insert(place); - let outbound: Vec<(EdgeId, EntityId, u64)> = state - .edges - .indexed(place..=place) + let outbound: Vec<(EdgeId, EntityId, u64)> = routes_at(place) .into_iter() - .map(|(_, edge_id)| (edge_id, &state.edges[&edge_id])) + .map(|edge_id| (edge_id, &state.edges[&edge_id])) .filter(|(_, record)| record.is_open()) .filter_map(|(edge_id, record)| { let (from, to) = record.endpoints(); diff --git a/native/aetherlight/src/clock.rs b/native/aetherlight/src/clock.rs index 3fe6c8a5d..572eb1bec 100644 --- a/native/aetherlight/src/clock.rs +++ b/native/aetherlight/src/clock.rs @@ -111,20 +111,36 @@ mod step { /// magnitudes. The kernel stays an exact function of the command sequence, and /// the tick cadence is one operational constant in `runtime.rs`. pub(super) fn derive_motion(state: &WorldState, to: FictionalMinutes) -> Motion { - let mut fulfilled = Vec::new(); - let mut pressed: BTreeMap<(SubjectId, PressureSource), u32> = BTreeMap::new(); - // Only subjects with something due: the commitments index answers it - // without walking every promise in the world. The dependencies walk below - // is still one row per subject holding a dependency: follow-up - // aetherlight-cross-partition-views. + // without walking every promise in the world. let due: std::collections::BTreeSet<SubjectId> = state .commitments .indexed(..=to) .into_iter() .map(|(_, subject)| subject) .collect(); - for subject in &due { + motion_of(state, to, due) +} + +/// What `derive_motion` was before the index: every subject holding a promise. +/// The index read must derive the same motion. +#[cfg(test)] +pub(super) fn derive_motion_by_scan(state: &WorldState, to: FictionalMinutes) -> Motion { + motion_of(state, to, state.commitments.keys().copied().collect()) +} + +/// The motion over `promisors`, which must include every subject with a +/// commitment due by `to`. The dependencies walk below is still one row per +/// subject holding a dependency: follow-up aetherlight-cross-partition-views. +fn motion_of( + state: &WorldState, + to: FictionalMinutes, + promisors: std::collections::BTreeSet<SubjectId>, +) -> Motion { + let mut fulfilled = Vec::new(); + let mut pressed: BTreeMap<(SubjectId, PressureSource), u32> = BTreeMap::new(); + + for subject in &promisors { let held = &state.commitments[subject]; // A retired subject cannot act, and neither fulfilling a routine nor // pressing an obligation or goal is anything but that subject acting: diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs index f8d632b81..944432454 100644 --- a/native/aetherlight/src/golden_tests.rs +++ b/native/aetherlight/src/golden_tests.rs @@ -258,14 +258,27 @@ fn incremental_digest_equals_full_recompute() { /// The clockwork world: `persons` persons, ten to a place, one Routine each /// with period `persons / 2`, due `1 + i mod (persons / 2)`, so a one-minute /// tick rolls two routines at every size and a speech reaches the same nine -/// listeners. +/// listeners. Every partition a read index serves is populated, because an +/// empty one hides its scan: one route between consecutive places, one +/// `Reach::Place` channel per place controlled by its first person, one +/// institution per place with a warden office held by that person, and two +/// Obligations past due from the first minute, so a tick presses two sources +/// at every size. fn clockwork_world(persons: usize) -> (WorldKernel, Vec<crate::SubjectId>, crate::AffordanceId) { use crate::patch::kernel_speak_grant; - use crate::patch::{EntityDeclaration, SubjectDeclaration}; - use crate::{CallerId, CommandEnvelope, CreateWorld, EntityKind, SubjectKind}; + use crate::patch::{ + AccessKind, AuthorityGrantRef, AuthorityTargetRef, ChannelDeclaration, EntityDeclaration, + ReachRef, RouteDeclaration, SubjectDeclaration, + }; + use crate::tests::{LEVY_KIND, WARDEN_OFFICE, authority_kind, office}; + use crate::{CallerId, CommandEnvelope, CreateWorld, Cost, EntityKind, SubjectKind}; + use std::collections::BTreeSet; let places = persons / 10; + let draft_place = |place: usize| Ref::Draft(DraftHandle::new(format!("place-{place}"))); + let draft_person = |person: usize| Ref::Draft(DraftHandle::new(format!("person-{person}"))); let mut declarations = Vec::new(); + let mut offices = Vec::new(); for place in 0..places { declarations.push(Declaration::Entity(EntityDeclaration { handle: DraftHandle::new(format!("place-{place}")), @@ -273,6 +286,48 @@ fn clockwork_world(persons: usize) -> (WorldKernel, Vec<crate::SubjectId>, crate kind: EntityKind::Place, container: None, })); + if place + 1 < places { + declarations.push(Declaration::Route(RouteDeclaration { + handle: DraftHandle::new(format!("route-{place}")), + label: format!("Route {place}"), + from: draft_place(place), + to: draft_place(place + 1), + access: AccessKind::Public, + cost: Cost(1), + })); + } + declarations.push(Declaration::Channel(ChannelDeclaration { + handle: DraftHandle::new(format!("channel-{place}")), + label: format!("Channel {place}"), + reach: ReachRef::Place(draft_place(place)), + controller: Some(draft_person(place * 10)), + })); + let institution = DraftHandle::new(format!("institution-{place}")); + declarations.push(Declaration::Subject(SubjectDeclaration { + handle: institution.clone(), + label: format!("Institution {place}"), + kind: SubjectKind::Institution, + affordances: BTreeSet::new(), + position: None, + import_key: None, + })); + offices.push(ComponentOp::GrantAuthority { + holder: Ref::Draft(institution.clone()), + grant: AuthorityGrantRef { + kind: authority_kind(LEVY_KIND), + over: AuthorityTargetRef::PlaceSubtree(draft_place(place)), + }, + }); + offices.push(ComponentOp::OpenOffice { + institution: Ref::Draft(institution.clone()), + office: office(WARDEN_OFFICE), + delegated: BTreeSet::from([authority_kind(LEVY_KIND)]), + }); + offices.push(ComponentOp::InstallIncumbent { + institution: Ref::Draft(institution), + office: office(WARDEN_OFFICE), + incumbent: draft_person(place * 10), + }); } for person in 0..persons { declarations.push(Declaration::Subject(SubjectDeclaration { @@ -290,7 +345,7 @@ fn clockwork_world(persons: usize) -> (WorldKernel, Vec<crate::SubjectId>, crate title: "Clockwork".into(), patch: WorldPatch { declarations, - operations: Vec::new(), + operations: offices, evidence: Vec::new(), }, grammar: None, @@ -302,7 +357,7 @@ fn clockwork_world(persons: usize) -> (WorldKernel, Vec<crate::SubjectId>, crate .map(|person| subject_by_label(&kernel.state, &format!("Person {person}"))) .collect(); let period = (persons / 2) as u64; - let routines = people + let mut routines: Vec<ComponentOp> = people .iter() .enumerate() .map(|(index, subject)| ComponentOp::CreateCommitment { @@ -315,6 +370,15 @@ fn clockwork_world(persons: usize) -> (WorldKernel, Vec<crate::SubjectId>, crate statement: Statement::new("Keeps the hour.").unwrap(), }) .collect(); + routines.extend(people[..2].iter().map(|subject| ComponentOp::CreateCommitment { + subject: Ref::Existing(*subject), + counterparty: Some(Ref::Existing(people[2])), + kind: CommitmentKind::Obligation, + due: FictionalMinutes(1), + period: None, + checks: Vec::new(), + statement: Statement::new("Owes the tithe.").unwrap(), + })); let placing = CommandEnvelope { world_id: kernel.state.header.world_id, expected_revision: kernel.state.revision, @@ -490,12 +554,14 @@ fn a_failed_apply_rolls_back() { kernel.state.state_digest, "{label}: the accumulator no longer matches the documents" ); + assert_indexes_derived(&kernel.state, &format!("{label}, after the failure")); let envelope = clockwork_envelope(&kernel, body); kernel .submit(envelope, &AuthenticatedCaller::verified_play()) .unwrap_or_else(|error| panic!("{label}: the next honest command: {error:?}")); assert_eq!(kernel.state.full_state_digest().unwrap(), kernel.state.state_digest); + assert_indexes_derived(&kernel.state, &format!("{label}, after the honest command")); } } } @@ -577,17 +643,21 @@ fn every_partition_is_digested_undone_and_finished() { } /// What one tick and one speech cost to commit as the world grows, by the -/// clockwork world above. Run on its own, in release, to read the numbers; no -/// time is asserted here. The timing gate belongs to the follow-up -/// `aetherlight-read-indexes-timing-gate`, because the world reads a commit -/// makes (`audience`, `derive_motion`) are still O(world) and bound the ratio. -/// `digest_work_is_equal_at_100_and_1600` is the gate on what this commit owns. +/// clockwork world above: time, document digests and rows read (Docs rows plus +/// index entries) per commit, and the 1600/100 ratios. Run on its own, in +/// release, to read the numbers; nothing is asserted here. Wall time is noise +/// at this scale (the same code ran a tick ratio of 2.8 to 4.9 over five +/// runs), so the gate is `read_work_is_equal_at_100_and_1600`, which counts +/// the rows each commit reads and fails when one grows with the world, and +/// `digest_work_is_equal_at_100_and_1600` for what a commit digests. /// /// `cargo test --release --lib clockwork_commit_cost -- --ignored --nocapture` #[test] #[ignore] fn clockwork_commit_cost() { - println!("persons create_ms tick_ms tick_digests speech_ms speech_digests"); + println!( + "persons create_ms tick_ms tick_digests tick_rows speech_ms speech_digests speech_rows" + ); let mut ticks_ms = Vec::new(); let mut speeches_ms = Vec::new(); for persons in [100usize, 400, 1600] { @@ -596,16 +666,18 @@ fn clockwork_commit_cost() { let create_ms = started.elapsed().as_secs_f64() * 1e3; let play = AuthenticatedCaller::verified_play(); - let (mut ticks, mut tick_digests) = (0.0, 0); + let (mut ticks, mut tick_digests, mut tick_rows) = (0.0, 0, 0); for _ in 0..30 { let tick = clockwork_envelope(&kernel, tick_body(1)); crate::digest::DOC_DIGESTS.with(|count| count.set(0)); + let rows = crate::docs::rows_read(); let started = Instant::now(); kernel.submit(tick, &play).expect("the tick commits"); ticks += started.elapsed().as_secs_f64() * 1e3; tick_digests = crate::digest::DOC_DIGESTS.with(|count| count.get()); + tick_rows = crate::docs::rows_read() - rows; } - let (mut speeches, mut speech_digests) = (0.0, 0); + let (mut speeches, mut speech_digests, mut speech_rows) = (0.0, 0, 0); for index in 0..30 { let act = clockwork_envelope( &kernel, @@ -615,13 +687,15 @@ fn clockwork_commit_cost() { }, ); crate::digest::DOC_DIGESTS.with(|count| count.set(0)); + let rows = crate::docs::rows_read(); let started = Instant::now(); kernel.submit(act, &play).expect("the speech commits"); speeches += started.elapsed().as_secs_f64() * 1e3; speech_digests = crate::digest::DOC_DIGESTS.with(|count| count.get()); + speech_rows = crate::docs::rows_read() - rows; } println!( - "{persons:>7} {create_ms:>9.1} {:>7.3} {tick_digests:>12} {:>9.3} {speech_digests:>14}", + "{persons:>7} {create_ms:>9.1} {:>7.3} {tick_digests:>12} {tick_rows:>9} {:>9.3} {speech_digests:>14} {speech_rows:>11}", ticks / 30.0, speeches / 30.0, ); @@ -758,3 +832,359 @@ fn a_commitment_due_at_or_before_the_clock_reads_past_due() { "the routine fell due behind the clock" ); } + +/// Rows (Docs rows and index entries) one submit read. +fn submit_counting_rows(kernel: &mut WorldKernel, body: CommandBody) -> u64 { + let envelope = clockwork_envelope(kernel, body); + let before = crate::docs::rows_read(); + kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .expect("the commit lands"); + crate::docs::rows_read() - before +} + +/// A commit's read work is what it touches, not what the world holds: a tick +/// that rolls two routines and presses two obligations, and a colocated speech, +/// read the same number of rows at 100 persons and at 1600. The count is taken +/// where reads are owned (`Docs`), so a reader that scans a partition cannot +/// hide from it. Wall time is not asserted anywhere: it is noise at this scale. +#[test] +fn read_work_is_equal_at_100_and_1600() { + let mut worked = Vec::new(); + for persons in [100usize, 1600] { + let (mut kernel, people, speak_entry) = clockwork_world(persons); + let mut counts = Vec::new(); + for _ in 0..3 { + counts.push(submit_counting_rows(&mut kernel, tick_body(1))); + } + for index in 0..3 { + let speech = CommandBody::Act { + actor: people[index], + invocation: speak(speak_entry, &format!("Speech {index}.")), + }; + counts.push(submit_counting_rows(&mut kernel, speech)); + } + assert!(counts.iter().all(|rows| *rows > 0), "{persons} persons: a commit read nothing"); + worked.push(counts); + } + assert_eq!(worked[0], worked[1], "read work grew with the world"); +} + +/// The reads a clockwork submit does not reach, inside one open transaction +/// each: who stands under a two-level subtree, discharging a commitment while +/// the world holds N pressure rows from other sources, one incumbent's +/// delegated authority, and a path of three routes. (An `AdmitPatch` resolves +/// against the whole world until follow-up `aetherlight-resolver-reads-world`, +/// so no submit shape reaches these.) +#[test] +fn operation_reads_are_equal_at_100_and_1600() { + use crate::patch::ResolvedOp; + use crate::{Cost, PressureSource}; + use std::collections::BTreeSet; + + let mut worked = Vec::new(); + for persons in [100usize, 1600] { + let (mut kernel, people, _) = clockwork_world(persons); + kernel + .submit(clockwork_envelope(&kernel, tick_body(1)), &AuthenticatedCaller::verified_play()) + .expect("the tick presses the obligations"); + let place = |label: &str| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared place") + .0 + }; + let (zero, one, two, three) = + (place("Place 0"), place("Place 1"), place("Place 2"), place("Place 3")); + + // N pressure rows from other sources, committed before the measured transaction. + kernel.state.begin(); + for person in &people { + kernel.state.pressures.entry(*person).or_default().insert( + PressureSource::Subject(people[0]), + crate::patch::PressureMagnitude(1), + ); + } + let folded = kernel.state.folded().unwrap(); + kernel.state.finish(folded); + + let state = &mut kernel.state; + let obligation = state.commitments[&people[0]] + .iter() + .find(|(_, commitment)| commitment.kind == CommitmentKind::Obligation) + .map(|(key, _)| *key) + .expect("the first person owes an obligation"); + + state.begin(); + // Place 1 inside place 0, place 2 inside place 1. + state.entities.get_mut(&one).unwrap().container = Some(zero); + state.entities.get_mut(&two).unwrap().container = Some(one); + + let mut counts = Vec::new(); + let mut measure = |read: &mut dyn FnMut()| { + let before = crate::docs::rows_read(); + read(); + let rows = crate::docs::rows_read() - before; + assert!(rows > 0, "a read counted nothing"); + counts.push(rows); + }; + let mut under = BTreeSet::new(); + measure(&mut || under = crate::under_place(state, zero)); + assert_eq!(under.len(), 30, "places 0, 1 and 2 hold ten persons each"); + let mut delegated = Default::default(); + measure(&mut || delegated = crate::delegated_authority(state, people[0])); + assert_eq!(delegated.len(), 1, "the first person holds one office"); + let authority = BTreeSet::new(); + let mut reached = false; + measure(&mut || reached = crate::action::reachable(state, people[0], &authority, three, Cost(3))); + assert!(reached, "three routes of cost one reach place 3"); + let mut applied = Ok(()); + let revision = state.revision + 1; + measure(&mut || { + applied = crate::apply_operation( + state, + &ResolvedOp::DischargeCommitment { subject: people[0], key: obligation }, + &[], + revision, + ); + }); + applied.expect("the obligation is discharged"); + assert!( + state.pressures[&people[0]] + .keys() + .all(|source| !matches!(source, PressureSource::Commitment { key, .. } if *key == obligation)), + "the pressure the obligation sourced is gone" + ); + state.rollback(); + worked.push(counts); + } + assert_eq!(worked[0], worked[1], "an operation's read work grew with the world"); +} + +fn assert_indexes_derived(state: &crate::WorldState, label: &str) { + for (schema, docs) in state.partitions() { + assert!(docs.index_is_derived(), "{label}: the read index of {schema} left its documents"); + } +} + +/// The states a test walks: every revision of the golden session as replay +/// derives it, the live and reopened golden world, each populated world, and +/// forty commits of the clockwork world. +fn walked_states() -> Vec<(String, crate::WorldState)> { + let mut states = Vec::new(); + let (kernel, _) = golden_session(); + let commits = kernel.journal.commits_for_test(); + for index in 0..commits.len() { + let replayed = crate::journal::verify_history(&commits[..=index]).unwrap(); + states.push((format!("golden revision {index}"), replayed)); + } + let reopened = WorldKernel::open(&kernel.export().unwrap()).unwrap(); + states.push(("golden reopened".into(), reopened.state)); + states.push(("golden live".into(), kernel.state)); + for (index, world) in populated_worlds().into_iter().enumerate() { + states.push((format!("populated world {index}"), world)); + } + let (mut kernel, people, speak_entry) = clockwork_world(100); + states.push(("clockwork created".into(), kernel.state.clone())); + for step in 0..40 { + let body = if step % 2 == 0 { + tick_body(1) + } else { + CommandBody::Act { + actor: people[step], + invocation: speak(speak_entry, &format!("Speech {step}.")), + } + }; + let envelope = clockwork_envelope(&kernel, body); + kernel.submit(envelope, &AuthenticatedCaller::verified_play()).unwrap(); + states.push((format!("clockwork commit {step}"), kernel.state.clone())); + } + states +} + +/// Every read index is the projection of its partition and nothing else, after +/// every commit the walked worlds make, however the world was reached. +#[test] +fn indexes_are_derived() { + for (label, state) in walked_states() { + assert_indexes_derived(&state, &label); + } +} + +/// The first place an index read and the scan it replaced disagree, if any. +fn reference_scan_disagreement(state: &crate::WorldState) -> Option<String> { + use crate::{Audience, Cost, PressureSource}; + let now = state.header.now; + for minutes in [1, 30] { + let to = FictionalMinutes(now.0 + minutes); + if crate::clock::derive_motion(state, to) != crate::clock::derive_motion_by_scan(state, to) { + return Some(format!("derive_motion over {minutes} minutes")); + } + } + let subjects: Vec<_> = state.subjects.keys().copied().collect(); + let places: Vec<_> = state + .entities + .iter() + .filter(|(_, record)| record.kind == crate::EntityKind::Place) + .map(|(id, _)| *id) + .collect(); + for subject in &subjects { + if crate::audience(state, *subject, &Audience::Colocated) + != crate::audience_by_scan(state, *subject, &Audience::Colocated) + { + return Some(format!("colocated audience of {subject:?}")); + } + if crate::delegated_authority(state, *subject) + != crate::delegated_authority_by_scan(state, *subject) + { + return Some(format!("delegated authority of {subject:?}")); + } + if crate::channels_controlled_by(state, *subject) + != crate::channels_controlled_by_by_scan(state, *subject) + { + return Some(format!("channels controlled by {subject:?}")); + } + let authority = crate::subject_authority(state, *subject); + for place in &places { + if crate::action::reachable(state, *subject, &authority, *place, Cost(3)) + != crate::action::reachable_by_scan(state, *subject, &authority, *place, Cost(3)) + { + return Some(format!("reachable {place:?} from {subject:?}")); + } + } + } + for place in &places { + if crate::under_place(state, *place) != crate::under_place_by_scan(state, *place) { + return Some(format!("under_place {place:?}")); + } + if crate::routes_at(state, *place) != crate::routes_at_by_scan(state, *place) { + return Some(format!("routes at {place:?}")); + } + } + for (channel, _) in state.channels.iter() { + let actor = subjects.first().copied()?; + if crate::audience(state, actor, &Audience::Channel(*channel)) + != crate::audience_by_scan(state, actor, &Audience::Channel(*channel)) + { + return Some(format!("audience of channel {channel:?}")); + } + } + let mut sources: Vec<PressureSource> = state + .pressures + .iter() + .flat_map(|(_, held)| held.keys().copied()) + .collect(); + sources.extend(subjects.first().map(|first| PressureSource::Subject(*first))); + for source in sources { + if crate::pressure_holders(state, source) != crate::pressure_holders_by_scan(state, source) { + return Some(format!("holders of {source:?}")); + } + } + None +} + +/// Each read an index answers equals the scan it replaced, at every walked state. +#[test] +fn index_reads_equal_reference_scans() { + for (label, state) in walked_states() { + assert_eq!(reference_scan_disagreement(&state), None, "{label}"); + } +} + +/// A read inside an open transaction sees what the transaction wrote, though +/// the index has not: a subject moved through `positions` leaves its old room +/// and joins the new one, a removed pressure row no longer lists its source, and +/// after the rollback the reads are what they were. +#[test] +fn an_index_read_mid_transaction_sees_the_log() { + use crate::patch::Position; + use crate::{Audience, PressureSource}; + let (mut kernel, people, _) = clockwork_world(20); + kernel + .submit(clockwork_envelope(&kernel, tick_body(1)), &AuthenticatedCaller::verified_play()) + .expect("the tick presses the obligations"); + let state = &mut kernel.state; + let (mover, in_old, in_new) = (people[1], people[2], people[11]); + let new_place = state.positions[&in_new].place; + assert_ne!(state.positions[&mover].place, new_place); + let obligation = state.commitments[&people[0]] + .iter() + .find(|(_, commitment)| commitment.kind == CommitmentKind::Obligation) + .map(|(key, _)| *key) + .expect("the first person owes an obligation"); + let source = PressureSource::Commitment { subject: people[0], key: obligation }; + let reads = |state: &crate::WorldState| { + ( + crate::audience(state, in_old, &Audience::Colocated), + crate::audience(state, in_new, &Audience::Colocated), + crate::pressure_holders(state, source), + ) + }; + let before = reads(state); + assert!(before.0.contains(&mover) && !before.1.contains(&mover)); + assert!(before.2.contains(&people[0])); + + state.begin(); + state.positions.insert(mover, Position { place: new_place }); + state.pressures.remove(&people[0]); + let during = reads(state); + assert!(!during.0.contains(&mover), "the old room still lists the mover"); + assert!(during.1.contains(&mover), "the new room does not list the mover"); + assert!(!during.2.contains(&people[0]), "a removed pressure row still lists its source"); + assert_eq!(reference_scan_disagreement(state), None, "mid-transaction reads equal the scans"); + state.rollback(); + + assert_indexes_derived(state, "after the rollback"); + assert_eq!(reads(state), before); +} + +/// The oracle can see an index that disagrees with its documents: damaged one +/// way (a document listed where it is not) or the other (a document left out), +/// every indexed partition reports it, and the reads the index serves then +/// differ from the scans they replaced. +#[test] +fn a_corrupted_index_is_detected() { + use std::collections::BTreeSet; + let mut worlds = populated_worlds(); + let (mut kernel, _, _) = clockwork_world(20); + kernel + .submit(clockwork_envelope(&kernel, tick_body(1)), &AuthenticatedCaller::verified_play()) + .unwrap(); + worlds.push(kernel.state); + let mut reported = BTreeSet::new(); + let mut misread = BTreeSet::new(); + for world in &worlds { + for index in 0..crate::WorldState::PARTITIONS { + for stray in [true, false] { + let mut damaged = world.clone(); + if !damaged.partitions_mut()[index].1.corrupt_index_first(stray) { + continue; + } + let schema = damaged.partitions()[index].0; + assert!( + !damaged.partitions()[index].1.index_is_derived(), + "{schema}: damage (stray {stray}) went unseen" + ); + reported.insert(schema); + if reference_scan_disagreement(&damaged).is_some() { + misread.insert(schema); + } + } + } + } + let indexed: BTreeSet<&str> = [ + "aetherlight.entity.v1", + "aetherlight.edge.v1", + "aetherlight.position.v1", + "aetherlight.channel.v1", + "aetherlight.selection.v1", + "aetherlight.commitments.v1", + "aetherlight.pressures.v1", + ] + .into(); + assert_eq!(reported, indexed, "exactly the indexed partitions can be damaged"); + assert_eq!(misread, indexed, "a damaged index must change what a reader answers"); +} diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index 91766348e..29a993bfd 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -2752,6 +2752,30 @@ fn audience(state: &WorldState, actor: SubjectId, of: &Audience) -> BTreeSet<Sub } } +/// What `audience` was before the index: every position compared with the +/// actor's, and `under_place_by_scan` for a channel's place. The index read +/// must equal it. +#[cfg(test)] +fn audience_by_scan(state: &WorldState, actor: SubjectId, of: &Audience) -> BTreeSet<SubjectId> { + match of { + Audience::Colocated => { + let Some(here) = state.positions.get(&actor).copied() else { + return BTreeSet::new(); + }; + state + .positions + .iter() + .filter(|(_, position)| **position == here) + .map(|(subject_id, _)| *subject_id) + .collect() + } + Audience::Channel(channel) => match state.channels.get(channel).map(|record| &record.reach) { + Some(Reach::Place(root)) => under_place_by_scan(state, *root), + _ => audience(state, actor, of), + }, + } +} + /// Whether an actor may broadcast into an audience: either the actor stands /// inside the declared reach, or — for a channel — the actor is that /// channel's controller. The controller's privilege is narrow: it lets the From f656cfdb1bb76c0dda5e7373e63e9db52ee8d60a Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 06:19:40 +0100 Subject: [PATCH 162/190] aetherlight: drop Counted's size_hint override Delegation to the inner iterator's hint; cargo-mutants found only equivalent mutants of it. The default hint costs nothing here. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/docs.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/native/aetherlight/src/docs.rs b/native/aetherlight/src/docs.rs index bb05fd192..68b5f10e5 100644 --- a/native/aetherlight/src/docs.rs +++ b/native/aetherlight/src/docs.rs @@ -46,9 +46,6 @@ impl<I: Iterator> Iterator for Counted<I> { } item } - fn size_hint(&self) -> (usize, Option<usize>) { - self.0.size_hint() - } } impl<I: DoubleEndedIterator> DoubleEndedIterator for Counted<I> { From c901d8b96ab5f0e03f080eee3a76470765fe9219 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 07:11:31 +0100 Subject: [PATCH 163/190] aetherlight: the gate world holds holdings, facts and knowledge at scale One grain holding and one known fact per person, a fact and a resource per place, and two dependencies (a fixed count: derive_motion still walks every dependency row, follow-up aetherlight-cross-partition-views). read_work now asserts the partitions are populated, so a scan of knowledge, holdings or facts grows the count and fails it. golden.digests untouched. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/golden_tests.rs | 51 ++++++++++++++++++++++++-- 1 file changed, 48 insertions(+), 3 deletions(-) diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs index 944432454..a1d9fdb74 100644 --- a/native/aetherlight/src/golden_tests.rs +++ b/native/aetherlight/src/golden_tests.rs @@ -267,10 +267,12 @@ fn incremental_digest_equals_full_recompute() { fn clockwork_world(persons: usize) -> (WorldKernel, Vec<crate::SubjectId>, crate::AffordanceId) { use crate::patch::kernel_speak_grant; use crate::patch::{ - AccessKind, AuthorityGrantRef, AuthorityTargetRef, ChannelDeclaration, EntityDeclaration, + AccessKind, AuthoredSource, AuthorityGrantRef, AuthorityTargetRef, ChannelDeclaration, + DependencyRef, EntityDeclaration, EvidenceRef, FactDeclaration, FactStandingRef, Quantity, ReachRef, RouteDeclaration, SubjectDeclaration, }; - use crate::tests::{LEVY_KIND, WARDEN_OFFICE, authority_kind, office}; + use crate::tests::{LEVY_KIND, TITHE_RECEIPT, WARDEN_OFFICE, authority_kind, office}; + use crate::Confidence; use crate::{CallerId, CommandEnvelope, CreateWorld, Cost, EntityKind, SubjectKind}; use std::collections::BTreeSet; @@ -302,6 +304,18 @@ fn clockwork_world(persons: usize) -> (WorldKernel, Vec<crate::SubjectId>, crate reach: ReachRef::Place(draft_place(place)), controller: Some(draft_person(place * 10)), })); + declarations.push(Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(format!("grain-{place}")), + label: format!("Grain {place}"), + kind: EntityKind::Resource, + container: None, + })); + declarations.push(Declaration::Fact(FactDeclaration { + handle: DraftHandle::new(format!("fact-{place}")), + label: format!("Fact {place}"), + statement: Statement::new("The place keeps its hour.").unwrap(), + standing: FactStandingRef::Canonical { evidence: EvidenceRef::new(TITHE_RECEIPT) }, + })); let institution = DraftHandle::new(format!("institution-{place}")); declarations.push(Declaration::Subject(SubjectDeclaration { handle: institution.clone(), @@ -330,6 +344,21 @@ fn clockwork_world(persons: usize) -> (WorldKernel, Vec<crate::SubjectId>, crate }); } for person in 0..persons { + let place = person / 10; + // One holding and one known fact per person, so `holdings`, `facts` and + // `knowledge` grow with the world and a scan of them breaks the gate. + offices.push(ComponentOp::Admit { + holder: draft_person(person), + resource: Ref::Draft(DraftHandle::new(format!("grain-{place}"))), + qty: Quantity(1), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }); + offices.push(ComponentOp::AcquireKnowledge { + subject: draft_person(person), + fact: Ref::Draft(DraftHandle::new(format!("fact-{place}"))), + source: AuthoredSource::Witnessed, + confidence: Confidence::Believed, + }); declarations.push(Declaration::Subject(SubjectDeclaration { handle: DraftHandle::new(format!("person-{person}")), label: format!("Person {person}"), @@ -339,6 +368,15 @@ fn clockwork_world(persons: usize) -> (WorldKernel, Vec<crate::SubjectId>, crate import_key: None, })); } + // Two dependencies, a fixed count: `derive_motion` still walks every + // dependency row (follow-up aetherlight-cross-partition-views), so a + // dependency per person would grow a tick's reads with the world. + for person in 0..2 { + offices.push(ComponentOp::Bind { + subject: draft_person(person), + target: DependencyRef::Subject(draft_person(2)), + }); + } let (mut kernel, _) = WorldKernel::create( CreateWorld { owner: owner(), @@ -346,7 +384,7 @@ fn clockwork_world(persons: usize) -> (WorldKernel, Vec<crate::SubjectId>, crate patch: WorldPatch { declarations, operations: offices, - evidence: Vec::new(), + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], }, grammar: None, }, @@ -853,6 +891,13 @@ fn read_work_is_equal_at_100_and_1600() { let mut worked = Vec::new(); for persons in [100usize, 1600] { let (mut kernel, people, speak_entry) = clockwork_world(persons); + // The gate holds only if the partitions are populated at scale: an empty + // one hides a scan of it. + let state = &kernel.state; + assert!(state.holdings.len() >= persons && state.knowledge.len() >= persons); + assert!(state.facts.len() >= persons / 10 && state.channels.len() == persons / 10); + assert!(state.positions.len() >= persons && state.commitments.len() >= persons); + assert!(state.edges.len() + 1 == persons / 10 && state.selection.len() == persons / 10); let mut counts = Vec::new(); for _ in 0..3 { counts.push(submit_counting_rows(&mut kernel, tick_body(1))); From 08d0c26fd8972567b5765f15fcd3d0c785464ef0 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 07:11:33 +0100 Subject: [PATCH 164/190] aetherlight: indexed counts the open-log walk, not only the entries it returns Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/docs.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/native/aetherlight/src/docs.rs b/native/aetherlight/src/docs.rs index 68b5f10e5..0b594fb7f 100644 --- a/native/aetherlight/src/docs.rs +++ b/native/aetherlight/src/docs.rs @@ -266,6 +266,9 @@ impl<K: Ord + Clone, V: Clone + PartialEq, P: Projection<V>> Docs<K, V, P> { .map(|(point, key)| (point.clone(), key.clone())) .collect(); if !self.touched.is_empty() { + // Every logged key is walked whatever the range, so each is a row read. + #[cfg(test)] + count_rows(self.touched.len() as u64); let mut points = Vec::new(); for key in self.touched.keys() { if let Some(value) = self.map.get(key) { @@ -540,6 +543,16 @@ mod tests { assert_eq!(rows_read() - before, 2); } + #[test] + fn walking_the_open_log_is_counted_even_when_nothing_matches() { + let mut docs = spread(&[(1, 10), (2, 21), (3, 33)]); + docs.insert(1, 11); + docs.insert(9, 99); + let before = rows_read(); + assert!(docs.indexed(5..=5).is_empty()); + assert_eq!(rows_read() - before, 2, "two logged keys were walked"); + } + #[test] fn a_damaged_index_is_seen_as_not_derived() { for stray in [true, false] { From a4341a008e28be585e4d0434e6f6eefd5dbe6335 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 07:12:17 +0100 Subject: [PATCH 165/190] aetherlight: commit the random-walk differential of indexed against the projection of the map Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/docs.rs | 53 ++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/native/aetherlight/src/docs.rs b/native/aetherlight/src/docs.rs index 0b594fb7f..ed37d2767 100644 --- a/native/aetherlight/src/docs.rs +++ b/native/aetherlight/src/docs.rs @@ -543,6 +543,59 @@ mod tests { assert_eq!(rows_read() - before, 2); } + /// Arbitrary interleavings of every write, finish and rollback, read back + /// over arbitrary ranges: `indexed` equals the projection computed from the + /// map at every step, and the index is the rebuild after each close. + #[test] + fn indexed_equals_truth_over_a_random_walk_of_writes_and_ranges() { + let mut state = 0x9E37_79B9_7F4A_7C15_u64; + let mut next = move |bound: u64| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state % bound + }; + let mut docs = spread(&[(0, 5), (1, 17), (2, 17)]); + for step in 0..4000 { + let key = next(12) as u8; + match next(8) { + 0 | 1 => { + docs.insert(key, next(100) as u8); + } + 2 => { + docs.remove(&key); + } + 3 => { + if let Some(value) = docs.get_mut(&key) { + *value = (next(100)) as u8; + } + } + 4 => { + let fresh = next(100) as u8; + docs.entry(key).or_insert(fresh); + } + 5 => { + docs.finish(); + assert!(docs.index_is_derived(), "step {step}: after finish"); + } + 6 => { + docs.rollback(); + assert!(docs.index_is_derived(), "step {step}: after rollback"); + } + _ => {} + } + let (a, b) = (next(11) as u8, next(11) as u8); + let (lo, hi) = (a.min(b), a.max(b)); + let all = truth(&docs); + assert_eq!(docs.indexed(..), all, "step {step}: full range"); + let within = |keep: &dyn Fn(u8) -> bool| -> Vec<(u8, u8)> { + all.iter().copied().filter(|(point, _)| keep(*point)).collect() + }; + assert_eq!(docs.indexed(lo..=hi), within(&|p| (lo..=hi).contains(&p)), "step {step}: {lo}..={hi}"); + assert_eq!(docs.indexed(..hi), within(&|p| p < hi), "step {step}: ..{hi}"); + } + } + #[test] fn walking_the_open_log_is_counted_even_when_nothing_matches() { let mut docs = spread(&[(1, 10), (2, 21), (3, 33)]); From 128c00bdad0fd9f6fdec5ba93ae6f6596f4d0e3f Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 07:14:23 +0100 Subject: [PATCH 166/190] aetherlight: a multivalue world, and the derived-index oracle checks the scans too A pressure target fed by three sources and an institution with three distinct incumbents (one in two offices) join the walked states, so a projection that keeps only the first or last point of a document loses a row the reference scans still see. indexes_are_derived now also compares every read with its _by_scan twin, since a rebuild through P::points agrees with a wrong projection. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/golden_tests.rs | 36 ++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs index a1d9fdb74..d56f1e342 100644 --- a/native/aetherlight/src/golden_tests.rs +++ b/native/aetherlight/src/golden_tests.rs @@ -1047,15 +1047,51 @@ fn walked_states() -> Vec<(String, crate::WorldState)> { kernel.submit(envelope, &AuthenticatedCaller::verified_play()).unwrap(); states.push((format!("clockwork commit {step}"), kernel.state.clone())); } + states.push(("multivalue world".into(), multivalue_world())); states } +/// A world where one document sits at several points: a pressure target fed by +/// three sources, and an institution whose offices have three distinct +/// incumbents, one of them in two offices. A projection that keeps only the +/// first or last of a document's points loses a row here and nowhere else. +fn multivalue_world() -> crate::WorldState { + use crate::patch::{Office, PressureMagnitude}; + use crate::tests::{LEVY_KIND, authority_kind, office}; + use crate::PressureSource; + let (mut kernel, people, _) = clockwork_world(20); + kernel + .submit(clockwork_envelope(&kernel, tick_body(1)), &AuthenticatedCaller::verified_play()) + .expect("the tick commits"); + let mut state = kernel.state; + let institution = *state.selection.keys().next().expect("an institution holds offices"); + state.begin(); + for source in [people[1], people[2], people[3]] { + state + .pressures + .entry(people[5]) + .or_default() + .insert(PressureSource::Subject(source), PressureMagnitude(1)); + } + let delegated = std::collections::BTreeSet::from([authority_kind(LEVY_KIND)]); + let offices = state.selection.get_mut(&institution).unwrap(); + for (name, incumbent) in [("bailiff", people[3]), ("steward", people[3]), ("reeve", people[4])] { + offices.insert(office(name), Office { incumbent: Some(incumbent), delegated: delegated.clone() }); + } + let folded = state.folded().unwrap(); + state.finish(folded); + state +} + /// Every read index is the projection of its partition and nothing else, after /// every commit the walked worlds make, however the world was reached. #[test] fn indexes_are_derived() { for (label, state) in walked_states() { assert_indexes_derived(&state, &label); + // The rebuild above uses the projection itself, so a wrong projection + // agrees with its own index; the scans it replaced do not. + assert_eq!(reference_scan_disagreement(&state), None, "{label}"); } } From 609b3ba5e960d897ca31eb170689a5d3b21b0f0c Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 07:37:37 +0100 Subject: [PATCH 167/190] aetherlight: pin the gate world's dependency and redress counts, owned by cross-partition-views Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/golden_tests.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs index d56f1e342..81276b3af 100644 --- a/native/aetherlight/src/golden_tests.rs +++ b/native/aetherlight/src/golden_tests.rs @@ -898,6 +898,15 @@ fn read_work_is_equal_at_100_and_1600() { assert!(state.facts.len() >= persons / 10 && state.channels.len() == persons / 10); assert!(state.positions.len() >= persons && state.commitments.len() >= persons); assert!(state.edges.len() + 1 == persons / 10 && state.selection.len() == persons / 10); + // Not at scale, on purpose: `derive_motion` still walks every dependency + // row, so a dependency per person would grow a tick's reads. The owner + // is follow-up aetherlight-cross-partition-views; when it lands this + // count flips to world scale (`>= persons`) so a scan of the partition + // is seen. + assert_eq!(state.dependencies.len(), 2); + // The gate world opens no forum, so `redress` is empty here; the same + // follow-up owns populating it at scale beside dependencies. + assert_eq!(state.redress.len(), 0); let mut counts = Vec::new(); for _ in 0..3 { counts.push(submit_counting_rows(&mut kernel, tick_body(1))); From f25dcb54ce9c1617e43da8c6c6767403f2672c66 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 13:10:34 +0100 Subject: [PATCH 168/190] Follow camera: delete the dead transposer/composer comments; add GameSettings.FollowCameraDistancePerReach (1.5) Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Resources/Settings.asset | 4 ++-- Assets/Scripts/Gameplay/ActionGameManager.cs | 3 --- Assets/Scripts/Gameplay/GameSettings.cs | 3 +++ 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Assets/Resources/Settings.asset b/Assets/Resources/Settings.asset index 1c37213be..7d89eea8e 100644 --- a/Assets/Resources/Settings.asset +++ b/Assets/Resources/Settings.asset @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:9ad71cb30db7301f1e81be7fec21edb6e6da54b1553a13e44cac7a1effc99c36 -size 12361 +oid sha256:d9d381e3b25ea04d92768f0633cb89668108229dcc17336b560d0cbbfbaed04f +size 12397 diff --git a/Assets/Scripts/Gameplay/ActionGameManager.cs b/Assets/Scripts/Gameplay/ActionGameManager.cs index efab44bd9..c4537a84b 100644 --- a/Assets/Scripts/Gameplay/ActionGameManager.cs +++ b/Assets/Scripts/Gameplay/ActionGameManager.cs @@ -191,9 +191,6 @@ public class ActionGameManager : MonoBehaviour //public PlayerInput Input; - // private CinemachineFramingTransposer _transposer; - // private CinemachineComposer _composer; - private bool _paused; private float _time; private int _zoomLevelIndex; diff --git a/Assets/Scripts/Gameplay/GameSettings.cs b/Assets/Scripts/Gameplay/GameSettings.cs index ec9f895a5..77855a148 100644 --- a/Assets/Scripts/Gameplay/GameSettings.cs +++ b/Assets/Scripts/Gameplay/GameSettings.cs @@ -14,6 +14,9 @@ public class GameSettings : ScriptableObject public float HeatstrokePhasingFloor = 0; public float HeatstrokePhasingFrequency = 5; public float WormholeDistanceRatio; + // The follow camera's distance from the hull's centre of mass, as a multiple of the hull's reach + // (Contacts.Radius); 1.5 keeps the Longinus at about 30 m. + public float FollowCameraDistancePerReach = 1.5f; public float DefaultViewDistance; public float[] MinimapZoomLevels; public int DefaultMinimapZoom; From e700ead68403b3a1ded34b4c14a9bbdb1fa8eb11 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 13:13:38 +0100 Subject: [PATCH 169/190] Follow camera: FrameFollow is the one writer of Follow, LookAt and distance; distance = FollowCameraDistancePerReach x Contacts.Radius Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/Gameplay/ActionGameManager.cs | 23 ++++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/Assets/Scripts/Gameplay/ActionGameManager.cs b/Assets/Scripts/Gameplay/ActionGameManager.cs index c4537a84b..6cfff750e 100644 --- a/Assets/Scripts/Gameplay/ActionGameManager.cs +++ b/Assets/Scripts/Gameplay/ActionGameManager.cs @@ -556,11 +556,7 @@ public class ActionGameManager : MonoBehaviour { FollowCamera.Follow = x.missile.transform; FollowCamera.LookAt = x.target ? x.target : x.missile.transform; - x.missile.OnKill += () => - { - FollowCamera.LookAt = ZoneRenderer.EntityInstances[CurrentEntity].LookAtPoint; - FollowCamera.Follow = ZoneRenderer.EntityInstances[CurrentEntity].transform; - }; + x.missile.OnKill += () => FrameFollow(CurrentEntity); }); } }); @@ -1089,8 +1085,7 @@ public class ActionGameManager : MonoBehaviour if (EventLog != null) EventLog.LogMessage(HaulFeed.Line(gain, ItemManager), gain.Adrift > 0 ? Color.yellow : Color.white); })); - FollowCamera.LookAt = ZoneRenderer.EntityInstances[CurrentEntity].LookAtPoint; - FollowCamera.Follow = ZoneRenderer.EntityInstances[CurrentEntity].transform; + FrameFollow(CurrentEntity); _articulationGroups = CurrentEntity.Equipment .Where(item => item.Behaviors.Any(x => x.Data is WeaponData && !(x.Data is LauncherData))) .GroupBy(item => ZoneRenderer.EntityInstances[CurrentEntity] @@ -1198,6 +1193,20 @@ public class ActionGameManager : MonoBehaviour _incomingLockIndicator = (incoming, incoming.GetComponent<Rotate>()); } + private CinemachineFramingTransposer _framingTransposer; + + // The one writer of the follow camera's Follow, LookAt and distance for an entity: the distance is + // the hull's reach (from its centre of mass, where Follow sits) times the authored ratio. + private void FrameFollow(Entity entity) + { + var instance = ZoneRenderer.EntityInstances[entity]; + FollowCamera.LookAt = instance.LookAtPoint; + FollowCamera.Follow = instance.transform; + if (_framingTransposer == null) + _framingTransposer = FollowCamera.GetCinemachineComponent<CinemachineFramingTransposer>(); + _framingTransposer.m_CameraDistance = Settings.FollowCameraDistancePerReach * Contacts.Radius(entity); + } + private void UpdatePlayerPanel() { ShipPanel.Display(CurrentEntity, true); From 5bf507aba0d757a6dbdffd0e31c6669500f901f8 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 14:18:45 +0100 Subject: [PATCH 170/190] Summons write no stance: ZoneStage.Summon loses its player anchor, Neutral writes no override ZoneStage.Place and AdmitPlaced write no IFF; authored stance is ScenarioStage's run-start verb (Hostile written both ways once, in Admit). A summoned ship now answers a provocation (Entity.Provoke), as the faction rule and grudges decide (ruling summons-follow-faction-logic). Closes the summon anchor refusals, which guarded an anchor that no longer exists. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/Scenario.cs | 2 + Assets/Scripts/ServerShared/ScenarioStage.cs | 66 +++++++------ .../AmmunitionStockingTests.cs | 2 +- tests/Aetheria.Shared.Tests/ScenarioTests.cs | 98 +++++++++---------- 4 files changed, 86 insertions(+), 82 deletions(-) diff --git a/Assets/Scripts/ServerShared/Scenario.cs b/Assets/Scripts/ServerShared/Scenario.cs index d1d79b87b..1db6d7687 100644 --- a/Assets/Scripts/ServerShared/Scenario.cs +++ b/Assets/Scripts/ServerShared/Scenario.cs @@ -33,6 +33,8 @@ public abstract class Scenario public abstract void Stage(ScenarioStage stage); } +// A run-start placement's stance toward the player. Hostile is written as an override both ways; Neutral writes nothing, +// so the faction rule and grudges decide. public enum ScenarioStance { Neutral, diff --git a/Assets/Scripts/ServerShared/ScenarioStage.cs b/Assets/Scripts/ServerShared/ScenarioStage.cs index 56bb50ea8..a39a94578 100644 --- a/Assets/Scripts/ServerShared/ScenarioStage.cs +++ b/Assets/Scripts/ServerShared/ScenarioStage.cs @@ -12,8 +12,9 @@ using float3 = CultMath.float3; // Every verb names what it could not do instead of throwing, so one bad name in a script lists every bad name. // Designs, hulls and products are named as the catalog names them. // ZoneStage is the placement vocabulary and the admission of what it placed; Zone.Admit stays the only admission. -// RunStart builds a ScenarioStage (a ZoneStage that also stages the player); ZoneStage.Summon builds a ZoneStage for a -// running zone. A ZoneStage has no Player verb, so a summon placing a player is unrepresentable. +// RunStart builds a ScenarioStage (a ZoneStage that also stages the player and authors stance); ZoneStage.Summon builds a +// ZoneStage for a running zone. A ZoneStage has no Player verb and no stance, so a summon placing a player or writing who +// fights whom is unrepresentable: a summon's stance is the faction rule's and its grudges'. public class ZoneStage { private readonly ItemManager _items; @@ -52,7 +53,6 @@ public class ZoneStage internal sealed class Placement { public Entity Entity; - public ScenarioStance Stance; public bool Piloted; public AgentTask Task; // What the pilot already knows at the start: an entity its sensors hold a track of (Approach). Seeded through the @@ -122,18 +122,17 @@ public class ZoneStage return new ScenarioFit(preset); } - // Anything else in the arena. A stance holds both ways between it and the player. A piloted ship gets the zone's - // pilot; an unpiloted entity has none and goes nowhere on its own unless it is placed moving: velocity is the planar - // velocity it starts with, and the sim carries it from there. A turret hull stays where it is put. - public Entity Place(ScenarioFit fit, float2 at, float2 facing = default, ScenarioStance stance = ScenarioStance.Neutral, bool piloted = false, - float2 velocity = default) + // Anything else in the arena. A piloted ship gets the zone's pilot; an unpiloted entity has none and goes nowhere on its + // own unless it is placed moving: velocity is the planar velocity it starts with, and the sim carries it from there. A + // turret hull stays where it is put. It writes no stance: who fights whom is the faction rule's (stance is ScenarioStage's). + public Entity Place(ScenarioFit fit, float2 at, float2 facing = default, bool piloted = false, float2 velocity = default) { var where = $"entity {_placements++}"; var entity = Build(fit, where, at, facing); if (entity == null) return null; entity.Velocity = velocity; if (piloted && !(entity is Ship)) _failures.Add($"{where}: {entity.Name} is not a ship hull, so it cannot be piloted"); - _placed.Add(new Placement { Entity = entity, Stance = stance, Piloted = piloted }); + _placed.Add(new Placement { Entity = entity, Piloted = piloted }); return entity; } @@ -181,17 +180,13 @@ public class ZoneStage } } - // Admits what was placed: each entity's stance set both ways with the player, then Zone.Admit with a pilot for each - // piloted one. A start state includes what a pilot knows (ruling stage-states-pilot-knowledge): its anchor is tracked + // Admits what was placed: Zone.Admit with a pilot for each piloted one. It writes no stance. A start state includes what a pilot knows (ruling stage-states-pilot-knowledge): its anchor is tracked // from the first step, by the sensors' own path (info gathered past the detection threshold), so they can lose it // like any track. The one owner of admitting placements. - private protected void AdmitPlaced(Ship player) + private protected void AdmitPlaced() { foreach (var placed in _placed) { - var hostile = placed.Stance == ScenarioStance.Hostile; - placed.Entity.SetIff(player, hostile); - player.SetIff(placed.Entity, hostile); Arena.Admit(placed.Entity, placed.Piloted, placed.Task); } foreach (var placed in _placed) @@ -200,22 +195,12 @@ public class ZoneStage } // Places ships into a running zone through the admission a run start uses: the script places with the stage's verbs, - // and the entities join with their stance toward the player, a pilot when piloted and the knowledge the script stated. + // and the entities join with a pilot when piloted and the knowledge the script stated. A summon writes no stance: the + // faction rule decides who fights whom, and a grudge (Entity.Provoke) turns the summoned faction on whoever attacks it. // Returns the placed entities in order, or null with every failure listed and the zone and the item stream and lot ledger unchanged. - // It draws from the live item stream and does not reseed (a reseed would give every summon the same fits). The anchor - // is the player's ship: the stance is written against it. - public static IReadOnlyList<Entity> Summon(ItemManager items, Zone zone, Ship player, Action<ZoneStage> script, List<string> failures) + // It draws from the live item stream and does not reseed (a reseed would give every summon the same fits). + public static IReadOnlyList<Entity> Summon(ItemManager items, Zone zone, Action<ZoneStage> script, List<string> failures) { - if (player == null || !player.IsPlayerShip) - { - failures.Add("summon: the anchor is not the player's ship"); - return null; - } - if (!zone.Entities.Contains(player)) - { - failures.Add("summon: the player is not in this zone"); - return null; - } var mark = items.Mark(); var stage = new ZoneStage(items, zone); script(stage); @@ -226,7 +211,7 @@ public class ZoneStage return null; } stage.StockUnauthoredAmmunition(); - stage.AdmitPlaced(player); + stage.AdmitPlaced(); return stage._placed.Select(placed => placed.Entity).ToList(); } @@ -271,7 +256,8 @@ public class ZoneStage } // The run-start stage: a ZoneStage that also stages the player, the credits the run starts with and the hull it -// starts in. Only RunStart builds one. +// starts in, and the one place a script authors stance: a Hostile placement is hostile both ways with the player, written +// once at admission. Neutral writes nothing (the faction rule and grudges decide). Only RunStart builds one. public sealed class ScenarioStage : ZoneStage { internal ScenarioStage(ItemManager items, Zone arena, string startingHull) : base(items, arena) @@ -285,6 +271,17 @@ public sealed class ScenarioStage : ZoneStage // What the run starts with: the gameplay settings' starting credits unless the scenario sets another amount. public int Credits { get; set; } + private readonly List<Entity> _hostile = new List<Entity>(); + + // Anything else in the arena, as ZoneStage.Place, with a stance toward the player: Hostile holds both ways from the start. + public new Entity Place(ScenarioFit fit, float2 at, float2 facing = default, ScenarioStance stance = ScenarioStance.Neutral, bool piloted = false, + float2 velocity = default) + { + var entity = base.Place(fit, at, facing, piloted, velocity); + if (entity != null && stance == ScenarioStance.Hostile) _hostile.Add(entity); + return entity; + } + internal bool PlayerPlaced { get; private set; } internal Ship PlayerShip { get; private set; } @@ -312,7 +309,12 @@ public sealed class ScenarioStage : ZoneStage StockUnauthoredAmmunition(); PlayerShip.IsPlayerShip = true; Arena.Admit(PlayerShip, piloted: false); - AdmitPlaced(PlayerShip); + foreach (var entity in _hostile) + { + entity.SetIff(PlayerShip, true); + PlayerShip.SetIff(entity, true); + } + AdmitPlaced(); } } diff --git a/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs b/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs index 02cd19c73..8381d325d 100644 --- a/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs +++ b/tests/Aetheria.Shared.Tests/AmmunitionStockingTests.cs @@ -113,7 +113,7 @@ public sealed partial class RunStartTests var (_, arena, staged, failures) = Launch(new Scripted(false, stage => stage.Player(stage.Bare("Djinni"), float2(0, 0))), Inputs(() => GalaxySeed)); Assert.True(failures.Count == 0, string.Join("; ", failures)); - var summoned = ZoneStage.Summon(_items, arena, staged.Player, stage => + var summoned = ZoneStage.Summon(_items, arena, stage => { stage.Place(stage.Fit(hull, slots), float2(300, 0)); var authored = stage.Place(stage.Fit(hull, slots), float2(-300, 0)); diff --git a/tests/Aetheria.Shared.Tests/ScenarioTests.cs b/tests/Aetheria.Shared.Tests/ScenarioTests.cs index 7144fffbf..41c7b0661 100644 --- a/tests/Aetheria.Shared.Tests/ScenarioTests.cs +++ b/tests/Aetheria.Shared.Tests/ScenarioTests.cs @@ -400,9 +400,9 @@ public sealed partial class RunStartTests } // A summon places into a running zone through the stage's admission (ruling ifl-ships-in-demo-as-tactical-view): after a run - // has started and stepped, a hostile piloted generated ship that approaches the player is a member with one agent, hostile - // both ways, and its pilot knows the player by the sensors' own path. Kills: a summon that skips the stance, the pilot or - // the knowledge seed. + // has started and stepped, a piloted generated ship that approaches the player is a member with one agent, and its pilot + // knows the player by the sensors' own path. It holds no stance either way (ruling summons-follow-faction-logic: the faction + // rule decides). Kills: a summon that skips the pilot or the knowledge seed, or that writes any override. [Fact] public void ASummonJoinsARunningZone() { @@ -411,9 +411,9 @@ public sealed partial class RunStartTests for (var tick = 0; tick < 20; tick++) zone.Update(.1f); var failures = new List<string>(); - var summoned = ZoneStage.Summon(_items, zone, player, stage => + var summoned = ZoneStage.Summon(_items, zone, stage => { - var placed = stage.Place(stage.Generated("Longinus"), float2(400, 0), stance: ScenarioStance.Hostile, piloted: true); + var placed = stage.Place(stage.Generated("Longinus"), float2(400, 0), piloted: true); stage.Approach(placed, player); }, failures); @@ -421,13 +421,50 @@ public sealed partial class RunStartTests var raider = Assert.Single(summoned); SafeAssert.In(zone, raider, "the summoned ship is admitted"); Assert.Equal(1, AgentsOf(zone, raider)); - Assert.True(player.IsHostileTo(raider) && raider.IsHostileTo(player), "hostile both ways"); + Assert.Null(raider.IffOverride(player)); + Assert.Null(player.IffOverride(raider)); Assert.Equal((_items.GameplaySettings.TargetDetectionInfoThreshold + 1f) / 2f, raider.EntityInfoGathered[player]); for (var tick = 0; tick < 20; tick++) zone.Update(.1f); - Assert.True(player.EntityHostility[raider] && raider.EntityHostility[player], "the live hostility agrees"); Assert.Equal(1, AgentsOf(zone, raider)); } + // A summon writes no pin, so the grudge a provocation raises still lands (an override already held is never replaced: + // Entity.Provoke). Kills: any stance written at summon, which blocks the formation from fighting back. + [Fact] + public void ASummonedShipAnswersAProvocation() + { + var zone = Arena(true); + var player = Stage(zone, new Scripted(true, stage => stage.Player(stage.Bare("Djinni"), float2(0, 0)))).Player; + var failures = new List<string>(); + var placed = Assert.Single(ZoneStage.Summon(_items, zone, stage => + stage.Place(stage.Generated("Longinus"), float2(400, 0), piloted: true), failures)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + + placed.Provoke(player); + + Assert.True(placed.IsHostileTo(player), "a provoked summon did not turn on its attacker"); + } + + // A run-start script's Hostile is the only authored stance: written both ways with the player. Neutral is the absence of + // an override, not a pin to false. Kills: Neutral writing false; a Hostile written one way only. + [Fact] + public void ANeutralPlacementWritesNoOverride() + { + var staged = Stage(Arena(true), new Scripted(true, stage => + { + stage.Player(stage.Bare("Djinni"), float2(0, 0)); + stage.Place(stage.Generated("Longinus"), float2(300, 0), stance: ScenarioStance.Hostile, piloted: true); + stage.Place(stage.Bare("Longinus"), float2(-300, 0), stance: ScenarioStance.Neutral); + })); + var player = staged.Player; + var hostile = staged.Entities[0]; + var neutral = staged.Entities[1]; + + Assert.Null(neutral.IffOverride(player)); + Assert.Null(player.IffOverride(neutral)); + Assert.True(hostile.IffOverride(player) == true && player.IffOverride(hostile) == true, "hostile both ways"); + } + // A summon naming a design the catalog lacks admits nothing, and names it. Kills: admitting before the failure check. [Fact] public void ARefusedSummonAdmitsNothing() @@ -438,9 +475,9 @@ public sealed partial class RunStartTests var agents = zone.Agents.ToList(); var failures = new List<string>(); - var summoned = ZoneStage.Summon(_items, zone, player, stage => + var summoned = ZoneStage.Summon(_items, zone, stage => { - stage.Place(stage.Generated("Longinus"), float2(400, 0), stance: ScenarioStance.Hostile, piloted: true); + stage.Place(stage.Generated("Longinus"), float2(400, 0), piloted: true); stage.Place(stage.Bare("No Such Hull"), float2(-400, 0)); }, failures); @@ -449,26 +486,6 @@ public sealed partial class RunStartTests SafeAssert.Unchanged(zone, entities, agents); } - // A summon needs the player to be in the zone it summons into: with the player docked it refuses, names why and admits nothing. - // Kills: dropping the membership check, which would write stance onto a non-member. - [Fact] - public void ASummonNeedsThePlayerInTheZone() - { - var zone = Arena(true); - var player = Stage(zone, new Scripted(true, stage => stage.Player(stage.Bare("Djinni"), float2(0, 0)))).Player; - Assert.True(zone.Remove(player)); - var entities = zone.Entities.ToList(); - var agents = zone.Agents.ToList(); - var failures = new List<string>(); - - var summoned = ZoneStage.Summon(_items, zone, player, stage => - stage.Place(stage.Bare("Longinus"), float2(400, 0), stance: ScenarioStance.Hostile), failures); - - Assert.Null(summoned); - Assert.Equal(new[] { "summon: the player is not in this zone" }, failures); - SafeAssert.Unchanged(zone, entities, agents); - } - // A refused summon leaves the item stream and the lot ledger (which a run save persists) where they were, so a refusal is neither // a draw nor a mint. Kills: a summon that keeps the draws or the lots of the fits it built before refusing. [Fact] @@ -481,7 +498,7 @@ public sealed partial class RunStartTests var lots = _items.Lots.Lots.Keys.ToList(); var failures = new List<string>(); - Assert.Null(ZoneStage.Summon(_items, zone, player, stage => + Assert.Null(ZoneStage.Summon(_items, zone, stage => { stage.Place(stage.Generated("Longinus"), float2(400, 0)); stage.Place(stage.Bare("No Such Hull"), float2(-400, 0)); @@ -493,23 +510,6 @@ public sealed partial class RunStartTests Assert.Equal(lots.OrderBy(id => id), _items.Lots.Lots.Keys.OrderBy(id => id)); } - // The anchor of a summon is the player's ship, not any ship in the zone. Kills: a summon that takes any zone member as the player. - [Fact] - public void ASummonNeedsThePlayersShipAsItsAnchor() - { - var zone = Arena(true); - var player = Stage(zone, new Scripted(true, stage => stage.Player(stage.Bare("Djinni"), float2(0, 0)))).Player; - var other = zone.Entities.OfType<Ship>().First(ship => !ship.IsPlayerShip); - var entities = zone.Entities.ToList(); - var agents = zone.Agents.ToList(); - var failures = new List<string>(); - - Assert.Null(ZoneStage.Summon(_items, zone, other, stage => stage.Place(stage.Bare("Longinus"), float2(400, 0), stance: ScenarioStance.Hostile), failures)); - - Assert.Equal(new[] { "summon: the anchor is not the player's ship" }, failures); - SafeAssert.Unchanged(zone, entities, agents); - } - // A faction's boss is the zone generator's to place (boss-hulls-exclusive): a preset naming the loadout Loadouts.BossOf // returns is refused, through a summon as through a run start. Kills: a Preset that places any catalog loadout. [Fact] @@ -522,8 +522,8 @@ public sealed partial class RunStartTests var agents = zone.Agents.ToList(); var failures = new List<string>(); - Assert.Null(ZoneStage.Summon(_items, zone, player, stage => - stage.Place(stage.Preset(boss.Name), float2(400, 0), stance: ScenarioStance.Hostile, piloted: true), failures)); + Assert.Null(ZoneStage.Summon(_items, zone, stage => + stage.Place(stage.Preset(boss.Name), float2(400, 0), piloted: true), failures)); Assert.Contains(failures, failure => failure.Contains(boss.Name) && failure.Contains("boss")); SafeAssert.Unchanged(zone, entities, agents); From ea328b00e5c12a867495da64dd497450bbd70f25 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 13:55:39 +0100 Subject: [PATCH 171/190] Faction.Relations at key 16 decides stance between NPC factions Hated toward a claimed faction is kill on sight in any zone, owned or not; Hostile to Beloved govern presence by security level through the existing PresencePermitted and trespass path. Entity.Regard is the one reader of the map: unset either side is Neutral, a faction regards itself Beloved, absent is Neutral, and a faction the catalog does not hold is Neutral. Relations are directed and stance reads the claimed faction from telemetry. The catalog authors none, so behaviour equals base until the table lands; the schema id change is re-saved in the next commit. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- Assets/Scripts/ServerShared/Corporations.cs | 7 +- Assets/Scripts/ServerShared/Entity.cs | 23 ++++- .../ContactRevealTests.cs | 29 +++++++ tests/Aetheria.Shared.Tests/FlightTests.cs | 20 ++++- .../IffAndCombatTests.cs | 84 +++++++++++++++++++ tests/Aetheria.Shared.Tests/ScenarioTests.cs | 35 ++++++++ 6 files changed, 189 insertions(+), 9 deletions(-) diff --git a/Assets/Scripts/ServerShared/Corporations.cs b/Assets/Scripts/ServerShared/Corporations.cs index 080f42aac..680436520 100644 --- a/Assets/Scripts/ServerShared/Corporations.cs +++ b/Assets/Scripts/ServerShared/Corporations.cs @@ -49,7 +49,10 @@ public class Faction // Keys 13 to 15 (overworldMusic, combatMusic, bossMusic) held Wwise ids; retired, never reuse them. - // Key 16 is reserved for Relations (operator ruling faction-relations-field). + // How this faction regards each other faction; absent is Neutral. Directed: this map says how this faction regards them, theirs + // says how they regard it. Read only through Entity.Regard (ruling faction-relations-field). + [Inspectable, CultReference(typeof(Faction), many: true), JsonProperty("relations"), Key(16)] + public Dictionary<CultRecordRef<Faction>, FactionRelationship> Relations = new Dictionary<CultRecordRef<Faction>, FactionRelationship>(); // The faction's rules of engagement; null fights as FactionDoctrine.Default. [Inspectable, JsonProperty("doctrine"), Key(17)] @@ -58,7 +61,7 @@ public class Faction // The maker's final assembly: the distribution every lot of theirs draws its own quality from, and the hard ceiling on each // of its roles (quality-lean-assembly-hard-ceiling). Null is not authored: a lot of theirs assembles at AssemblyDistribution's // defaults. assembly-from-maker derives it once at the part mean plus a tolerance margin (quality-min-tolerance-binned-assembly); - // tune it in Studio after that. Key 16 is reserved for Relations and 18 for Livery. Key 20 was assemblyDeviation (retired); never reuse it. + // tune it in Studio after that. Key 18 is reserved for Livery. Key 20 was assemblyDeviation (retired); never reuse it. [Inspectable, JsonProperty("assembly"), Key(19)] public AssemblyDistribution Assembly; diff --git a/Assets/Scripts/ServerShared/Entity.cs b/Assets/Scripts/ServerShared/Entity.cs index 2f3062ff2..9edf45e19 100644 --- a/Assets/Scripts/ServerShared/Entity.cs +++ b/Assets/Scripts/ServerShared/Entity.cs @@ -1261,13 +1261,15 @@ public abstract class Entity // This observer's stance toward `other`: its own override, else its belief. Allies (the observer's own non-null faction) are // known by datalink; any other contact is believed by the telemetry received with its track, and unknown (never hostile) - // without it. In a zone owned by a faction a contact is hostile when its claimed faction is the owner's and the owner does - // not permit its presence, or when this is the owner's ship and believes the contact trespasses. + // without it. A contact whose claimed faction this observer's faction Hates is hostile in any zone, owned or not; Hostile to + // Beloved govern presence instead. In a zone owned by a faction a contact is hostile when its claimed faction is the owner's and + // the owner does not permit its presence, or when this is the owner's ship and believes the contact trespasses. public bool IsHostileTo(Entity other) { if (_iffOverrides.TryGetValue(other, out var overrideHostile)) return overrideHostile; if (Faction != null && other.Faction == Faction) return false; if (!_telemetry.TryGetValue(other, out var claimed)) return false; + if (Regard(Faction, claimed) == FactionRelationship.Hated) return true; var owner = Zone.GalaxyZone.Owner; if (owner == null) return false; return (claimed == owner && !(PresencePermitted?.Value ?? true)) || (Faction == owner && BelievesTrespassing(other)); @@ -1300,14 +1302,27 @@ public abstract class Entity return false; } - // TODO: Inter-faction relationships + // How `faction` regards this entity's faction. public FactionRelationship GetFactionRelationship(Faction faction) { if (faction == null) return FactionRelationship.Neutral; if (this is Ship {IsPlayerShip: true}) return Zone.Galaxy.FactionRelationships[faction]; - return faction == Faction ? FactionRelationship.Beloved : FactionRelationship.Neutral; + return Regard(faction, Faction); + } + + // The one reader of Faction.Relations: how `regarding` regards `regarded`. Unset either side is Neutral, a faction regards + // itself Beloved, and absent from the map is Neutral. A faction the catalog does not hold has no key and is Neutral. + private FactionRelationship Regard(Faction regarding, Faction regarded) + { + if (regarding == null || regarded == null) return FactionRelationship.Neutral; + if (regarding == regarded) return FactionRelationship.Beloved; + if (regarding.Relations == null || regarding.Relations.Count == 0) return FactionRelationship.Neutral; + var key = ItemManager.ItemData.TryGetHandle(regarded)?.Key; + return key != null && regarding.Relations.TryGetValue(new CultRecordRef<Faction>(key.Value), out var relationship) + ? relationship + : FactionRelationship.Neutral; } public static bool IsPresencePermitted(FactionRelationship relationship, SecurityLevel securityLevel) => diff --git a/tests/Aetheria.Shared.Tests/ContactRevealTests.cs b/tests/Aetheria.Shared.Tests/ContactRevealTests.cs index b7d1b88ab..65c69d21b 100644 --- a/tests/Aetheria.Shared.Tests/ContactRevealTests.cs +++ b/tests/Aetheria.Shared.Tests/ContactRevealTests.cs @@ -1991,4 +1991,33 @@ public sealed partial class ContactRevealTests : IDisposable Assert.False(bystander.IsHostileTo(intruder)); Assert.DoesNotContain(intruder, bystander.VisibleEnemies); } + + // The owner's own map decides whom it permits in its Critical area: with a Friendly entry for the visitor's faction she is + // permitted and the patrol holds her no enemy once tracked; with no entry she trespasses and the patrol does (base behaviour). + // Kills: the NPC arm of GetFactionRelationship left constant. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void RelationsDecidePresenceInOwnedSpace(bool friendly) + { + var patrol = Add(float3(0, 0, 0), new[] { "Eye", "Gun" }); + var visitor = Visitor(float3(0, 0, 60), player: false); + var owner = patrol.Faction; + _openCache.Upsert(owner); + var visitorRef = _openCache.Upsert(visitor.Faction); + if (friendly) + { + owner.Relations[visitorRef] = FactionRelationship.Friendly; + _openCache.Upsert(owner); + } + OwnedGalaxy(owner); + Tick(.05f); + Assert.Equal(friendly, visitor.PresencePermitted.Value); + + patrol.EntityInfoGathered[visitor] = 1f; + Tick(.05f); + + Assert.True(patrol.VisibleEntities.Contains(visitor)); + Assert.Equal(!friendly, patrol.IsHostileTo(visitor)); + } } diff --git a/tests/Aetheria.Shared.Tests/FlightTests.cs b/tests/Aetheria.Shared.Tests/FlightTests.cs index 1cb2f9c48..a50b02d13 100644 --- a/tests/Aetheria.Shared.Tests/FlightTests.cs +++ b/tests/Aetheria.Shared.Tests/FlightTests.cs @@ -941,8 +941,8 @@ public sealed class FlightTests : IDisposable Assert.Equal(turns, turn != 0f); } - // Faction.Doctrine rides at wire slot 17; slot 16 is reserved for Relations; BossLoadout rides at 22, which sets the array's length. - // Kills: the key moved. + // Faction.Relations rides at wire slot 16 and Faction.Doctrine at 17; BossLoadout rides at 22, which sets the array's length. + // Kills: either key moved. [Fact] public void TheFactionDoctrineRidesAtWireSlot17() { @@ -952,11 +952,25 @@ public sealed class FlightTests : IDisposable CultDocumentMessagePackSerialization.OptionsFor(typeof(Faction).Assembly))); Assert.Equal(23, slots.Length); // 19 is Assembly, 21 is Places, 22 is BossLoadout - Assert.Null(slots[16]); + Assert.Empty(Assert.IsAssignableFrom<System.Collections.IDictionary>(slots[16])); // 16 is Relations, none authored here var doctrine = Assert.IsType<object[]>(slots[17]); Assert.Equal(6f, Convert.ToSingle(doctrine[1])); } + // A faction's relations survive the wire with the regarded faction and the stance. Kills: a wrong key or a field the wire leaves out. + [Fact] + public void ARelationsMapRoundTrips() + { + var regarded = new CultRecordRef<Faction>(new CultRecordKey("faction:regarded")); + var faction = new Faction { Name = "Grudging", Relations = { [regarded] = FactionRelationship.Hated } }; + var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(Faction).Assembly); + + var back = MessagePack.MessagePackSerializer.Deserialize<Faction>(MessagePack.MessagePackSerializer.Serialize(faction, options), options); + + Assert.Equal(FactionRelationship.Hated, Assert.Single(back.Relations).Value); + Assert.Equal(regarded.Key, Assert.Single(back.Relations).Key.Key); + } + // A cast faction that already has a doctrine keeps it, whatever it holds: one that differs in its engagement and one // that differs only below it. Kills: the keep tested on the engagement alone, or on any one field. [Fact] diff --git a/tests/Aetheria.Shared.Tests/IffAndCombatTests.cs b/tests/Aetheria.Shared.Tests/IffAndCombatTests.cs index b2a01e356..c7c146927 100644 --- a/tests/Aetheria.Shared.Tests/IffAndCombatTests.cs +++ b/tests/Aetheria.Shared.Tests/IffAndCombatTests.cs @@ -444,4 +444,88 @@ public sealed class IffAndCombatTests : IDisposable Assert.Empty(eligible); } + + // Two cached factions (Relations are read through the catalog's keys), with A regarding B as given when it is given, and a + // ship of each in the world's one ownerless zone. + private (Ship a, Ship b) Rivals(ItemManager items, Zone zone, FactionRelationship? aRegardsB) + { + var a = new Faction { Name = "A" }; + var b = new Faction { Name = "B" }; + items.ItemData.Upsert(a); + var bRef = items.ItemData.Upsert(b); + if (aRegardsB.HasValue) + { + a.Relations[bRef] = aRegardsB.Value; + items.ItemData.Upsert(a); + } + return (NewShip(items, zone, a), NewShip(items, zone, b)); + } + + // Hated is kill on sight in any zone, owned or not, once the claim is received with the track; it is directed, so B's stance + // toward A reads B's map. Kills: no Hated branch; reading the regarded side's map; reading other.Faction instead of the claim. + [Fact] + public void HatedIsKillOnSightInAnOwnerlessZone() + { + var (items, zone) = BuildWorld(); + var (a, b) = Rivals(items, zone, FactionRelationship.Hated); + + Assert.False(a.IsHostileTo(b)); // untracked: no claim to hate + + Detect(a, b); + Detect(b, a); + + Assert.True(a.IsHostileTo(b)); + Assert.True(a.EntityHostility[b]); + Assert.False(b.IsHostileTo(a)); + Assert.False(b.EntityHostility[a]); + } + + // The ladder below Hated governs presence in owned space, not fire. Kills: treating Hostile or worse as kill on sight. + [Theory] + [InlineData(FactionRelationship.Hostile)] + [InlineData(FactionRelationship.Neutral)] + [InlineData(FactionRelationship.Beloved)] + public void ARelationShortOfHatedIsNotKillOnSight(FactionRelationship relationship) + { + var (items, zone) = BuildWorld(); + var (a, b) = Rivals(items, zone, relationship); + + Detect(a, b); + Detect(b, a); + + Assert.False(a.IsHostileTo(b)); + Assert.False(b.IsHostileTo(a)); + } + + // An IFF override is the observer's own word and outranks what its faction holds. Kills: the relation branch placed before the override. + [Fact] + public void AnOverrideOutranksARelation() + { + var (items, zone) = BuildWorld(); + var (a, b) = Rivals(items, zone, FactionRelationship.Hated); + Detect(a, b); + Assert.True(a.IsHostileTo(b)); + + a.SetIff(b, false); + + Assert.False(a.IsHostileTo(b)); + Assert.False(a.EntityHostility[b]); + } + + // A faction the catalog does not hold has no key, so it is regarded Neutral and nothing throws. Kills: RefOf in the lookup. + [Fact] + public void AFactionOutsideTheCacheIsRegardedNeutral() + { + var (items, zone) = BuildWorld(); + var a = new Faction { Name = "A" }; + items.ItemData.Upsert(a); + a.Relations[items.ItemData.Upsert(new Faction { Name = "Elsewhere" })] = FactionRelationship.Hated; + items.ItemData.Upsert(a); + var ship = NewShip(items, zone, a); + var stranger = NewShip(items, zone, new Faction { Name = "Stranger" }); + + Detect(ship, stranger); + + Assert.False(ship.IsHostileTo(stranger)); + } } diff --git a/tests/Aetheria.Shared.Tests/ScenarioTests.cs b/tests/Aetheria.Shared.Tests/ScenarioTests.cs index 41c7b0661..f7a8f6a78 100644 --- a/tests/Aetheria.Shared.Tests/ScenarioTests.cs +++ b/tests/Aetheria.Shared.Tests/ScenarioTests.cs @@ -857,4 +857,39 @@ public sealed partial class RunStartTests stale.Add(scenario.Name + " names " + retired); Assert.True(stale.Count == 0, "scenario briefs naming gear the catalog no longer has: " + string.Join("; ", stale)); } + + // The ruling's played case: nothing but the catalog's Relations makes two NPC factions fight. Two piloted ships of the cast's + // Zhe and Luc sit 400 apart in the arena; with Luc's record Hated toward Zhe the Zhestokost ship is hit or gone inside 60 s, + // and without it both keep full armor. Kills: no Hated branch; the relation read from the wrong side; a scenario stance doing + // the work. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void TwoFactionsFightByRelationAlone(bool hated) + { + var zhe = _galaxy.ResolveFaction("Zhe"); + var luc = _galaxy.ResolveFaction("Luc"); + if (hated) + { + luc.Relations ??= new Dictionary<CultRecordRef<Faction>, FactionRelationship>(); + luc.Relations[_cache.RefOf(zhe)] = FactionRelationship.Hated; + } + Entity zheShip = null, lucShip = null; + var (_, arena, _, failures) = Launch(new Scripted(false, stage => + { + stage.Player(stage.Bare("Djinni"), float2(0, 0)); + zheShip = stage.Place(stage.Generated("Longinus", zhe), float2(2000, 0), piloted: true); + lucShip = stage.Place(stage.Generated("Longinus", luc), float2(2000, 400), piloted: true); + })); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + Assert.Same(zhe, zheShip.Faction); + Assert.Same(luc, lucShip.Faction); + + for (var tick = 0; tick < 600; tick++) arena.Update(.1f); + + bool Intact(Entity ship) => arena.Entities.Contains(ship) && + ship.Armor.Cast<float>().Sum() >= ship.MaxArmor.Cast<float>().Sum(); + Assert.Equal(!hated, Intact(zheShip)); + if (!hated) Assert.True(Intact(lucShip)); + } } From 4ce6e14d00d6a5d584fd6bc32ca7b153aeed886d Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 14:01:27 +0100 Subject: [PATCH 172/190] Catalog: re-saved through AetheriaStores after Faction.Relations changed its schema id Every Faction record upserted as loaded and flushed through the game's own store composition; nothing authored. Relations stays null in all 16. The other 396 records are untouched, and every one of the 412 serialises to the same payload as before. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- GameData/Aetheria.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GameData/Aetheria.cc b/GameData/Aetheria.cc index ef463cde8..b58ec27b4 100644 --- a/GameData/Aetheria.cc +++ b/GameData/Aetheria.cc @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:62a6678e741e296449b6ac8cd8698e071a873ea39bc9c0303abe68887310dceb -size 220731 +oid sha256:58e9e0ceadc3b4908491563eb9dfad8ee062024b036a4d3d3cab1e00c168cda9 +size 225267 From ae0f6f34632061f3e6a676eaf0611ef90c061cb4 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 15:13:37 +0100 Subject: [PATCH 173/190] Stance follows the telemetry claim: pin it, and correct the Hated test's comment StanceFollowsTheClaimNotTheLiveFaction changes ships' actual factions after they were tracked; reading other.Faction in the Hated branch instead of the claim now fails it (verified by mutation). HatedIsKillOnSightInAnOwnerlessZone no longer claims that kill. Note on the previous commit's catalog re-save: besides the 16 Faction schema ids, the records' Places arrays gained persisted element ids, which the payload comparison (element ids not serialised in it) did not show. Accepted low resave-payload-claim-loose. The player arm of GetFactionRelationship needs an entity to regard: follow-up regard-player-arm. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- .../IffAndCombatTests.cs | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/tests/Aetheria.Shared.Tests/IffAndCombatTests.cs b/tests/Aetheria.Shared.Tests/IffAndCombatTests.cs index c7c146927..2d44b8ebb 100644 --- a/tests/Aetheria.Shared.Tests/IffAndCombatTests.cs +++ b/tests/Aetheria.Shared.Tests/IffAndCombatTests.cs @@ -462,7 +462,7 @@ public sealed class IffAndCombatTests : IDisposable } // Hated is kill on sight in any zone, owned or not, once the claim is received with the track; it is directed, so B's stance - // toward A reads B's map. Kills: no Hated branch; reading the regarded side's map; reading other.Faction instead of the claim. + // toward A reads B's map. Kills: no Hated branch; reading the regarded side's map. [Fact] public void HatedIsKillOnSightInAnOwnerlessZone() { @@ -528,4 +528,28 @@ public sealed class IffAndCombatTests : IDisposable Assert.False(ship.IsHostileTo(stranger)); } + + // Stance follows the faction the contact claimed when it was tracked, not the faction it flies now. Kills: reading other.Faction + // instead of the telemetry claim. + [Fact] + public void StanceFollowsTheClaimNotTheLiveFaction() + { + var (items, zone) = BuildWorld(); + var (a, b) = Rivals(items, zone, FactionRelationship.Hated); + var other = new Faction { Name = "C" }; + items.ItemData.Upsert(other); + var neutral = NewShip(items, zone, other); + + Detect(a, b); + Detect(a, neutral); + Assert.True(a.IsHostileTo(b)); + Assert.False(a.IsHostileTo(neutral)); + + var hated = b.Faction; + b.Faction = other; // each keeps what it claimed when tracked, until it is claimed again + neutral.Faction = hated; + + Assert.True(a.IsHostileTo(b)); + Assert.False(a.IsHostileTo(neutral)); + } } From 08cda21b1a94b855252b062f90381a6cb455b713 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 13:23:16 +0100 Subject: [PATCH 174/190] aetherlight: cross-partition views (live due, failing dependencies) derived at finish views.rs owns Views { live_due, failing }, folded only by WorldState::finish from the open change lists of commitments, subjects, dependencies, edges, holdings and positions, before the logs close. Derived like a Docs index: not digested, not encoded, ignored by equality, rebuilt by replay on open, never touched by rollback. derive_motion reads it with clean logs (asserted) and no longer walks every dependency row or visits retired subjects' dead pledges. DueAt leaves commitments (the due question has one owner); dependencies gains the DependsOn index the fold uses to re-judge a changed route's or placement's dependents. The old walks live on as cfg(test) derive_motion_by_scan and Views::rebuild; views_are_derived, view_reads_equal_reference_scans, a_corrupted_view_is_detected and a debug refusal of an open-log read pin them. golden.digests is byte-identical. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/clock.rs | 67 ++++--- native/aetherlight/src/docs.rs | 3 +- native/aetherlight/src/golden_tests.rs | 188 +++++++++++++++++++- native/aetherlight/src/lib.rs | 31 ++-- native/aetherlight/src/views.rs | 231 +++++++++++++++++++++++++ 5 files changed, 465 insertions(+), 55 deletions(-) create mode 100644 native/aetherlight/src/views.rs diff --git a/native/aetherlight/src/clock.rs b/native/aetherlight/src/clock.rs index 572eb1bec..69994054a 100644 --- a/native/aetherlight/src/clock.rs +++ b/native/aetherlight/src/clock.rs @@ -7,7 +7,9 @@ //! the span. use super::patch::{Commitment, CommitmentKey, CommitmentKind, DependencyTarget, MAX_ROUTE_COST}; -use super::{PressureMagnitude, PressureSource, SubjectId, WorldState, action, is_retired}; +use super::{PressureMagnitude, PressureSource, SubjectId, WorldState, action, views}; +#[cfg(test)] +use super::is_retired; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; @@ -110,45 +112,47 @@ mod step { /// and one thousand-minute tick over the same span produce different /// magnitudes. The kernel stays an exact function of the command sequence, and /// the tick cadence is one operational constant in `runtime.rs`. +/// +/// What is due, and which dependencies fail, is read from `Views` (the one owner +/// of both questions: a live subject's due commitments and a live subject's +/// unavailable dependencies), so a tick reads the work it does and not the +/// world. A view is true only with clean logs, so both callers (`reduce`, and +/// `apply_effect`'s `TimeAdvanced` arm before its first write) call it clean. pub(super) fn derive_motion(state: &WorldState, to: FictionalMinutes) -> Motion { - // Only subjects with something due: the commitments index answers it - // without walking every promise in the world. - let due: std::collections::BTreeSet<SubjectId> = state - .commitments - .indexed(..=to) - .into_iter() - .map(|(_, subject)| subject) - .collect(); - motion_of(state, to, due) + debug_assert!(views::readable(state), "the views are read with an open log"); + motion_of(state, to, &state.views.due_by(to), state.views.failing().copied()) } -/// What `derive_motion` was before the index: every subject holding a promise. -/// The index read must derive the same motion. +/// What `derive_motion` was before the views: every subject holding a promise +/// and every dependency row, with retirement and availability judged on the +/// spot. The view reads must derive the same motion. #[cfg(test)] pub(super) fn derive_motion_by_scan(state: &WorldState, to: FictionalMinutes) -> Motion { - motion_of(state, to, state.commitments.keys().copied().collect()) + let live = |subject: &SubjectId| !is_retired(state, *subject); + let promisors = state.commitments.keys().copied().filter(live).collect(); + let failing: Vec<_> = state + .dependencies + .iter() + .filter(|(subject, _)| live(subject)) + .flat_map(|(subject, targets)| targets.iter().map(move |target| (*subject, *target))) + .filter(|(subject, target)| dependency_unavailable(state, *subject, *target)) + .collect(); + motion_of(state, to, &promisors, failing.into_iter()) } -/// The motion over `promisors`, which must include every subject with a -/// commitment due by `to`. The dependencies walk below is still one row per -/// subject holding a dependency: follow-up aetherlight-cross-partition-views. +/// The motion over `promisors`, which must hold every live subject with a +/// commitment due by `to`, and the `failing` dependencies of live subjects. fn motion_of( state: &WorldState, to: FictionalMinutes, - promisors: std::collections::BTreeSet<SubjectId>, + promisors: &std::collections::BTreeSet<SubjectId>, + failing: impl Iterator<Item = (SubjectId, DependencyTarget)>, ) -> Motion { let mut fulfilled = Vec::new(); let mut pressed: BTreeMap<(SubjectId, PressureSource), u32> = BTreeMap::new(); - for subject in &promisors { + for subject in promisors { let held = &state.commitments[subject]; - // A retired subject cannot act, and neither fulfilling a routine nor - // pressing an obligation or goal is anything but that subject acting: - // its commitments stay in history, un-discharged and un-deleted, but - // the clock stops moving them the moment they are its. - if is_retired(state, *subject) { - continue; - } for (key, commitment) in held { if commitment.due > to { continue; @@ -179,16 +183,9 @@ fn motion_of( } } - for (subject, targets) in &state.dependencies { - if is_retired(state, *subject) { - continue; - } - for target in targets { - if dependency_unavailable(state, *subject, *target) { - let source = PressureSource::Dependency(*target); - *pressed.entry((*subject, source)).or_default() += step::DEPENDENCY_UNAVAILABLE; - } - } + for (subject, target) in failing { + let source = PressureSource::Dependency(target); + *pressed.entry((subject, source)).or_default() += step::DEPENDENCY_UNAVAILABLE; } Motion { diff --git a/native/aetherlight/src/docs.rs b/native/aetherlight/src/docs.rs index ed37d2767..55b01e404 100644 --- a/native/aetherlight/src/docs.rs +++ b/native/aetherlight/src/docs.rs @@ -27,8 +27,9 @@ pub(crate) fn rows_read() -> u64 { ROWS_READ.with(|rows| rows.get()) } +/// Counts rows a view read, where the view is owned (test builds). #[cfg(test)] -fn count_rows(rows: u64) { +pub(crate) fn count_rows(rows: u64) { ROWS_READ.with(|count| count.set(count.get() + rows)); } diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs index 81276b3af..c72fc841e 100644 --- a/native/aetherlight/src/golden_tests.rs +++ b/native/aetherlight/src/golden_tests.rs @@ -593,6 +593,10 @@ fn a_failed_apply_rolls_back() { "{label}: the accumulator no longer matches the documents" ); assert_indexes_derived(&kernel.state, &format!("{label}, after the failure")); + assert!( + kernel.state.views.same_as(&crate::views::Views::rebuild(&kernel.state)), + "{label}: the failure left the views behind" + ); let envelope = clockwork_envelope(&kernel, body); kernel @@ -600,6 +604,10 @@ fn a_failed_apply_rolls_back() { .unwrap_or_else(|error| panic!("{label}: the next honest command: {error:?}")); assert_eq!(kernel.state.full_state_digest().unwrap(), kernel.state.state_digest); assert_indexes_derived(&kernel.state, &format!("{label}, after the honest command")); + assert!( + kernel.state.views.same_as(&crate::views::Views::rebuild(&kernel.state)), + "{label}: the views left their documents" + ); } } } @@ -1056,7 +1064,95 @@ fn walked_states() -> Vec<(String, crate::WorldState)> { kernel.submit(envelope, &AuthenticatedCaller::verified_play()).unwrap(); states.push((format!("clockwork commit {step}"), kernel.state.clone())); } + let reopened = WorldKernel::open(&kernel.export().unwrap()).unwrap(); + states.push(("clockwork reopened".into(), reopened.state)); states.push(("multivalue world".into(), multivalue_world())); + states.extend(view_scenario()); + states +} + +/// The commands that move what the views join, one at a time, each state kept: +/// dependencies bound on a route, a resource and a subject; the route closed +/// and reopened; the resource's holding emptied and refilled; a depended-on +/// subject loses its position; a dependent released; and a subject that holds +/// past-due routines and a failing dependency retires. +fn view_scenario() -> Vec<(String, crate::WorldState)> { + use crate::patch::{DependencyRef, EvidenceRef, Quantity}; + use crate::tests::TITHE_RECEIPT; + let (mut kernel, people, _) = clockwork_world(20); + let route = *kernel.state.edges.keys().next().expect("a route"); + let grain = |label: &str| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared resource") + .0 + }; + let (grain_0, grain_1) = (grain("Grain 0"), grain("Grain 1")); + let bind = |subject: usize, target: DependencyRef| ComponentOp::Bind { + subject: Ref::Existing(people[subject]), + target, + }; + let steps: Vec<(&str, CommandBody)> = vec![ + ( + "binds", + operations(vec![ + bind(5, DependencyRef::Route(Ref::Existing(route))), + bind(6, DependencyRef::Resource(Ref::Existing(grain_1))), + bind(7, DependencyRef::Subject(Ref::Existing(people[8]))), + bind(7, DependencyRef::Resource(Ref::Existing(grain_0))), + bind(3, DependencyRef::Subject(Ref::Existing(people[4]))), + ]), + ), + ("the route closes", operations(vec![ComponentOp::CloseRoute { route: Ref::Existing(route) }])), + ("the route reopens", operations(vec![ComponentOp::OpenRoute { route: Ref::Existing(route) }])), + ( + "a holding empties", + operations(vec![ComponentOp::Consume { + holder: Ref::Existing(people[7]), + resource: Ref::Existing(grain_0), + qty: Quantity(1), + }]), + ), + ( + "the holding refills", + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Admit { + holder: Ref::Existing(people[7]), + resource: Ref::Existing(grain_0), + qty: Quantity(1), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }], + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], + }, + }, + ), + ("the route closes again", operations(vec![ComponentOp::CloseRoute { route: Ref::Existing(route) }])), + ("a long tick", tick_body(30)), + ("a depended-on subject retires", operations(vec![ComponentOp::Retire { subject: Ref::Existing(people[8]) }])), + ( + "a dependent is released", + operations(vec![ComponentOp::Release { + subject: Ref::Existing(people[3]), + target: DependencyRef::Subject(Ref::Existing(people[4])), + }]), + ), + ("a failing, past-due subject retires", operations(vec![ComponentOp::Retire { subject: Ref::Existing(people[6]) }])), + ("the route reopens after the retirement", operations(vec![ComponentOp::OpenRoute { route: Ref::Existing(route) }])), + ("a last tick", tick_body(30)), + ]; + let mut states = vec![("scenario created".to_owned(), kernel.state.clone())]; + for (name, body) in steps { + let envelope = clockwork_envelope(&kernel, body); + kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .unwrap_or_else(|error| panic!("{name}: {error:?}")); + states.push((format!("scenario: {name}"), kernel.state.clone())); + } states } @@ -1107,13 +1203,6 @@ fn indexes_are_derived() { /// The first place an index read and the scan it replaced disagree, if any. fn reference_scan_disagreement(state: &crate::WorldState) -> Option<String> { use crate::{Audience, Cost, PressureSource}; - let now = state.header.now; - for minutes in [1, 30] { - let to = FictionalMinutes(now.0 + minutes); - if crate::clock::derive_motion(state, to) != crate::clock::derive_motion_by_scan(state, to) { - return Some(format!("derive_motion over {minutes} minutes")); - } - } let subjects: Vec<_> = state.subjects.keys().copied().collect(); let places: Vec<_> = state .entities @@ -1146,6 +1235,15 @@ fn reference_scan_disagreement(state: &crate::WorldState) -> Option<String> { } } } + let targets: std::collections::BTreeSet<_> = + state.dependencies.values().flat_map(|held| held.iter().copied()).collect(); + for target in targets { + let mut by_index = crate::views::Views::dependents_of(state, target); + by_index.sort(); + if by_index != crate::views::Views::dependents_by_scan(state, target) { + return Some(format!("dependents of {target:?}")); + } + } for place in &places { if crate::under_place(state, *place) != crate::under_place_by_scan(state, *place) { return Some(format!("under_place {place:?}")); @@ -1271,10 +1369,84 @@ fn a_corrupted_index_is_detected() { "aetherlight.position.v1", "aetherlight.channel.v1", "aetherlight.selection.v1", - "aetherlight.commitments.v1", + "aetherlight.dependencies.v1", "aetherlight.pressures.v1", ] .into(); assert_eq!(reported, indexed, "exactly the indexed partitions can be damaged"); assert_eq!(misread, indexed, "a damaged index must change what a reader answers"); } + +/// A view is derived from the documents and nothing else: after every commit of +/// the walked worlds, however each was reached, it is what a scan of the +/// committed documents builds. +#[test] +fn views_are_derived() { + for (label, state) in walked_states() { + assert!( + state.views.same_as(&crate::views::Views::rebuild(&state)), + "{label}: the views left their documents" + ); + } +} + +/// The motion the views derive is the motion the scans derive: every live +/// subject's due commitments and failing dependencies, over short and long +/// spans, in every walked state (which holds routes that close and reopen, +/// holdings that empty, subjects that lose a position, and subjects that retire +/// holding past-due routines and failing dependencies). +#[test] +fn view_reads_equal_reference_scans() { + let mut pressed_dependency = false; + for (label, state) in walked_states() { + for minutes in [1, 30, 5_000] { + let to = FictionalMinutes(state.header.now.0 + minutes); + let motion = crate::clock::derive_motion(&state, to); + assert_eq!(motion, crate::clock::derive_motion_by_scan(&state, to), "{label}, {minutes} minutes"); + pressed_dependency |= motion + .pressed + .iter() + .any(|written| matches!(written.source, crate::PressureSource::Dependency(_))); + } + } + assert!(pressed_dependency, "no walked state had a failing dependency to compare"); +} + +/// A damaged view is seen by the oracle and changes what the clock derives: a +/// stray failing row presses a dependency nobody holds, and a missing due +/// point leaves its subjects unmoved. +#[test] +fn a_corrupted_view_is_detected() { + let (mut kernel, _, _) = clockwork_world(20); + kernel + .submit(clockwork_envelope(&kernel, tick_body(1)), &AuthenticatedCaller::verified_play()) + .unwrap(); + let state = kernel.state; + let to = FictionalMinutes(state.header.now.0 + 30); + assert!(state.views.same_as(&crate::views::Views::rebuild(&state))); + for stray in [true, false] { + let mut damaged = state.clone(); + assert!(damaged.views.corrupt_for_test(stray), "stray {stray}"); + assert!( + !damaged.views.same_as(&crate::views::Views::rebuild(&damaged)), + "stray {stray}: the oracle did not see the damage" + ); + assert_ne!( + crate::clock::derive_motion(&damaged, to), + crate::clock::derive_motion_by_scan(&damaged, to), + "stray {stray}: the damage changed no read" + ); + } +} + +/// A view is read only with clean logs: reading one while a partition it joins +/// has an open write is refused, not answered from a stale fold. +#[cfg(debug_assertions)] +#[test] +#[should_panic(expected = "open log")] +fn a_view_read_with_an_open_log_is_refused() { + let (mut kernel, people, _) = clockwork_world(20); + kernel.state.begin(); + kernel.state.positions.remove(&people[3]); + crate::clock::derive_motion(&kernel.state, FictionalMinutes(1)); +} diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index 29a993bfd..9f5ebb20c 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -67,6 +67,7 @@ mod grammar; mod import_key_tests; mod journal; mod patch; +mod views; pub(crate) use action::ActionMismatch; pub(crate) use clock::Motion; @@ -102,6 +103,7 @@ use patch::{EdgeRecord, EntityRecord, LedgerDelta, ResolvedOp, ResolvedPatch}; use digest::{LtHash16, Partition}; use docs::{Changed, DocKey, Docs, Tracked}; +use views::Views; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet}; @@ -472,6 +474,10 @@ macro_rules! world_state { header: Tracked<WorldHeader>, revision: u64, $($(#[$meta])* $field: Docs<$key, $value $(, $proj)?>,)* + /// Derived from the partitions at every `finish`: outside every + /// document, so neither digested nor encoded, and equal whatever + /// it holds (see `views`). + views: Views, // The chain head: outside every document. accumulator: LtHash16, state_digest: String, @@ -497,6 +503,7 @@ macro_rules! world_state { header, revision: 0, $($field: Docs::default(),)* + views: Views::default(), accumulator: LtHash16::default(), state_digest: String::new(), last_commit_digest: None, @@ -533,17 +540,15 @@ impl docs::Projection<Position> for StandsAt { } } -/// `DueAt`: when a subject's commitments fall due, one entry per distinct due. +/// `DependsOn`: who depends on a target. `Views` reads it to re-judge the +/// dependents of a route or a placement that changed. #[derive(Clone, Debug)] -struct DueAt; +struct DependsOn; -impl docs::Projection<BTreeMap<CommitmentKey, Commitment>> for DueAt { - type Point = FictionalMinutes; - fn points(value: &BTreeMap<CommitmentKey, Commitment>, out: &mut Vec<FictionalMinutes>) { - let first = out.len(); - out.extend(value.values().map(|commitment| commitment.due)); - out[first..].sort(); - out.dedup(); +impl docs::Projection<BTreeSet<DependencyTarget>> for DependsOn { + type Point = DependencyTarget; + fn points(value: &BTreeSet<DependencyTarget>, out: &mut Vec<DependencyTarget>) { + out.extend(value.iter().copied()); } } @@ -611,7 +616,7 @@ world_state! { /// unrepresentable and "nothing" has one shape. holdings: Docs<SubjectId, BTreeMap<EntityId, Quantity>> = "aetherlight.holdings.v1"; /// What each subject depends on. Never empty for a present key. - dependencies: Docs<SubjectId, BTreeSet<DependencyTarget>> = "aetherlight.dependencies.v1"; + dependencies: Docs<SubjectId, BTreeSet<DependencyTarget>, DependsOn> = "aetherlight.dependencies.v1"; /// One row per `EntityKind::Fact` entity, and no orphan either way. Facts /// are write-once: declaration and `AssertClaim` are the only writers, and /// standing never changes after admission. @@ -637,7 +642,7 @@ world_state! { /// is admission-only state. redress: Docs<GrievanceKindName, Forum> = "aetherlight.redress.v1"; /// What each subject has promised. Never empty for a present key. - commitments: Docs<SubjectId, BTreeMap<CommitmentKey, Commitment>, DueAt> = "aetherlight.commitments.v1"; + commitments: Docs<SubjectId, BTreeMap<CommitmentKey, Commitment>> = "aetherlight.commitments.v1"; /// Pressure *on* each subject, keyed target-major then source. Never empty /// for a present key; no stored zero magnitude. Lived meaning: read by /// projection and by nothing that decides. @@ -1308,6 +1313,10 @@ impl WorldState { ) -> Vec<Changed<SubjectId, BTreeMap<CommitmentKey, Commitment>>> { self.accumulator = accumulator; self.header.finish(); + // The views fold from the open logs, so they come before the logs close. + let mut views = std::mem::take(&mut self.views); + views.fold(self); + self.views = views; let commitments = self.commitments.finish(); for (_, docs) in self.partitions_mut() { docs.finish_log(); diff --git a/native/aetherlight/src/views.rs b/native/aetherlight/src/views.rs new file mode 100644 index 000000000..e48d87111 --- /dev/null +++ b/native/aetherlight/src/views.rs @@ -0,0 +1,231 @@ +//! Cross-partition views: what a read needs that no one partition's index can +//! answer. +//! +//! A `Docs` projection is a pure function of one document. Two questions the +//! clock asks are joins: "is this dependency failing" reads dependencies with +//! edges, holdings and positions (two of its arms are anti-joins: a resource +//! not held, a subject not placed), and "is this due commitment live" reads +//! commitments with `subjects.retired`. [`Views`] answers them as state derived +//! from those partitions' change lists, so a tick reads the work due and the +//! rows failing instead of every dependency or every dead pledge in the world. +//! +//! `Views` is derived, never state: not digested, not encoded, never exported, +//! and ignored by `WorldState`'s equality (its `PartialEq` is always true, as a +//! `Docs` index is ignored). The one writer is [`Views::fold`], called by +//! `WorldState::finish` from the open logs before they close, so replay (genesis +//! and every replayed commit close through `finish`) rebuilds it on open and a +//! rollback has nothing to undo: the view never saw the transaction. It is read +//! only with clean logs, which `derive_motion` asserts. + +use super::clock::dependency_unavailable; +#[cfg(test)] +use super::docs; +use super::patch::DependencyTarget; +use super::{EntityId, FictionalMinutes, SubjectId, WorldState, is_retired}; +use std::collections::{BTreeMap, BTreeSet}; +use uuid::Uuid; + +#[derive(Clone, Debug, Default)] +pub(crate) struct Views { + /// When live subjects' commitments fall due: a point for each distinct + /// due, holding the subjects that have a commitment due then. A retired + /// subject has no point. + live_due: BTreeMap<FictionalMinutes, BTreeSet<SubjectId>>, + /// The (dependent, target) pairs failing a live dependent: a closed route, + /// a resource the dependent does not hold, a subject nobody places. + failing: BTreeSet<(SubjectId, DependencyTarget)>, +} + +/// A view is derived and carries no content of its own, so two worlds with the +/// same documents are equal whatever their views hold. +impl PartialEq for Views { + fn eq(&self, _: &Self) -> bool { + true + } +} + +impl Eq for Views {} + +/// Whether the six partitions the views read have no open log: the only time a +/// view is true. +pub(crate) fn readable(state: &WorldState) -> bool { + state.commitments.is_clean() + && state.subjects.is_clean() + && state.dependencies.is_clean() + && state.edges.is_clean() + && state.holdings.is_clean() + && state.positions.is_clean() +} + +/// The subjects with a dependency on `target`, from the dependencies +/// partition's `DependsOn` index (true mid-transaction). +fn dependents(state: &WorldState, target: DependencyTarget) -> Vec<SubjectId> { + state + .dependencies + .indexed(target..=target) + .into_iter() + .map(|(_, subject)| subject) + .collect() +} + +impl Views { + /// Subjects with a live commitment due at or before `to`. + pub(crate) fn due_by(&self, to: FictionalMinutes) -> BTreeSet<SubjectId> { + #[cfg(test)] + docs::count_rows(self.live_due.range(..=to).map(|(_, held)| held.len() as u64).sum()); + self.live_due + .range(..=to) + .flat_map(|(_, held)| held.iter().copied()) + .collect() + } + + /// Every failing (dependent, target), in order. + pub(crate) fn failing(&self) -> impl Iterator<Item = &(SubjectId, DependencyTarget)> { + #[cfg(test)] + docs::count_rows(self.failing.len() as u64); + self.failing.iter() + } + + /// Brings the views up to the open logs of the six partitions. Called by + /// `WorldState::finish` before the logs close; nothing else writes a view. + pub(crate) fn fold(&mut self, state: &WorldState) { + // Dues. A subject whose commitments or retirement changed loses the + // points its commitments held before and regains them if it is live. + let mut before: BTreeMap<SubjectId, Option<_>> = BTreeMap::new(); + for (subject, old, _) in state.commitments.changes() { + before.insert(*subject, old); + } + for (subject, _, _) in state.subjects.changes() { + before.entry(*subject).or_insert_with(|| state.commitments.get(subject)); + } + for (subject, old) in &before { + for commitment in old.into_iter().flat_map(|held| held.values()) { + if let Some(due) = self.live_due.get_mut(&commitment.due) { + due.remove(subject); + if due.is_empty() { + self.live_due.remove(&commitment.due); + } + } + } + if is_retired(state, *subject) { + continue; + } + for commitment in state.commitments.get(subject).into_iter().flat_map(|held| held.values()) { + self.live_due.entry(commitment.due).or_default().insert(*subject); + } + } + + // Failing dependencies. A subject whose dependencies, holdings or + // retirement changed has every row re-judged; a route or a placement + // that changed re-judges its dependents. + let rejudged: BTreeSet<SubjectId> = state + .dependencies + .changes() + .map(|(subject, _, _)| *subject) + .chain(state.holdings.changes().map(|(subject, _, _)| *subject)) + .chain(state.subjects.changes().map(|(subject, _, _)| *subject)) + .collect(); + for subject in &rejudged { + let rows: Vec<_> = self + .failing + .range( + (*subject, DependencyTarget::Resource(EntityId(Uuid::nil()))) + ..=(*subject, DependencyTarget::Subject(SubjectId(Uuid::max()))), + ) + .copied() + .collect(); + for row in rows { + self.failing.remove(&row); + } + if is_retired(state, *subject) { + continue; + } + for target in state.dependencies.get(subject).into_iter().flatten() { + if dependency_unavailable(state, *subject, *target) { + self.failing.insert((*subject, *target)); + } + } + } + let moved: BTreeSet<DependencyTarget> = state + .edges + .changes() + .map(|(edge, _, _)| DependencyTarget::Route(*edge)) + .chain(state.positions.changes().map(|(subject, _, _)| DependencyTarget::Subject(*subject))) + .collect(); + for target in moved { + for dependent in dependents(state, target) { + if rejudged.contains(&dependent) { + continue; + } + let row = (dependent, target); + if !is_retired(state, dependent) && dependency_unavailable(state, dependent, target) { + self.failing.insert(row); + } else { + self.failing.remove(&row); + } + } + } + } +} + +/// The views as a scan of the committed documents derives them, and the +/// oracle's other tools (test builds). +#[cfg(test)] +impl Views { + pub(crate) fn rebuild(state: &WorldState) -> Self { + let mut views = Self::default(); + for (subject, held) in state.commitments.iter() { + if is_retired(state, *subject) { + continue; + } + for commitment in held.values() { + views.live_due.entry(commitment.due).or_default().insert(*subject); + } + } + for (subject, targets) in state.dependencies.iter() { + if is_retired(state, *subject) { + continue; + } + for target in targets { + if dependency_unavailable(state, *subject, *target) { + views.failing.insert((*subject, *target)); + } + } + } + views + } + + /// Content equality, which `PartialEq` deliberately is not. + pub(crate) fn same_as(&self, other: &Self) -> bool { + self.live_due == other.live_due && self.failing == other.failing + } + + /// Damages the view in one place: a stray failing row, else a missing + /// due point (the latest, which only its own subjects sit at). False when there + /// is nothing to damage that way. + pub(crate) fn corrupt_for_test(&mut self, stray: bool) -> bool { + if stray { + let row = (SubjectId(Uuid::from_u128(1)), DependencyTarget::Subject(SubjectId(Uuid::from_u128(2)))); + return self.failing.insert(row); + } + let Some(due) = self.live_due.keys().next_back().copied() else { + return false; + }; + self.live_due.remove(&due); + true + } + + /// The subjects with a dependency on `target`, by a scan of every row. + pub(crate) fn dependents_by_scan(state: &WorldState, target: DependencyTarget) -> Vec<SubjectId> { + state + .dependencies + .iter() + .filter(|(_, held)| held.contains(&target)) + .map(|(subject, _)| *subject) + .collect() + } + + pub(crate) fn dependents_of(state: &WorldState, target: DependencyTarget) -> Vec<SubjectId> { + dependents(state, target) + } +} From 8112234597f0f46b3d0fdc920b646a560d61aebc Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 13:29:44 +0100 Subject: [PATCH 175/190] aetherlight: the gate world grows dependencies, retirements, forums and checks to world scale A dependency per person (to the previous live person), two failing on the last place's grain, a forum per place, a Holds check on every routine, every tenth person from the 35th retired, and the clock moved one period so every routine is past due. The fixed-count pins on dependencies and redress go; the gate asserts the population at scale, so a walk of dependencies, retired pledges, holdings or forums fails it. PROVENANCE records the cut. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/PROVENANCE.md | 62 ++++++++++++- native/aetherlight/src/golden_tests.rs | 120 +++++++++++++++++++------ 2 files changed, 152 insertions(+), 30 deletions(-) diff --git a/native/aetherlight/PROVENANCE.md b/native/aetherlight/PROVENANCE.md index 63ab68646..be2799b84 100644 --- a/native/aetherlight/PROVENANCE.md +++ b/native/aetherlight/PROVENANCE.md @@ -462,9 +462,63 @@ session, the populated worlds and forty clockwork commits. `indexes_are_derived` rebuilds every index from its map after each commit, after reopen and after each failed apply; `a_corrupted_index_is_detected` damages each index both ways. -Reads that still scan, each with its owner: `derive_motion`'s dependencies loop and -`snapshot` (the host's whole-world projection, never on the commit path); the -resolver's reads of the whole world in `AdmitPatch` -(`aetherlight-resolver-reads-world`); `aetherlight-cross-partition-views`. The +Reads that still scan, each with its owner: `snapshot` (the host's whole-world +projection, never on the commit path); the resolver's reads of the whole world in +`AdmitPatch` (`aetherlight-resolver-reads-world`). The "Timing" paragraph of AL3b above is superseded: the gate it deferred is `read_work_is_equal_at_100_and_1600`. + +## Cut AL3d-2: cross-partition views + +Authority: cut `aetherlight-cross-partition-views` r1 of campaign +`aetheria-release`; rulings `cultnet-scale-is-not-negotiable`, +`aetherlight-narrative-state-owner`, `terminus-clockwork-world`, +`dialogue-is-world-action`. Base `609b3ba5e`. No digested byte moves: +`fixtures/golden.digests` is identical at every commit of the cut. + +Two questions the clock asks are joins, so no one partition's index answers them +(a `Docs` projection is a pure function of one document). Whether a dependency is +failing joins `dependencies` with `edges`, `holdings` and `positions`, and two of +its arms are anti-joins (a resource not held, a subject not placed); whether a due +commitment is live joins `commitments` with `subjects.retired`. `views.rs` owns +both as `Views { live_due, failing }`: `live_due` is the subjects with a +commitment due at each minute, retired subjects excluded, and `failing` is the +(dependent, target) pairs failing a live dependent. + +`Views` is derived state, a sibling of the `Docs` indexes and not a projection: a +field of `WorldState` outside `partitions()`, so not digested, not encoded and +never exported; its `PartialEq` is always true, so equality is the documents'. +Its one writer is `Views::fold`, called by `WorldState::finish` before the logs +close, from the `changes()` of the six partitions the views join. A subject whose +commitments or retirement changed loses its due points and regains them if it is +live; a subject whose dependencies, holdings or retirement changed has its +failing rows re-judged; a changed route or placement re-judges its dependents, +which the new `DependsOn` index on `dependencies` names. Rollback never touches +it, because the view never saw the transaction; genesis and every replayed +commit close through the same `finish`, so open rebuilds it by replay. + +`derive_motion` reads the views only with clean logs (`debug_assert` on the six +partitions; both callers satisfy it: `reduce`, and `apply_effect`'s +`TimeAdvanced` arm before its first write). `DueAt` is deleted, so the due +question has one owner, and `motion_of` no longer walks every dependency row or +visits retired subjects' past-due routines. Motion is byte-identical. The old +walks are `cfg(test)`: `derive_motion_by_scan` over every promisor and every +dependency, and `Views::rebuild`. A test that forges partitions and then calls +`derive_motion` must close its writes through `finish`; a forged state that never +finishes has a stale view by design, the same contract as a `Docs` index. + +Oracles: `views_are_derived` (the view is the rebuild after every walked commit, +reopen and failed apply, over a scenario world that closes and reopens a route, +empties and refills a holding, removes a depended-on subject's position, releases +a dependency and retires a subject holding past-due routines and a failing +dependency), `view_reads_equal_reference_scans`, `a_corrupted_view_is_detected` +and a debug refusal of a read with an open log. View reads are counted where they +are owned, like `Docs` reads, so the gate sees them. + +The gate world grows with them: a dependency per person (to the previous live +person, so each stays satisfied), two failing (persons 0 and 1 on the last +place's grain), a forum per place, every routine checking that its person holds +their place's grain, every tenth person from the 35th retired, and the clock +moved one period so every routine is past due. The fixed-count pins on +`dependencies` and `redress` are gone; `read_work_is_equal_at_100_and_1600` now +asserts the population at scale. diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs index c72fc841e..a6182b5f0 100644 --- a/native/aetherlight/src/golden_tests.rs +++ b/native/aetherlight/src/golden_tests.rs @@ -261,15 +261,26 @@ fn incremental_digest_equals_full_recompute() { /// listeners. Every partition a read index serves is populated, because an /// empty one hides its scan: one route between consecutive places, one /// `Reach::Place` channel per place controlled by its first person, one -/// institution per place with a warden office held by that person, and two -/// Obligations past due from the first minute, so a tick presses two sources -/// at every size. +/// institution per place with a warden office held by that person and a forum +/// for the place's grievances, and two Obligations past due from the first +/// minute, so a tick presses two sources at every size. +/// +/// Dependencies, retirement and checks grow with the world too, because +/// a partition that stays small hides the walk of it. Every person binds to the +/// previous live person (a satisfied dependency), and persons 0 and 1 also to +/// the last place's grain, which they do not hold: two failing dependencies at +/// every size. Every tenth person from the 35th retires (never a controller or +/// incumbent, who are place * 10), and every routine checks that its person +/// holds their place's grain. The clock then moves one period, so every +/// routine is past due: the live ones roll once, a retired person's stays due +/// for good, and a one-minute tick from there rolls two routines at every size. fn clockwork_world(persons: usize) -> (WorldKernel, Vec<crate::SubjectId>, crate::AffordanceId) { use crate::patch::kernel_speak_grant; use crate::patch::{ AccessKind, AuthoredSource, AuthorityGrantRef, AuthorityTargetRef, ChannelDeclaration, - DependencyRef, EntityDeclaration, EvidenceRef, FactDeclaration, FactStandingRef, Quantity, - ReachRef, RouteDeclaration, SubjectDeclaration, + DependencyRef, EntityDeclaration, EvidenceRef, FactDeclaration, FactStandingRef, + GrievanceKindName, PreconditionRef, Quantity, ReachRef, RouteDeclaration, + SubjectDeclaration, }; use crate::tests::{LEVY_KIND, TITHE_RECEIPT, WARDEN_OFFICE, authority_kind, office}; use crate::Confidence; @@ -338,10 +349,15 @@ fn clockwork_world(persons: usize) -> (WorldKernel, Vec<crate::SubjectId>, crate delegated: BTreeSet::from([authority_kind(LEVY_KIND)]), }); offices.push(ComponentOp::InstallIncumbent { - institution: Ref::Draft(institution), + institution: Ref::Draft(institution.clone()), office: office(WARDEN_OFFICE), incumbent: draft_person(place * 10), }); + offices.push(ComponentOp::OpenForum { + grievance: GrievanceKindName(format!("grievance_{place}")), + forum: Ref::Draft(institution), + standing: AuthorityTargetRef::PlaceSubtree(draft_place(place)), + }); } for person in 0..persons { let place = person / 10; @@ -368,14 +384,26 @@ fn clockwork_world(persons: usize) -> (WorldKernel, Vec<crate::SubjectId>, crate import_key: None, })); } - // Two dependencies, a fixed count: `derive_motion` still walks every - // dependency row (follow-up aetherlight-cross-partition-views), so a - // dependency per person would grow a tick's reads with the world. - for person in 0..2 { - offices.push(ComponentOp::Bind { - subject: draft_person(person), - target: DependencyRef::Subject(draft_person(2)), - }); + let retires = |person: usize| person >= 35 && (person - 35) % 10 == 0; + for person in 0..persons { + if person > 0 { + // The previous person, or the one before when that one retires and + // so leaves the topology: the dependency stays satisfied. + let previous = if retires(person - 1) { person - 2 } else { person - 1 }; + offices.push(ComponentOp::Bind { + subject: draft_person(person), + target: DependencyRef::Subject(draft_person(previous)), + }); + } + if person < 2 { + offices.push(ComponentOp::Bind { + subject: draft_person(person), + target: DependencyRef::Resource(Ref::Draft(DraftHandle::new(format!( + "grain-{}", + places - 1 + )))), + }); + } } let (mut kernel, _) = WorldKernel::create( CreateWorld { @@ -395,6 +423,13 @@ fn clockwork_world(persons: usize) -> (WorldKernel, Vec<crate::SubjectId>, crate .map(|person| subject_by_label(&kernel.state, &format!("Person {person}"))) .collect(); let period = (persons / 2) as u64; + let grain_of_place: std::collections::BTreeMap<String, crate::EntityId> = kernel + .state + .entities + .iter() + .filter(|(_, record)| record.kind == EntityKind::Resource) + .map(|(id, record)| (record.label.clone(), *id)) + .collect(); let mut routines: Vec<ComponentOp> = people .iter() .enumerate() @@ -404,7 +439,10 @@ fn clockwork_world(persons: usize) -> (WorldKernel, Vec<crate::SubjectId>, crate kind: CommitmentKind::Routine, due: FictionalMinutes(1 + index as u64 % period), period: Some(TickMinutes::new(period as u32).unwrap()), - checks: Vec::new(), + checks: vec![PreconditionRef::Holds { + resource: Ref::Existing(grain_of_place[&format!("Grain {}", index / 10)]), + at_least: Quantity(1), + }], statement: Statement::new("Keeps the hour.").unwrap(), }) .collect(); @@ -426,6 +464,21 @@ fn clockwork_world(persons: usize) -> (WorldKernel, Vec<crate::SubjectId>, crate kernel .submit(placing, &AuthenticatedCaller::verified_play()) .expect("the routines are placed"); + let retired: Vec<ComponentOp> = (0..persons) + .filter(|person| retires(*person)) + .map(|person| ComponentOp::Retire { subject: Ref::Existing(people[person]) }) + .collect(); + if !retired.is_empty() { + let envelope = clockwork_envelope(&kernel, operations(retired)); + kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .expect("the retirements land"); + } + // One period on: every routine is past due, the live ones roll once. + let envelope = clockwork_envelope(&kernel, tick_body(period as u32)); + kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .expect("the clock moves one period"); let speak_entry = *kernel .state .affordance_catalog @@ -904,17 +957,32 @@ fn read_work_is_equal_at_100_and_1600() { let state = &kernel.state; assert!(state.holdings.len() >= persons && state.knowledge.len() >= persons); assert!(state.facts.len() >= persons / 10 && state.channels.len() == persons / 10); - assert!(state.positions.len() >= persons && state.commitments.len() >= persons); + let retired: Vec<_> = + people.iter().copied().filter(|person| crate::is_retired(state, *person)).collect(); + assert!(retired.len() >= persons / 20, "{persons} persons: too few retired subjects"); + assert_eq!(state.positions.len() + retired.len(), persons, "a retired subject has no position"); + assert!(state.commitments.len() >= persons); + for person in &retired { + assert!( + state.commitments[person].values().any(|commitment| { + commitment.kind == CommitmentKind::Routine && commitment.due <= state.header.now + }), + "{persons} persons: a retired subject holds no past-due routine" + ); + } + for held in state.commitments.values() { + for commitment in held.values().filter(|c| c.kind == CommitmentKind::Routine) { + assert!( + matches!(commitment.checks.as_slice(), [crate::patch::BoundPrecondition::Holds { .. }]), + "{persons} persons: a routine without its Holds check" + ); + } + } assert!(state.edges.len() + 1 == persons / 10 && state.selection.len() == persons / 10); - // Not at scale, on purpose: `derive_motion` still walks every dependency - // row, so a dependency per person would grow a tick's reads. The owner - // is follow-up aetherlight-cross-partition-views; when it lands this - // count flips to world scale (`>= persons`) so a scan of the partition - // is seen. - assert_eq!(state.dependencies.len(), 2); - // The gate world opens no forum, so `redress` is empty here; the same - // follow-up owns populating it at scale beside dependencies. - assert_eq!(state.redress.len(), 0); + // A dependency per person and a forum per place, so a walk of either + // is seen; the clock reads only the two that fail. + assert!(state.dependencies.len() >= persons); + assert_eq!(state.redress.len(), persons / 10); let mut counts = Vec::new(); for _ in 0..3 { counts.push(submit_counting_rows(&mut kernel, tick_body(1))); @@ -1056,7 +1124,7 @@ fn walked_states() -> Vec<(String, crate::WorldState)> { tick_body(1) } else { CommandBody::Act { - actor: people[step], + actor: people[step % 30], invocation: speak(speak_entry, &format!("Speech {step}.")), } }; From 19d514dc93dcf536751a178cf73db271c7424122 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 15:04:32 +0100 Subject: [PATCH 176/190] aetherlight: releasing a dependency removes the pressure it raised Release deleted the dependency row only, so a pressed dependency's pressure row outlived it and verify_state_shape refused the world at open (export then open failed CorruptJournal). The Release arm now clears the dependency's pressure through set_pressure, the one pressure writer. Pre-existing at 609b3ba5e. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/golden_tests.rs | 48 ++++++++++++++++++++++++++ native/aetherlight/src/lib.rs | 3 ++ 2 files changed, 51 insertions(+) diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs index a6182b5f0..d0f242ce3 100644 --- a/native/aetherlight/src/golden_tests.rs +++ b/native/aetherlight/src/golden_tests.rs @@ -1518,3 +1518,51 @@ fn a_view_read_with_an_open_log_is_refused() { kernel.state.positions.remove(&people[3]); crate::clock::derive_motion(&kernel.state, FictionalMinutes(1)); } + +/// A dependency's pressure ends with the dependency: bind to a resource the +/// subject does not hold, let a tick press it, release it, and the row is gone +/// and the world still reopens from its export. +#[test] +fn releasing_a_dependency_removes_the_pressure_it_raised() { + use crate::patch::DependencyRef; + use crate::{DependencyTarget, PressureSource}; + let (mut kernel, people, _) = clockwork_world(20); + let grain_1 = *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "Grain 1") + .expect("a declared resource") + .0; + let target = DependencyTarget::Resource(grain_1); + let pressed = PressureSource::Dependency(target); + let submit = |kernel: &mut WorldKernel, body| { + let envelope = clockwork_envelope(kernel, body); + kernel.submit(envelope, &AuthenticatedCaller::verified_play()).expect("the command lands"); + }; + submit( + &mut kernel, + operations(vec![ComponentOp::Bind { + subject: Ref::Existing(people[6]), + target: DependencyRef::Resource(Ref::Existing(grain_1)), + }]), + ); + submit(&mut kernel, tick_body(1)); + assert!( + kernel.state.pressures.get(&people[6]).is_some_and(|held| held.contains_key(&pressed)), + "the tick pressed the failing dependency" + ); + submit( + &mut kernel, + operations(vec![ComponentOp::Release { + subject: Ref::Existing(people[6]), + target: DependencyRef::Resource(Ref::Existing(grain_1)), + }]), + ); + assert!( + kernel.state.pressures.get(&people[6]).is_none_or(|held| !held.contains_key(&pressed)), + "the released dependency's pressure row stayed" + ); + let reopened = WorldKernel::open(&kernel.export().unwrap()).expect("the world reopens"); + assert_eq!(reopened.state, kernel.state); +} diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index 9f5ebb20c..a50c58a79 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -2006,6 +2006,9 @@ fn apply_operation( if empty { state.dependencies.remove(subject); } + // The pressure a failing dependency raised is that dependency's + // own: it ends with it, or the world fails its shape check at open. + set_pressure(state, *subject, PressureSource::Dependency(*target), 0); } } ResolvedOp::GrantAuthority { holder, grant } From aa9e91247d5fd7737080612029ee7320777ac5ad Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 15:11:28 +0100 Subject: [PATCH 177/190] aetherlight: fold the views of a bulk commit in rows proportional to the change The moved-targets arm called Docs::indexed once per changed placement or route, and indexed walks every touched key while a log is open, so genesis and every replayed commit paid touched dependencies x changed targets. Docs::indexed_unchanged names the committed index entries of keys the log did not change, with no log walk; a changed dependencies key is already re-judged whole, so the fold loses nothing. folding_a_bulk_commit_reads_rows_in_proportion_to_the_change pins it by rows read. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/docs.rs | 38 ++++++++++++++++++++++++++ native/aetherlight/src/golden_tests.rs | 31 +++++++++++++++++++++ native/aetherlight/src/views.rs | 25 ++++++++--------- 3 files changed, 81 insertions(+), 13 deletions(-) diff --git a/native/aetherlight/src/docs.rs b/native/aetherlight/src/docs.rs index 55b01e404..c9120754b 100644 --- a/native/aetherlight/src/docs.rs +++ b/native/aetherlight/src/docs.rs @@ -289,6 +289,30 @@ impl<K: Ord + Clone, V: Clone + PartialEq, P: Projection<V>> Docs<K, V, P> { found } + /// The committed index's (point, key) entries inside `range` for keys the + /// open log did not change: no walk of the log, so a bulk transaction pays + /// for the entries it returns and not for every key it touched. A key the + /// log changed is the caller's to judge from `changes()`. + pub(crate) fn indexed_unchanged<R: std::ops::RangeBounds<P::Point>>( + &self, + range: R, + ) -> Vec<(P::Point, K)> { + let found: Vec<(P::Point, K)> = self + .index + .range((range.start_bound(), range.end_bound())) + .flat_map(|(point, keys)| keys.iter().map(move |key| (point, key))) + .filter(|(_, key)| { + self.touched + .get(*key) + .is_none_or(|old| self.map.get(*key) == old.as_ref()) + }) + .map(|(point, key)| (point.clone(), key.clone())) + .collect(); + #[cfg(test)] + count_rows(found.len() as u64); + found + } + /// Whether the index is exactly the projection of the map (test builds). #[cfg(test)] pub(crate) fn index_is_derived(&self) -> bool { @@ -597,6 +621,20 @@ mod tests { } } + #[test] + fn indexed_unchanged_names_the_committed_entries_of_keys_the_log_did_not_change() { + let mut docs = spread(&[(1, 10), (2, 21), (3, 33), (4, 11)]); + docs.insert(1, 55); // changed + docs.remove(&2); // removed + docs.insert(3, 33); // touched, written back: unchanged + docs.insert(9, 11); // added: not in the committed index + let before = rows_read(); + let found = docs.indexed_unchanged(1..=1); + assert_eq!(found, vec![(1, 4)], "only the committed entries of unchanged keys"); + assert_eq!(rows_read() - before, 1, "no walk of the log, only the entries returned"); + assert_eq!(docs.indexed_unchanged(..), vec![(1, 4), (3, 3)], "key 3 written back counts as unchanged"); + } + #[test] fn walking_the_open_log_is_counted_even_when_nothing_matches() { let mut docs = spread(&[(1, 10), (2, 21), (3, 33)]); diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs index d0f242ce3..c3a5cba05 100644 --- a/native/aetherlight/src/golden_tests.rs +++ b/native/aetherlight/src/golden_tests.rs @@ -1566,3 +1566,34 @@ fn releasing_a_dependency_removes_the_pressure_it_raised() { let reopened = WorldKernel::open(&kernel.export().unwrap()).expect("the world reopens"); assert_eq!(reopened.state, kernel.state); } + +/// A bulk commit (genesis, a large patch, every replayed commit at open) moves +/// many placements and touches many dependencies at once. Folding the views +/// for it reads rows in proportion to what the commit changed, not to changed +/// targets times touched dependencies: every person moves and binds a route in +/// one transaction, and 1600 persons read under six times the rows of 400. +#[test] +fn folding_a_bulk_commit_reads_rows_in_proportion_to_the_change() { + use crate::patch::Position; + use crate::DependencyTarget; + let mut rows = Vec::new(); + for persons in [400usize, 1600] { + let (kernel, people, _) = clockwork_world(persons); + let mut state = kernel.state; + let route = *state.edges.keys().next().expect("a route"); + let place = state.positions[&people[0]].place; + state.begin(); + for person in people.iter().filter(|person| state.positions.contains_key(person)).copied().collect::<Vec<_>>() { + state.positions.insert(person, Position { place }); + state.dependencies.entry(person).or_default().insert(DependencyTarget::Route(route)); + } + let mut views = std::mem::take(&mut state.views); + let before = crate::docs::rows_read(); + views.fold(&state); + rows.push(crate::docs::rows_read() - before); + state.views = views; + state.rollback(); + } + assert!(rows[1] > rows[0], "{rows:?}: a bigger commit read no more"); + assert!(rows[1] < rows[0] * 6, "the fold read {} rows at 400 persons and {} at 1600", rows[0], rows[1]); +} diff --git a/native/aetherlight/src/views.rs b/native/aetherlight/src/views.rs index e48d87111..ac3de4a3d 100644 --- a/native/aetherlight/src/views.rs +++ b/native/aetherlight/src/views.rs @@ -57,17 +57,6 @@ pub(crate) fn readable(state: &WorldState) -> bool { && state.positions.is_clean() } -/// The subjects with a dependency on `target`, from the dependencies -/// partition's `DependsOn` index (true mid-transaction). -fn dependents(state: &WorldState, target: DependencyTarget) -> Vec<SubjectId> { - state - .dependencies - .indexed(target..=target) - .into_iter() - .map(|(_, subject)| subject) - .collect() -} - impl Views { /// Subjects with a live commitment due at or before `to`. pub(crate) fn due_by(&self, to: FictionalMinutes) -> BTreeSet<SubjectId> { @@ -152,8 +141,11 @@ impl Views { .map(|(edge, _, _)| DependencyTarget::Route(*edge)) .chain(state.positions.changes().map(|(subject, _, _)| DependencyTarget::Subject(*subject))) .collect(); + // A changed dependencies key is already in `rejudged`, so the dependents + // left to judge are the unchanged ones, which the committed index names + // without walking the log once per target. for target in moved { - for dependent in dependents(state, target) { + for (_, dependent) in state.dependencies.indexed_unchanged(target..=target) { if rejudged.contains(&dependent) { continue; } @@ -225,7 +217,14 @@ impl Views { .collect() } + /// The subjects with a dependency on `target`, from the dependencies + /// partition's `DependsOn` index (true mid-transaction). pub(crate) fn dependents_of(state: &WorldState, target: DependencyTarget) -> Vec<SubjectId> { - dependents(state, target) + state + .dependencies + .indexed(target..=target) + .into_iter() + .map(|(_, subject)| subject) + .collect() } } From ba6c2dcd05370c3d51d1e71e1a653a319e99579a Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 15:12:10 +0100 Subject: [PATCH 178/190] aetherlight: a retired dependent's route closing leaves no failing row, pinned The view scenario retires a subject bound to a route and then closes the route; dropping the retired-dependent guard in the fold's moved-targets arm now fails views_are_derived. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/golden_tests.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs index c3a5cba05..dcfadfeb9 100644 --- a/native/aetherlight/src/golden_tests.rs +++ b/native/aetherlight/src/golden_tests.rs @@ -1199,6 +1199,8 @@ fn view_scenario() -> Vec<(String, crate::WorldState)> { }, }, ), + // A retired dependent never fails: closing the route it names must leave no row. + ("a dependent on the route retires", operations(vec![ComponentOp::Retire { subject: Ref::Existing(people[5]) }])), ("the route closes again", operations(vec![ComponentOp::CloseRoute { route: Ref::Existing(route) }])), ("a long tick", tick_body(30)), ("a depended-on subject retires", operations(vec![ComponentOp::Retire { subject: Ref::Existing(people[8]) }])), From e76ba61ee6780e1e41793ccb423f0ea2a636e30c Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 15:12:29 +0100 Subject: [PATCH 179/190] aetherlight: the clean-log contract of a view read holds in release builds derive_motion asserts, not debug_asserts, that the six partitions the views join have no open log, so a stale view cannot be read silently in a shipped build; the refusal test runs in every profile. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/clock.rs | 5 +++-- native/aetherlight/src/golden_tests.rs | 1 - 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/native/aetherlight/src/clock.rs b/native/aetherlight/src/clock.rs index 69994054a..eaee01512 100644 --- a/native/aetherlight/src/clock.rs +++ b/native/aetherlight/src/clock.rs @@ -116,10 +116,11 @@ mod step { /// What is due, and which dependencies fail, is read from `Views` (the one owner /// of both questions: a live subject's due commitments and a live subject's /// unavailable dependencies), so a tick reads the work it does and not the -/// world. A view is true only with clean logs, so both callers (`reduce`, and +/// world. A view is true only with clean logs, so it is read behind a check +/// that holds in every build (six flag tests), and both callers (`reduce`, and /// `apply_effect`'s `TimeAdvanced` arm before its first write) call it clean. pub(super) fn derive_motion(state: &WorldState, to: FictionalMinutes) -> Motion { - debug_assert!(views::readable(state), "the views are read with an open log"); + assert!(views::readable(state), "the views are read with an open log"); motion_of(state, to, &state.views.due_by(to), state.views.failing().copied()) } diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs index dcfadfeb9..a7451b3ca 100644 --- a/native/aetherlight/src/golden_tests.rs +++ b/native/aetherlight/src/golden_tests.rs @@ -1511,7 +1511,6 @@ fn a_corrupted_view_is_detected() { /// A view is read only with clean logs: reading one while a partition it joins /// has an open write is refused, not answered from a stale fold. -#[cfg(debug_assertions)] #[test] #[should_panic(expected = "open log")] fn a_view_read_with_an_open_log_is_refused() { From 8fa2545675474e0971079ef8945896fe6497ee39 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 15:13:24 +0100 Subject: [PATCH 180/190] aetherlight: the timing harness reports medians of 200 interleaved commits, and an open cost harness clockwork_commit_cost takes the median of 200 samples with ticks and speeches interleaved instead of a 30-sample mean per kind, whose speech ratio swung 2 to 4 over runs with flat rows. open_cost (ignored, like it) reports median open times at 200 to 3200 persons, the bulk path the per-commit gate does not reach. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/golden_tests.rs | 93 +++++++++++++++++--------- 1 file changed, 62 insertions(+), 31 deletions(-) diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs index a7451b3ca..242ca2a6e 100644 --- a/native/aetherlight/src/golden_tests.rs +++ b/native/aetherlight/src/golden_tests.rs @@ -745,15 +745,22 @@ fn every_partition_is_digested_undone_and_finished() { /// clockwork world above: time, document digests and rows read (Docs rows plus /// index entries) per commit, and the 1600/100 ratios. Run on its own, in /// release, to read the numbers; nothing is asserted here. Wall time is noise -/// at this scale (the same code ran a tick ratio of 2.8 to 4.9 over five -/// runs), so the gate is `read_work_is_equal_at_100_and_1600`, which counts -/// the rows each commit reads and fails when one grows with the world, and +/// at this scale (a 30-sample mean ratio of speech ran 2.1 to 4.2 over runs +/// whose rows were flat), so each figure is the median of 200 commits, ticks +/// and speeches interleaved so drift and cache state fall on both, and the +/// gate is `read_work_is_equal_at_100_and_1600`, which counts the rows each +/// commit reads and fails when one grows with the world, and /// `digest_work_is_equal_at_100_and_1600` for what a commit digests. /// /// `cargo test --release --lib clockwork_commit_cost -- --ignored --nocapture` #[test] #[ignore] fn clockwork_commit_cost() { + const SAMPLES: usize = 200; + fn median(mut values: Vec<f64>) -> f64 { + values.sort_by(|a, b| a.partial_cmp(b).expect("a time")); + values[values.len() / 2] + } println!( "persons create_ms tick_ms tick_digests tick_rows speech_ms speech_digests speech_rows" ); @@ -765,49 +772,73 @@ fn clockwork_commit_cost() { let create_ms = started.elapsed().as_secs_f64() * 1e3; let play = AuthenticatedCaller::verified_play(); - let (mut ticks, mut tick_digests, mut tick_rows) = (0.0, 0, 0); - for _ in 0..30 { - let tick = clockwork_envelope(&kernel, tick_body(1)); - crate::digest::DOC_DIGESTS.with(|count| count.set(0)); - let rows = crate::docs::rows_read(); - let started = Instant::now(); - kernel.submit(tick, &play).expect("the tick commits"); - ticks += started.elapsed().as_secs_f64() * 1e3; - tick_digests = crate::digest::DOC_DIGESTS.with(|count| count.get()); - tick_rows = crate::docs::rows_read() - rows; - } - let (mut speeches, mut speech_digests, mut speech_rows) = (0.0, 0, 0); - for index in 0..30 { - let act = clockwork_envelope( - &kernel, + let (mut ticks, mut speeches) = (Vec::new(), Vec::new()); + let (mut tick_digests, mut tick_rows, mut speech_digests, mut speech_rows) = (0, 0, 0, 0); + for index in 0..SAMPLES { + let body = if index % 2 == 0 { + CommandBody::AdvanceTime { minutes: TickMinutes::new(1).unwrap() } + } else { CommandBody::Act { - actor: people[index], + actor: people[index % 30], invocation: speak(speak_entry, &format!("Speech {index}.")), - }, - ); + } + }; + let is_tick = index % 2 == 0; + let envelope = clockwork_envelope(&kernel, body); crate::digest::DOC_DIGESTS.with(|count| count.set(0)); let rows = crate::docs::rows_read(); let started = Instant::now(); - kernel.submit(act, &play).expect("the speech commits"); - speeches += started.elapsed().as_secs_f64() * 1e3; - speech_digests = crate::digest::DOC_DIGESTS.with(|count| count.get()); - speech_rows = crate::docs::rows_read() - rows; + kernel.submit(envelope, &play).expect("the commit lands"); + let elapsed = started.elapsed().as_secs_f64() * 1e3; + let digests = crate::digest::DOC_DIGESTS.with(|count| count.get()); + let rows = crate::docs::rows_read() - rows; + if is_tick { + ticks.push(elapsed); + (tick_digests, tick_rows) = (digests, rows); + } else { + speeches.push(elapsed); + (speech_digests, speech_rows) = (digests, rows); + } } + let (tick, speech) = (median(ticks), median(speeches)); println!( - "{persons:>7} {create_ms:>9.1} {:>7.3} {tick_digests:>12} {tick_rows:>9} {:>9.3} {speech_digests:>14} {speech_rows:>11}", - ticks / 30.0, - speeches / 30.0, + "{persons:>7} {create_ms:>9.1} {tick:>7.3} {tick_digests:>12} {tick_rows:>9} {speech:>9.3} {speech_digests:>14} {speech_rows:>11}", ); - ticks_ms.push(ticks / 30.0); - speeches_ms.push(speeches / 30.0); + ticks_ms.push(tick); + speeches_ms.push(speech); } println!( - "ratio 1600/100: tick {:.2} speech {:.2}", + "ratio of medians 1600/100: tick {:.2} speech {:.2}", ticks_ms[2] / ticks_ms[0], speeches_ms[2] / speeches_ms[0] ); } +/// What opening a world costs as it grows: `WorldKernel::open` of the clockwork +/// world's export replays genesis and every commit as bulk commits, which the +/// per-commit gate does not see. Median of five opens per size; nothing asserted +/// (rows are pinned by `folding_a_bulk_commit_reads_rows_in_proportion_to_the_change`). +/// +/// `cargo test --release --lib open_cost -- --ignored --nocapture` +#[test] +#[ignore] +fn open_cost() { + println!("persons open_ms"); + for persons in [200usize, 400, 800, 1600, 3200] { + let (kernel, _, _) = clockwork_world(persons); + let exported = kernel.export().unwrap(); + let mut times: Vec<f64> = (0..5) + .map(|_| { + let started = Instant::now(); + WorldKernel::open(&exported).expect("the world opens"); + started.elapsed().as_secs_f64() * 1e3 + }) + .collect(); + times.sort_by(|a, b| a.partial_cmp(b).expect("a time")); + println!("{persons:>7} {:>7.1}", times[2]); + } +} + /// A document written back to what it was costs no digest: the transaction /// logged it, and folding finds nothing changed. A real change costs two (the /// old, subtracted, and the new, added) and moves the accumulator. From b63284349aff650ad587bafc7d736e2912c823a2 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 15:21:39 +0100 Subject: [PATCH 181/190] aetherlight: a seeded differential test holds the views to their rebuild and the scans Random bind, release, route, holding, relocate, retire, tick, speech and refused commands over the clockwork world, reopened every 50 commits; after each, views == rebuild and derive_motion == scan at +1, +30 and +5000. PROVENANCE records the Soul pass 1 fixes and the failing-dependency cost the gate does not defend. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/PROVENANCE.md | 22 ++++ native/aetherlight/src/golden_tests.rs | 156 +++++++++++++++++++++++++ 2 files changed, 178 insertions(+) diff --git a/native/aetherlight/PROVENANCE.md b/native/aetherlight/PROVENANCE.md index be2799b84..5aba5ac0f 100644 --- a/native/aetherlight/PROVENANCE.md +++ b/native/aetherlight/PROVENANCE.md @@ -522,3 +522,25 @@ their place's grain, every tenth person from the 35th retired, and the clock moved one period so every routine is past due. The fixed-count pins on `dependencies` and `redress` are gone; `read_work_is_equal_at_100_and_1600` now asserts the population at scale. + +Soul pass 1 (fix batch). The fold's moved-targets arm reads the dependencies +`DependsOn` index through `Docs::indexed_unchanged`, which names the committed +entries of keys the open log did not change and does not walk the log; a changed +dependencies key is already re-judged whole, so a bulk commit (genesis, every +replayed commit at open) folds in rows proportional to what it changed +(`folding_a_bulk_commit_reads_rows_in_proportion_to_the_change`). The clean-log +check on a view read is an `assert!`, not a `debug_assert!`: six flag tests, held +in every build. `Release` now clears the pressure its dependency raised through +`set_pressure`; before, a pressed dependency's pressure row outlived it and the +export failed to reopen (pre-existing at `609b3ba5e`). A seeded differential test +(`views_equal_their_rebuild_and_the_scans_over_random_commands`) holds the views +to their rebuild and the motion to the scans over random bind, release, route, +holding, relocate, retire, tick, speech and refused commands, reopening every 50. + +Not defended by the gate, on purpose: a tick's cost is linear in the number of +failing dependencies, because each failing dependency presses a pressure row each +tick. The gate world pins failing at two, so growth in failing is not seen; that +cost is inherent to pressing and is not a read of the world. `open` of a large +world is superlinear in rows from readers outside this cut (the resolver's reads +of the whole world at genesis, owner `aetherlight-resolver-reads-world`); +`open_cost` reports it. diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs index 242ca2a6e..4a801b748 100644 --- a/native/aetherlight/src/golden_tests.rs +++ b/native/aetherlight/src/golden_tests.rs @@ -1629,3 +1629,159 @@ fn folding_a_bulk_commit_reads_rows_in_proportion_to_the_change() { assert!(rows[1] > rows[0], "{rows:?}: a bigger commit read no more"); assert!(rows[1] < rows[0] * 6, "the fold read {} rows at 400 persons and {} at 1600", rows[0], rows[1]); } + +/// Every kind of command that moves what the views join, drawn at random from a +/// seeded stream over the clockwork world (bind and release on a subject, a +/// route and a resource; routes closed and opened; holdings emptied and filled; +/// subjects relocated and retired; ticks and speech; refused commands), with the +/// world reopened from its export every 50 commits. After every commit, kept or +/// refused, the views are what a scan of the documents builds and the motion +/// they derive is the motion the scans derive, over short and long spans; each +/// reopened world holds the live views. Seeds are fixed, so a failure replays. +#[test] +fn views_equal_their_rebuild_and_the_scans_over_random_commands() { + use crate::patch::{DependencyRef, EvidenceRef, Quantity}; + use crate::tests::TITHE_RECEIPT; + use crate::DependencyTarget; + use std::collections::BTreeMap; + + let mut kept: BTreeMap<&'static str, usize> = BTreeMap::new(); + for seed in [1u64, 2, 3] { + let (mut kernel, people, speak_entry) = clockwork_world(40); + let routes: Vec<_> = kernel.state.edges.keys().copied().collect(); + let grains: Vec<_> = (0..4) + .map(|place| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == format!("Grain {place}")) + .expect("a declared resource") + .0 + }) + .collect(); + let mut state = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1; + let mut next = move |bound: usize| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + (state % bound as u64) as usize + }; + for step in 0..150 { + let person = people[next(people.len())]; + let route = routes[next(routes.len())]; + let grain = grains[next(grains.len())]; + let target = match next(3) { + 0 => DependencyRef::Subject(Ref::Existing(people[next(people.len())])), + 1 => DependencyRef::Route(Ref::Existing(route)), + _ => DependencyRef::Resource(Ref::Existing(grain)), + }; + let ops = |op| operations(vec![op]); + let (name, body) = match next(16) { + 0 | 1 => ("bind", ops(ComponentOp::Bind { subject: Ref::Existing(person), target })), + 2 | 3 => { + // Release something that is bound, so releases succeed. + let bound: Vec<_> = kernel + .state + .dependencies + .iter() + .flat_map(|(subject, held)| held.iter().map(|target| (*subject, *target))) + .collect(); + if bound.is_empty() { + ("tick", tick_body(1)) + } else { + let (subject, held) = bound[next(bound.len())]; + let target = match held { + DependencyTarget::Subject(other) => DependencyRef::Subject(Ref::Existing(other)), + DependencyTarget::Route(edge) => DependencyRef::Route(Ref::Existing(edge)), + DependencyTarget::Resource(entity) => DependencyRef::Resource(Ref::Existing(entity)), + }; + ("release", ops(ComponentOp::Release { subject: Ref::Existing(subject), target })) + } + } + 4 => ("close", ops(ComponentOp::CloseRoute { route: Ref::Existing(route) })), + 5 => ("open", ops(ComponentOp::OpenRoute { route: Ref::Existing(route) })), + 6 => ( + "consume", + ops(ComponentOp::Consume { + holder: Ref::Existing(person), + resource: Ref::Existing(grain), + qty: Quantity(1), + }), + ), + 7 => ( + "admit", + CommandBody::AdmitPatch { + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Admit { + holder: Ref::Existing(person), + resource: Ref::Existing(grain), + qty: Quantity(1), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }], + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], + }, + }, + ), + 8 => { + // Along a route that touches where the subject stands. + let here = kernel.state.positions.get(&person).map(|position| position.place); + let via = kernel + .state + .edges + .iter() + .find(|(_, edge)| { + let (from, to) = edge.endpoints(); + here.is_some_and(|place| place == from || place == to) + }) + .map(|(edge, _)| *edge) + .unwrap_or(route); + ("relocate", ops(ComponentOp::Relocate { subject: Ref::Existing(person), via: Ref::Existing(via) })) + } + 9 if next(5) == 0 => ("retire", ops(ComponentOp::Retire { subject: Ref::Existing(person) })), + 13 => ( + "speech", + CommandBody::Act { + actor: person, + invocation: speak(speak_entry, &format!("Speech {step}.")), + }, + ), + 14 => ( + "refused", + ops(ComponentOp::Bind { + subject: Ref::Existing(person), + target: DependencyRef::Subject(Ref::Existing(person)), + }), + ), + _ => ("tick", tick_body(1 + next(25) as u32)), + }; + let envelope = clockwork_envelope(&kernel, body); + if kernel.submit(envelope, &AuthenticatedCaller::verified_play()).is_ok() { + *kept.entry(name).or_default() += 1; + } + let label = format!("seed {seed}, commit {step} ({name})"); + assert!( + kernel.state.views.same_as(&crate::views::Views::rebuild(&kernel.state)), + "{label}: the views left their documents" + ); + for minutes in [1, 30, 5_000] { + let to = FictionalMinutes(kernel.state.header.now.0 + minutes); + assert_eq!( + crate::clock::derive_motion(&kernel.state, to), + crate::clock::derive_motion_by_scan(&kernel.state, to), + "{label}: motion over {minutes} minutes" + ); + } + if step % 50 == 49 { + let reopened = WorldKernel::open(&kernel.export().unwrap()) + .unwrap_or_else(|error| panic!("{label}: the world does not reopen: {error:?}")); + assert_eq!(reopened.state, kernel.state, "{label}: reopened state"); + assert!(reopened.state.views.same_as(&kernel.state.views), "{label}: reopened views"); + } + } + } + for name in ["bind", "release", "close", "open", "consume", "admit", "relocate", "retire", "speech", "tick"] { + assert!(kept.get(name).copied().unwrap_or(0) > 0, "no {name} ever landed: {kept:?}"); + } +} From 396bc6a63ff2a4add62c6ab4bab2769f8d4f4470 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 13:17:05 +0100 Subject: [PATCH 182/190] aetherlight: import keys and affordance kinds are read through indexes Subjects gain a ByImportKey index and the affordance catalog a ByKind index. held_import_keys and the per-patch kind_names set are deleted: import_key_fault takes a held predicate, and admit_resolved, resolve_patch and verify_state_shape's open-time check ask the index (or nothing, at open). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/golden_tests.rs | 34 ++++++++++++++ native/aetherlight/src/journal.rs | 3 +- native/aetherlight/src/lib.rs | 65 +++++++++++++++++++++++--- native/aetherlight/src/patch.rs | 41 ++++++---------- 4 files changed, 108 insertions(+), 35 deletions(-) diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs index 4a801b748..382e728bc 100644 --- a/native/aetherlight/src/golden_tests.rs +++ b/native/aetherlight/src/golden_tests.rs @@ -673,6 +673,16 @@ fn populated_worlds() -> Vec<crate::WorldState> { WorldKernel::create(creation(title), &auth_principal(owner())).unwrap().0 }; let mut worlds = vec![golden_session().0.state]; + // Two subjects holding import keys, so the subjects' `ByImportKey` index has + // points to read and to damage. + let mut keyed = crate::tests::creation("Keyed"); + for declaration in &mut keyed.patch.declarations { + if let Declaration::Subject(subject) = declaration { + let record = subject.label.clone(); + subject.import_key = Some(crate::ImportKey::new("aetherlight.fixture", record)); + } + } + worlds.push(WorldKernel::create(keyed, &auth_principal(owner())).unwrap().0.state); let mut kernel = created("Civic"); civic_world(&mut kernel); worlds.push(kernel.state); @@ -1345,6 +1355,28 @@ fn reference_scan_disagreement(state: &crate::WorldState) -> Option<String> { return Some(format!("dependents of {target:?}")); } } + let strange = crate::ImportKey::new("aetherlight.fixture", "held by nobody"); + for key in state + .subjects + .values() + .filter_map(|subject| subject.import_key.as_ref()) + .chain(std::iter::once(&strange)) + { + if state.import_key_held(key) != crate::import_key_held_by_scan(state, key) { + return Some(format!("import key {key:?} held")); + } + } + let unnamed = crate::patch::AffordanceKindName("no such kind".into()); + for kind in state + .affordance_catalog + .values() + .map(|entry| &entry.kind) + .chain(std::iter::once(&unnamed)) + { + if state.kind_taken(kind) != crate::kind_taken_by_scan(state, kind) { + return Some(format!("affordance kind {kind:?} taken")); + } + } for place in &places { if crate::under_place(state, *place) != crate::under_place_by_scan(state, *place) { return Some(format!("under_place {place:?}")); @@ -1465,6 +1497,8 @@ fn a_corrupted_index_is_detected() { } } let indexed: BTreeSet<&str> = [ + "aetherlight.subject.v1", + "aetherlight.affordance.v1", "aetherlight.entity.v1", "aetherlight.edge.v1", "aetherlight.position.v1", diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index 1d795e086..929ce057c 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -520,10 +520,9 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> )); } let mut declared_keys = BTreeSet::new(); - let no_held = BTreeSet::new(); for subject in state.subjects.values() { if let Some(key) = &subject.import_key - && super::patch::import_key_fault(key, &no_held, &mut declared_keys).is_some() + && super::patch::import_key_fault(key, |_| false, &mut declared_keys).is_some() { return Err(JournalError::Corrupt( "subject import key is malformed or held by two subjects".into(), diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index a50c58a79..9aa732548 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -96,10 +96,12 @@ use patch::{ }; #[cfg(test)] pub(crate) use patch::{ - AffordanceKindName, AuthorityGrantRef, AuthorityKindName, AuthorityTargetRef, ComponentOpKind, + AuthorityGrantRef, AuthorityKindName, AuthorityTargetRef, ComponentOpKind, EffectSlot, OutcomeBand, Precondition, RoleSpec, }; -use patch::{EdgeRecord, EntityRecord, LedgerDelta, ResolvedOp, ResolvedPatch}; +use patch::{ + AffordanceKindName, EdgeRecord, EntityRecord, LedgerDelta, ResolvedOp, ResolvedPatch, +}; use digest::{LtHash16, Partition}; use docs::{Changed, DocKey, Docs, Tracked}; @@ -606,8 +608,32 @@ impl docs::Projection<BTreeMap<OfficeName, Office>> for ByIncumbent { } } +/// `ByImportKey`: the subject that holds an import key. Retired subjects keep +/// theirs, so a key is never reissued. +#[derive(Clone, Debug)] +struct ByImportKey; + +impl docs::Projection<SubjectState> for ByImportKey { + type Point = ImportKey; + fn points(value: &SubjectState, out: &mut Vec<ImportKey>) { + out.extend(value.import_key.clone()); + } +} + +/// `ByKind`: the catalog entry that names an affordance kind, so a kind is +/// taken exactly when a point holds an entry. +#[derive(Clone, Debug)] +struct ByKind; + +impl docs::Projection<Affordance> for ByKind { + type Point = AffordanceKindName; + fn points(value: &Affordance, out: &mut Vec<AffordanceKindName>) { + out.push(value.kind.clone()); + } +} + world_state! { - subjects: Docs<SubjectId, SubjectState> = "aetherlight.subject.v1"; + subjects: Docs<SubjectId, SubjectState, ByImportKey> = "aetherlight.subject.v1"; entities: Docs<EntityId, EntityRecord, ChildOf> = "aetherlight.entity.v1"; edges: Docs<EdgeId, EdgeRecord, ByEndpoint> = "aetherlight.edge.v1"; positions: Docs<SubjectId, Position, StandsAt> = "aetherlight.position.v1"; @@ -649,7 +675,7 @@ world_state! { pressures: Docs<SubjectId, BTreeMap<PressureSource, PressureMagnitude>, BySource> = "aetherlight.pressures.v1"; /// What an affordance *is*. World-authored and written by `admit_resolved` /// alone. - affordance_catalog: Docs<AffordanceId, Affordance> = "aetherlight.affordance.v1"; + affordance_catalog: Docs<AffordanceId, Affordance, ByKind> = "aetherlight.affordance.v1"; /// Who may exercise which entry: a row exists if and only if the subject /// holds at least one verb. A grant carries no payload, so a duplicate /// grant is unrepresentable rather than checked. @@ -1271,7 +1297,7 @@ fn require_play(caller: &CallerId) -> Result<(), KernelError> { /// `WorldState` so the genesis lane, which resolves declarations before any /// `WorldState` exists, can call the same owner instead of hand-copying the /// literal it would otherwise always evaluate to. -fn is_genesis(revision: u64, subjects: &Docs<SubjectId, SubjectState>) -> bool { +fn is_genesis(revision: u64, subjects: &Docs<SubjectId, SubjectState, ByImportKey>) -> bool { revision == 0 && subjects.is_empty() } @@ -1542,11 +1568,11 @@ fn admit_resolved( // The subjects map's only writer holds the same injectivity the resolver // checks, decided by the same function. { - let held = patch::held_import_keys(state.subjects.values()); let mut declared = BTreeSet::new(); for subject in &resolved.subjects { if let Some(key) = &subject.subject.import_key - && patch::import_key_fault(key, &held, &mut declared).is_some() + && patch::import_key_fault(key, |key| state.import_key_held(key), &mut declared) + .is_some() { return Err(KernelError::Invariant( "admitted subject's import key is malformed, held or repeated".into(), @@ -2668,6 +2694,31 @@ fn channel_referents_exist(state: &WorldState, record: &ChannelRecord) -> bool { .is_none_or(|subject_id| state.subjects.contains_key(&subject_id)) } +impl WorldState { + /// Whether a subject, retired or not, holds this import key. One point read + /// of `ByImportKey`. + fn import_key_held(&self, key: &ImportKey) -> bool { + !self.subjects.indexed(key.clone()..=key.clone()).is_empty() + } + + /// Whether a catalog entry already names this affordance kind. + fn kind_taken(&self, kind: &AffordanceKindName) -> bool { + !self.affordance_catalog.indexed(kind.clone()..=kind.clone()).is_empty() + } +} + +/// What `import_key_held` and `kind_taken` were before their indexes: every +/// subject, every catalog entry. The index reads must equal them. +#[cfg(test)] +fn import_key_held_by_scan(state: &WorldState, key: &ImportKey) -> bool { + state.subjects.values().any(|subject| subject.import_key.as_ref() == Some(key)) +} + +#[cfg(test)] +fn kind_taken_by_scan(state: &WorldState, kind: &AffordanceKindName) -> bool { + state.affordance_catalog.values().any(|entry| &entry.kind == kind) +} + /// Whether a subject is retired: the one statement of retirement, read by /// audience derivation, preconditions and resolvers. Only an actual `Retire` /// sets `SubjectState.retired`. diff --git a/native/aetherlight/src/patch.rs b/native/aetherlight/src/patch.rs index 7bf53d956..31dbb7ba1 100644 --- a/native/aetherlight/src/patch.rs +++ b/native/aetherlight/src/patch.rs @@ -958,28 +958,19 @@ pub(super) enum ImportKeyFault { Duplicate, } -/// The keys the subjects hold, retired ones included, so a key is never -/// reissued. Derived on demand; no stored index. -pub(super) fn held_import_keys<'a>( - subjects: impl IntoIterator<Item = &'a super::SubjectState>, -) -> BTreeSet<&'a ImportKey> { - subjects - .into_iter() - .filter_map(|subject| subject.import_key.as_ref()) - .collect() -} - /// The one decision on a key: malformed, held by a subject already in the -/// world, or already claimed in `declared` (which it joins). Every door that -/// admits or loads subjects calls this, so none can decide otherwise. +/// world (`held` asks the subjects' `ByImportKey` index, retired ones +/// included, so a key is never reissued), or already claimed in `declared` +/// (which it joins). Every door that admits or loads subjects calls this, so +/// none can decide otherwise. pub(super) fn import_key_fault<'a>( key: &'a ImportKey, - held: &BTreeSet<&ImportKey>, + held: impl Fn(&ImportKey) -> bool, declared: &mut BTreeSet<&'a ImportKey>, ) -> Option<ImportKeyFault> { if !key.is_canonical() { Some(ImportKeyFault::Malformed) - } else if held.contains(key) { + } else if held(key) { Some(ImportKeyFault::Held) } else if !declared.insert(key) { Some(ImportKeyFault::Duplicate) @@ -2414,7 +2405,7 @@ fn resolve_affordance( site: Site, reference: &Ref<AffordanceId>, index: &BTreeMap<DraftHandle, RefKind>, - catalog: &Docs<AffordanceId, Affordance>, + catalog: &Docs<AffordanceId, Affordance, super::ByKind>, mismatches: &mut Vec<Mismatch>, ) -> Option<Key<AffordanceId>> { match reference { @@ -2726,7 +2717,7 @@ fn resolve_subject( site: Site, reference: &Ref<SubjectId>, index: &BTreeMap<DraftHandle, RefKind>, - subjects: &Docs<SubjectId, SubjectState>, + subjects: &Docs<SubjectId, SubjectState, super::ByImportKey>, mismatches: &mut Vec<Mismatch>, ) -> Option<Key<SubjectId>> { match reference { @@ -3083,16 +3074,13 @@ pub(super) fn resolve_patch( let speak = kernel_speak_entry(); check_against_grammar(state, &speak_handle, &speak.kind, &speak.roles, &mut mismatches); } - let mut kind_names: BTreeSet<AffordanceKindName> = state - .affordance_catalog - .values() - .map(|entry| entry.kind.clone()) - .collect(); + // The kinds this patch declares; a kind the catalog already names is asked + // of its `ByKind` index. + let mut declared_kinds: BTreeSet<AffordanceKindName> = BTreeSet::new(); if genesis { - kind_names.insert(kernel_speak_entry().kind); + declared_kinds.insert(kernel_speak_entry().kind); } - let held_keys = held_import_keys(state.subjects.values()); let mut declared_keys: BTreeSet<&ImportKey> = BTreeSet::new(); for (position, declaration) in patch.declarations.iter().enumerate() { let (handle, label, kind) = match declaration { @@ -3137,7 +3125,7 @@ pub(super) fn resolve_patch( && let Some(key) = &subject.import_key { let handle = subject.handle.clone(); - match import_key_fault(key, &held_keys, &mut declared_keys) { + match import_key_fault(key, |key| state.import_key_held(key), &mut declared_keys) { Some(ImportKeyFault::Malformed) => { mismatches.push(Mismatch::MalformedImportKey { handle }); } @@ -3166,7 +3154,8 @@ pub(super) fn resolve_patch( &affordance.roles, &mut mismatches, ); - if !kind_names.insert(affordance.kind.clone()) { + let taken = state.kind_taken(&affordance.kind); + if !declared_kinds.insert(affordance.kind.clone()) || taken { mismatches.push(Mismatch::DuplicateAffordanceKind { handle: affordance.handle.clone(), }); From b41cae3b87978ec05a2cc439d8457a8b8788ceda Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 13:25:23 +0100 Subject: [PATCH 183/190] aetherlight: apply_operations checks conservation and disjointness from the log Conservation sums only the holders the transaction wrote, with before taken from each holder's value when the operations began; disjointness judges only the holders whose grants, offices or institutions the transaction touched, through holder_overlaps, which overlapping_holder now also calls for the open-time whole-world check. resource_total becomes the test-only resource_total_by_scan. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/golden_tests.rs | 93 +++++++++++++++++++ native/aetherlight/src/lib.rs | 121 ++++++++++++++++++------- 2 files changed, 181 insertions(+), 33 deletions(-) diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs index 382e728bc..98373b59d 100644 --- a/native/aetherlight/src/golden_tests.rs +++ b/native/aetherlight/src/golden_tests.rs @@ -1135,6 +1135,99 @@ fn operation_reads_are_equal_at_100_and_1600() { assert_eq!(worked[0], worked[1], "an operation's read work grew with the world"); } +/// The commit lane's checks read what the transaction wrote, not the world: +/// conservation sums the holders that were written, disjointness judges the +/// holders whose authority was written, and both cost the same rows at 100 and +/// 1600 persons. Each shape also has to be answered right: a holder already +/// written when the operations begin is measured from where it stood then, and +/// an overlap made by installing an incumbent, or by a grant, is refused with +/// every other holder untouched. +#[test] +fn apply_checks_read_the_log() { + use crate::patch::{AuthorityGrant, AuthorityTarget, ResolvedOp}; + use crate::tests::{LEVY_KIND, WARDEN_OFFICE, authority_kind, office}; + use crate::{Quantity, apply_operations}; + + let mut worked = Vec::new(); + for persons in [100usize, 1600] { + let (mut kernel, people, _) = clockwork_world(persons); + let place = |label: &str| { + *kernel.state.entities.iter().find(|(_, record)| record.label == label).expect("declared").0 + }; + let (zero, one, grain) = (place("Place 0"), place("Place 1"), place("Grain 0")); + let institution = subject_by_label(&kernel.state, "Institution 0"); + let level = AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: AuthorityTarget::PlaceSubtree(one), + }; + let revision = kernel.state.revision + 1; + let transfer = ResolvedOp::Transfer { from: people[0], to: people[1], resource: grain, qty: Quantity(1) }; + let mut counts = Vec::new(); + let state = &mut kernel.state; + + // A transfer between two of ten holders: nothing else is read. + state.begin(); + let before = crate::docs::rows_read(); + apply_operations(state, std::slice::from_ref(&transfer), &[], revision) + .expect("a conserving transfer applies"); + counts.push(crate::docs::rows_read() - before); + state.rollback(); + + // A holder written before the operations begin is measured from there. + state.begin(); + crate::set_held(state, people[0], grain, 5); + let before = crate::docs::rows_read(); + apply_operations(state, std::slice::from_ref(&transfer), &[], revision) + .expect("the entry value is the before, not the value the transaction began with"); + counts.push(crate::docs::rows_read() - before); + state.rollback(); + + // Place 1 inside place 0, committed, with person 5's own grant over place 1. + state.begin(); + state.entities.get_mut(&one).unwrap().container = Some(zero); + state.authority.insert(people[5], std::collections::BTreeSet::from([level.clone()])); + let folded = state.folded().unwrap(); + state.finish(folded); + crate::journal::verify_state_shape(state).expect("the world is still disjoint"); + + // A grant that overlaps the warden's lent ground is refused. + state.begin(); + let overlap = ResolvedOp::GrantAuthority { holder: people[0], grant: level.clone() }; + let before = crate::docs::rows_read(); + let refused = apply_operations(state, &[overlap], &[], revision).unwrap_err(); + counts.push(crate::docs::rows_read() - before); + assert!( + matches!(&refused, crate::KernelError::Invariant(m) if m.contains("overlapping")), + "{persons}: {refused:?}" + ); + state.rollback(); + + // Seating a holder of overlapping ground in the office is refused too. + state.begin(); + let install = ResolvedOp::InstallIncumbent { + institution, + office: office(WARDEN_OFFICE), + incumbent: people[5], + }; + let before = crate::docs::rows_read(); + let refused = apply_operations(state, &[install], &[], revision).unwrap_err(); + counts.push(crate::docs::rows_read() - before); + assert!( + matches!(&refused, crate::KernelError::Invariant(m) if m.contains("overlapping")), + "{persons}: {refused:?}" + ); + state.rollback(); + + // Custody is point reads, which are free; the disjointness judgments read + // the office index. A refusal stops at the first overlapping holder, and + // which holder that is depends on id order, so its reads are bounded + // rather than equal: a few rows, where a scan of the world reads thousands. + assert!(counts[2..].iter().all(|rows| (1..=8).contains(rows)), "{persons}: {counts:?}"); + worked.push(counts[..2].to_vec()); + } + assert_eq!(worked[0], worked[1], "a commit check's read work grew with the world"); +} + fn assert_indexes_derived(state: &crate::WorldState, label: &str) { for (schema, docs) in state.partitions() { assert!(docs.index_is_derived(), "{label}: the read index of {schema} left its documents"); diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index 9aa732548..c3837d8ad 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -1685,16 +1685,17 @@ fn admit_resolved( apply_operations(state, &resolved.operations, &resolved.evidence, resolves_to) } -/// The component writer for every lane: snapshot the before-totals for every -/// resource the operations name, apply each operation, accumulate the ledger -/// deltas, and prove conservation once. Declaration admission calls it after its -/// declaration loops; an exercised affordance's lowered effects call it -/// directly. One writer, one conservation statement. +/// The component writer for every lane: apply each operation, accumulate the +/// ledger deltas, and prove conservation once. Declaration admission calls it +/// after its declaration loops; an exercised affordance's lowered effects call +/// it directly. One writer, one conservation statement. /// /// A forged effect reaches this function without ever passing the resolver, so -/// conservation is re-derived over the committed partitions, against the same -/// equation, with `before` read from state rather than from anything the effect -/// asserts. +/// conservation and disjointness are re-derived here, from the transaction's own +/// log: only a holder the operations wrote can change either answer, because +/// every other holder appears on both sides of the equation and no other +/// jurisdiction moved. `before` is what each written holder held when this +/// function was entered, never anything the effect asserts. fn apply_operations( state: &mut WorldState, operations: &[ResolvedOp], @@ -1704,9 +1705,16 @@ fn apply_operations( let mut deltas: BTreeMap<EntityId, LedgerDelta> = BTreeMap::new(); for operation in operations { for resource in operation_resources(operation) { - deltas.entry(resource).or_default().before = resource_total(state, resource); + deltas.entry(resource).or_default(); } } + // Holders already written when the operations begin (the declarations + // above, normally none): what they hold now is their `before`. + let at_entry: BTreeMap<SubjectId, Option<BTreeMap<EntityId, Quantity>>> = state + .holdings + .changes() + .map(|(holder, _, now)| (*holder, now.cloned())) + .collect(); for operation in operations { apply_operation(state, operation, evidence, resolves_to)?; match operation { @@ -1731,15 +1739,25 @@ fn apply_operations( _ => {} } } - for (resource, delta) in &mut deltas { - delta.after = resource_total(state, *resource); + let held_of = |held: Option<&BTreeMap<EntityId, Quantity>>, resource: &EntityId| { + held.and_then(|held| held.get(resource)).map_or(0, |quantity| u128::from(quantity.0)) + }; + for (holder, logged, now) in state.holdings.changes() { + let before = match at_entry.get(holder) { + Some(recorded) => recorded.as_ref(), + None => logged, + }; + for (resource, delta) in &mut deltas { + delta.before += held_of(before, resource); + delta.after += held_of(now, resource); + } } if patch::check_ledger(&deltas).is_some() { return Err(KernelError::Invariant("custody does not conserve".into())); } - // Disjointness, re-derived over the committed partitions for the same - // reason conservation is: a forged effect reaches this function without - // passing the resolver. + // Disjointness, re-derived for the same reason conservation is: a forged + // effect reaches this function without passing the resolver. Only a holder + // the transaction touched can have gained an overlap. if operations.iter().any(|operation| { matches!( operation, @@ -1747,7 +1765,7 @@ fn apply_operations( | ResolvedOp::OpenOffice { .. } | ResolvedOp::InstallIncumbent { .. } ) - }) && overlapping_holder(state).is_some() + }) && touched_holders(state).into_iter().any(|holder| holder_overlaps(state, holder)) { return Err(KernelError::Invariant( "one subject holds two overlapping jurisdictions of one kind".into(), @@ -1756,6 +1774,37 @@ fn apply_operations( Ok(()) } +/// Every subject whose effective authority the open transaction may have +/// changed: whose own grants were written, whose offices were written (old +/// incumbent and new), and the incumbents of an institution whose grants were +/// written or whose retirement flipped, because an office lends what its +/// institution holds. +fn touched_holders(state: &WorldState) -> BTreeSet<SubjectId> { + let mut touched = BTreeSet::new(); + let mut institutions = BTreeSet::new(); + for (holder, _, _) in state.authority.changes() { + touched.insert(*holder); + institutions.insert(*holder); + } + for (institution, old, new) in state.selection.changes() { + for offices in [old, new].into_iter().flatten() { + touched.extend(offices.values().filter_map(|office| office.incumbent)); + } + institutions.insert(*institution); + } + for (subject, old, new) in state.subjects.changes() { + if old.map(|record| record.retired) != new.map(|record| record.retired) { + institutions.insert(*subject); + } + } + for institution in institutions { + if let Some(offices) = state.selection.get(&institution) { + touched.extend(offices.values().filter_map(|office| office.incumbent)); + } + } + touched +} + /// Every resource an operation names, so `admit_resolved` can read its committed /// total before touching it. fn operation_resources(operation: &ResolvedOp) -> Vec<EntityId> { @@ -1773,7 +1822,10 @@ fn operation_resources(operation: &ResolvedOp) -> Vec<EntityId> { } } -fn resource_total(state: &WorldState, resource: EntityId) -> u128 { +/// What `apply_operations` sums before and after: every holder. Conservation +/// reads only the holders a transaction wrote, and this is the reference. +#[cfg(test)] +fn resource_total_by_scan(state: &WorldState, resource: EntityId) -> u128 { state .holdings .values() @@ -2944,14 +2996,17 @@ fn overlapping_holder(state: &WorldState) -> Option<SubjectId> { .filter_map(|office| office.incumbent), ) .collect(); - holders.into_iter().find(|holder| { - let effective: Vec<AuthorityGrant> = - subject_authority(state, *holder).into_iter().collect(); - effective.iter().enumerate().any(|(index, one)| { - effective[index + 1..].iter().any(|other| { - one.kind == other.kind - && patch::targets_overlap(&state.entities, one.over, other.over) - }) + holders.into_iter().find(|holder| holder_overlaps(state, *holder)) +} + +/// Whether one subject's effective authority holds two grants of one kind over +/// overlapping ground. The pairwise check `overlapping_holder` runs over every +/// holder, and `apply_operations` over the holders a transaction touched. +fn holder_overlaps(state: &WorldState, holder: SubjectId) -> bool { + let effective: Vec<AuthorityGrant> = subject_authority(state, holder).into_iter().collect(); + effective.iter().enumerate().any(|(index, one)| { + effective[index + 1..].iter().any(|other| { + one.kind == other.kind && patch::targets_overlap(&state.entities, one.over, other.over) }) }) } @@ -6157,7 +6212,7 @@ mod custody_tests { assert_eq!(holding(&kernel, custody.holder, custody.tithe), 4); assert_eq!(holding(&kernel, custody.counterparty, custody.tithe), 3); - assert_eq!(resource_total(&kernel.state, custody.tithe), 7); + assert_eq!(resource_total_by_scan(&kernel.state, custody.tithe), 7); assert_eq!(kernel.state.entities, entities); assert_eq!(kernel.state.edges, edges); assert_eq!(kernel.state.positions, positions); @@ -6221,8 +6276,8 @@ mod custody_tests { assert_eq!(holding(&kernel, custody.holder, custody.tithe), 2); assert_eq!(holding(&kernel, custody.holder, custody.ingot), 5); - assert_eq!(resource_total(&kernel.state, custody.tithe), 2); - assert_eq!(resource_total(&kernel.state, custody.ingot), 5); + assert_eq!(resource_total_by_scan(&kernel.state, custody.tithe), 2); + assert_eq!(resource_total_by_scan(&kernel.state, custody.ingot), 5); } #[test] @@ -6494,13 +6549,13 @@ mod custody_tests { // The opening balance was created by `Admit` alone: before is zero, // admitted is the balance, and the total equals the sum of the two. assert_eq!( - resource_total(&kernel.state, custody.tithe), + resource_total_by_scan(&kernel.state, custody.tithe), u128::from(OPENING_BALANCE) ); - assert_eq!(resource_total(&kernel.state, custody.ingot), 0); + assert_eq!(resource_total_by_scan(&kernel.state, custody.ingot), 0); - let tithe_before = resource_total(&kernel.state, custody.tithe); - let ingot_before = resource_total(&kernel.state, custody.ingot); + let tithe_before = resource_total_by_scan(&kernel.state, custody.tithe); + let ingot_before = resource_total_by_scan(&kernel.state, custody.ingot); let receipt = submit_play( &mut kernel, @@ -6530,11 +6585,11 @@ mod custody_tests { // Transfer contributes to no term; transform contributes one spent and // one gained; consume contributes one consumed. Nothing was admitted. assert_eq!( - resource_total(&kernel.state, custody.tithe), + resource_total_by_scan(&kernel.state, custody.tithe), tithe_before - 1 - 2 ); assert_eq!( - resource_total(&kernel.state, custody.ingot), + resource_total_by_scan(&kernel.state, custody.ingot), ingot_before + 2 ); assert_eq!(holding(&kernel, custody.holder, custody.tithe), 2); From f18c6d5e185b7ea41bbcc2b1eba355739ee7da82 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 13:37:59 +0100 Subject: [PATCH 184/190] aetherlight: the resolver's candidate graph is an overlay, not a copy of the world resolve_patch no longer seeds fifteen maps by copying every partition. Each candidate map is an Overlay over its committed partition (patch/candidate.rs): reads fall through by point get, the patch's writes sit in a local map. The scale-sensitive reads are named methods of Candidate: occupants_under, offices_of, offices_held_by, kind_taken, import_key_held, custody, and a running overlap set re-judged at every write to authority, offices or retirement, which is graph_overlaps' answer because the committed world is disjoint. The seeding block and the old scans live on only as test references (Materialized), and the new tests hold every named read to them. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/golden_tests.rs | 2 +- native/aetherlight/src/patch.rs | 669 ++--------- native/aetherlight/src/patch/candidate.rs | 1294 +++++++++++++++++++++ 3 files changed, 1416 insertions(+), 549 deletions(-) create mode 100644 native/aetherlight/src/patch/candidate.rs diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs index 98373b59d..2d91d55a5 100644 --- a/native/aetherlight/src/golden_tests.rs +++ b/native/aetherlight/src/golden_tests.rs @@ -667,7 +667,7 @@ fn a_failed_apply_rolls_back() { /// Worlds that between them hold a document in every partition: the golden /// session, the civic, custody and speech benches and the ticked clock bench. -fn populated_worlds() -> Vec<crate::WorldState> { +pub(crate) fn populated_worlds() -> Vec<crate::WorldState> { use crate::tests::{auth_principal, civic_world, creation, custody_world, owner, speech_world}; let created = |title: &str| { WorldKernel::create(creation(title), &auth_principal(owner())).unwrap().0 diff --git a/native/aetherlight/src/patch.rs b/native/aetherlight/src/patch.rs index 31dbb7ba1..b01de3373 100644 --- a/native/aetherlight/src/patch.rs +++ b/native/aetherlight/src/patch.rs @@ -24,6 +24,9 @@ use std::collections::{BTreeMap, BTreeSet, btree_map::Entry}; use unicode_properties::{GeneralCategory, UnicodeGeneralCategory}; use uuid::Uuid; +mod candidate; +use candidate::{Candidate, Overlay}; + #[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] #[serde(rename_all = "snake_case")] pub enum EntityKind { @@ -2064,25 +2067,6 @@ struct OfficeCandidate { delegated: BTreeSet<AuthorityKindName>, } -/// Whether two jurisdictions of one kind cover common ground. Structural on -/// purpose: identity for named subordinates, containment for territory, and -/// never across the two, so the answer cannot decay when a subject walks -/// somewhere. Containment is fixed at declaration, so every way of creating an -/// overlap is a checked operation. -fn candidate_targets_overlap( - left: &AuthorityTargetKey, - right: &AuthorityTargetKey, - containers: &BTreeMap<Key<EntityId>, Key<EntityId>>, -) -> bool { - match (left, right) { - (AuthorityTargetKey::Subject(one), AuthorityTargetKey::Subject(other)) => one == other, - (AuthorityTargetKey::PlaceSubtree(one), AuthorityTargetKey::PlaceSubtree(other)) => { - key_covers_place(one, other, containers) || key_covers_place(other, one, containers) - } - _ => false, - } -} - /// Whether a candidate `Subject` grant target and a candidate `PlaceSubtree` /// grant target of one kind name overlapping ground: a `PlaceSubtree` grant /// covers a `Subject` grant's target when the subject's committed position @@ -2090,7 +2074,7 @@ fn candidate_targets_overlap( /// candidate graph, because `covers` reads committed position and /// containment, not anything a patch declares; a target still in this /// patch's drafts has no committed position and so cannot overlap here. This -/// is the one cross-shape case `candidate_targets_overlap` leaves alone by +/// is the one cross-shape case `Candidate::targets_overlap` leaves alone by /// construction — same-shape overlap is its job, not this one's. fn grant_targets_nest( state: &super::WorldState, @@ -2158,36 +2142,6 @@ fn canonical_grants(grants: &BTreeSet<GrantKey>) -> BTreeSet<AuthorityGrant> { .collect() } -/// Own grants plus what every held office lends, over the candidate graph. The -/// canonical twin is `scope_components` plus `effective_authority`; this one -/// answers the same question before any ID is minted. -fn candidate_effective_authority( - holder: &Key<SubjectId>, - authority: &BTreeMap<Key<SubjectId>, BTreeSet<GrantKey>>, - selection: &BTreeMap<(Key<SubjectId>, OfficeName), OfficeCandidate>, - retired: &BTreeSet<Key<SubjectId>>, -) -> BTreeSet<GrantKey> { - let mut effective = authority.get(holder).cloned().unwrap_or_default(); - for ((institution, _), office) in selection { - if office.incumbent.as_ref() != Some(holder) { - continue; - } - // A retired institution lends nothing, the same predicate - // `delegated_authority` reads canonically: `Retire` does not vacate - // offices, so the resolver and the kernel must not disagree about - // whether a dead institution's grants still reach its office-holders. - if retired.contains(institution) { - continue; - } - for grant in authority.get(institution).into_iter().flatten() { - if office.delegated.contains(&grant.kind) { - effective.insert(grant.clone()); - } - } - } - effective -} - /// A fact in the candidate graph. Only its standing matters to resolution: the /// statement is never read and never compared. #[derive(Clone, Debug, PartialEq, Eq)] @@ -2234,40 +2188,6 @@ enum AudienceKey { Channel(Key<EntityId>), } -/// Whether a subject is inside an audience over the candidate graph: the same -/// question `audience()` answers over committed state, asked before any ID is -/// minted. A controller is inside its own channel's audience for the purpose of -/// speaking on it — the horn belongs to the temple. -fn candidate_in_audience( - subject: &Key<SubjectId>, - audience: &AudienceKey, - speaker: &Key<SubjectId>, - positions: &BTreeMap<Key<SubjectId>, Key<EntityId>>, - channels: &BTreeMap<Key<EntityId>, ChannelCandidate>, - containers: &BTreeMap<Key<EntityId>, Key<EntityId>>, -) -> bool { - match audience { - AudienceKey::Colocated => match (positions.get(speaker), positions.get(subject)) { - (Some(here), Some(there)) => here == there, - _ => false, - }, - AudienceKey::Channel(channel) => { - let Some(record) = channels.get(channel) else { - return false; - }; - if record.controller.as_ref() == Some(subject) { - return true; - } - match &record.reach { - ReachKey::Subjects(members) => members.contains(subject), - ReachKey::Place(root) => positions - .get(subject) - .is_some_and(|place| key_covers_place(root, place, containers)), - } - } - } -} - #[derive(Clone, Debug)] struct RouteCandidate { from: Key<EntityId>, @@ -2824,37 +2744,6 @@ fn resolve_dependency_target( } } -/// Whether any subject in the candidate graph holds two grants of one kind over -/// overlapping ground, from any combination of direct grant and office -/// delegation. -fn graph_overlaps( - authority: &BTreeMap<Key<SubjectId>, BTreeSet<GrantKey>>, - selection: &BTreeMap<(Key<SubjectId>, OfficeName), OfficeCandidate>, - containers: &BTreeMap<Key<EntityId>, Key<EntityId>>, - retired: &BTreeSet<Key<SubjectId>>, -) -> bool { - let holders: BTreeSet<&Key<SubjectId>> = authority - .keys() - .chain( - selection - .values() - .filter_map(|office| office.incumbent.as_ref()), - ) - .collect(); - holders.into_iter().any(|holder| { - let effective: Vec<GrantKey> = - candidate_effective_authority(holder, authority, selection, retired) - .into_iter() - .collect(); - effective.iter().enumerate().any(|(index, one)| { - effective[index + 1..].iter().any(|other| { - one.kind == other.kind - && candidate_targets_overlap(&one.over, &other.over, containers) - }) - }) - }) -} - /// The candidate kind of a subject reference: the declared kind for a handle /// this patch introduces, the committed kind otherwise. fn subject_kind_of( @@ -3002,7 +2891,7 @@ fn resolve_authority_target( /// What a holder holds in the candidate map. Absence is zero, at both levels. fn candidate_held( - holdings: &BTreeMap<(Key<SubjectId>, Key<EntityId>), Quantity>, + holdings: &Overlay<'_, (Key<SubjectId>, Key<EntityId>), Quantity>, holder: &Key<SubjectId>, resource: &Key<EntityId>, ) -> u64 { @@ -3013,7 +2902,7 @@ fn candidate_held( /// Zero removes the slot, so one representation of nothing survives the patch. fn candidate_set( - holdings: &mut BTreeMap<(Key<SubjectId>, Key<EntityId>), Quantity>, + holdings: &mut Overlay<'_, (Key<SubjectId>, Key<EntityId>), Quantity>, holder: &Key<SubjectId>, resource: &Key<EntityId>, value: u64, @@ -3074,11 +2963,9 @@ pub(super) fn resolve_patch( let speak = kernel_speak_entry(); check_against_grammar(state, &speak_handle, &speak.kind, &speak.roles, &mut mismatches); } - // The kinds this patch declares; a kind the catalog already names is asked - // of its `ByKind` index. - let mut declared_kinds: BTreeSet<AffordanceKindName> = BTreeSet::new(); + let mut graph = Candidate::new(state); if genesis { - declared_kinds.insert(kernel_speak_entry().kind); + graph.declare_kind(kernel_speak_entry().kind); } let mut declared_keys: BTreeSet<&ImportKey> = BTreeSet::new(); @@ -3125,7 +3012,7 @@ pub(super) fn resolve_patch( && let Some(key) = &subject.import_key { let handle = subject.handle.clone(); - match import_key_fault(key, |key| state.import_key_held(key), &mut declared_keys) { + match import_key_fault(key, |key| graph.import_key_held(key), &mut declared_keys) { Some(ImportKeyFault::Malformed) => { mismatches.push(Mismatch::MalformedImportKey { handle }); } @@ -3154,8 +3041,7 @@ pub(super) fn resolve_patch( &affordance.roles, &mut mismatches, ); - let taken = state.kind_taken(&affordance.kind); - if !declared_kinds.insert(affordance.kind.clone()) || taken { + if graph.declare_kind(affordance.kind.clone()) { mismatches.push(Mismatch::DuplicateAffordanceKind { handle: affordance.handle.clone(), }); @@ -3192,253 +3078,6 @@ pub(super) fn resolve_patch( } } - // The candidate graph: canonical topology plus everything this patch - // declares. Containment, endpoints, and preconditions all read it. - let mut containers: BTreeMap<Key<EntityId>, Key<EntityId>> = state - .entities - .iter() - .filter_map(|(entity_id, record)| { - record - .container - .map(|container| (Key::Existing(*entity_id), Key::Existing(container))) - }) - .collect(); - let mut routes: BTreeMap<Key<EdgeId>, RouteCandidate> = state - .edges - .iter() - .map(|(edge_id, record)| { - let (from, to) = record.endpoints(); - ( - Key::Existing(*edge_id), - RouteCandidate { - from: Key::Existing(from), - to: Key::Existing(to), - access: record.access().clone(), - cost: record.cost(), - open: record.is_open(), - }, - ) - }) - .collect(); - let mut positions: BTreeMap<Key<SubjectId>, Key<EntityId>> = state - .positions - .iter() - .map(|(subject_id, position)| (Key::Existing(*subject_id), Key::Existing(position.place))) - .collect(); - let mut holdings: BTreeMap<(Key<SubjectId>, Key<EntityId>), Quantity> = state - .holdings - .iter() - .flat_map(|(subject_id, held)| { - held.iter().map(move |(entity_id, quantity)| { - ( - (Key::Existing(*subject_id), Key::Existing(*entity_id)), - *quantity, - ) - }) - }) - .collect(); - let seeded_holdings = holdings.clone(); - let mut dependencies: BTreeSet<(Key<SubjectId>, TargetKey)> = state - .dependencies - .iter() - .flat_map(|(subject_id, bound)| { - bound.iter().map(move |target| { - ( - Key::Existing(*subject_id), - match target { - DependencyTarget::Resource(id) => TargetKey::Resource(Key::Existing(*id)), - DependencyTarget::Route(id) => TargetKey::Route(Key::Existing(*id)), - DependencyTarget::Subject(id) => TargetKey::Subject(Key::Existing(*id)), - }, - ) - }) - }) - .collect(); - let mut authority: BTreeMap<Key<SubjectId>, BTreeSet<GrantKey>> = state - .authority - .iter() - .map(|(subject_id, grants)| { - ( - Key::Existing(*subject_id), - grants.iter().map(grant_key_of).collect(), - ) - }) - .collect(); - let mut selection: BTreeMap<(Key<SubjectId>, OfficeName), OfficeCandidate> = state - .selection - .iter() - .flat_map(|(institution, offices)| { - offices.iter().map(move |(name, office)| { - ( - (Key::Existing(*institution), name.clone()), - OfficeCandidate { - incumbent: office.incumbent.map(Key::Existing), - delegated: office.delegated.clone(), - }, - ) - }) - }) - .collect(); - let mut redress: BTreeMap<GrievanceKindName, (Key<SubjectId>, AuthorityTargetKey)> = state - .redress - .iter() - .map(|(grievance, forum)| { - ( - grievance.clone(), - (Key::Existing(forum.forum), target_key_of(forum.standing)), - ) - }) - .collect(); - let mut facts: BTreeMap<Key<EntityId>, FactCandidate> = state - .facts - .iter() - .map(|(entity_id, record)| { - ( - Key::Existing(*entity_id), - match &record.standing { - FactStanding::Canonical { .. } => FactCandidate::Canonical, - FactStanding::Claimed { by } => FactCandidate::Claimed(Key::Existing(*by)), - FactStanding::Ruled => FactCandidate::Ruled, - }, - ) - }) - .collect(); - // `Retire` and the affordance grant operations read and write these - // candidates. `retired` seeds from the committed subject rows: a declared subject is always - // fresh and unretired, so drafts start out of the set. `affordance_holdings` - // seeds from committed `affordance_grants` and is extended below for a - // subject this same patch declares. - let mut retired: BTreeSet<Key<SubjectId>> = state - .subjects - .keys() - .filter(|subject_id| super::is_retired(state, **subject_id)) - .map(|subject_id| Key::Existing(*subject_id)) - .collect(); - let mut affordance_holdings: BTreeMap<Key<SubjectId>, BTreeSet<Key<AffordanceId>>> = state - .affordance_grants - .iter() - .map(|(subject_id, granted)| { - ( - Key::Existing(*subject_id), - granted.iter().map(|id| Key::Existing(*id)).collect(), - ) - }) - .collect(); - let mut channels: BTreeMap<Key<EntityId>, ChannelCandidate> = state - .channels - .iter() - .map(|(entity_id, record)| { - ( - Key::Existing(*entity_id), - ChannelCandidate { - reach: match &record.reach { - Reach::Subjects(members) => { - ReachKey::Subjects(members.iter().copied().map(Key::Existing).collect()) - } - Reach::Place(place) => ReachKey::Place(Key::Existing(*place)), - }, - controller: record.controller.map(Key::Existing), - }, - ) - }) - .collect(); - // Keys and payload, so an `AcquireKnowledge` that changes nothing is - // `NoOperationEffect` before any ID is minted. `Witness` is modelled here - // too: its landing is a subtree of `positions`, both maps are candidate - // maps, and so the fan-out it will perform at apply is derivable now — a - // subject this patch relocated into the subtree counts, and a witness that - // reaches nobody is refused at resolve exactly as `apply_operation` - // refuses it. - // - // `Communicate` never enters, and the difference is not scale. A telling is - // an act whose occurrence does not depend on its reception: its empty - // fan-out is legal, so there is nothing for this map to refuse and no - // refusal for it to predict. A witnessed event is only its reception, so - // its landing is its legality. - // - // Neither operation can write `Told`. This map can represent a `Told` - // entry, but no `ComponentOp` can construct one: `AcquireKnowledge` takes - // an `AuthoredSource`, `Witness` takes no source at all, and neither type - // has a `Told` variant — - // `action::no_component_op_kind_lowers_to_a_told_knowledge_write` pins both - // lowering sites that could otherwise drift. If a future operation is ever - // given the power to write `Told` directly — bypassing `Communicate`'s own - // apply-time fan-out — it must model that fan-out into this candidate graph - // first, or `resolve_patch` will silently reason about a knowledge state - // the apply pass will not produce. - let mut knowledge: BTreeMap<(Key<SubjectId>, Key<EntityId>), KnowledgeCandidate> = state - .knowledge - .iter() - .map(|((subject_id, fact), entry)| { - ( - (Key::Existing(*subject_id), Key::Existing(*fact)), - KnowledgeCandidate { - confidence: entry.confidence, - source: match entry.source { - KnowledgeSource::Witnessed => KnowledgeSourceKey::Witnessed, - KnowledgeSource::Evidenced => KnowledgeSourceKey::Evidenced, - KnowledgeSource::Told { by, via } => KnowledgeSourceKey::Told { - by: Key::Existing(by), - via: via.map(Key::Existing), - }, - KnowledgeSource::Seen { by } => KnowledgeSourceKey::Seen { - by: Key::Existing(by), - }, - }, - }, - ) - }) - .collect(); - // Presence is all a discharge asks, and a create cannot collide: the key is - // command-derived and the index is unique within one patch. - let mut commitments: BTreeSet<(Key<SubjectId>, CommitmentKey)> = state - .commitments - .iter() - .flat_map(|(subject_id, held)| { - held.keys() - .map(move |key| (Key::Existing(*subject_id), *key)) - }) - .collect(); - let mut pressures: BTreeMap<(Key<SubjectId>, PressureSourceKey), u32> = state - .pressures - .iter() - .flat_map(|(target, held)| { - held.iter().map(move |(source, magnitude)| { - ( - ( - Key::Existing(*target), - match source { - PressureSource::Commitment { subject, key } => { - PressureSourceKey::Commitment { - subject: Key::Existing(*subject), - key: *key, - } - } - PressureSource::Dependency(DependencyTarget::Resource(entity_id)) => { - PressureSourceKey::Dependency(TargetKey::Resource(Key::Existing( - *entity_id, - ))) - } - PressureSource::Dependency(DependencyTarget::Route(edge_id)) => { - PressureSourceKey::Dependency(TargetKey::Route(Key::Existing( - *edge_id, - ))) - } - PressureSource::Dependency(DependencyTarget::Subject(subject_id)) => { - PressureSourceKey::Dependency(TargetKey::Subject(Key::Existing( - *subject_id, - ))) - } - PressureSource::Subject(subject_id) => { - PressureSourceKey::Subject(Key::Existing(*subject_id)) - } - }, - ), - magnitude.0, - ) - }) - }) - .collect(); let mut deltas: BTreeMap<Key<EntityId>, LedgerDelta> = BTreeMap::new(); let mut declared_places: Vec<(DraftHandle, Key<EntityId>)> = Vec::new(); @@ -3465,7 +3104,7 @@ pub(super) fn resolve_patch( &state.entities, &mut mismatches, ) { - containers.insert(Key::Draft(entity.handle.clone()), parent); + graph.containers.insert(Key::Draft(entity.handle.clone()), parent); } } } @@ -3484,7 +3123,7 @@ pub(super) fn resolve_patch( FactStandingRef::Ruled => Some(FactCandidate::Ruled), }; if let Some(standing) = standing { - facts.insert(Key::Draft(fact.handle.clone()), standing); + graph.facts.insert(Key::Draft(fact.handle.clone()), standing); } } Declaration::Channel(channel) => { @@ -3503,7 +3142,7 @@ pub(super) fn resolve_patch( &mut mismatches, ); if let (Some(reach), Some(controller)) = (reach, controller) { - channels.insert( + graph.channels.insert( Key::Draft(channel.handle.clone()), ChannelCandidate { reach, controller }, ); @@ -3523,7 +3162,7 @@ pub(super) fn resolve_patch( } } if !granted.is_empty() { - affordance_holdings.insert(Key::Draft(subject.handle.clone()), granted); + graph.affordance_holdings.insert(Key::Draft(subject.handle.clone()), granted); } if let Some(reference) = &subject.position && let Some(place) = resolve_entity( @@ -3535,7 +3174,7 @@ pub(super) fn resolve_patch( &mut mismatches, ) { - positions.insert(Key::Draft(subject.handle.clone()), place); + graph.positions.insert(Key::Draft(subject.handle.clone()), place); } } Declaration::Route(route) => { @@ -3566,7 +3205,7 @@ pub(super) fn resolve_patch( referent: route.handle.clone(), }); } - routes.insert( + graph.routes.insert( Key::Draft(route.handle.clone()), RouteCandidate { from, @@ -3585,7 +3224,7 @@ pub(super) fn resolve_patch( // admission already refused cycles, so every cycle contains a declared // place; walking from each declared place names them all. for (handle, start) in &declared_places { - if contains_itself(start, &containers) { + if graph.contains_itself(start) { mismatches.push(Mismatch::ContainmentCycle { referent: handle.clone(), }); @@ -3663,7 +3302,7 @@ pub(super) fn resolve_patch( // A retired subject cannot act, and making a promise is // acting: refused here the same way `RetiredSubjectActed` // refuses a retired office incumbent below. - if retired.contains(&subject_key) { + if graph.is_retired(&subject_key) { mismatches.push(Mismatch::RetiredSubjectActed { operation: position, }); @@ -3684,13 +3323,16 @@ pub(super) fn resolve_patch( if !checks_resolve { continue; } - commitments.insert(( - subject_key, - CommitmentKey { - command: command_id, - index: position as u32, - }, - )); + graph.commitments.insert( + ( + subject_key, + CommitmentKey { + command: command_id, + index: position as u32, + }, + ), + (), + ); } ComponentOp::DischargeCommitment { subject, key } => { let Some(subject_key) = resolve_subject( @@ -3702,7 +3344,7 @@ pub(super) fn resolve_patch( ) else { continue; }; - if !commitments.remove(&(subject_key, *key)) { + if graph.commitments.remove(&(subject_key, *key)).is_none() { mismatches.push(Mismatch::UnknownCommitment { operation: position, }); @@ -3724,7 +3366,7 @@ pub(super) fn resolve_patch( continue; }; let slot = (target_key, source_key); - let current = pressures.get(&slot).copied().unwrap_or_default(); + let current = graph.pressures.get(&slot).unwrap_or_default(); let next = if advancing { current.saturating_add(by.0) } else { @@ -3737,9 +3379,9 @@ pub(super) fn resolve_patch( operation: position, }); } else if next == 0 { - pressures.remove(&slot); + graph.pressures.remove(&slot); } else { - pressures.insert(slot, next); + graph.pressures.insert(slot, next); } } ComponentOp::ResolvePressure { source, target } => { @@ -3755,7 +3397,7 @@ pub(super) fn resolve_patch( let (Some(target_key), Some(source_key)) = (target_key, source_key) else { continue; }; - if pressures.remove(&(target_key, source_key)).is_none() { + if graph.pressures.remove(&(target_key, source_key)).is_none() { mismatches.push(Mismatch::NoOperationEffect { operation: position, }); @@ -3779,18 +3421,18 @@ pub(super) fn resolve_patch( let (Some(subject_key), Some(route_key)) = (subject_key, route_key) else { continue; }; - let Some(route) = routes.get(&route_key).cloned() else { + let Some(route) = graph.routes.get(&route_key) else { continue; }; let mut admitted = true; - match positions.get(&subject_key) { + match graph.positions.get(&subject_key) { None => { mismatches.push(Mismatch::UnplacedSubject { operation: position, }); admitted = false; } - Some(place) if *place != route.from => { + Some(place) if place != route.from => { mismatches.push(Mismatch::SubjectNotAtOrigin { operation: position, }); @@ -3813,12 +3455,7 @@ pub(super) fn resolve_patch( let opened = match &route.to { Key::Existing(destination) => route_admits( state, - &canonical_grants(&candidate_effective_authority( - &subject_key, - &authority, - &selection, - &retired, - )), + &canonical_grants(&graph.effective_authority(&subject_key)), &route.access, *destination, ), @@ -3831,7 +3468,7 @@ pub(super) fn resolve_patch( admitted = false; } if admitted { - positions.insert(subject_key, route.to); + graph.positions.insert(subject_key, route.to); } } ComponentOp::Retire { subject } => { @@ -3844,15 +3481,15 @@ pub(super) fn resolve_patch( ) else { continue; }; - if retired.contains(&subject_key) { + if graph.is_retired(&subject_key) { mismatches.push(Mismatch::NoOperationEffect { operation: position, }); continue; } - retired.insert(subject_key.clone()); - positions.remove(&subject_key); - affordance_holdings.remove(&subject_key); + graph.retire(subject_key.clone()); + graph.positions.remove(&subject_key); + graph.affordance_holdings.remove(&subject_key); } ComponentOp::OpenRoute { route } | ComponentOp::CloseRoute { route } => { let open = matches!(operation, ComponentOp::OpenRoute { .. }); @@ -3865,7 +3502,7 @@ pub(super) fn resolve_patch( ) else { continue; }; - let Some(candidate) = routes.get_mut(&route_key) else { + let Some(candidate) = graph.routes.get_mut(&route_key) else { continue; }; if candidate.open == open { @@ -3891,7 +3528,7 @@ pub(super) fn resolve_patch( continue; } let Some(route_key) = route_key else { continue }; - let Some(candidate) = routes.get_mut(&route_key) else { + let Some(candidate) = graph.routes.get_mut(&route_key) else { continue; }; if candidate.cost == *cost { @@ -3949,7 +3586,7 @@ pub(super) fn resolve_patch( if qty.0 == 0 { continue; } - let held = candidate_held(&holdings, &from_key, &resource_key); + let held = candidate_held(&graph.holdings, &from_key, &resource_key); let Some(remaining) = held.checked_sub(qty.0) else { mismatches.push(Mismatch::InsufficientCustody { operation: position, @@ -3957,15 +3594,15 @@ pub(super) fn resolve_patch( continue; }; let Some(credited) = - candidate_held(&holdings, &to_key, &resource_key).checked_add(qty.0) + candidate_held(&graph.holdings, &to_key, &resource_key).checked_add(qty.0) else { mismatches.push(Mismatch::QuantityOverflow { operation: position, }); continue; }; - candidate_set(&mut holdings, &from_key, &resource_key, remaining); - candidate_set(&mut holdings, &to_key, &resource_key, credited); + candidate_set(&mut graph.holdings, &from_key, &resource_key, remaining); + candidate_set(&mut graph.holdings, &to_key, &resource_key, credited); // A transfer contributes to no ledger term: the equation proves // it, because moving a different amount out than in breaks the // resource's total. @@ -4020,7 +3657,7 @@ pub(super) fn resolve_patch( continue; } let Some(remaining) = - candidate_held(&holdings, &holder_key, &from_key).checked_sub(qty.0) + candidate_held(&graph.holdings, &holder_key, &from_key).checked_sub(qty.0) else { mismatches.push(Mismatch::InsufficientCustody { operation: position, @@ -4028,15 +3665,15 @@ pub(super) fn resolve_patch( continue; }; let Some(gained) = - candidate_held(&holdings, &holder_key, &into_key).checked_add(qty.0) + candidate_held(&graph.holdings, &holder_key, &into_key).checked_add(qty.0) else { mismatches.push(Mismatch::QuantityOverflow { operation: position, }); continue; }; - candidate_set(&mut holdings, &holder_key, &from_key, remaining); - candidate_set(&mut holdings, &holder_key, &into_key, gained); + candidate_set(&mut graph.holdings, &holder_key, &from_key, remaining); + candidate_set(&mut graph.holdings, &holder_key, &into_key, gained); deltas.entry(from_key).or_default().spent += u128::from(qty.0); deltas.entry(into_key).or_default().gained += u128::from(qty.0); } @@ -4072,14 +3709,14 @@ pub(super) fn resolve_patch( continue; } let Some(remaining) = - candidate_held(&holdings, &holder_key, &resource_key).checked_sub(qty.0) + candidate_held(&graph.holdings, &holder_key, &resource_key).checked_sub(qty.0) else { mismatches.push(Mismatch::InsufficientCustody { operation: position, }); continue; }; - candidate_set(&mut holdings, &holder_key, &resource_key, remaining); + candidate_set(&mut graph.holdings, &holder_key, &resource_key, remaining); deltas.entry(resource_key).or_default().consumed += u128::from(qty.0); } ComponentOp::Admit { @@ -4121,14 +3758,14 @@ pub(super) fn resolve_patch( continue; } let Some(admitted) = - candidate_held(&holdings, &holder_key, &resource_key).checked_add(qty.0) + candidate_held(&graph.holdings, &holder_key, &resource_key).checked_add(qty.0) else { mismatches.push(Mismatch::QuantityOverflow { operation: position, }); continue; }; - candidate_set(&mut holdings, &holder_key, &resource_key, admitted); + candidate_set(&mut graph.holdings, &holder_key, &resource_key, admitted); deltas.entry(resource_key).or_default().admitted += u128::from(qty.0); } ComponentOp::Mint { @@ -4163,14 +3800,14 @@ pub(super) fn resolve_patch( continue; } let Some(minted) = - candidate_held(&holdings, &holder_key, &resource_key).checked_add(qty.0) + candidate_held(&graph.holdings, &holder_key, &resource_key).checked_add(qty.0) else { mismatches.push(Mismatch::QuantityOverflow { operation: position, }); continue; }; - candidate_set(&mut holdings, &holder_key, &resource_key, minted); + candidate_set(&mut graph.holdings, &holder_key, &resource_key, minted); deltas.entry(resource_key).or_default().admitted += u128::from(qty.0); } ComponentOp::Bind { subject, target } | ComponentOp::Release { subject, target } => { @@ -4199,14 +3836,14 @@ pub(super) fn resolve_patch( continue; } let slot = (subject_key, target_key); - if dependencies.contains(&slot) == bind { + if graph.dependencies.contains_key(&slot) == bind { mismatches.push(Mismatch::NoOperationEffect { operation: position, }); } else if bind { - dependencies.insert(slot); + graph.dependencies.insert(slot, ()); } else { - dependencies.remove(&slot); + graph.dependencies.remove(&slot); } } ComponentOp::GrantAuthority { holder, grant } @@ -4244,12 +3881,11 @@ pub(super) fn resolve_patch( // reach `targets_overlap`/`verify_state_shape`, which stay // structural and position-independent; a later `Relocate` // that creates this shape is not re-derived as a violation. + let mut grants = graph.grants_of(&holder_key); if granting - && authority.get(&holder_key).is_some_and(|grants| { - grants.iter().any(|other| { - other.kind == entry.kind - && grant_targets_nest(state, &entry.over, &other.over) - }) + && grants.iter().any(|other| { + other.kind == entry.kind + && grant_targets_nest(state, &entry.over, &other.over) }) { mismatches.push(Mismatch::OverlappingJurisdiction { @@ -4257,25 +3893,17 @@ pub(super) fn resolve_patch( }); continue; } - let held = authority - .get(&holder_key) - .is_some_and(|grants| grants.contains(&entry)); - if held == granting { + if grants.contains(&entry) == granting { mismatches.push(Mismatch::NoOperationEffect { operation: position, }); - } else if granting { - authority.entry(holder_key).or_default().insert(entry); } else { - let empty = if let Some(grants) = authority.get_mut(&holder_key) { - grants.remove(&entry); - grants.is_empty() + if granting { + grants.insert(entry); } else { - false - }; - if empty { - authority.remove(&holder_key); + grants.remove(&entry); } + graph.set_grants(holder_key, grants); } } ComponentOp::GrantAffordance { subject, affordance } @@ -4300,32 +3928,28 @@ pub(super) fn resolve_patch( continue; }; // A retired subject holds no grant a patch may touch. - if retired.contains(&subject_key) { + if graph.is_retired(&subject_key) { mismatches.push(Mismatch::GrantsToRetired { operation: position, }); continue; } - let held = affordance_holdings - .get(&subject_key) - .is_some_and(|granted| granted.contains(&affordance_key)); - if held == granting { + let mut granted = graph.affordance_holdings.get(&subject_key).unwrap_or_default(); + if granted.contains(&affordance_key) == granting { mismatches.push(Mismatch::NoOperationEffect { operation: position, }); continue; } if granting { - affordance_holdings - .entry(subject_key) - .or_default() - .insert(affordance_key); + granted.insert(affordance_key); } else { - let granted = affordance_holdings.entry(subject_key.clone()).or_default(); granted.remove(&affordance_key); - if granted.is_empty() { - affordance_holdings.remove(&subject_key); - } + } + if granted.is_empty() { + graph.affordance_holdings.remove(&subject_key); + } else { + graph.affordance_holdings.insert(subject_key, granted); } } ComponentOp::OpenOffice { @@ -4358,23 +3982,21 @@ pub(super) fn resolve_patch( continue; } let slot = (institution_key, office.clone()); - let incumbent = selection - .get(&slot) - .and_then(|current| current.incumbent.clone()); - if selection - .get(&slot) + let current = graph.office(&slot); + if current + .as_ref() .is_some_and(|current| ¤t.delegated == delegated) { mismatches.push(Mismatch::NoOperationEffect { operation: position, }); } else { - selection.insert( + graph.set_office( slot, - OfficeCandidate { - incumbent, + Some(OfficeCandidate { + incumbent: current.and_then(|current| current.incumbent), delegated: delegated.clone(), - }, + }), ); } } @@ -4398,25 +4020,25 @@ pub(super) fn resolve_patch( continue; }; let slot = (institution_key, office.clone()); - let Some(current) = selection.get(&slot).cloned() else { + let Some(current) = graph.office(&slot) else { mismatches.push(Mismatch::UnknownOffice { operation: position, }); continue; }; if closing { - selection.remove(&slot); + graph.set_office(slot, None); } else if current.incumbent.is_none() { mismatches.push(Mismatch::NoOperationEffect { operation: position, }); } else { - selection.insert( + graph.set_office( slot, - OfficeCandidate { + Some(OfficeCandidate { incumbent: None, ..current - }, + }), ); } } @@ -4452,23 +4074,21 @@ pub(super) fn resolve_patch( else { continue; }; - if retired.contains(&incumbent_key) { + if graph.is_retired(&incumbent_key) { mismatches.push(Mismatch::RetiredSubjectActed { operation: position, }); continue; } let slot = (institution_key.clone(), office.clone()); - let Some(current) = selection.get(&slot).cloned() else { + let Some(current) = graph.office(&slot) else { mismatches.push(Mismatch::UnknownOffice { operation: position, }); continue; }; - if selection.iter().any(|((held_by, name), other)| { - *held_by == institution_key - && name != office - && other.incumbent.as_ref() == Some(&incumbent_key) + if graph.offices_of(&institution_key).iter().any(|(name, other)| { + name != office && other.incumbent.as_ref() == Some(&incumbent_key) }) { mismatches.push(Mismatch::DuplicateIncumbency { operation: position, @@ -4480,12 +4100,12 @@ pub(super) fn resolve_patch( operation: position, }); } else { - selection.insert( + graph.set_office( slot, - OfficeCandidate { + Some(OfficeCandidate { incumbent: Some(incumbent_key), ..current - }, + }), ); } } @@ -4516,16 +4136,16 @@ pub(super) fn resolve_patch( let (Some(forum_key), Some(standing_key)) = (forum_key, standing_key) else { continue; }; - if redress.get(grievance) == Some(&(forum_key.clone(), standing_key.clone())) { + if graph.redress.get(grievance) == Some((forum_key.clone(), standing_key.clone())) { mismatches.push(Mismatch::NoOperationEffect { operation: position, }); } else { - redress.insert(grievance.clone(), (forum_key, standing_key)); + graph.redress.insert(grievance.clone(), (forum_key, standing_key)); } } ComponentOp::CloseForum { grievance } => { - if redress.remove(grievance).is_none() { + if graph.redress.remove(grievance).is_none() { mismatches.push(Mismatch::UnknownForum { operation: position, }); @@ -4555,7 +4175,7 @@ pub(super) fn resolve_patch( let (Some(subject_key), Some(fact_key)) = (subject_key, fact_key) else { continue; }; - if retired.contains(&subject_key) { + if graph.is_retired(&subject_key) { mismatches.push(Mismatch::RetiredSubjectActed { operation: position, }); @@ -4564,7 +4184,7 @@ pub(super) fn resolve_patch( // Evidenced knowledge is knowledge of canon. A receipt cannot // vouch for an assertion the kernel never evaluated. if *source == AuthoredSource::Evidenced - && facts.get(&fact_key) != Some(&FactCandidate::Canonical) + && graph.facts.get(&fact_key) != Some(FactCandidate::Canonical) { mismatches.push(Mismatch::EvidencedKnowledgeOfClaim { operation: position, @@ -4579,12 +4199,12 @@ pub(super) fn resolve_patch( }, }; let slot = (subject_key, fact_key); - if knowledge.get(&slot) == Some(&entry) { + if graph.knowledge.get(&slot) == Some(entry.clone()) { mismatches.push(Mismatch::NoOperationEffect { operation: position, }); } else { - knowledge.insert(slot, entry); + graph.knowledge.insert(slot, entry); } } ComponentOp::Forget { subject, fact } => { @@ -4606,13 +4226,13 @@ pub(super) fn resolve_patch( let (Some(subject_key), Some(fact_key)) = (subject_key, fact_key) else { continue; }; - if retired.contains(&subject_key) { + if graph.is_retired(&subject_key) { mismatches.push(Mismatch::RetiredSubjectActed { operation: position, }); continue; } - if knowledge.remove(&(subject_key, fact_key)).is_none() { + if graph.knowledge.remove(&(subject_key, fact_key)).is_none() { mismatches.push(Mismatch::NoOperationEffect { operation: position, }); @@ -4646,7 +4266,7 @@ pub(super) fn resolve_patch( else { continue; }; - if retired.contains(&speaker_key) { + if graph.is_retired(&speaker_key) { mismatches.push(Mismatch::RetiredSubjectActed { operation: position, }); @@ -4654,14 +4274,7 @@ pub(super) fn resolve_patch( } // Ontology admission: communication reaches only subjects inside // the channel's reach, and a speaker outside it is not speaking. - if !candidate_in_audience( - &speaker_key, - &audience, - &speaker_key, - &positions, - &channels, - &containers, - ) { + if !graph.in_audience(&speaker_key, &audience, &speaker_key) { mismatches.push(Mismatch::SpeakerOutsideAudience { operation: position, }); @@ -4702,13 +4315,12 @@ pub(super) fn resolve_patch( confidence: *confidence, source: KnowledgeSourceKey::Witnessed, }; - let recipients: Vec<Key<SubjectId>> = positions - .iter() - .filter(|(subject_key, standing)| { - key_covers_place(&place_key, standing, &containers) - && !knowledge.contains_key(&((*subject_key).clone(), fact_key.clone())) + let recipients: Vec<Key<SubjectId>> = graph + .occupants_under(&place_key) + .into_iter() + .filter(|subject_key| { + !graph.knowledge.contains_key(&(subject_key.clone(), fact_key.clone())) }) - .map(|(subject_key, _)| (*subject_key).clone()) .collect(); if recipients.is_empty() { mismatches.push(Mismatch::NoOperationEffect { @@ -4716,7 +4328,7 @@ pub(super) fn resolve_patch( }); } else { for subject_key in recipients { - knowledge.insert((subject_key, fact_key.clone()), entry.clone()); + graph.knowledge.insert((subject_key, fact_key.clone()), entry.clone()); } } } @@ -4739,7 +4351,7 @@ pub(super) fn resolve_patch( let (Some(channel_key), Some(reach_key)) = (channel_key, reach_key) else { continue; }; - let Some(candidate) = channels.get_mut(&channel_key) else { + let Some(candidate) = graph.channels.get_mut(&channel_key) else { continue; }; if candidate.reach == reach_key { @@ -4773,7 +4385,7 @@ pub(super) fn resolve_patch( else { continue; }; - let Some(candidate) = channels.get_mut(&channel_key) else { + let Some(candidate) = graph.channels.get_mut(&channel_key) else { continue; }; if candidate.controller == controller_key { @@ -4795,7 +4407,7 @@ pub(super) fn resolve_patch( ComponentOp::GrantAuthority { .. } | ComponentOp::OpenOffice { .. } | ComponentOp::InstallIncumbent { .. } - ) && graph_overlaps(&authority, &selection, &containers, &retired) + ) && graph.overlapping() { mismatches.push(Mismatch::OverlappingJurisdiction { operation: position, @@ -4808,16 +4420,7 @@ pub(super) fn resolve_patch( // individually balance but whose net does not is impossible, and an // intermediate negative was already caught above as `InsufficientCustody`. for (resource_key, delta) in &mut deltas { - delta.before = seeded_holdings - .iter() - .filter(|((_, resource), _)| resource == resource_key) - .map(|(_, quantity)| u128::from(quantity.0)) - .sum(); - delta.after = holdings - .iter() - .filter(|((_, resource), _)| resource == resource_key) - .map(|(_, quantity)| u128::from(quantity.0)) - .sum(); + (delta.before, delta.after) = graph.custody(resource_key); } if let Some(resource) = check_ledger(&deltas) { mismatches.push(Mismatch::CustodyNotConserved { @@ -5560,36 +5163,6 @@ fn resolve_pressure_source( } } -/// Whether `place` is `root`, or reaches it through the candidate container -/// chain. The walk is bounded by the graph size, so a cycle that does not -/// include either end still terminates. -fn key_covers_place( - root: &Key<EntityId>, - place: &Key<EntityId>, - containers: &BTreeMap<Key<EntityId>, Key<EntityId>>, -) -> bool { - let mut current = Some(place); - for _ in 0..=containers.len() { - match current { - None => return false, - Some(node) if node == root => return true, - Some(node) => current = containers.get(node), - } - } - false -} - -/// Whether a place reaches itself through its container chain: the same walk, -/// started one link up so a place is not its own ancestor by definition. -fn contains_itself( - start: &Key<EntityId>, - containers: &BTreeMap<Key<EntityId>, Key<EntityId>>, -) -> bool { - containers - .get(start) - .is_some_and(|parent| key_covers_place(start, parent, containers)) -} - /// Whether `place` is `root` or is contained in it, over canonical state: one /// upward walk in the shape of [`containment_terminates`], bounded by the graph /// size. It is total because `admit_resolved` refuses a non-terminating chain, @@ -5613,7 +5186,7 @@ pub(super) fn covers_place( false } -/// The canonical twin of the candidate graph's `candidate_targets_overlap`: whether two +/// The canonical twin of the candidate graph's `Candidate::targets_overlap`: whether two /// jurisdictions of one kind cover common ground. pub(super) fn targets_overlap( entities: &Docs<EntityId, EntityRecord, ChildOf>, @@ -6520,7 +6093,7 @@ mod tests { ); } - /// PA.f48: `candidate_effective_authority` is the resolver's twin of + /// PA.f48: `Candidate::effective_authority` is the resolver's twin of /// `delegated_authority`, and must share its predicate for "is this /// institution live". Retiring the lending institution and granting the /// same ground directly to its former office-holder, in one patch, must diff --git a/native/aetherlight/src/patch/candidate.rs b/native/aetherlight/src/patch/candidate.rs new file mode 100644 index 000000000..1934f0048 --- /dev/null +++ b/native/aetherlight/src/patch/candidate.rs @@ -0,0 +1,1294 @@ +//! The candidate graph of one resolution: what the world holds plus what the +//! patch writes, without copying the world. +//! +//! Every candidate map is an [`Overlay`]: the committed partition read through a +//! base function, and the patch's own writes in a local map. Nothing here +//! iterates a committed partition; each scale-sensitive read is a named method +//! of [`Candidate`] whose cost is bounded by what the patch wrote plus what the +//! read returns, through the partitions' point reads and `indexed`. A +//! `Candidate` lives for one `resolve_patch` call and is never written back: +//! `admit_resolved` stays the only writer of the ontology partitions. + +use super::{ + AffordanceKindName, AudienceKey, AuthorityTargetKey, ChannelCandidate, CommitmentKey, + DependencyTarget, FactCandidate, GrantKey, GrievanceKindName, ImportKey, Key, + KnowledgeCandidate, KnowledgeSource, KnowledgeSourceKey, OfficeCandidate, OfficeName, + PressureSource, PressureSourceKey, Quantity, Reach, ReachKey, RouteCandidate, TargetKey, + grant_key_of, target_key_of, +}; +use crate::{AffordanceId, EdgeId, EntityId, SubjectId, WorldState}; +use std::collections::{BTreeMap, BTreeSet}; + +/// One committed partition seen through a patch: reads fall through to the +/// partition by point get, writes land in `local`, and a removal is a `None` +/// there. A `Key::Draft` key has no committed value, so its base is `None`. +pub(super) struct Overlay<'s, K: Ord + Clone, V: Clone> { + state: &'s WorldState, + base: fn(&WorldState, &K) -> Option<V>, + local: BTreeMap<K, Option<V>>, +} + +impl<'s, K: Ord + Clone, V: Clone> Overlay<'s, K, V> { + fn new(state: &'s WorldState, base: fn(&WorldState, &K) -> Option<V>) -> Self { + Self { state, base, local: BTreeMap::new() } + } + + pub(super) fn get(&self, key: &K) -> Option<V> { + match self.local.get(key) { + Some(written) => written.clone(), + None => (self.base)(self.state, key), + } + } + + pub(super) fn contains_key(&self, key: &K) -> bool { + match self.local.get(key) { + Some(written) => written.is_some(), + None => (self.base)(self.state, key).is_some(), + } + } + + pub(super) fn insert(&mut self, key: K, value: V) { + self.local.insert(key, Some(value)); + } + + /// The value the key held, if any. + pub(super) fn remove(&mut self, key: &K) -> Option<V> { + let held = self.get(key); + if held.is_some() { + self.local.insert(key.clone(), None); + } + held + } + + /// Copies the committed value into `local` on first mutable touch; a miss + /// writes nothing. + pub(super) fn get_mut(&mut self, key: &K) -> Option<&mut V> { + if !self.local.contains_key(key) { + let committed = (self.base)(self.state, key)?; + self.local.insert(key.clone(), Some(committed)); + } + self.local.get_mut(key)?.as_mut() + } + + /// The entries the patch has touched, removals as `None`. + pub(super) fn local(&self) -> &BTreeMap<K, Option<V>> { + &self.local + } +} + +fn existing<Id: Copy>(key: &Key<Id>) -> Option<Id> { + match key { + Key::Existing(id) => Some(*id), + Key::Draft(_) => None, + } +} + +fn target_of(key: &TargetKey) -> Option<DependencyTarget> { + Some(match key { + TargetKey::Resource(id) => DependencyTarget::Resource(existing(id)?), + TargetKey::Route(id) => DependencyTarget::Route(existing(id)?), + TargetKey::Subject(id) => DependencyTarget::Subject(existing(id)?), + }) +} + +fn source_of(key: &PressureSourceKey) -> Option<PressureSource> { + Some(match key { + PressureSourceKey::Commitment { subject, key } => { + PressureSource::Commitment { subject: existing(subject)?, key: *key } + } + PressureSourceKey::Dependency(target) => PressureSource::Dependency(target_of(target)?), + PressureSourceKey::Subject(subject) => PressureSource::Subject(existing(subject)?), + }) +} + +fn office_candidate(office: &crate::Office) -> OfficeCandidate { + OfficeCandidate { + incumbent: office.incumbent.map(Key::Existing), + delegated: office.delegated.clone(), + } +} + +fn base_container(state: &WorldState, key: &Key<EntityId>) -> Option<Key<EntityId>> { + state.entities.get(&existing(key)?)?.container.map(Key::Existing) +} + +fn base_route(state: &WorldState, key: &Key<EdgeId>) -> Option<RouteCandidate> { + let record = state.edges.get(&existing(key)?)?; + let (from, to) = record.endpoints(); + Some(RouteCandidate { + from: Key::Existing(from), + to: Key::Existing(to), + access: record.access().clone(), + cost: record.cost(), + open: record.is_open(), + }) +} + +fn base_position(state: &WorldState, key: &Key<SubjectId>) -> Option<Key<EntityId>> { + state.positions.get(&existing(key)?).map(|position| Key::Existing(position.place)) +} + +fn base_holding(state: &WorldState, key: &(Key<SubjectId>, Key<EntityId>)) -> Option<Quantity> { + let (holder, resource) = (existing(&key.0)?, existing(&key.1)?); + state.holdings.get(&holder)?.get(&resource).copied() +} + +fn base_dependency(state: &WorldState, key: &(Key<SubjectId>, TargetKey)) -> Option<()> { + let (subject, target) = (existing(&key.0)?, target_of(&key.1)?); + state.dependencies.get(&subject)?.contains(&target).then_some(()) +} + +fn base_grants(state: &WorldState, key: &Key<SubjectId>) -> Option<BTreeSet<GrantKey>> { + state.authority.get(&existing(key)?).map(|grants| grants.iter().map(grant_key_of).collect()) +} + +fn base_office(state: &WorldState, key: &(Key<SubjectId>, OfficeName)) -> Option<OfficeCandidate> { + state.selection.get(&existing(&key.0)?)?.get(&key.1).map(office_candidate) +} + +fn base_forum( + state: &WorldState, + key: &GrievanceKindName, +) -> Option<(Key<SubjectId>, AuthorityTargetKey)> { + state + .redress + .get(key) + .map(|forum| (Key::Existing(forum.forum), target_key_of(forum.standing))) +} + +fn base_fact(state: &WorldState, key: &Key<EntityId>) -> Option<FactCandidate> { + state.facts.get(&existing(key)?).map(|record| match &record.standing { + crate::FactStanding::Canonical { .. } => FactCandidate::Canonical, + crate::FactStanding::Claimed { by } => FactCandidate::Claimed(Key::Existing(*by)), + crate::FactStanding::Ruled => FactCandidate::Ruled, + }) +} + +fn base_retired(state: &WorldState, key: &Key<SubjectId>) -> Option<()> { + crate::is_retired(state, existing(key)?).then_some(()) +} + +fn base_affordances( + state: &WorldState, + key: &Key<SubjectId>, +) -> Option<BTreeSet<Key<AffordanceId>>> { + state + .affordance_grants + .get(&existing(key)?) + .map(|granted| granted.iter().map(|id| Key::Existing(*id)).collect()) +} + +fn base_channel(state: &WorldState, key: &Key<EntityId>) -> Option<ChannelCandidate> { + state.channels.get(&existing(key)?).map(|record| ChannelCandidate { + reach: match &record.reach { + Reach::Subjects(members) => { + ReachKey::Subjects(members.iter().copied().map(Key::Existing).collect()) + } + Reach::Place(place) => ReachKey::Place(Key::Existing(*place)), + }, + controller: record.controller.map(Key::Existing), + }) +} + +fn base_knowledge( + state: &WorldState, + key: &(Key<SubjectId>, Key<EntityId>), +) -> Option<KnowledgeCandidate> { + let (subject, fact) = (existing(&key.0)?, existing(&key.1)?); + state.knowledge.get(&(subject, fact)).map(|entry| KnowledgeCandidate { + confidence: entry.confidence, + source: match entry.source { + KnowledgeSource::Witnessed => KnowledgeSourceKey::Witnessed, + KnowledgeSource::Evidenced => KnowledgeSourceKey::Evidenced, + KnowledgeSource::Told { by, via } => KnowledgeSourceKey::Told { + by: Key::Existing(by), + via: via.map(Key::Existing), + }, + KnowledgeSource::Seen { by } => KnowledgeSourceKey::Seen { by: Key::Existing(by) }, + }, + }) +} + +fn base_commitment(state: &WorldState, key: &(Key<SubjectId>, CommitmentKey)) -> Option<()> { + state.commitments.get(&existing(&key.0)?)?.contains_key(&key.1).then_some(()) +} + +fn base_pressure(state: &WorldState, key: &(Key<SubjectId>, PressureSourceKey)) -> Option<u32> { + let (target, source) = (existing(&key.0)?, source_of(&key.1)?); + state.pressures.get(&target)?.get(&source).map(|magnitude| magnitude.0) +} + +/// The candidate graph: canonical topology plus everything this patch declares +/// and operates. Containment, endpoints, and preconditions all read it. +/// +/// `authority`, `selection` and `retired` are private: a write to any of them +/// goes through a method that re-judges the holders whose candidate effective +/// authority it can change, so `overlapping` is always the set of holders that +/// hold two grants of one kind over overlapping ground, exactly what a scan of +/// every holder would answer. That equality holds because the committed world is +/// disjoint (every commit checks it, and opening a world verifies it), so only +/// a holder the patch touched can enter the set. +pub(super) struct Candidate<'s> { + state: &'s WorldState, + pub(super) containers: Overlay<'s, Key<EntityId>, Key<EntityId>>, + pub(super) routes: Overlay<'s, Key<EdgeId>, RouteCandidate>, + pub(super) positions: Overlay<'s, Key<SubjectId>, Key<EntityId>>, + pub(super) holdings: Overlay<'s, (Key<SubjectId>, Key<EntityId>), Quantity>, + pub(super) dependencies: Overlay<'s, (Key<SubjectId>, TargetKey), ()>, + authority: Overlay<'s, Key<SubjectId>, BTreeSet<GrantKey>>, + selection: Overlay<'s, (Key<SubjectId>, OfficeName), OfficeCandidate>, + pub(super) redress: Overlay<'s, GrievanceKindName, (Key<SubjectId>, AuthorityTargetKey)>, + pub(super) facts: Overlay<'s, Key<EntityId>, FactCandidate>, + retired: Overlay<'s, Key<SubjectId>, ()>, + pub(super) affordance_holdings: Overlay<'s, Key<SubjectId>, BTreeSet<Key<AffordanceId>>>, + pub(super) channels: Overlay<'s, Key<EntityId>, ChannelCandidate>, + pub(super) knowledge: Overlay<'s, (Key<SubjectId>, Key<EntityId>), KnowledgeCandidate>, + pub(super) commitments: Overlay<'s, (Key<SubjectId>, CommitmentKey), ()>, + pub(super) pressures: Overlay<'s, (Key<SubjectId>, PressureSourceKey), u32>, + /// The affordance kinds this patch declares. + kinds: BTreeSet<AffordanceKindName>, + overlapping: BTreeSet<Key<SubjectId>>, +} + +impl<'s> Candidate<'s> { + pub(super) fn new(state: &'s WorldState) -> Self { + Self { + state, + containers: Overlay::new(state, base_container), + routes: Overlay::new(state, base_route), + positions: Overlay::new(state, base_position), + holdings: Overlay::new(state, base_holding), + dependencies: Overlay::new(state, base_dependency), + authority: Overlay::new(state, base_grants), + selection: Overlay::new(state, base_office), + redress: Overlay::new(state, base_forum), + facts: Overlay::new(state, base_fact), + retired: Overlay::new(state, base_retired), + affordance_holdings: Overlay::new(state, base_affordances), + channels: Overlay::new(state, base_channel), + knowledge: Overlay::new(state, base_knowledge), + commitments: Overlay::new(state, base_commitment), + pressures: Overlay::new(state, base_pressure), + kinds: BTreeSet::new(), + overlapping: BTreeSet::new(), + } + } + + // ---- Named reads ------------------------------------------------------- + + /// Whether the affordance kind is already named: by the catalog (its + /// `ByKind` index) or by this patch. + pub(super) fn kind_taken(&self, kind: &AffordanceKindName) -> bool { + self.kinds.contains(kind) || self.state.kind_taken(kind) + } + + /// Names a kind for this patch, reporting whether it was already taken. + pub(super) fn declare_kind(&mut self, kind: AffordanceKindName) -> bool { + let taken = self.kind_taken(&kind); + self.kinds.insert(kind); + taken + } + + /// Whether a subject in the world, retired or not, holds this import key + /// (the subjects' `ByImportKey` index). + pub(super) fn import_key_held(&self, key: &ImportKey) -> bool { + self.state.import_key_held(key) + } + + /// Every subject standing at or under a place: the committed subtree's + /// occupants (`under_place`) less every subject this patch gave a position + /// or took one from, plus the subjects whose written position the candidate + /// containment places under it. A written position can only be a draft + /// place's or a relocation's, so the committed subtree cannot hold it. + pub(super) fn occupants_under(&self, place: &Key<EntityId>) -> BTreeSet<Key<SubjectId>> { + let mut occupants: BTreeSet<Key<SubjectId>> = match place { + Key::Existing(root) => { + crate::under_place(self.state, *root).into_iter().map(Key::Existing).collect() + } + Key::Draft(_) => BTreeSet::new(), + }; + let written = self.positions.local(); + occupants.retain(|subject| !written.contains_key(subject)); + for (subject, standing) in written { + if let Some(standing) = standing + && self.covers(place, standing) + { + occupants.insert(subject.clone()); + } + } + occupants + } + + /// The offices of one institution: the committed row merged with the + /// patch's writes to its offices. + pub(super) fn offices_of( + &self, + institution: &Key<SubjectId>, + ) -> BTreeMap<OfficeName, OfficeCandidate> { + let mut offices = BTreeMap::new(); + if let Some(id) = existing(institution) + && let Some(committed) = self.state.selection.get(&id) + { + offices.extend( + committed.iter().map(|(name, office)| (name.clone(), office_candidate(office))), + ); + } + let from = (institution.clone(), OfficeName(String::new())); + for ((held_by, name), written) in self.selection.local().range(from..) { + if held_by != institution { + break; + } + match written { + Some(office) => { + offices.insert(name.clone(), office.clone()); + } + None => { + offices.remove(name); + } + } + } + offices + } + + /// Every office a subject holds, by (institution, name): the committed + /// offices it holds (`ByIncumbent`) unless the patch rewrote them, plus the + /// written offices that name it. + pub(super) fn offices_held_by( + &self, + holder: &Key<SubjectId>, + ) -> BTreeMap<(Key<SubjectId>, OfficeName), OfficeCandidate> { + let mut held = BTreeMap::new(); + let written = self.selection.local(); + if let Some(id) = existing(holder) { + for (_, institution) in self.state.selection.indexed(id..=id) { + for (name, office) in &self.state.selection[&institution] { + let slot = (Key::Existing(institution), name.clone()); + if office.incumbent == Some(id) && !written.contains_key(&slot) { + held.insert(slot, office_candidate(office)); + } + } + } + } + for (slot, office) in written { + if let Some(office) = office + && office.incumbent.as_ref() == Some(holder) + { + held.insert(slot.clone(), office.clone()); + } + } + held + } + + /// What a resource's total was and is: the sum over the holders the patch + /// wrote, before and after. Every other holder is on both sides of the + /// equation and cancels. + pub(super) fn custody(&self, resource: &Key<EntityId>) -> (u128, u128) { + let (mut before, mut after) = (0u128, 0u128); + for ((holder, held), written) in self.holdings.local() { + if held != resource { + continue; + } + let committed = base_holding(self.state, &(holder.clone(), held.clone())); + before += committed.map_or(0, |quantity| u128::from(quantity.0)); + after += written.map_or(0, |quantity| u128::from(quantity.0)); + } + (before, after) + } + + /// Whether `place` is `root`, or reaches it through the candidate container + /// chain. The walk is bounded by the graph size, so a cycle that does not + /// include either end still terminates. + pub(super) fn covers(&self, root: &Key<EntityId>, place: &Key<EntityId>) -> bool { + let bound = self.state.entities.len() + self.containers.local().len(); + let mut current = Some(place.clone()); + for _ in 0..=bound { + match current { + None => return false, + Some(node) if node == *root => return true, + Some(node) => current = self.containers.get(&node), + } + } + false + } + + /// Whether a place reaches itself through its container chain: the same + /// walk, started one link up so a place is not its own ancestor by + /// definition. + pub(super) fn contains_itself(&self, start: &Key<EntityId>) -> bool { + self.containers.get(start).is_some_and(|parent| self.covers(start, &parent)) + } + + /// Whether two jurisdictions of one kind cover common ground. Structural on + /// purpose: identity for named subordinates, containment for territory, and + /// never across the two, so the answer cannot decay when a subject walks + /// somewhere. Containment is fixed at declaration, so every way of creating + /// an overlap is a checked operation. + fn targets_overlap(&self, left: &AuthorityTargetKey, right: &AuthorityTargetKey) -> bool { + match (left, right) { + (AuthorityTargetKey::Subject(one), AuthorityTargetKey::Subject(other)) => one == other, + (AuthorityTargetKey::PlaceSubtree(one), AuthorityTargetKey::PlaceSubtree(other)) => { + self.covers(one, other) || self.covers(other, one) + } + _ => false, + } + } + + // ---- Authority, offices and retirement ---------------------------------- + + pub(super) fn grants_of(&self, holder: &Key<SubjectId>) -> BTreeSet<GrantKey> { + self.authority.get(holder).unwrap_or_default() + } + + pub(super) fn office(&self, slot: &(Key<SubjectId>, OfficeName)) -> Option<OfficeCandidate> { + self.selection.get(slot) + } + + pub(super) fn is_retired(&self, subject: &Key<SubjectId>) -> bool { + self.retired.contains_key(subject) + } + + /// Own grants plus what every held office lends, over the candidate graph. + /// A retired institution lends nothing, the same predicate + /// `delegated_authority` reads canonically: `Retire` does not vacate + /// offices, so the resolver and the kernel must not disagree about whether + /// a dead institution's grants still reach its office-holders. + pub(super) fn effective_authority(&self, holder: &Key<SubjectId>) -> BTreeSet<GrantKey> { + let mut effective = self.grants_of(holder); + for ((institution, _), office) in self.offices_held_by(holder) { + if self.is_retired(&institution) { + continue; + } + for grant in self.grants_of(&institution) { + if office.delegated.contains(&grant.kind) { + effective.insert(grant); + } + } + } + effective + } + + /// Whether any holder in the candidate graph holds two grants of one kind + /// over overlapping ground, from any combination of direct grant and office + /// delegation. + pub(super) fn overlapping(&self) -> bool { + !self.overlapping.is_empty() + } + + /// Replaces a subject's own grants; an empty set removes the row. + pub(super) fn set_grants(&mut self, holder: Key<SubjectId>, grants: BTreeSet<GrantKey>) { + if grants.is_empty() { + self.authority.remove(&holder); + } else { + self.authority.insert(holder.clone(), grants); + } + // An institution's grants reach its office-holders. + let mut affected = self.incumbents_of(&holder); + affected.insert(holder); + self.rejudge(affected); + } + + /// Writes one office, or closes it (`None`). + pub(super) fn set_office( + &mut self, + slot: (Key<SubjectId>, OfficeName), + office: Option<OfficeCandidate>, + ) { + let mut affected = BTreeSet::new(); + affected.extend(self.selection.get(&slot).and_then(|old| old.incumbent)); + affected.extend(office.iter().filter_map(|new| new.incumbent.clone())); + match office { + Some(office) => self.selection.insert(slot, office), + None => { + self.selection.remove(&slot); + } + } + self.rejudge(affected); + } + + /// Marks a subject retired. A retired institution lends nothing, so its + /// office-holders are judged again. + pub(super) fn retire(&mut self, subject: Key<SubjectId>) { + self.retired.insert(subject.clone(), ()); + let affected = self.incumbents_of(&subject); + self.rejudge(affected); + } + + fn incumbents_of(&self, institution: &Key<SubjectId>) -> BTreeSet<Key<SubjectId>> { + self.offices_of(institution).into_values().filter_map(|office| office.incumbent).collect() + } + + fn rejudge(&mut self, holders: BTreeSet<Key<SubjectId>>) { + for holder in holders { + let effective: Vec<GrantKey> = self.effective_authority(&holder).into_iter().collect(); + let overlaps = effective.iter().enumerate().any(|(index, one)| { + effective[index + 1..].iter().any(|other| { + one.kind == other.kind && self.targets_overlap(&one.over, &other.over) + }) + }); + if overlaps { + self.overlapping.insert(holder); + } else { + self.overlapping.remove(&holder); + } + } + } + + /// Whether `subject` stands in the audience, over the candidate graph: the + /// same question `audience()` answers over committed state, asked before + /// any ID is minted. A controller is inside its own channel's audience for + /// the purpose of speaking on it: the horn belongs to the temple. + pub(super) fn in_audience( + &self, + subject: &Key<SubjectId>, + audience: &AudienceKey, + speaker: &Key<SubjectId>, + ) -> bool { + match audience { + AudienceKey::Colocated => { + match (self.positions.get(speaker), self.positions.get(subject)) { + (Some(here), Some(there)) => here == there, + _ => false, + } + } + AudienceKey::Channel(channel) => { + let Some(record) = self.channels.get(channel) else { + return false; + }; + if record.controller.as_ref() == Some(subject) { + return true; + } + match &record.reach { + ReachKey::Subjects(members) => members.contains(subject), + ReachKey::Place(root) => self + .positions + .get(subject) + .is_some_and(|place| self.covers(root, &place)), + } + } + } + } +} + +/// The reference the overlays are measured against, in test builds only: the +/// candidate graph as it was before overlays, every partition copied into a map +/// and every read a scan of those maps. +#[cfg(test)] +pub(super) struct Materialized { + pub(super) containers: BTreeMap<Key<EntityId>, Key<EntityId>>, + pub(super) routes: BTreeMap<Key<EdgeId>, RouteCandidate>, + pub(super) positions: BTreeMap<Key<SubjectId>, Key<EntityId>>, + pub(super) holdings: BTreeMap<(Key<SubjectId>, Key<EntityId>), Quantity>, + pub(super) dependencies: BTreeSet<(Key<SubjectId>, TargetKey)>, + pub(super) authority: BTreeMap<Key<SubjectId>, BTreeSet<GrantKey>>, + pub(super) selection: BTreeMap<(Key<SubjectId>, OfficeName), OfficeCandidate>, + pub(super) redress: BTreeMap<GrievanceKindName, (Key<SubjectId>, AuthorityTargetKey)>, + pub(super) facts: BTreeMap<Key<EntityId>, FactCandidate>, + pub(super) retired: BTreeSet<Key<SubjectId>>, + pub(super) affordance_holdings: BTreeMap<Key<SubjectId>, BTreeSet<Key<AffordanceId>>>, + pub(super) channels: BTreeMap<Key<EntityId>, ChannelCandidate>, + pub(super) knowledge: BTreeMap<(Key<SubjectId>, Key<EntityId>), KnowledgeCandidate>, + pub(super) commitments: BTreeSet<(Key<SubjectId>, CommitmentKey)>, + pub(super) pressures: BTreeMap<(Key<SubjectId>, PressureSourceKey), u32>, +} + +#[cfg(test)] +fn apply_written<K: Ord + Clone, V: Clone>(map: &mut BTreeMap<K, V>, local: &BTreeMap<K, Option<V>>) { + for (key, written) in local { + match written { + Some(value) => { + map.insert(key.clone(), value.clone()); + } + None => { + map.remove(key); + } + } + } +} + +#[cfg(test)] +fn apply_written_set<K: Ord + Clone>(set: &mut BTreeSet<K>, local: &BTreeMap<K, Option<()>>) { + for (key, written) in local { + if written.is_some() { + set.insert(key.clone()); + } else { + set.remove(key); + } + } +} + +#[cfg(test)] +impl Materialized { + /// The committed world copied whole: what the resolver seeded its candidate + /// maps with, moved here as the reference. + pub(super) fn seeded(state: &WorldState) -> Self { + let containers: BTreeMap<Key<EntityId>, Key<EntityId>> = state + .entities + .iter() + .filter_map(|(entity_id, record)| { + record + .container + .map(|container| (Key::Existing(*entity_id), Key::Existing(container))) + }) + .collect(); + let routes: BTreeMap<Key<EdgeId>, RouteCandidate> = state + .edges + .iter() + .map(|(edge_id, record)| { + let (from, to) = record.endpoints(); + ( + Key::Existing(*edge_id), + RouteCandidate { + from: Key::Existing(from), + to: Key::Existing(to), + access: record.access().clone(), + cost: record.cost(), + open: record.is_open(), + }, + ) + }) + .collect(); + let positions: BTreeMap<Key<SubjectId>, Key<EntityId>> = state + .positions + .iter() + .map(|(subject_id, position)| (Key::Existing(*subject_id), Key::Existing(position.place))) + .collect(); + let holdings: BTreeMap<(Key<SubjectId>, Key<EntityId>), Quantity> = state + .holdings + .iter() + .flat_map(|(subject_id, held)| { + held.iter().map(move |(entity_id, quantity)| { + ( + (Key::Existing(*subject_id), Key::Existing(*entity_id)), + *quantity, + ) + }) + }) + .collect(); + let dependencies: BTreeSet<(Key<SubjectId>, TargetKey)> = state + .dependencies + .iter() + .flat_map(|(subject_id, bound)| { + bound.iter().map(move |target| { + ( + Key::Existing(*subject_id), + match target { + DependencyTarget::Resource(id) => TargetKey::Resource(Key::Existing(*id)), + DependencyTarget::Route(id) => TargetKey::Route(Key::Existing(*id)), + DependencyTarget::Subject(id) => TargetKey::Subject(Key::Existing(*id)), + }, + ) + }) + }) + .collect(); + let authority: BTreeMap<Key<SubjectId>, BTreeSet<GrantKey>> = state + .authority + .iter() + .map(|(subject_id, grants)| { + ( + Key::Existing(*subject_id), + grants.iter().map(grant_key_of).collect(), + ) + }) + .collect(); + let selection: BTreeMap<(Key<SubjectId>, OfficeName), OfficeCandidate> = state + .selection + .iter() + .flat_map(|(institution, offices)| { + offices.iter().map(move |(name, office)| { + ( + (Key::Existing(*institution), name.clone()), + OfficeCandidate { + incumbent: office.incumbent.map(Key::Existing), + delegated: office.delegated.clone(), + }, + ) + }) + }) + .collect(); + let redress: BTreeMap<GrievanceKindName, (Key<SubjectId>, AuthorityTargetKey)> = state + .redress + .iter() + .map(|(grievance, forum)| { + ( + grievance.clone(), + (Key::Existing(forum.forum), target_key_of(forum.standing)), + ) + }) + .collect(); + let facts: BTreeMap<Key<EntityId>, FactCandidate> = state + .facts + .iter() + .map(|(entity_id, record)| { + ( + Key::Existing(*entity_id), + match &record.standing { + crate::FactStanding::Canonical { .. } => FactCandidate::Canonical, + crate::FactStanding::Claimed { by } => FactCandidate::Claimed(Key::Existing(*by)), + crate::FactStanding::Ruled => FactCandidate::Ruled, + }, + ) + }) + .collect(); + // `Retire` and the affordance grant operations read and write these + // candidates. `retired` seeds from the committed subject rows: a declared subject is always + // fresh and unretired, so drafts start out of the set. `affordance_holdings` + // seeds from committed `affordance_grants` and is extended below for a + // subject this same patch declares. + let retired: BTreeSet<Key<SubjectId>> = state + .subjects + .keys() + .filter(|subject_id| crate::is_retired(state, **subject_id)) + .map(|subject_id| Key::Existing(*subject_id)) + .collect(); + let affordance_holdings: BTreeMap<Key<SubjectId>, BTreeSet<Key<AffordanceId>>> = state + .affordance_grants + .iter() + .map(|(subject_id, granted)| { + ( + Key::Existing(*subject_id), + granted.iter().map(|id| Key::Existing(*id)).collect(), + ) + }) + .collect(); + let channels: BTreeMap<Key<EntityId>, ChannelCandidate> = state + .channels + .iter() + .map(|(entity_id, record)| { + ( + Key::Existing(*entity_id), + ChannelCandidate { + reach: match &record.reach { + Reach::Subjects(members) => { + ReachKey::Subjects(members.iter().copied().map(Key::Existing).collect()) + } + Reach::Place(place) => ReachKey::Place(Key::Existing(*place)), + }, + controller: record.controller.map(Key::Existing), + }, + ) + }) + .collect(); + // Keys and payload, so an `AcquireKnowledge` that changes nothing is + // `NoOperationEffect` before any ID is minted. `Witness` is modelled here + // too: its landing is a subtree of `positions`, both maps are candidate + // maps, and so the fan-out it will perform at apply is derivable now — a + // subject this patch relocated into the subtree counts, and a witness that + // reaches nobody is refused at resolve exactly as `apply_operation` + // refuses it. + // + // `Communicate` never enters, and the difference is not scale. A telling is + // an act whose occurrence does not depend on its reception: its empty + // fan-out is legal, so there is nothing for this map to refuse and no + // refusal for it to predict. A witnessed event is only its reception, so + // its landing is its legality. + // + // Neither operation can write `Told`. This map can represent a `Told` + // entry, but no `ComponentOp` can construct one: `AcquireKnowledge` takes + // an `AuthoredSource`, `Witness` takes no source at all, and neither type + // has a `Told` variant — + // `action::no_component_op_kind_lowers_to_a_told_knowledge_write` pins both + // lowering sites that could otherwise drift. If a future operation is ever + // given the power to write `Told` directly — bypassing `Communicate`'s own + // apply-time fan-out — it must model that fan-out into this candidate graph + // first, or `resolve_patch` will silently reason about a knowledge state + // the apply pass will not produce. + let knowledge: BTreeMap<(Key<SubjectId>, Key<EntityId>), KnowledgeCandidate> = state + .knowledge + .iter() + .map(|((subject_id, fact), entry)| { + ( + (Key::Existing(*subject_id), Key::Existing(*fact)), + KnowledgeCandidate { + confidence: entry.confidence, + source: match entry.source { + KnowledgeSource::Witnessed => KnowledgeSourceKey::Witnessed, + KnowledgeSource::Evidenced => KnowledgeSourceKey::Evidenced, + KnowledgeSource::Told { by, via } => KnowledgeSourceKey::Told { + by: Key::Existing(by), + via: via.map(Key::Existing), + }, + KnowledgeSource::Seen { by } => KnowledgeSourceKey::Seen { + by: Key::Existing(by), + }, + }, + }, + ) + }) + .collect(); + // Presence is all a discharge asks, and a create cannot collide: the key is + // command-derived and the index is unique within one patch. + let commitments: BTreeSet<(Key<SubjectId>, CommitmentKey)> = state + .commitments + .iter() + .flat_map(|(subject_id, held)| { + held.keys() + .map(move |key| (Key::Existing(*subject_id), *key)) + }) + .collect(); + let pressures: BTreeMap<(Key<SubjectId>, PressureSourceKey), u32> = state + .pressures + .iter() + .flat_map(|(target, held)| { + held.iter().map(move |(source, magnitude)| { + ( + ( + Key::Existing(*target), + match source { + PressureSource::Commitment { subject, key } => { + PressureSourceKey::Commitment { + subject: Key::Existing(*subject), + key: *key, + } + } + PressureSource::Dependency(DependencyTarget::Resource(entity_id)) => { + PressureSourceKey::Dependency(TargetKey::Resource(Key::Existing( + *entity_id, + ))) + } + PressureSource::Dependency(DependencyTarget::Route(edge_id)) => { + PressureSourceKey::Dependency(TargetKey::Route(Key::Existing( + *edge_id, + ))) + } + PressureSource::Dependency(DependencyTarget::Subject(subject_id)) => { + PressureSourceKey::Dependency(TargetKey::Subject(Key::Existing( + *subject_id, + ))) + } + PressureSource::Subject(subject_id) => { + PressureSourceKey::Subject(Key::Existing(*subject_id)) + } + }, + ), + magnitude.0, + ) + }) + }) + .collect(); + Self { + containers, + routes, + positions, + holdings, + dependencies, + authority, + selection, + redress, + facts, + retired, + affordance_holdings, + channels, + knowledge, + commitments, + pressures, + } + } + + /// Whether `place` is `root`, or reaches it through the container chain. + pub(super) fn covers(&self, root: &Key<EntityId>, place: &Key<EntityId>) -> bool { + let mut current = Some(place); + for _ in 0..=self.containers.len() { + match current { + None => return false, + Some(node) if node == root => return true, + Some(node) => current = self.containers.get(node), + } + } + false + } + + fn targets_overlap(&self, left: &AuthorityTargetKey, right: &AuthorityTargetKey) -> bool { + match (left, right) { + (AuthorityTargetKey::Subject(one), AuthorityTargetKey::Subject(other)) => one == other, + (AuthorityTargetKey::PlaceSubtree(one), AuthorityTargetKey::PlaceSubtree(other)) => { + self.covers(one, other) || self.covers(other, one) + } + _ => false, + } + } + + /// Every subject whose position the container chain puts under `place`. + pub(super) fn occupants_under(&self, place: &Key<EntityId>) -> BTreeSet<Key<SubjectId>> { + self.positions + .iter() + .filter(|(_, standing)| self.covers(place, standing)) + .map(|(subject, _)| subject.clone()) + .collect() + } + + pub(super) fn offices_of( + &self, + institution: &Key<SubjectId>, + ) -> BTreeMap<OfficeName, OfficeCandidate> { + self.selection + .iter() + .filter(|((held_by, _), _)| held_by == institution) + .map(|((_, name), office)| (name.clone(), office.clone())) + .collect() + } + + pub(super) fn offices_held_by( + &self, + holder: &Key<SubjectId>, + ) -> BTreeMap<(Key<SubjectId>, OfficeName), OfficeCandidate> { + self.selection + .iter() + .filter(|(_, office)| office.incumbent.as_ref() == Some(holder)) + .map(|(slot, office)| (slot.clone(), office.clone())) + .collect() + } + + /// Own grants plus what every held office lends, walking every office. + pub(super) fn effective_authority(&self, holder: &Key<SubjectId>) -> BTreeSet<GrantKey> { + let mut effective = self.authority.get(holder).cloned().unwrap_or_default(); + for ((institution, _), office) in &self.selection { + if office.incumbent.as_ref() != Some(holder) || self.retired.contains(institution) { + continue; + } + for grant in self.authority.get(institution).into_iter().flatten() { + if office.delegated.contains(&grant.kind) { + effective.insert(grant.clone()); + } + } + } + effective + } + + /// Every holder in the graph with two grants of one kind over overlapping + /// ground, from any combination of direct grant and office delegation. + pub(super) fn overlapping_holders(&self) -> BTreeSet<Key<SubjectId>> { + let holders: BTreeSet<&Key<SubjectId>> = self + .authority + .keys() + .chain(self.selection.values().filter_map(|office| office.incumbent.as_ref())) + .collect(); + holders + .into_iter() + .filter(|holder| { + let effective: Vec<GrantKey> = + self.effective_authority(holder).into_iter().collect(); + effective.iter().enumerate().any(|(index, one)| { + effective[index + 1..].iter().any(|other| { + one.kind == other.kind && self.targets_overlap(&one.over, &other.over) + }) + }) + }) + .cloned() + .collect() + } + + /// What a resource's holders hold in all. + pub(super) fn total(&self, resource: &Key<EntityId>) -> u128 { + self.holdings + .iter() + .filter(|((_, held), _)| held == resource) + .map(|(_, quantity)| u128::from(quantity.0)) + .sum() + } +} + +#[cfg(test)] +impl Candidate<'_> { + /// Every candidate map, in full: the committed world with the patch's writes + /// applied. The named reads must equal scans of it. + pub(super) fn materialized(&self) -> Materialized { + let mut all = Materialized::seeded(self.state); + apply_written(&mut all.containers, self.containers.local()); + apply_written(&mut all.routes, self.routes.local()); + apply_written(&mut all.positions, self.positions.local()); + apply_written(&mut all.holdings, self.holdings.local()); + apply_written_set(&mut all.dependencies, self.dependencies.local()); + apply_written(&mut all.authority, self.authority.local()); + apply_written(&mut all.selection, self.selection.local()); + apply_written(&mut all.redress, self.redress.local()); + apply_written(&mut all.facts, self.facts.local()); + apply_written_set(&mut all.retired, self.retired.local()); + apply_written(&mut all.affordance_holdings, self.affordance_holdings.local()); + apply_written(&mut all.channels, self.channels.local()); + apply_written(&mut all.knowledge, self.knowledge.local()); + apply_written_set(&mut all.commitments, self.commitments.local()); + apply_written(&mut all.pressures, self.pressures.local()); + all + } + + /// The holders the running judgement holds as overlapping. + pub(super) fn overlapping_holders(&self) -> &BTreeSet<Key<SubjectId>> { + &self.overlapping + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::patch::DraftHandle; + use crate::tests::{ + BAILIFF_OFFICE, LEVY_KIND, WARDEN_OFFICE, auth_principal, authority_kind, civic_world, + creation, office, operations, owner, reject_play, + }; + use crate::{Mismatch, WorldKernel}; + + fn civic_kernel(title: &str) -> (WorldKernel, crate::tests::Topology, crate::tests::Civic) { + let (mut kernel, _) = WorldKernel::create(creation(title), &auth_principal(owner())).unwrap(); + let (topology, civic, _) = civic_world(&mut kernel); + (kernel, topology, civic) + } + + fn levy_over(place: Key<EntityId>) -> GrantKey { + GrantKey { kind: authority_kind(LEVY_KIND), over: AuthorityTargetKey::PlaceSubtree(place) } + } + + /// Every named read, asked of the overlay and of a scan of the materialized + /// maps, must agree. + fn agrees( + graph: &Candidate<'_>, + label: &str, + places: &[Key<EntityId>], + holders: &[Key<SubjectId>], + resource: &Key<EntityId>, + ) { + let all = graph.materialized(); + for place in places { + assert_eq!(graph.occupants_under(place), all.occupants_under(place), "{label}: under {place:?}"); + } + for holder in holders { + assert_eq!(graph.offices_of(holder), all.offices_of(holder), "{label}: offices of {holder:?}"); + assert_eq!( + graph.offices_held_by(holder), + all.offices_held_by(holder), + "{label}: offices held by {holder:?}" + ); + assert_eq!( + graph.effective_authority(holder), + all.effective_authority(holder), + "{label}: authority of {holder:?}" + ); + } + let overlapping = all.overlapping_holders(); + assert_eq!(graph.overlapping_holders(), &overlapping, "{label}: who overlaps"); + assert_eq!(graph.overlapping(), !overlapping.is_empty(), "{label}: whether anyone overlaps"); + // The written holders' sums stand in for the totals: every other holder + // is on both sides, so the two differ by the same amount. + let (before, after) = graph.custody(resource); + let seeded = Materialized::seeded(graph.state).total(resource); + assert_eq!( + after as i128 - before as i128, + all.total(resource) as i128 - seeded as i128, + "{label}: custody" + ); + for kind in ["speak", "levy", "novel"] { + let kind = AffordanceKindName(kind.into()); + assert_eq!( + graph.kind_taken(&kind), + crate::kind_taken_by_scan(graph.state, &kind) || graph.kinds.contains(&kind), + "{label}: kind {kind:?}" + ); + } + } + + /// The patch walks the places the clockwork rules care about: a subject + /// leaving and entering a subtree, a declared place and a declared subject + /// in it, a retirement, a vacated and refilled office, a grant that + /// overlaps what an office lends and its revocation, the retirement of the + /// lending institution, a declared institution, and custody written both + /// ways. After every step each named read equals a scan of the maps the + /// patch would have copied. + #[test] + fn candidate_reads_equal_materialized_scans() { + let (kernel, topology, civic) = civic_kernel("Candidate"); + let state = &kernel.state; + let (hall, chamber, road) = + (Key::Existing(civic.hall), Key::Existing(civic.chamber), Key::Existing(topology.road)); + let (treasury, reeve, farmer, outsider) = ( + Key::Existing(civic.treasury), + Key::Existing(civic.reeve), + Key::Existing(civic.farmer), + Key::Existing(civic.outsider), + ); + let grain = Key::Existing(civic.grain); + let annex: Key<EntityId> = Key::Draft(DraftHandle::new("annex")); + let scribe: Key<SubjectId> = Key::Draft(DraftHandle::new("scribe")); + let ministry: Key<SubjectId> = Key::Draft(DraftHandle::new("ministry")); + let places = [hall.clone(), chamber.clone(), road.clone(), annex.clone()]; + let holders = + [treasury.clone(), reeve.clone(), farmer.clone(), outsider.clone(), scribe.clone(), ministry.clone()]; + let check = |graph: &Candidate<'_>, label: &str| agrees(graph, label, &places, &holders, &grain); + + let mut graph = Candidate::new(state); + check(&graph, "untouched"); + assert!(!graph.overlapping() && graph.offices_held_by(&reeve).len() == 1); + assert_eq!( + graph.occupants_under(&hall).len(), + 3, + "the treasury, the reeve and the farmer stand under the hall" + ); + + graph.positions.insert(farmer.clone(), road.clone()); + check(&graph, "a subject leaves the subtree"); + assert!(!graph.occupants_under(&hall).contains(&farmer)); + + graph.positions.insert(outsider.clone(), chamber.clone()); + check(&graph, "a subject enters the subtree"); + assert!(graph.occupants_under(&hall).contains(&outsider)); + + graph.containers.insert(annex.clone(), chamber.clone()); + graph.positions.insert(scribe.clone(), annex.clone()); + check(&graph, "a declared place holds a declared subject"); + assert!(graph.occupants_under(&hall).contains(&scribe)); + assert_eq!(graph.occupants_under(&annex), BTreeSet::from([scribe.clone()])); + + graph.retire(farmer.clone()); + graph.positions.remove(&farmer); + check(&graph, "a subject is retired"); + assert!(!graph.occupants_under(&road).contains(&farmer)); + + let warden = (treasury.clone(), office(WARDEN_OFFICE)); + let seat = graph.office(&warden).expect("the treasury opens a warden office"); + graph.set_office(warden.clone(), Some(OfficeCandidate { incumbent: None, ..seat.clone() })); + check(&graph, "the warden office is vacated"); + assert!(graph.offices_held_by(&reeve).is_empty()); + graph.set_office(warden.clone(), Some(OfficeCandidate { incumbent: Some(outsider.clone()), ..seat })); + check(&graph, "the warden office is refilled"); + assert_eq!(graph.offices_held_by(&outsider).len(), 1); + assert_eq!(graph.offices_of(&treasury).len(), 2); + + // The outsider now holds levy over the hall through the office; a levy + // over the chamber of their own overlaps it. + graph.set_grants(outsider.clone(), BTreeSet::from([levy_over(chamber.clone())])); + check(&graph, "an overlapping grant"); + assert_eq!(graph.overlapping_holders(), &BTreeSet::from([outsider.clone()])); + graph.set_grants(outsider.clone(), BTreeSet::new()); + check(&graph, "the grant is revoked"); + assert!(!graph.overlapping()); + graph.set_grants(outsider.clone(), BTreeSet::from([levy_over(chamber.clone())])); + assert!(graph.overlapping()); + graph.retire(treasury.clone()); + check(&graph, "the lending institution is retired"); + assert!(!graph.overlapping(), "a retired institution lends nothing"); + + // A declared institution lends a declared place to a declared subject. + graph.set_grants(ministry.clone(), BTreeSet::from([levy_over(annex.clone())])); + let seat = (ministry.clone(), office("reeve")); + graph.set_office( + seat.clone(), + Some(OfficeCandidate { + incumbent: Some(scribe.clone()), + delegated: BTreeSet::from([authority_kind(LEVY_KIND)]), + }), + ); + check(&graph, "a declared institution seats a declared subject"); + assert_eq!(graph.effective_authority(&scribe), BTreeSet::from([levy_over(annex.clone())])); + graph.set_grants(scribe.clone(), BTreeSet::from([levy_over(chamber.clone())])); + check(&graph, "the declared subject's own grant covers the lent place"); + assert_eq!(graph.overlapping_holders(), &BTreeSet::from([scribe.clone()])); + graph.set_office(seat, None); + check(&graph, "the office is closed"); + assert!(!graph.overlapping()); + + // Custody, written both ways: the farmer's grain goes, the scribe's comes. + graph.holdings.insert((farmer.clone(), grain.clone()), Quantity(2)); + graph.holdings.insert((scribe.clone(), grain.clone()), Quantity(5)); + graph.holdings.remove(&(outsider.clone(), grain.clone())); + check(&graph, "custody is rewritten"); + assert_eq!(graph.custody(&grain), (14, 7), "two of seven, five of none, and none of seven"); + + assert!(!graph.declare_kind(AffordanceKindName("novel".into()))); + assert!(graph.declare_kind(AffordanceKindName("novel".into())), "a kind is named once"); + assert!(graph.declare_kind(AffordanceKindName("speak".into())), "the catalog names speak"); + check(&graph, "kinds"); + } + + /// An overlay nobody has written reads exactly the partition the old seeding + /// copied, key for key, in every world that holds a document in some + /// partition; and a draft key, or an id nothing holds, reads as absent. + #[test] + fn an_untouched_overlay_reads_what_the_seeding_copied() { + let worlds = crate::golden_tests::populated_worlds(); + for state in &worlds { + let graph = Candidate::new(state); + let all = Materialized::seeded(state); + macro_rules! same { + ($($map:ident),*) => {$( + for (key, value) in &all.$map { + assert_eq!( + format!("{:?}", graph.$map.get(key)), + format!("{:?}", Some(value)), + stringify!($map) + ); + } + )*}; + } + macro_rules! same_set { + ($($map:ident),*) => {$( + for key in &all.$map { + assert!(graph.$map.contains_key(key), stringify!($map)); + } + )*}; + } + same!(containers, routes, positions, holdings, redress, facts, affordance_holdings, channels, knowledge, pressures); + same_set!(dependencies, commitments); + for (key, value) in &all.authority { + assert_eq!(&graph.grants_of(key), value); + } + for (slot, value) in &all.selection { + assert_eq!(graph.office(slot).as_ref(), Some(value)); + } + for key in &all.retired { + assert!(graph.is_retired(key)); + } + let nobody: Key<SubjectId> = Key::Existing(SubjectId::issue()); + let nowhere: Key<EntityId> = Key::Existing(EntityId::issue()); + let drafted: Key<SubjectId> = Key::Draft(DraftHandle::new("drafted")); + assert!(graph.positions.get(&nobody).is_none() && graph.positions.get(&drafted).is_none()); + assert!(graph.containers.get(&nowhere).is_none()); + assert!(graph.grants_of(&nobody).is_empty() && !graph.is_retired(&drafted)); + assert!(graph.office(&(nobody, office(WARDEN_OFFICE))).is_none()); + assert!(graph.occupants_under(&nowhere).is_empty()); + assert_eq!(graph.effective_authority(&drafted), BTreeSet::new()); + } + } + + /// The first overlap of a patch is named at the operation that made it, and + /// every later widening operation is named too while it stands; a revoke + /// that clears it makes the later widening operation clean. + #[test] + fn overlap_mismatches_are_unchanged() { + let (mut kernel, _, civic) = civic_kernel("Overlaps"); + let snapshot = kernel.snapshot().unwrap(); + let grant = |holder: SubjectId| crate::ComponentOp::GrantAuthority { + holder: crate::Ref::Existing(holder), + grant: crate::AuthorityGrantRef { + kind: authority_kind(LEVY_KIND), + over: crate::AuthorityTargetRef::PlaceSubtree(crate::Ref::Existing(civic.chamber)), + }, + }; + let revoke = |holder: SubjectId| match grant(holder) { + crate::ComponentOp::GrantAuthority { holder, grant } => { + crate::ComponentOp::RevokeAuthority { holder, grant } + } + other => other, + }; + let seat = crate::ComponentOp::InstallIncumbent { + institution: crate::Ref::Existing(civic.treasury), + office: office(BAILIFF_OFFICE), + incumbent: crate::Ref::Existing(civic.farmer), + }; + let at = |operation: usize| Mismatch::OverlappingJurisdiction { operation }; + + // The reeve holds the warden's levy over the hall, so a levy over the + // chamber of the reeve's own overlaps it, and the seating that follows + // still sees an overlap standing. + let both = reject_play( + &mut kernel, + &snapshot, + operations(vec![grant(civic.reeve), seat.clone()]), + ); + assert_eq!(both, vec![at(0), at(1)]); + + let cleared = reject_play( + &mut kernel, + &snapshot, + operations(vec![grant(civic.reeve), revoke(civic.reeve), seat]), + ); + assert_eq!(cleared, vec![at(0)]); + } +} From aac972260f2c49ac786dee21c79d9b69301f6871 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 13:49:33 +0100 Subject: [PATCH 185/190] aetherlight: gate the patch lane's read work, and record the cut patch_read_work_is_equal_at_100_and_1600 submits ten patch shapes through AdmitPatch and holds their rows read equal at 100, 400 and 1600 persons. The DischargeCommitment case that called apply_operation directly moves into it. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/PROVENANCE.md | 70 +++++++ native/aetherlight/src/golden_tests.rs | 258 +++++++++++++++++++++---- 2 files changed, 286 insertions(+), 42 deletions(-) diff --git a/native/aetherlight/PROVENANCE.md b/native/aetherlight/PROVENANCE.md index 5aba5ac0f..d0cbdd073 100644 --- a/native/aetherlight/PROVENANCE.md +++ b/native/aetherlight/PROVENANCE.md @@ -544,3 +544,73 @@ cost is inherent to pressing and is not a read of the world. `open` of a large world is superlinear in rows from readers outside this cut (the resolver's reads of the whole world at genesis, owner `aetherlight-resolver-reads-world`); `open_cost` reports it. + +## Cut AL3d-1: the patch lane reads what the patch touches + +Authority: cut `aetherlight-resolver-reads-world` r1 of campaign +`aetheria-release`; rulings `cultnet-scale-is-not-negotiable`, +`aetherlight-narrative-state-owner`, `terminus-clockwork-world`, +`dialogue-is-world-action`. Base `609b3ba5e`. No digested byte moves: +`fixtures/golden.digests` is identical at every commit of the cut. + +`resolve_patch` used to seed fifteen candidate maps by copying every partition, +collect every catalog kind and every subject's import key into sets, and re-judge +every holder for overlap after each widening operation. Its reads grew with the +world: 936, 3696 and 14736 rows for one `DischargeCommitment` at 100, 400 and 1600 +persons, and 14,000 or more for every other shape. It now reads what the patch +touches. + +`patch/candidate.rs` owns the candidate graph of one resolution. Each candidate map +is an `Overlay`: the committed partition read through a base function (a point get; +a `Key::Draft` key has none), and the patch's writes in a local map. `Candidate` +holds the fifteen overlays and the named reads, each bounded by what the patch +wrote plus what it returns: `occupants_under` (`under_place` over `ChildOf` and +`StandsAt`, corrected by the written positions), `offices_of` and `offices_held_by` +(the committed row or `ByIncumbent`, corrected by the written offices), `kind_taken` +(`ByKind` on the catalog) and `import_key_held` (`ByImportKey` on the subjects), +`custody` (the sums over the written holders only: every other holder is on both +sides of the equation and cancels). `authority`, `selection` and `retired` are +private to the module: a write goes through `set_grants`, `set_office` or `retire`, +which re-judge the holders whose effective authority it can change (the holder and +an institution's incumbents; an office's old and new incumbent) and keep +`overlapping`, the set of holders with two grants of one kind over overlapping +ground. A widening operation is `OverlappingJurisdiction` exactly when the set is +non-empty. That is what `graph_overlaps` answered, because the committed world is +disjoint (every commit checks it and opening a world verifies it), so only a holder +the patch touched can enter the set. The mismatch list is unchanged, including the +later widening operations after a first overlap and a revoke that clears it +(`overlap_mismatches_are_unchanged`). The candidate lives for one `resolve_patch` +call and is never written back; `admit_resolved` stays the only writer of the +ontology partitions. + +`apply_operations` derives its two checks from the transaction's log. Conservation +sums the holders `holdings` logged as changed, each from its value when the +operations began (so a holder already written by the declarations above it is +measured from there). Disjointness judges only the holders whose grants, offices or +institution the transaction touched, through `holder_overlaps`, which +`overlapping_holder` also calls for the open-time whole-world check +(`verify_state_shape`, whole-world on purpose). `resource_total` survives only as +the test reference `resource_total_by_scan`. + +Two partitions gained read indexes, `subjects` by `ByImportKey` and +`affordance_catalog` by `ByKind`, so `held_import_keys` and the per-patch kind set +are gone and `import_key_fault` asks a predicate. + +The seeding block, `graph_overlaps`, the old effective-authority walk and +`key_covers_place` live on only as `cfg(test)` references (`Materialized`, whose +`seeded` is the old block verbatim). `candidate_reads_equal_materialized_scans` +walks a civic world through the shapes that move each read (a subject leaving and +entering a subtree, a declared place and subject, a retirement, a vacated and +refilled office, an overlapping grant and its revocation, the retirement of the +lending institution, a declared institution, custody written both ways) and holds +every named read and the overlap set to the scan after every step; +`an_untouched_overlay_reads_what_the_seeding_copied` holds every base function to +the copy in each populated world. The gate is +`golden_tests::patch_read_work_is_equal_at_100_and_1600`: ten patch shapes through +`AdmitPatch` read the same rows at 100, 400 and 1600 persons (at most 21 each), +and `apply_checks_read_the_log` pins the commit lane's two checks. The +`DischargeCommitment` case of `operation_reads_are_equal_at_100_and_1600`, which +called `apply_operation` directly, moved into the gate. + +Reads that still scan: `snapshot` (follow-up `aetherlight-snapshot-history-fold`) +and `verify_state_shape` at open, by design. diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs index 2d91d55a5..fa929271f 100644 --- a/native/aetherlight/src/golden_tests.rs +++ b/native/aetherlight/src/golden_tests.rs @@ -1041,16 +1041,224 @@ fn read_work_is_equal_at_100_and_1600() { assert_eq!(worked[0], worked[1], "read work grew with the world"); } -/// The reads a clockwork submit does not reach, inside one open transaction -/// each: who stands under a two-level subtree, discharging a commitment while -/// the world holds N pressure rows from other sources, one incumbent's -/// delegated authority, and a path of three routes. (An `AdmitPatch` resolves -/// against the whole world until follow-up `aetherlight-resolver-reads-world`, -/// so no submit shape reaches these.) +/// What a patch reads is what it touches, not what the world holds: ten patch +/// shapes, each submitted through `AdmitPatch` (resolution against the +/// candidate graph, the reducer, and the commit's own checks), read the same +/// number of rows at 100, 400 and 1600 persons (some read none: point reads are +/// not rows). The count is taken where reads +/// are owned (`Docs`), so a resolver arm that copies a partition, collects keys +/// from every subject, sums a resource over every holder, or judges every holder +/// for overlap cannot hide from it. The shapes run in order on one world, so +/// each leaves the world the next one reads. +#[test] +fn patch_read_work_is_equal_at_100_and_1600() { + use crate::patch::{ + AuthorityGrantRef, AuthorityTargetRef, AuthoredSource, DependencyRef, FactDeclaration, + FactStandingRef, PressureMagnitude, PressureSourceRef, Quantity, SubjectDeclaration, + }; + use crate::tests::{LEVY_KIND, WARDEN_OFFICE, authority_kind, office}; + use crate::{Confidence, ImportKey, SubjectKind}; + use std::collections::BTreeSet; + + let mut shapes: Vec<&'static str> = Vec::new(); + let mut worked: Vec<Vec<u64>> = Vec::new(); + for persons in [100usize, 400, 1600] { + let (mut kernel, people, _) = clockwork_world(persons); + let label = |kernel: &WorldKernel, label: &str| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .unwrap_or_else(|| panic!("{label} is declared")) + .0 + }; + let (place_zero, grain, fact_one) = ( + label(&kernel, "Place 0"), + label(&kernel, "Grain 0"), + label(&kernel, "Fact 1"), + ); + let route = *kernel + .state + .edges + .iter() + .find(|(_, record)| record.label() == "Route 0") + .expect("the first route is declared") + .0; + let institution = subject_by_label(&kernel.state, "Institution 0"); + + // The tick presses the two obligations; then every other person is + // pressed by one source, so the pressure partition holds a row for each. + kernel + .submit(clockwork_envelope(&kernel, tick_body(1)), &AuthenticatedCaller::verified_play()) + .expect("the tick presses the obligations"); + let pressing: Vec<ComponentOp> = people[1..] + .iter() + .map(|person| ComponentOp::AdvancePressure { + source: PressureSourceRef::Subject(Ref::Existing(people[0])), + target: Ref::Existing(*person), + by: PressureMagnitude(1), + }) + .collect(); + kernel + .submit( + clockwork_envelope(&kernel, operations(pressing)), + &AuthenticatedCaller::verified_play(), + ) + .expect("the pressure rows land"); + assert!(kernel.state.pressures.len() >= persons, "the pressure partition is at scale"); + let obligation = kernel.state.commitments[&people[0]] + .iter() + .find(|(_, commitment)| commitment.kind == CommitmentKind::Obligation) + .map(|(key, _)| *key) + .expect("the first person owes an obligation"); + + let patch = |declarations: Vec<Declaration>, operations: Vec<ComponentOp>| { + CommandBody::AdmitPatch { + patch: WorldPatch { declarations, operations, evidence: Vec::new() }, + } + }; + let bodies: Vec<(&'static str, CommandBody)> = vec![ + ( + "discharge a past-due obligation", + patch( + Vec::new(), + vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(people[0]), + key: obligation, + }], + ), + ), + ( + "relocate along a route", + patch( + Vec::new(), + vec![ComponentOp::Relocate { subject: Ref::Existing(people[5]), via: Ref::Existing(route) }], + ), + ), + ( + "declare a subject with an import key", + patch( + vec![Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("newcomer"), + label: "The Newcomer".into(), + kind: SubjectKind::Person, + affordances: BTreeSet::new(), + position: Some(Ref::Existing(place_zero)), + import_key: Some(ImportKey::new("aetherlight.gate", "newcomer")), + })], + Vec::new(), + ), + ), + ( + "transfer grain", + patch( + Vec::new(), + vec![ComponentOp::Transfer { + from: Ref::Existing(people[0]), + to: Ref::Existing(people[1]), + resource: Ref::Existing(grain), + qty: Quantity(1), + }], + ), + ), + ( + "witness a fact declared in the same patch", + patch( + vec![Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("omen"), + label: "The Omen".into(), + statement: Statement::new("The lamp gutters.").unwrap(), + standing: FactStandingRef::Ruled, + })], + vec![ComponentOp::Witness { + fact: Ref::Draft(DraftHandle::new("omen")), + place: Ref::Existing(place_zero), + confidence: Confidence::Believed, + }], + ), + ), + ( + "grant authority", + patch( + Vec::new(), + vec![ComponentOp::GrantAuthority { + holder: Ref::Existing(people[7]), + grant: AuthorityGrantRef { + kind: authority_kind(LEVY_KIND), + over: AuthorityTargetRef::Subject(Ref::Existing(people[8])), + }, + }], + ), + ), + ( + "install an incumbent", + patch( + Vec::new(), + vec![ComponentOp::InstallIncumbent { + institution: Ref::Existing(institution), + office: office(WARDEN_OFFICE), + incumbent: Ref::Existing(people[3]), + }], + ), + ), + ( + "acquire knowledge", + patch( + Vec::new(), + vec![ComponentOp::AcquireKnowledge { + subject: Ref::Existing(people[2]), + fact: Ref::Existing(fact_one), + source: AuthoredSource::Witnessed, + confidence: Confidence::Believed, + }], + ), + ), + ( + "bind a dependency", + patch( + Vec::new(), + vec![ComponentOp::Bind { + subject: Ref::Existing(people[4]), + target: DependencyRef::Subject(Ref::Existing(people[2])), + }], + ), + ), + ( + "retire a subject", + patch(Vec::new(), vec![ComponentOp::Retire { subject: Ref::Existing(people[9]) }]), + ), + ]; + let mut counts = Vec::new(); + for (shape, body) in bodies { + let rows = submit_counting_rows(&mut kernel, body); + if persons == 100 { + shapes.push(shape); + } + counts.push(rows); + } + eprintln!("{persons:>5} persons, rows per shape: {counts:?}"); + worked.push(counts); + } + for (index, shape) in shapes.iter().enumerate() { + let rows: Vec<u64> = worked.iter().map(|counts| counts[index]).collect(); + assert!( + rows.windows(2).all(|pair| pair[0] == pair[1]), + "{shape}: rows read grew with the world (100, 400, 1600): {rows:?}" + ); + } + // A shape that is point reads all the way down reads no rows at all; the + // counter must still be live, or equality proves nothing. + assert!(worked[0].iter().sum::<u64>() > 0, "no shape read a row: the counter is dead"); +} + +/// The pure reads no submit shape isolates, inside one open transaction each: +/// who stands under a two-level subtree, one incumbent's delegated authority, and +/// a path of three routes. (What a patch reads is gated through `AdmitPatch` by +/// `patch_read_work_is_equal_at_100_and_1600`.) #[test] fn operation_reads_are_equal_at_100_and_1600() { - use crate::patch::ResolvedOp; - use crate::{Cost, PressureSource}; + use crate::Cost; use std::collections::BTreeSet; let mut worked = Vec::new(); @@ -1071,24 +1279,7 @@ fn operation_reads_are_equal_at_100_and_1600() { let (zero, one, two, three) = (place("Place 0"), place("Place 1"), place("Place 2"), place("Place 3")); - // N pressure rows from other sources, committed before the measured transaction. - kernel.state.begin(); - for person in &people { - kernel.state.pressures.entry(*person).or_default().insert( - PressureSource::Subject(people[0]), - crate::patch::PressureMagnitude(1), - ); - } - let folded = kernel.state.folded().unwrap(); - kernel.state.finish(folded); - let state = &mut kernel.state; - let obligation = state.commitments[&people[0]] - .iter() - .find(|(_, commitment)| commitment.kind == CommitmentKind::Obligation) - .map(|(key, _)| *key) - .expect("the first person owes an obligation"); - state.begin(); // Place 1 inside place 0, place 2 inside place 1. state.entities.get_mut(&one).unwrap().container = Some(zero); @@ -1112,23 +1303,6 @@ fn operation_reads_are_equal_at_100_and_1600() { let mut reached = false; measure(&mut || reached = crate::action::reachable(state, people[0], &authority, three, Cost(3))); assert!(reached, "three routes of cost one reach place 3"); - let mut applied = Ok(()); - let revision = state.revision + 1; - measure(&mut || { - applied = crate::apply_operation( - state, - &ResolvedOp::DischargeCommitment { subject: people[0], key: obligation }, - &[], - revision, - ); - }); - applied.expect("the obligation is discharged"); - assert!( - state.pressures[&people[0]] - .keys() - .all(|source| !matches!(source, PressureSource::Commitment { key, .. } if *key == obligation)), - "the pressure the obligation sourced is gone" - ); state.rollback(); worked.push(counts); } From 1541cb6c4fedabc1dc7bcc5f97ad3802bd585463 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 15:53:23 +0100 Subject: [PATCH 186/190] aetherlight: apply_operations judges a holder restored to its start value The conservation sum covers the union of the holders written at entry and the holders the log reports, so a holder written before the operations and returned to its transaction-start value (absent from changes()) still counts. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/golden_tests.rs | 27 ++++++++++++++++++++++++++ native/aetherlight/src/lib.rs | 17 ++++++++++++++-- 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs index fa929271f..b71a3c0a7 100644 --- a/native/aetherlight/src/golden_tests.rs +++ b/native/aetherlight/src/golden_tests.rs @@ -2086,3 +2086,30 @@ fn views_equal_their_rebuild_and_the_scans_over_random_commands() { assert!(kept.get(name).copied().unwrap_or(0) > 0, "no {name} ever landed: {kept:?}"); } } + +/// A holder written before the operations begin and returned by them to the +/// value it had when the transaction opened is no longer in the log, yet it +/// moved: conservation reads it from the entry record, so the transfer that +/// restores it is judged as conserving. +#[test] +fn apply_conserves_a_holder_restored_to_its_start_value() { + use crate::patch::ResolvedOp; + use crate::{Quantity, apply_operations}; + + let (mut kernel, people, _) = clockwork_world(20); + let grain = *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "Grain 1") + .expect("declared") + .0; + let revision = kernel.state.revision + 1; + let state = &mut kernel.state; + state.begin(); + crate::set_held(state, people[0], grain, 5); + let transfer = ResolvedOp::Transfer { from: people[0], to: people[1], resource: grain, qty: Quantity(5) }; + apply_operations(state, std::slice::from_ref(&transfer), &[], revision) + .expect("moving the pre-written five on conserves it"); + state.rollback(); +} diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index c3837d8ad..e8c28e300 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -1742,14 +1742,27 @@ fn apply_operations( let held_of = |held: Option<&BTreeMap<EntityId, Quantity>>, resource: &EntityId| { held.and_then(|held| held.get(resource)).map_or(0, |quantity| u128::from(quantity.0)) }; + // The holders judged are the union of those written at entry and those the + // log now reports: a holder written before the operations and returned to + // its transaction-start value is absent from `changes()` but still moved. + type Held<'a> = Option<&'a BTreeMap<EntityId, Quantity>>; + let mut judged: BTreeMap<SubjectId, (Held<'_>, Held<'_>)> = BTreeMap::new(); for (holder, logged, now) in state.holdings.changes() { let before = match at_entry.get(holder) { Some(recorded) => recorded.as_ref(), None => logged, }; + judged.insert(*holder, (before, now)); + } + for (holder, recorded) in &at_entry { + judged + .entry(*holder) + .or_insert_with(|| (recorded.as_ref(), state.holdings.get(holder))); + } + for (before, now) in judged.values() { for (resource, delta) in &mut deltas { - delta.before += held_of(before, resource); - delta.after += held_of(now, resource); + delta.before += held_of(*before, resource); + delta.after += held_of(*now, resource); } } if patch::check_ledger(&deltas).is_some() { From 022db116e5bcec938cbad47c7c5ebbf7a9de7647 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 15:53:24 +0100 Subject: [PATCH 187/190] aetherlight: pin the patch behaviours three triaged mutants showed unpinned One holder with a same-kind levy over two subjects, a pressure advanced then resolved or reduced inside one patch, and a declared subject's own affordance granted or revoked-then-granted: each fails under its mutant (candidate.rs targets_overlap ==, patch.rs pressure next == 0, patch.rs !granted.is_empty()). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/golden_tests.rs | 111 +++++++++++++++++++++++++ 1 file changed, 111 insertions(+) diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs index b71a3c0a7..b830c9269 100644 --- a/native/aetherlight/src/golden_tests.rs +++ b/native/aetherlight/src/golden_tests.rs @@ -2113,3 +2113,114 @@ fn apply_conserves_a_holder_restored_to_its_start_value() { .expect("moving the pre-written five on conserves it"); state.rollback(); } + +/// Patches whose later operations read what earlier ones wrote, judged by the +/// resolver and committed: each is a legal sequence and must be accepted, or, +/// where the sequence changes nothing, refused cleanly by the resolver with the +/// commit never reached. +mod within_one_patch { + use super::{clockwork_envelope, clockwork_world}; + use crate::patch::{ + AuthorityGrantRef, AuthorityTargetRef, Declaration, DraftHandle, Mismatch, + PressureMagnitude, PressureSourceRef, SubjectDeclaration, + }; + use crate::tests::{LEVY_KIND, authority_kind}; + use crate::{ + AuthenticatedCaller, CommandBody, ComponentOp, KernelError, Ref, SubjectKind, SubjectId, + WorldKernel, WorldPatch, + }; + use std::collections::BTreeSet; + + fn submit(kernel: &mut WorldKernel, patch: WorldPatch) -> Result<(), KernelError> { + let envelope = clockwork_envelope(kernel, CommandBody::AdmitPatch { patch }); + kernel.submit(envelope, &AuthenticatedCaller::verified_play()).map(|_| ()) + } + + fn ops(operations: Vec<ComponentOp>) -> WorldPatch { + WorldPatch { declarations: vec![], operations, evidence: vec![] } + } + + fn levy_over(holder: SubjectId, over: SubjectId) -> ComponentOp { + ComponentOp::GrantAuthority { + holder: Ref::Existing(holder), + grant: AuthorityGrantRef { + kind: authority_kind(LEVY_KIND), + over: AuthorityTargetRef::Subject(Ref::Existing(over)), + }, + } + } + + /// Two jurisdictions of one kind over different subjects are disjoint, so + /// one holder may hold both. + #[test] + fn one_holder_may_hold_one_kind_over_two_subjects() { + let (mut kernel, p, _) = clockwork_world(30); + submit(&mut kernel, ops(vec![levy_over(p[0], p[5]), levy_over(p[0], p[6])])) + .expect("levy over two different subjects does not overlap"); + } + + fn source(subject: SubjectId) -> PressureSourceRef { + PressureSourceRef::Subject(Ref::Existing(subject)) + } + + /// A pressure advanced by one operation is there for the next to resolve, + /// and one reduced to nothing is gone for the next to advance afresh. + #[test] + fn a_pressure_advanced_in_a_patch_is_read_by_the_next_operation() { + let (mut kernel, p, _) = clockwork_world(30); + submit(&mut kernel, ops(vec![ + ComponentOp::AdvancePressure { source: source(p[0]), target: Ref::Existing(p[12]), by: PressureMagnitude(2) }, + ComponentOp::ResolvePressure { source: source(p[0]), target: Ref::Existing(p[12]) }, + ])) + .expect("advance then resolve the same slot"); + + submit(&mut kernel, ops(vec![ + ComponentOp::AdvancePressure { source: source(p[0]), target: Ref::Existing(p[13]), by: PressureMagnitude(2) }, + ComponentOp::ReducePressure { source: source(p[0]), target: Ref::Existing(p[13]), by: PressureMagnitude(2) }, + ComponentOp::AdvancePressure { source: source(p[0]), target: Ref::Existing(p[13]), by: PressureMagnitude(1) }, + ])) + .expect("advance, reduce to nothing, advance again"); + } + + fn declared(name: &str, affordance: crate::AffordanceId) -> Declaration { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(name), + label: name.into(), + kind: SubjectKind::Person, + affordances: BTreeSet::from([Ref::Existing(affordance)]), + position: None, + import_key: None, + }) + } + + /// A subject declared with an affordance already has it: granting it is no + /// change, and the resolver says so itself, rather than admitting what the + /// commit then refuses. Revoking it first makes the grant a change. + #[test] + fn a_declared_affordance_is_known_to_the_operations_that_follow() { + let (mut kernel, _, speak) = clockwork_world(30); + let draft = |name: &str| Ref::Draft(DraftHandle::new(name)); + + let refused = submit(&mut kernel, WorldPatch { + declarations: vec![declared("scribe", speak)], + operations: vec![ComponentOp::GrantAffordance { subject: draft("scribe"), affordance: Ref::Existing(speak) }], + evidence: vec![], + }) + .unwrap_err(); + assert!( + matches!(&refused, KernelError::PatchRejected(m) + if m == &[Mismatch::NoOperationEffect { operation: 0 }]), + "{refused:?}" + ); + + submit(&mut kernel, WorldPatch { + declarations: vec![declared("scribe2", speak)], + operations: vec![ + ComponentOp::RevokeAffordance { subject: draft("scribe2"), affordance: Ref::Existing(speak) }, + ComponentOp::GrantAffordance { subject: draft("scribe2"), affordance: Ref::Existing(speak) }, + ], + evidence: vec![], + }) + .expect("revoke then grant is a change"); + } +} From 7ef60a7d21f491625174ea5774e8e80f972b7def Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 15:56:02 +0100 Subject: [PATCH 188/190] aetherlight: touched_holders no longer reads retirement flips A retirement only removes lent authority, so it cannot add an overlap; the clause changed no answer over 20000 forged lists. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/lib.rs | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index e8c28e300..892a8e34f 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -1790,8 +1790,8 @@ fn apply_operations( /// Every subject whose effective authority the open transaction may have /// changed: whose own grants were written, whose offices were written (old /// incumbent and new), and the incumbents of an institution whose grants were -/// written or whose retirement flipped, because an office lends what its -/// institution holds. +/// written, because an office lends what its institution holds. A retirement +/// only removes lent authority, so it cannot add an overlap and is not read. fn touched_holders(state: &WorldState) -> BTreeSet<SubjectId> { let mut touched = BTreeSet::new(); let mut institutions = BTreeSet::new(); @@ -1805,11 +1805,6 @@ fn touched_holders(state: &WorldState) -> BTreeSet<SubjectId> { } institutions.insert(*institution); } - for (subject, old, new) in state.subjects.changes() { - if old.map(|record| record.retired) != new.map(|record| record.retired) { - institutions.insert(*subject); - } - } for institution in institutions { if let Some(offices) = state.selection.get(&institution) { touched.extend(offices.values().filter_map(|office| office.incumbent)); From 693fa444af6e16305c2183582b51731c806f8383 Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 15:56:03 +0100 Subject: [PATCH 189/190] aetherlight: a seeded property test over random patch sequences Ten seeds of thirty random patches through the kernel: the resolver and apply_operations never disagree (no Invariant error), a refusal writes nothing and repeats, and every accepted commit leaves indexes equal to scans, no overlap standing and the grain total unchanged. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/src/golden_tests.rs | 179 +++++++++++++++++++++++++ 1 file changed, 179 insertions(+) diff --git a/native/aetherlight/src/golden_tests.rs b/native/aetherlight/src/golden_tests.rs index b830c9269..bba7e99a1 100644 --- a/native/aetherlight/src/golden_tests.rs +++ b/native/aetherlight/src/golden_tests.rs @@ -2224,3 +2224,182 @@ mod within_one_patch { .expect("revoke then grant is a change"); } } + +/// Seeded random patch sequences through the real kernel. The resolver judges +/// each patch against its overlay, `apply_operations` re-derives conservation +/// and disjointness from the transaction log, and the full-scan references +/// judge the committed world: the three must agree after every step. +/// +/// Per step, in a world of grain holders, institutions with a warden office, +/// pressures and a speak affordance: +/// - the outcome is an accepted commit or a `PatchRejected` mismatch set, never +/// a kernel `Invariant` error (the resolver admitted what apply refuses); +/// - a refused patch changes no document, and the same patch refused again +/// gives the same mismatches; +/// - after an accepted one every index equals its scan, no subject holds two +/// overlapping jurisdictions of one kind, and the grain total is unchanged +/// (the generator transfers and never mints). +#[test] +fn random_patch_sequences_agree_with_the_scan_references() { + use crate::patch::{ + AuthorityGrantRef, AuthorityTargetRef, PressureMagnitude, PressureSourceRef, Quantity, + }; + use crate::tests::{LEVY_KIND, WARDEN_OFFICE, authority_kind, office}; + use crate::{EntityKind, SubjectKind}; + + struct Rng(u64); + impl Rng { + fn below(&mut self, n: usize) -> usize { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + (self.0 % n as u64) as usize + } + } + + let (mut accepted, mut refused, mut multi) = (0usize, 0usize, 0usize); + for seed in 1..=10u64 { + let (mut kernel, people, speak) = clockwork_world(30); + let labelled = |kernel: &WorldKernel, kind: EntityKind| -> Vec<crate::EntityId> { + let mut found: Vec<_> = kernel + .state + .entities + .iter() + .filter(|(_, record)| record.kind == kind) + .map(|(id, record)| (record.label.clone(), *id)) + .collect(); + found.sort(); + found.into_iter().map(|(_, id)| id).collect() + }; + let places = labelled(&kernel, EntityKind::Place); + let grains = labelled(&kernel, EntityKind::Resource); + let institutions: Vec<_> = (0..places.len()) + .map(|place| subject_by_label(&kernel.state, &format!("Institution {place}"))) + .collect(); + let grain_total = |kernel: &WorldKernel| -> u128 { + grains.iter().map(|grain| crate::resource_total_by_scan(&kernel.state, *grain)).sum() + }; + let total = grain_total(&kernel); + let mut rng = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1); + + for step in 0..30 { + // A small pool of subjects, so patches collide often. + let person = |rng: &mut Rng| Ref::Existing(people[rng.below(6)]); + let levy_target = |rng: &mut Rng| { + if rng.below(2) == 0 { + AuthorityTargetRef::Subject(Ref::Existing(people[rng.below(6)])) + } else { + AuthorityTargetRef::PlaceSubtree(Ref::Existing(places[rng.below(3)])) + } + }; + let mut declarations = Vec::new(); + let mut operations = Vec::new(); + for index in 0..1 + rng.below(4) { + let op = match rng.below(14) { + 0..=2 => { + let holder = if rng.below(4) == 0 { + Ref::Existing(institutions[rng.below(3)]) + } else { + person(&mut rng) + }; + ComponentOp::GrantAuthority { + holder, + grant: AuthorityGrantRef { kind: authority_kind(LEVY_KIND), over: levy_target(&mut rng) }, + } + } + 3 => ComponentOp::RevokeAuthority { + holder: person(&mut rng), + grant: AuthorityGrantRef { kind: authority_kind(LEVY_KIND), over: levy_target(&mut rng) }, + }, + 4 => ComponentOp::InstallIncumbent { + institution: Ref::Existing(institutions[rng.below(3)]), + office: office(WARDEN_OFFICE), + incumbent: person(&mut rng), + }, + 5 => ComponentOp::VacateOffice { + institution: Ref::Existing(institutions[rng.below(3)]), + office: office(WARDEN_OFFICE), + }, + 6 => ComponentOp::AdvancePressure { + source: PressureSourceRef::Subject(person(&mut rng)), + target: person(&mut rng), + by: PressureMagnitude(1 + rng.below(3) as u32), + }, + 7 => ComponentOp::ReducePressure { + source: PressureSourceRef::Subject(person(&mut rng)), + target: person(&mut rng), + by: PressureMagnitude(1 + rng.below(3) as u32), + }, + 8 => ComponentOp::ResolvePressure { + source: PressureSourceRef::Subject(person(&mut rng)), + target: person(&mut rng), + }, + 9 => ComponentOp::GrantAffordance { subject: person(&mut rng), affordance: Ref::Existing(speak) }, + 10 => ComponentOp::RevokeAffordance { subject: person(&mut rng), affordance: Ref::Existing(speak) }, + 11 => ComponentOp::Transfer { + from: person(&mut rng), + to: person(&mut rng), + resource: Ref::Existing(grains[rng.below(3)]), + qty: Quantity(1), + }, + 12 => { + let name = format!("s{step}-{index}"); + declarations.push(Declaration::Subject(crate::patch::SubjectDeclaration { + handle: DraftHandle::new(&name), + label: format!("Drafted {seed}-{name}"), + kind: SubjectKind::Person, + affordances: std::collections::BTreeSet::from([Ref::Existing(speak)]), + position: None, + import_key: None, + })); + ComponentOp::GrantAffordance { + subject: Ref::Draft(DraftHandle::new(&name)), + affordance: Ref::Existing(speak), + } + } + _ if rng.below(8) == 0 => ComponentOp::Retire { subject: person(&mut rng) }, + _ => ComponentOp::ResolvePressure { + source: PressureSourceRef::Subject(person(&mut rng)), + target: person(&mut rng), + }, + }; + operations.push(op); + } + let patch = WorldPatch { declarations, operations, evidence: vec![] }; + let documents = kernel.state.documents().unwrap(); + let again = clockwork_envelope(&kernel, CommandBody::AdmitPatch { patch: patch.clone() }); + let outcome = kernel.submit( + clockwork_envelope(&kernel, CommandBody::AdmitPatch { patch }), + &AuthenticatedCaller::verified_play(), + ); + match outcome { + Ok(_) => { + accepted += 1; + assert_eq!(reference_scan_disagreement(&kernel.state), None, "seed {seed} step {step}"); + assert_indexes_derived(&kernel.state, &format!("seed {seed} step {step}")); + for subject in kernel.state.subjects.keys() { + assert!( + !crate::holder_overlaps(&kernel.state, *subject), + "seed {seed} step {step}: {subject:?} holds overlapping jurisdictions" + ); + } + assert_eq!(grain_total(&kernel), total, "seed {seed} step {step}: custody"); + } + Err(KernelError::PatchRejected(mismatches)) => { + refused += 1; + multi += usize::from(mismatches.len() > 1); + assert_eq!(kernel.state.documents().unwrap(), documents, "seed {seed} step {step}: a refusal wrote"); + // The same patch against the same world: the same refusal. + let repeat = kernel.submit(again, &AuthenticatedCaller::verified_play()); + assert!( + matches!(&repeat, Err(KernelError::PatchRejected(m)) if *m == mismatches), + "seed {seed} step {step}: {repeat:?}" + ); + } + Err(other) => panic!("seed {seed} step {step}: resolver and apply disagree: {other:?}"), + } + } + } + // The generator must reach both sides, or the loop proves nothing. + assert!(accepted >= 40 && refused >= 40 && multi >= 1, "{accepted} accepted, {refused} refused, {multi} multi"); +} From faf44f857a9596e64dac1e7ec79577de103895ce Mon Sep 17 00:00:00 2001 From: soul <s@x> Date: Fri, 20 Nov 2026 15:56:27 +0100 Subject: [PATCH 190/190] aetherlight: record the fix batch and the accepted counter-blind-sizes finding Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- native/aetherlight/PROVENANCE.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/native/aetherlight/PROVENANCE.md b/native/aetherlight/PROVENANCE.md index d0cbdd073..d56b93a69 100644 --- a/native/aetherlight/PROVENANCE.md +++ b/native/aetherlight/PROVENANCE.md @@ -614,3 +614,15 @@ called `apply_operation` directly, moved into the gate. Reads that still scan: `snapshot` (follow-up `aetherlight-snapshot-history-fold`) and `verify_state_shape` at open, by design. + +Fix batch (verdict s1). `apply_operations` sums the union of the holders written at +entry and the holders the log reports, so a holder written before the operations and +restored to its start value still counts. Three missed mutants were not equivalent +and are pinned by `golden_tests::within_one_patch`; `random_patch_sequences_agree_with_the_scan_references` +runs seeded random patches through the kernel and holds resolver, apply and the scan +references to one answer. The retirement-flip clause of `touched_holders` is gone +(a retirement only removes lent authority). Accepted, not fixed +(`counter-blind-sizes`): the read gates count rows through the counted API, which +point reads bypass by design, and wire patches are capped at 128 operations +(`MAX_PATCH_OPERATIONS`), so the flat-read gates measure patches no larger than that; +nothing measures a patch whose operation count grows with the world.