Compare commits

...
Sign in to create a new pull request.
Author SHA1 Message Date
1a87c68fc7 Merge pull request "ClientRuntimeLoader: client assemblies must resolve under a trusted root" (#1)
Windows run by Kiko was at 739e2bd (83 pass, 1 SynthPlayback failure), not 9ce4eb8. Engine tests at 9ce4eb8 on Linux: 86 pass, 2 pre-existing D3D12 failures (no d3d11.dll).
2026-11-07 11:50:04 +00:00
Aqua
9ce4eb8d06 Host startup failure names the escaped exception type; test cleanup warns when it cannot delete
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 11:48:52 +00:00
Aqua
739e2bd93e Client runtime: load assemblies by path again so Assembly.Location is the file; tolerate locked files in test cleanup
Render plan and fractal scene derive directories from Assembly.Location; the in-memory load emptied it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 11:35:13 +00:00
Aqua
d2f280d9f2 Client runtime: escape logged paths once by code point, report untrusted mount points as refusals, load assemblies without file locks
Exception messages carry raw paths and every console write escapes them once (Printable iterates runes: astral format characters and lone surrogates). AquariumHost reports startup refusals escaped. IOException from link resolution becomes InvalidOperationException. Managed assemblies load from memory so the temp dir can be deleted on Windows. The newline-in-file-name test is skipped on Windows.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 11:30:47 +00:00
Aqua
467a97f540 Trusted root: lexical check before any filesystem access, cached env setting, stricter log escaping
Review (Heimdall): a path outside the pinned root (as resolved or as given) is refused by
string comparison before File.Exists or any link is followed; the trusted-root setting is
its own small type that takes the environment variable once, caches it and refuses blank
values; Printable also escapes backslash, format characters (bidi, zero-width) and the
line and paragraph separators; dev-watch matches the host ack by the unique slot leaf with
doubled backslashes; dev-reload prunes live-slots and rejects stale reopen state up front.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 11:04:00 +00:00
Aqua
45b0b38a2e Trusted root: assemblies-only dir, env cleared on every path, string checks first, escaped logs
Review (Heimdall): dev scripts keep slots and live-slots under artifacts/dev-reload/assemblies
and pass that as the root, not the whole dev root; --client-trusted-root refuses an empty or
missing value and the environment variable is cleared on every path; the UNC/fully-qualified
string rule runs before File.Exists on a pointer target; control characters are escaped in
every logged path.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 10:57:09 +00:00
Aqua
7ec7a0f909 ClientRuntimeLoader: pin the resolved root, load the resolved path, check dependencies
Review (Heimdall): the root is resolved once at construction and a volume root
is refused and the effective root logged; the loader loads and records the
resolved final path (so a pointer naming a link does not reload every poll);
dependency and native-library resolution go through the same check; the
AQUARIUM_CLIENT_TRUSTED_ROOT variable is cleared after reading. Tests: UNC in any
separator mix, volume root, pinned root, resolved-path storage, junction and
symlink tests that report an explicit skip instead of passing silently.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 10:51:45 +00:00
Aqua
e0fc49b720 dev-reload: trusted root is the dev root, so dev-watch live-slots reloads load
dev-watch writes the reload pointer under artifacts/dev-reload/live-slots, a
sibling of slots; a slot-directory root refused every watch reload and the
reopen path. Test: a sibling directory loads inside an explicit root, not under
the default root, and an outside assembly is still refused.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 10:47:56 +00:00
Aqua
d44666ec69 ClientRuntimeLoader: client assemblies must resolve under a trusted root
The reload pointer, and the initial --client-assembly, named any path and ran
whatever it held in the engine process. Reload now refuses relative and UNC
paths and anything that, links followed, lies outside the trusted root
(--client-trusted-root or AQUARIUM_CLIENT_TRUSTED_ROOT; default: the directory
of the initial assembly). dev-reload passes its slot directory as the root.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 10:45:23 +00:00
Meta Vens
34aaebfb94 Merge readme-front-door: README front door
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 20:15:19 +02:00
Meta Vens
8be7e2288e README front door: value, problem, entry points, live versus planned
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 20:10:35 +02:00
Meta Vens
b58217758b Record planet-work rulings Q-F1..Q-F4
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 14:08:04 +02:00
Meta Vens
90d42b4d57 Map the adopted planet work against Asura (Imagination, 2026-09-30)
Validation: the July planetary runtime has no code owner (CultMath deleted it,
the CultLib branch never merged) and contradicts Asura's HLSL-only field and
gradient rule. Recommendation: retire, archive the donor ref; the one live idea
(Geometry drops its duplicate vector types) must land before Asura Cut 3.
Q-F1..Q-F4 open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 14:04:10 +02:00
Meta Vens
e053486f09 Wire AGENTS.md into Claude Code memory
Claude Code reads CLAUDE.md, not AGENTS.md, so this repo's doctrine was
invisible to it. This one-line import makes the existing AGENTS.md load
without duplicating or renaming it. Codex is unaffected.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-29 12:19:45 +02:00
Meta Vens
d755d9c5e0 Remove dead Saga library, obsolete AquaSynth alpha packages, closed scratch note
REC-109 / REC-019 dead-code subtraction pass on Fensalir.

Deleted, all re-verified fresh against origin/main (dc35ecc) and against
every other repo under F:/Projects, not just Fensalir:

- src/Saga/ (SagaOrgan.cs, Saga.csproj, README.md) and its Fensalir.sln
  project entry (GUID 30324495-56BE-4D45-80E8-CE03C24726C8, including its
  ProjectConfigurationPlatforms and NestedProjects lines). `rg -n
  'SagaOrgan|SagaFlowRequest|SagaCoriolisFrame|SagaForcingSource|
  SagaAdvectionSample|SagaCovariance2D' --glob '!src/Saga/SagaOrgan.cs' .`
  found zero consumers inside Fensalir; the same pattern run across the rest
  of F:/Projects (excluding Fensalir and this census doc) found only the
  census's own prose, no other repo referencing these symbols.

- packages/AquaSynth.Core.0.1.0-alpha.2.nupkg,
  packages/AquaSynth.Faust.0.1.0-alpha.2.nupkg,
  packages/AquaSynth.Faust.0.1.0-alpha.3.nupkg. Confirmed
  src/Aquarium.Engine/Aquarium.Engine.csproj:15 references only
  AquaSynth.Faust 0.1.0-alpha.4, whose nuspec pins Core alpha.3 (both kept).
  Verified by building Aquarium.Engine.csproj (with -p:CultLibRoot pointed
  at the sibling CultLib checkout, since the CultMath project reference is
  otherwise only resolvable from Fensalir's normal on-disk location next to
  CultLib) against the trimmed packages/ feed: restore and build succeeded,
  proving alpha.4/alpha.3 satisfy the manifest with the three obsolete
  files gone.

- state/scratch-fractal-surface-visible.md. `rg -n -F
  'scratch-fractal-surface-visible.md' .` found zero references inside
  Fensalir; the one repo-wide hit (gamecult-site's generated
  repo-doc-tree/fensalir.json) is a static catalog listing, not a code or
  build consumer. Content read in full: a closed "Kept/Changed/Still not
  good enough" retrospective note, not an open TODO, with no admission path
  into any durable doc.

Verification: dotnet build succeeded post-deletion for
Aquarium.Engine.Contracts, Aquarium.Engine (exercises the trimmed AquaSynth
package feed and the CultMath sibling reference), Aquarium.Engine.Fractal,
and Aquarium.Engine.Fractal.Tests (which also restores Aquarium.Zyphos and
Aquarium.Fensalir). `dotnet restore Fensalir.sln` itself fails in this
worktree because CultMath is a relative sibling-path reference
(../../../CultLib) that does not exist next to a temp worktree — a
pre-existing property of the manifest, not something this change caused;
per-project builds above cover the touched surfaces instead.

Not touched, out of scope for this pass: the inert render-graph
pass/camera/debug-view surface, Clear() no-ops, GetResource/GetRenderTarget
— all flagged in the same census section but requiring broader review.

Collision check: primary checkout (codex/cultmath-monorepo) has zero diff
against origin/main on every touched path. Executed in worktree
claude/dross-2026-09-13 off origin/main, not the primary checkout.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-13 14:38:54 +02:00
Meta Vens
dc35ecc69b Consume CultMath from CultLib 2026-08-26 17:56:15 +02:00
21 changed files with 1266 additions and 315 deletions

3
CLAUDE.md Normal file
View file

@ -0,0 +1,3 @@
Repository doctrine for this project lives in AGENTS.md, shared with Codex.
@AGENTS.md

View file

@ -9,7 +9,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Engine.Contracts",
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Engine", "src\Aquarium.Engine\Aquarium.Engine.csproj", "{51FE01D8-9EEF-46B2-8D8C-3307AC2221C1}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Engine", "src\Aquarium.Engine\Aquarium.Engine.csproj", "{51FE01D8-9EEF-46B2-8D8C-3307AC2221C1}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CultMath", "..\CultMath\src\CultMath\CultMath.csproj", "{0089E341-25F2-43FC-8FD9-CBD1AE646D91}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CultMath", "..\CultLib\packages\cultmath\src\CultMath\CultMath.csproj", "{0089E341-25F2-43FC-8FD9-CBD1AE646D91}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Sample.Minimal", "src\Aquarium.Sample.Minimal\Aquarium.Sample.Minimal.csproj", "{7564E6C2-FF01-4B5B-8C2B-F9CD796858BA}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Sample.Minimal", "src\Aquarium.Sample.Minimal\Aquarium.Sample.Minimal.csproj", "{7564E6C2-FF01-4B5B-8C2B-F9CD796858BA}"
EndProject EndProject
@ -29,8 +29,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Fractal.Receipt",
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Fensalir", "src\Aquarium.Fensalir\Aquarium.Fensalir.csproj", "{F9274D99-3CC6-42B6-9817-EC7F19663B1D}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Fensalir", "src\Aquarium.Fensalir\Aquarium.Fensalir.csproj", "{F9274D99-3CC6-42B6-9817-EC7F19663B1D}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Saga", "src\Saga\Saga.csproj", "{30324495-56BE-4D45-80E8-CE03C24726C8}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@ -161,18 +159,6 @@ Global
{F9274D99-3CC6-42B6-9817-EC7F19663B1D}.Release|x64.Build.0 = Release|Any CPU {F9274D99-3CC6-42B6-9817-EC7F19663B1D}.Release|x64.Build.0 = Release|Any CPU
{F9274D99-3CC6-42B6-9817-EC7F19663B1D}.Release|x86.ActiveCfg = Release|Any CPU {F9274D99-3CC6-42B6-9817-EC7F19663B1D}.Release|x86.ActiveCfg = Release|Any CPU
{F9274D99-3CC6-42B6-9817-EC7F19663B1D}.Release|x86.Build.0 = Release|Any CPU {F9274D99-3CC6-42B6-9817-EC7F19663B1D}.Release|x86.Build.0 = Release|Any CPU
{30324495-56BE-4D45-80E8-CE03C24726C8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{30324495-56BE-4D45-80E8-CE03C24726C8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{30324495-56BE-4D45-80E8-CE03C24726C8}.Debug|x64.ActiveCfg = Debug|Any CPU
{30324495-56BE-4D45-80E8-CE03C24726C8}.Debug|x64.Build.0 = Debug|Any CPU
{30324495-56BE-4D45-80E8-CE03C24726C8}.Debug|x86.ActiveCfg = Debug|Any CPU
{30324495-56BE-4D45-80E8-CE03C24726C8}.Debug|x86.Build.0 = Debug|Any CPU
{30324495-56BE-4D45-80E8-CE03C24726C8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{30324495-56BE-4D45-80E8-CE03C24726C8}.Release|Any CPU.Build.0 = Release|Any CPU
{30324495-56BE-4D45-80E8-CE03C24726C8}.Release|x64.ActiveCfg = Release|Any CPU
{30324495-56BE-4D45-80E8-CE03C24726C8}.Release|x64.Build.0 = Release|Any CPU
{30324495-56BE-4D45-80E8-CE03C24726C8}.Release|x86.ActiveCfg = Release|Any CPU
{30324495-56BE-4D45-80E8-CE03C24726C8}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
@ -187,6 +173,5 @@ Global
{A9D41C48-7E78-4D75-A814-0C1500245EFC} = {0AB3BF05-4346-4AA6-1389-037BE0695223} {A9D41C48-7E78-4D75-A814-0C1500245EFC} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
{C0D1BFAC-B1B4-4350-92A7-D537AE382909} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84} {C0D1BFAC-B1B4-4350-92A7-D537AE382909} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84}
{F9274D99-3CC6-42B6-9817-EC7F19663B1D} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {F9274D99-3CC6-42B6-9817-EC7F19663B1D} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{30324495-56BE-4D45-80E8-CE03C24726C8} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
EndGlobalSection EndGlobalSection
EndGlobal EndGlobal

View file

@ -13,6 +13,14 @@ evidence, and synth-backed sound.
The repo is not the Epiphany Aquarium client. Epiphany lives in The repo is not the Epiphany Aquarium client. Epiphany lives in
`GameCult/Aquarium-Engine` and consumes Fensalir as the runtime dependency. `GameCult/Aquarium-Engine` and consumes Fensalir as the runtime dependency.
**Valuable here:** the spatio-temporal evidence reservoir (`ResampledImportanceReservoir<TSample>` and `TemporalSpatialEvidenceReservoir` in `src/Aquarium.Engine.Fractal/Temporal/`), the `.aquageo` fractal field DSL in `src/Aquarium.Engine.Fractal`, and the engine/client contract in `src/Aquarium.Engine.Contracts/AquariumRuntimeContracts.cs` (`IAquariumRuntime`).
**Problem it solves:** interactive visual clients need a renderer that decides which field evidence deserves rendering, fusion and residency under a budget, instead of each client owning temporal truth or drawing private geometry. Fensalir holds that machinery once; client repos own meaning.
**Entry points:** `dotnet build Fensalir.sln`; run a client with `scripts/dev-reload.ps1 -ClientProject <csproj>` (see Run below). Start reading at `docs/engine-client-boundary.md` and `docs/temporal-spatial-evidence-reservoir.md`; the target pipeline is `docs/perfect-fensalir-machine-roadmap.md`. The smallest client is `src/Aquarium.Sample.Minimal`; `src/Aquarium.Fensalir` and `src/Aquarium.Zyphos` are demo clients.
**Live versus planned:** live are the Win32 host, D3D12 renderer, hot reload, headless capture, AquaSynth/WASAPI audio, CPU reservoirs, fractal probe samples, evidence tracks and validator coverage. Planned (see the roadmap) are full GPU reservoir storage and page residency.
## What Runs ## What Runs
The host executable in `src/Aquarium.Engine` loads a client assembly that The host executable in `src/Aquarium.Engine` loads a client assembly that
@ -136,9 +144,6 @@ how WASAPI or Faust got invited to the party.
audio/synth host, bundled assets, and renderer-owned shaders. audio/synth host, bundled assets, and renderer-owned shaders.
- `src/Aquarium.Engine.Fractal`: `.aquageo`, IFS/fractal fields, temporal - `src/Aquarium.Engine.Fractal`: `.aquageo`, IFS/fractal fields, temporal
reservoirs, evidence tracks, contribution cache, and lowering machinery. reservoirs, evidence tracks, contribution cache, and lowering machinery.
- `src/Saga`: stochastic planetary flow middleware for cube-sphere Transport
fields, arbitrary forcing, Coriolis-aware advection, and learned atmosphere /
ocean / debris flow packets.
- `src/Aquarium.Fensalir`: Fensalir splash/art reconstruction demo. - `src/Aquarium.Fensalir`: Fensalir splash/art reconstruction demo.
- `src/Aquarium.Sample.Minimal`: tiny client proving the runtime boundary. - `src/Aquarium.Sample.Minimal`: tiny client proving the runtime boundary.
- `src/Aquarium.Zyphos`: planetary/fractal terrain demo. - `src/Aquarium.Zyphos`: planetary/fractal terrain demo.
@ -153,8 +158,8 @@ Requirements:
- Windows - Windows
- .NET SDK matching `global.json` - .NET SDK matching `global.json`
- sibling repos currently expected at `E:\Projects\CultMath` and - sibling `CultLib` checkout beside this repo (override with the `CultLibRoot`
`E:\Projects\CultLib` MSBuild property); CultMath is consumed from `CultLib/packages/cultmath`
```powershell ```powershell
dotnet build Fensalir.sln dotnet build Fensalir.sln

View file

@ -13,8 +13,6 @@ historical branch scar.
## Fields, Reservoirs, And Fractals ## Fields, Reservoirs, And Fractals
- `../src/Saga/README.md`: studio-facing Saga middleware pitch and subproject
overview for stochastic planetary flow.
- `papers/fensalir-pipeline.tex`: living MiKTeX paper for the Fensalir - `papers/fensalir-pipeline.tex`: living MiKTeX paper for the Fensalir
pipeline, research spine, domain reservoir model, and evaluation plan. pipeline, research spine, domain reservoir model, and evaluation plan.
- `papers/fensalir-native-domain-reservoirs.tex`: focused SIGGRAPH-shaped - `papers/fensalir-native-domain-reservoirs.tex`: focused SIGGRAPH-shaped

View file

@ -0,0 +1,479 @@
# Fensalir planet work: validation and reorientation beside Asura
Status: Imagination pass 1, 2026-09-30. Nothing committed and no working tree
switched. The build probes ran on Yggdrasil through `ygg-verify.sh`, using
composite snapshots in a scratch repo. That repo lives in the scratchpad, not
in any project.
Adopting instruction (operator, 2026-09-30): "Fensalir planet work is old,
needs validation and reorientation beside the Asura campaign".
## Rulings (operator, 2026-09-30)
- **Q-F1: no planet terrain in Fensalir for now.** The July planetary runtime retires behind an archive
tag. A landing-scale Zyphos would be a new campaign built on Asura, not a revival of that runtime.
- **Q-F2: park the flow docs,** with a status line: parked, superseded by Asura for the field, no code.
- **Q-F3: triage now.** Eyes classifies each non-planet line on the donor ref before anything is tagged or
deleted: the 66 Bokusho commits, the Eve native surface work, Leap/stereo, and the reservoir work. P1
waits for that triage.
- **Q-F4: delete Geometry's duplicate vector types before Asura Cut 3** (P4, in CultLib). This is on
Asura's critical path.
## Pinned heads (every `file:line` below is against these)
| Repo | Ref | SHA | Note |
| --- | --- | --- | --- |
| Fensalir | `origin/main` = local `main` | `e053486` | 3 commits past the merge base, all housekeeping |
| Fensalir | `origin/codex/geometry-ownership-migration` (the donor) | `42778c1` | 125 ahead of merge base `57b6040` (2026-05-30) |
| Fensalir | `origin/codex/leap-packed-depth` | `492d123` | the donor minus its last commit |
| CultLib | `origin/main` | `93fe1b9` | includes the bounded-least-squares merge; local `main` is `069ecc3` |
| CultLib | `origin/codex/geometry-ownership-migration` | `6a65369` | the donor's other half: 31 ahead of `a58daa5` (2026-07-12), 832 behind |
| CultLib | tags `gamecult-geometry{,-rs,-unity}-v0.1.0` | `b65619f` | pushed to origin, on `origin/codex/geometry-cultmesh-unity-release`, not in main |
| CultMath (standalone, retired) | `main` | `1c007a5` | "Point CultMath history at its CultLib home"; planetary deleted at `6a16260` |
| Asura | `main` | `63f9216` | snoise fix status recorded; the fix is on CultLib `hands/cultmath-snoise-grad` `0a5f4bf` |
## Verdict
**Retire the planet work. Do not land it.** The donor has no surviving code
owner: CultMath deleted the planetary runtime in July, and CultLib never merged
it. Asura has since claimed the planet field with a design that contradicts the
donor's central promises. Its erosion port is the one Asura already judged "not
a source". Its only consumer is a Fensalir demo client that has not changed
since 2026-05-30.
One idea from the geometry half is still live and time-sensitive: deleting the
duplicate vector types from `GameCult.Geometry`. That is separate work, but it
has a closing window. Once Asura Cut 3 ships `GameCult.Geometry.dll` into Unity,
the duplicate `CultVec3` becomes public Unity API (Q-F4).
Most of the branch is not planet work at all. 66 Bokusho commits, 10 Eve
commits, and the Leap/stereo and reservoir work ride on the same ref. They need
their own adoption decision before any ref is deleted (Q-F3).
---
## 1. Validation report
### 1.1 What the donor actually is
Grouping `git log 57b6040..42778c1` by subject:
| Slice | Commits | Dates | Size |
| --- | --- | --- | --- |
| Leap stereo depth, point cloud, reservoir history, camera fusion, loopback audio | ~20 | 05-30 to 05-31 | inside the 61-file, +8832/−279 pre-planet diff |
| Eve native surface client (Direct2D, CultUI previews) | ~17 | 05-31 to 06-02 | same |
| Bokusho brush simulation on D3D12 | 66 | 06-12 to 06-16 | `BokushoBrushSimulation.cs` +1076, `D3D12BokushoBrush.hlsl` +699, tests +1143 |
| **Planet slice** | **23** | **07-12 to 07-22** | **61 files, +2865/−359 (`5854630^..42778c1`)** |
Inside the planet slice, only the last three commits are the "geometry ownership
migration":
- `2531df5` moves Fensalir onto CultMath's July planetary runtime.
- `492d123` deletes Fensalir's `CubeFace`, `CubeFacePosition` and `CubeTileKey`.
- `42778c1` renames every consumer from `cultmath_planetary_*` to
`gamecult_geometry_planetary_*`.
Its partner commits live in CultLib (`13e8c56..6a65369`) and CultMath (`6a16260`).
### 1.2 Merge probes (`git merge-tree --write-tree`)
- **Fensalir, donor into `origin/main`: 7 conflicts.**
- Content conflicts in `Fensalir.sln`, `README.md`, `docs/README.md` and
`src/Aquarium.Engine/Aquarium.Engine.csproj`.
- The csproj conflict matters. Main's `dc35ecc` moved CultMath to
`$(CultLibRoot)\packages\cultmath\...` (`Aquarium.Engine.csproj:4,26` at
`e053486`). The donor still points at the standalone repo
(`..\..\..\CultMath\src\CultMath\CultMath.csproj`, `Aquarium.Engine.csproj:25`
and `Aquarium.Engine.Contracts.csproj:10` at `42778c1`).
- Modify/delete conflicts in `src/Saga/{README.md,Saga.csproj,SagaOrgan.cs}`.
Main deleted Saga as dead in `d755d9c`; the donor still migrates it.
- **CultLib, July branch into `origin/main`: 23 conflicts.**
- 13 are source and docs, including a modify/delete on
`CultDocumentMessagePackGenerator.cs`, which main deleted. The others are in
`CultManagedDocument.cs`, the serialization code, `GameCult.Geometry.csproj`
and `README.md`, `GeometryDocumentTests.cs` and `build-unity-package.ps1`.
- 10 are prebuilt Unity DLLs and pdbs.
- The branch is 832 commits behind. That is not a merge; it would be a
re-implementation.
### 1.3 Build probes (Yggdrasil, `mcr.microsoft.com/dotnet/sdk:10.0`, Linux)
The probes use three composite snapshots in the scratch repo. Each lays the
three repos out as siblings, the way the csproj relative paths expect.
| Probe | Layout | Result |
| --- | --- | --- |
| **mainline** | Fensalir `e053486` + CultLib `93fe1b9` | `Aquarium.Engine.Fractal` builds. Fractal tests: **167/167 pass** |
| **then** (the July world) | Fensalir `42778c1` + CultLib `6a65369` + CultMath `b43cf49` | Restore fails first with NU1101: `CultMath 0.1.0` comes only from a git-ignored local feed (`CultLib/Directory.Build.props:18-19` at `6a65369`: `..\CultMath\.tools\local-feed`). After `dotnet pack` of CultMath `b43cf49` and passing the feed explicitly, the lib builds and the Fractal tests give **169/170**. The failure is `ProjectionTests.CheckedInProjectionReportMatchesSampler`, which passes on mainline. The donor regenerated `research/rendering/fractal-projection-report.md` against the July projection code on Windows; this was not chased. |
| **now** (donor against today's owners) | Fensalir `42778c1` + CultLib `93fe1b9` + CultMath `1c007a5` | **Fails** with 10 unique errors (`FRACTAL_LIB_EXIT=1`). Nine are CS0246 for `PlanetaryCubeFace`, `PlanetaryTileAddress` and `PlanetaryFaceCoordinate` (`FractalDslCompiler.cs:505`, `FractalStableKeyBuilder.cs:8`, `ICubeSphereProjection.cs:11`, `NormalizeCubeSphereProjection.cs:11`, `ProjectionDistortionResult.cs:8`, `ProjectionDistortionSampler.cs:14,61,68`, `TangentCubeSphereProjection.cs:11`). The tenth is CS1704: two assemblies named `CultMath` are loaded, one from the standalone repo through the donor's `Contracts` reference and one from CultLib `packages/cultmath` through `GameCult.Geometry`. The donor straddles the pre-monorepo and monorepo layouts. |
Static proof that "now" cannot build, independent of the probe: every
`Planetary*` symbol the donor consumes is absent from CultLib main.
- The donor uses these (`git grep` at `42778c1`): `PlanetaryCubeFace` (47 uses),
`PlanetaryTileAddress` (24), `PlanetarySurfacePages`,
`PlanetaryProjectionKind`, `PlanetaryFaceCoordinate`, `PlanetaryPageSampling`,
`PlanetaryPageLayout`, `PlanetaryResidualResidency`, `PlanetaryLodSelector`,
`PlanetaryGpuPageBuilder`, `AdvancedErosionParameters` and the
`GameCultGeometry*` HLSL structs.
- Counts on CultLib `93fe1b9`: `PlanetaryCubeFace` 0, `PlanetaryTileAddress` 0,
`PlanetaryTopology` 0.
- `src/GameCult.Geometry/Shaders/` does not exist on main, so
`#include "GameCult.Geometry/GameCult.Geometry.hlsl"`
(`D3D12ZyphosTerrain.hlsli:4` at `42778c1`) has nothing to resolve.
**Not run, because it needs Windows and D3D12:**
- `tests/Aquarium.Engine.Tests`: `D3D12PlanetarySurfacePageTests`,
`D3D12PlanetaryTopologyParityTests` and `D3D12AdvancedErosionParityTests`,
which are GPU readback parity tests;
- `Aquarium.Engine` itself (Vortice D3D12);
- the Zyphos client.
Per the workstation budget, none of this ran on Starfire. Given the verdict,
it does not need to run at all: the GPU parity would prove a runtime nobody
will keep.
### 1.4 What is still right, and what has rotted
Still right:
- The donor's direction of dependency. Algorithms sit in a library and D3D12
resources stay in Fensalir. That matches the doctrine and Asura's own shape
(CultLib algorithms, consumer-owned rendering).
- The July migration plan's authority sentence: "CultMath owns how numeric
primitives behave; GameCult.Geometry owns what those primitives mean in
space" (CultLib `docs/cultmath-gamecult-geometry-migration-plan.md:56-57` at
`6a65369`). CultLib main adopted the same split at `63d6094` (2026-08-26),
and `HlslMirrorTests.cs:7-15` on main enforces the CultMath side.
- The idea of deleting `CultVec2`/`CultVec3` (CultLib `317b7d5`). Main still
carries both (see Q-F4).
Rotted:
1. **Ownership of the planet field.** The donor's objective
(`docs/cultmath-planetary-field-runtime-plan.md:3-15` at `42778c1`) makes a
shared library the canonical planet field for "Aetheria's daemon
simulation, Unity's three-dimensional planet renderer, Fensalir's D3D12
renderer, and Electron/Web strategic maps". Asura now owns Aetheria's
planets and rules the opposite:
- The field is HLSL only, and the CPU never evaluates it (Asura
`docs/target.md:42-47`, invariant 2).
- There is no landing and no surface streaming (the scope boundary).
- The donor's authoritative CPU queries, residency LOD and QSC page
streaming are therefore out of scope, or forbidden outright.
2. **The erosion port.** Asura's 4b-iii already rejected the July
`spherical_erosion` because it "lerps raw phases across cells instead of
blending phasors, which is not Phacelle" (`docs/cut-map.md:1132-1135`,
`:1736` at `63f9216`). Phacelle is going into CultMath fresh (2a-ii-b).
3. **Derivatives.** Zyphos's base field is ad hoc sine plates with a
central-difference gradient (`D3D12ZyphosTerrain.hlsli:113-129` at
`42778c1`). That is the pattern Asura's invariant 8 exists to prevent.
4. **The code owner is gone.** CultMath deleted the planetary runtime
(`6a16260`, reachable from CultLib main through the subtree). The receiving
CultLib branch never merged. On mainline the runtime is orphaned: it exists
only on unmerged branches and the three pushed `v0.1.0` tags.
5. **The build contract.** It needs an untracked local NuGet feed (see 1.3)
and paths from before the monorepo.
6. **The CultLib geometry half diverged from main's ruling.**
- The branch absorbs CSG into `GameCult.Geometry` (`6b44f96`). Main ruled
that `GameCult.Geometry.Csg` owns CSG production behaviour (`63d6094`,
`src/GameCult.Geometry/README.md`), and that repo shipped `distance(p)`
at `d84acb6`.
- The branch also adds a geometry worker, `CultGeometryWorkerDocuments`,
`CultGeometryWorkerProvider` and "v2 contracts". None of these exist on
main, and main's documents never moved to v2.
---
## 2. Ownership table
| Piece (donor) | Where it sits in the donor | Owner today | Disposition |
| --- | --- | --- | --- |
| Planet field definition, base field and erosion as one function | CultLib branch `src/GameCult.Geometry/Planetary/PlanetaryField.cs`, `Shaders/Planetary.hlsl` | **Asura** (field in HLSL, per body archetype) | Retire. Duplicates Asura's field |
| Advanced erosion filter (Johansen port) and `SphericalErosion` | branch `Planetary/AdvancedErosionFilter.cs`, `SphericalErosion.cs`, `Shaders/AdvancedErosionFilter.hlsl` | **Asura** 4b-iii (`AsuraErosion.hlsl`, fresh port with provenance) | Retire. Asura already ruled it "not a source" |
| Phacelle and noise primitives | embedded in the erosion port | **CultMath** (2a-ii-b `phacelle`, `CultPhasor`) | Retire the embedded copy |
| Cube-sphere/QSC topology, tile addresses, page layout, residency, LOD selection, patch meshes, radial refinement | branch `Planetary/PlanetaryTopology.cs`, `PlanetaryPages.cs`, `PlanetaryResidency.cs`, `PlanetaryPatch.cs`, `PlanetaryRadialRefinement.cs` | **No live consumer.** Asura meshes with surface nets and tiles per quad; streaming is out of scope | Retire. Revive only through a new campaign with a named consumer (Q-F1) |
| CPU ray, region and great-circle queries for an "Aetheria daemon" | branch `Planetary/PlanetaryQueries.cs` | **Forbidden** by Asura invariant 2. The dock-site query is Asura's | Retire |
| Map projections and `CMPT` tile codec (Electron maps) | branch `PlanetaryProjection.cs`, `PlanetaryMapTileEncoding.cs`, TS decoder | No consumer exists or is planned | Retire |
| `org.gamecult.geometry` Unity package and planetary viewer sample | branch `unity/org.gamecult.geometry/**`, tags `b65619f` | Superseded: Asura Cut 3 ships Geometry inside `org.gamecult.cultlib` | Retire the branch. Keep the pushed tags as immutable history (Q-F3) |
| Frequency-band selection by sample footprint | branch `Planetary/ErosionFrequencyBands.cs` | **Asura** (band limits per lowering; target invariant 8, Q11) | Retire. Same concept, and Asura implements it fresh |
| D3D12 page buffers, root parameters 29-32, dispatch, patch raster, debug modes | Fensalir `D3D12Renderer.cs:99-102,223` and about 157 planetary lines; `AquariumRenderPlan.cs:526-565` (render ABI) at `42778c1` | **Fensalir** would own it if Fensalir rendered planets. Its only producer is the retired runtime | Retire with the runtime |
| DXC include resolver for `Packages/org.gamecult.cultmath/shaders/` and `GameCult.Geometry/` | Fensalir `D3D12ShaderCompiler.cs:68-102` at `42778c1` | Fensalir. On main no shader includes CultMath HLSL at all | Retire. Its search paths are also stale (the standalone `CultMath/shaders`, pre-monorepo). Rebuild against `packages/cultmath/shaders` when a Fensalir shader first includes CultMath |
| Zyphos terrain shaders, page and patch entry points, `ZyphosPlanetarySurfacePages` | Fensalir `src/Aquarium.Zyphos/**` at `42778c1` | Fensalir's demo client. Main's Zyphos keeps its pre-July analytic sphere | Retire |
| Fensalir's `CubeFace`, `CubeFacePosition`, `CubeTileKey` and the projection code in `Aquarium.Engine.Fractal` | **Main keeps them.** The donor deleted them in favour of Geometry | **Fensalir** (fractal DSL, projection reports; 167 tests green on main) | Keep on main; nothing to do. The donor's deletion is void once the runtime is retired |
| Planetary flow organ (ocean and atmosphere advection), documentation only | Fensalir main: `docs/planetary-flow-{organ,nn-architecture,implementation-plan}.md` (289/462/185 lines); `docs/README.md:39-44`; `state/map.yaml:114-120` and the flow `next_actions` entries after `:171` | Fensalir, as plans. No code exists; last touched 2026-05-29. Not in Asura's scope (no atmospheres or oceans) | Q-F2 |
| Vector-type unification (delete `CultVec2`/`CultVec3`/`CultRect` in favour of CultMath `float2`/`float3`/`rect`) | CultLib branch `317b7d5`, `364c9cd` | **CultMath** owns the vector vocabulary (main `63d6094`). Main still has the duplicates: `CultGeometryPrimitives.cs:11,62,128` and the `origin` parameter of `CultGeometryIsoSurface.cs:42` and `CultGeometrySurfaceNets.cs:47` | Q-F4: a fresh cut on main, not the branch code |
| CSG absorption, geometry worker, v2 schemas, Rust `gamecult-geometry-rs` | CultLib branch | CSG: `GameCult.Geometry.Csg` (main's ruling). The rest have no owner and no consumer | Retire with the branch |
### Duplication against Asura (one side is cut, not kept in parallel)
| Concept | Donor | Asura | Side cut |
| --- | --- | --- | --- |
| Planet shape function | `PlanetaryFieldDefinition` plus base-field provider (CPU and HLSL) | the field `f(p) = |p| − (1 + h(u))`, HLSL only | donor |
| Erosion | July port with raw-phase lerp | 4b-iii fresh port, exact Phacelle, provenance file | donor |
| Level of detail | QSC pages, residency, projected-error LOD | surface-net grid resolution plus per-body tile N | donor. Asura's scope rules streaming out |
| Band limiting | `ErosionFrequencyBands` | per-lowering band limit (Q11) | donor |
| Unity packaging | `org.gamecult.geometry` | `org.gamecult.cultlib` (Cut 3, default A) | donor |
---
## 3. Cuts
Every cut below is deletion or documentation, with no new code. Numbers are
prefixed `P` so they cannot be confused with Asura's cut numbers.
### P0. Operator rulings (Self; blocks everything below)
Q-F1 and Q-F3 must be ruled before P1. Q-F2 gates P3. Q-F4 gates P4.
### P1. Archive the refs, then delete them (Fensalir, CultLib, standalone CultMath)
- **Precondition:** Q-F3 ruled. The non-planet work on the Fensalir donor
(Bokusho, Eve surface, Leap) must be either archived with it or adopted
separately first.
- **Deletes first:**
- Fensalir remote branches: `codex/geometry-ownership-migration` (`42778c1`)
and `codex/leap-packed-depth` (`492d123`, a strict ancestor).
- CultLib remote branches: `codex/geometry-ownership-migration` (`6a65369`)
and `codex/geometry-cultmesh-unity-release` (`b65619f`).
- The standalone CultMath remote `codex/geometry-ownership-migration`
(`b43cf49`), already an ancestor of CultMath `main`, so deleting it loses
nothing.
- **Then:**
- An annotated tag at each unique tip, so every commit stays reachable:
- Fensalir `archive/geometry-ownership-migration` → `42778c1`;
- CultLib `archive/geometry-ownership-migration` → `6a65369`;
- CultLib `archive/geometry-cultmesh-unity-release` → `b65619f`, if a
branch ref is wanted beyond the release tags that already pin it.
- The tag message names this map and the ruling.
- The published `gamecult-geometry{,-rs,-unity}-v0.1.0` tags stay: they are
released, immutable artifacts.
- **Authority map:**
- Owner of planet shape: Asura. Owner of numeric primitives: CultMath.
- Derived: the archive tags are history only, and nothing resolves a build
from them.
- Forbidden writers: any branch that could be merged back to revive
`Planetary*` in CultLib, or `cultmath_planetary_*` in CultMath.
- Shared paths: none. No mainline build references these refs; the mainline
probe proves Fensalir main builds without them.
- **Verification:**
- `git merge-base --is-ancestor <old tip> archive/<name>` for each deleted
ref, run before deleting.
- `git ls-remote --heads origin | grep -c geometry-ownership` gives 0 in all
three repos.
- Mainline probe re-run (Fensalir `e053486` + CultLib main): 167/167.
- Negative: `git grep -c "Planetary" origin/main -- src packages` in CultLib
stays at its current count (only `HlslMirrorTests.cs:12,14`).
- **Subtraction:** 5 remote branch refs, net of the 2–3 archive tags. The
unmerged surface removed from view is Fensalir +11,650/−591 (116 files) and
CultLib +14,933/−317 (156 files). No mainline lines change.
- **Hands budget:** about 20k tokens. It is ref surgery and needs the
operator's credentials for the pushes.
### P2. Asura documents: replace "do not delete it" with the ruling (Asura, docs only)
- **Deletes first, at Asura `63f9216`:**
- `docs/target.md:110-113`: the "Not consumers" bullet naming the branches.
- `docs/cut-map.md:814-820`, Cut 3's "Not a source", including
"do not delete it; see findings".
- **Then:**
- One sentence in each place: the July planetary line was retired on
2026-09-30 and archived at the tags from P1; Asura is the sole owner of
planet shape.
- `cut-map.md:1132-1135` and `:1736` keep their technical reason (raw-phase
lerp, not Phacelle). They point at the archive tag instead of the branch
names.
- `target.md:252` (the substrate fact about the `unity-v0.1.0` tag) stays
true and is unchanged.
- **Authority map:** `target.md` owns the ends, so the retirement ruling is
recorded under its dated operator rulings. The cut map only points at it.
- **Verification:**
- `rg -n "codex/geometry-" docs/` in Asura gives 0 lines.
- `rg -n "do not delete it" docs/` gives 0.
- **Subtraction:** about −8 +4 lines.
- **Timing:** Self can do this in the same pass that records the rulings. It
does not touch 2a-ii.
### P3. Fensalir main: record the disposition; flow docs per Q-F2 (Fensalir `main`)
- **If Q-F2 = retire. Deletes first, at `e053486`:**
- `docs/planetary-flow-organ.md`, `docs/planetary-flow-nn-architecture.md`
and `docs/planetary-flow-implementation-plan.md` (936 lines);
- `docs/README.md:39-44`;
- `state/map.yaml:114-120`, and the flow entries in `next_actions` (the
bullets beginning "Build the planetary flow organ" and "For planetary flow
modeling", about 10 lines after `:171`).
- **If Q-F2 = park:** add one "Status: parked 2026-09-30, no consumer" line at
the top of each of the three docs instead.
- **Then, either way:**
- One line in `state/map.yaml`: Fensalir renders no planet terrain beyond
the Zyphos demo's analytic sphere. Planet shape for GameCult games is
Asura's. If Fensalir ever renders an Asura body, it lowers Asura's field
HLSL and owns only D3D12 resources.
- Fix `README.md:141` from "planetary/fractal terrain demo" to "fractal
terrain demo", only if the operator agrees the demo carries no planet
ambition. Otherwise leave it.
- **Authority map:** Fensalir owns its renderer and demos. It claims no planet
field.
- **Verification:**
- `git grep -n -i "planetary" origin/main -- docs/README.md state/map.yaml`
matches the intended remainder.
- The mainline Fractal probe still gives 167/167; docs cannot break it.
- **Subtraction:** retire gives about −950 lines and +2. Park gives +3.
- **Hands budget:** about 15k tokens.
### P4. CultLib: collapse `CultVec2`, `CultVec3` and `CultRect` into CultMath, before Asura Cut 3 (only if Q-F4 = A)
- **Why now:**
- Asura Cut 3 (`docs/cut-map.md:801`) ships `GameCult.Geometry.dll` in
`org.gamecult.cultlib` 1.1.0.
- Both extractors take `CultVec3 origin`, so the duplicate type becomes
Unity public API in that release. Deleting it afterwards is a semver
major.
- `CultGeometrySurfaceNets.cs:83` already converts `CultVec3` to `float3`
internally.
- **Deletes first, at CultLib `93fe1b9`:**
- In `src/GameCult.Geometry/CultGeometryPrimitives.cs`:
- `CultVec2` (`:11-60`) and `CultVec3` (`:62-126`);
- `CultRect` (`:128-197`), which duplicates CultMath `rect`
(`packages/cultmath/src/CultMath/rect.cs:7`, added 2026-08-07).
- `CultCircle` and `CultSphere` stay; they are spatial meaning, and that is
Geometry's. They are rebuilt on `float2`/`float3`.
- **Then:**
- `CultGeometryIsoSurface.Extract(..., float3 origin = default, ...)`
(`:42`) and `CultGeometrySurfaceNets.Extract(..., float3 origin = default,
...)` (`:47`); delete the conversion at `:83`.
- Update the tests: `GeometryDocumentTests.cs` (16 uses), `IsoSurfaceTests.cs`
and `SurfaceNetsTests.cs`.
- Update `src/GameCult.Geometry/README.md`.
- **Explicitly out of scope:** CultMesh's native-slice value-type names
`"CultVec2"` and `"CultVec3"` (`packages/cultmesh-ts/test/cultmesh.test.ts:1717,2440,2453`,
and `src/GameCult.Mesh/docs/public-api.md`). Those are wire vocabulary with
their own owner. Record them as a finding for the CultMesh owner; do not
rename them here.
- **Authority map:**
- Owner: CultMath owns vector and rectangle values. Geometry owns what they
mean in space.
- Forbidden writers: any type in `GameCult.Geometry` that carries x/y/z
fields.
- **Verification (Yggdrasil):**
- `dotnet test tests/GameCult.Geometry.Tests`, with the per-file counts. The
Surface Nets byte-identical fixtures from Asura Cut 2 (31 fixtures) must
stay byte-identical.
- Negative: `git grep -n "CultVec\|CultRect" -- src/GameCult.Geometry tests/GameCult.Geometry.Tests`
gives 0.
- Stryker `--since:93fe1b9` on the touched files.
- **Subtraction:** about −190 lines of duplicate value types, plus test
churn, net negative.
- **Sequencing:** after Q13 (it blocks Cut 3 anyway) and before Cut 3's
release tag. It can run beside 2a-ii-b.
- **Hands budget:** about 60k tokens.
---
## 4. Sequencing against Asura
```text
Asura: 2a-ii-a snoise fix (Hands done 0a5f4bf, Soul running) -> 2a-ii-b Phacelle -> 2a-ii-c cultmath 0.3.0 (with bounded LS, already on main 93fe1b9)
\
Q13 (Geometry CultReference strings) ------------------------------------> Cut 3 cultlib-unity 1.1.0 ---> 4a ...
P4 (Q-F4 = A) ------------------/ (must land before this tag)
This map: P0 rulings -> P2 (Asura docs, any time) ; P1 (refs, after Q-F3) ; P3 (Fensalir docs, after Q-F2)
```
- None of P1–P3 touches CultMath or CultLib source, so none can collide with
the snoise fix, Phacelle, or the 0.3.0 release that carries bounded least
squares.
- P4 is the only cut on Asura's critical path. It must land before Cut 3's
tag, and it touches `GameCult.Geometry`, which Cut 3 packages. Run it in its
own worktree from `main`, never in the snoise worktree.
- The Asura campaign gains nothing from the donor. 4b-iii stays a fresh port.
---
## 5. Operator questions (one fork each)
### Q-F1. What is a planet in Fensalir *for*?
Asura answers this for Aetheria: orbital tiny planets, no landing. The donor
answered it for "every renderer, including an Aetheria daemon and strategic
maps", and that answer has been overtaken. What remains is Fensalir's own
Zyphos demo: the domain catalog runs from planet to continent, forest, tree,
leaf and pebble field (`ZyphosSpatialDomainCatalog.cs` on main). That is
landing-scale LOD, which Asura rules out.
- **A. No planet terrain in Fensalir for now.** Retire the donor (P1–P3). If a
GameCult game later wants planets in Fensalir, it lowers Asura's field HLSL.
- **B. Zyphos needs landing-scale planets.** That is a new campaign with its
own target. It would decide whether streaming LOD extends Asura's field
(one field, two lowerings) or is a separate organ. It must not revive the
July runtime as a second planet-field owner.
- **C. Keep the donor alive as a Fensalir-private runtime.** This recreates a
second planet-field authority beside Asura, over an orphaned library.
**Recommended: A.** Nothing on main consumes the donor. The Zyphos client has
not moved since 2026-05-30. B stays open as a future campaign and loses nothing
by waiting.
### Q-F2. The planetary *flow* documents in Fensalir: what are they for now?
There are three documents (936 lines) for a cube-sphere ocean and atmosphere
advection organ with neural-network budgets (FlowNet-S/M/T). No code exists,
they were last touched 2026-05-29, and their only client is the Zyphos demo.
Asura is not affected. Separately, Asura's target queues "the flow field as the
single owner of motion in Aetheria" as a later campaign. That is a different
flow.
- **A. Retire** (P3 deletes them). If Zyphos oceans return, their campaign
starts from a target, not from these plans.
- **B. Park them** with a status line.
**Recommended: B, weakly.** They carry real research (datasets, model sizing),
nothing depends on them, and parking costs 3 lines. Choose A if you want the
docs tree to describe only live machinery.
### Q-F3. The non-planet work that rides on the same Fensalir branch
The donor ref also holds 66 Bokusho commits (a D3D12 port beside the TS/WebGPU
`bokusho` repo), 10 Eve native-surface commits, and the Leap/stereo depth,
reservoir and loopback-audio work. None is on Fensalir main.
- **A. Archive the whole ref** under one tag in P1, and route each of those
lines to its own adoption decision later.
- **B. Adopt them before touching the ref.**
**Recommended: A.** An archive tag keeps every commit reachable, so B is still
possible afterwards. This map does not judge those lines.
### Q-F4. Delete Geometry's duplicate vectors before Asura Cut 3 ships them to Unity?
What is `CultVec3` for? Nothing that `float3` does not already do, and the
surface-nets code converts it straight to `float3` (`CultGeometrySurfaceNets.cs:83`).
The July branch deleted it, and main never did.
- **A. P4 before Cut 3:** no semver cost, and about −190 lines.
- **B. Ship Cut 3 as is:** a later deletion is a major bump for
`org.gamecult.cultlib`.
**Recommended: A.** It is the one piece of the geometry half that is right, and
it gets more expensive after Cut 3's release.
## 6. Findings not assigned to a cut
- **Unreproducible build (CultLib `6a65369`).** The July CultLib branch
restores `CultMath 0.1.0` from a git-ignored local feed. The "Fensalir and
Aetheria green" receipts in its progress document
(`docs/cultmath-gamecult-geometry-migration-progress.md`, stage 6) could not
have been reproduced from committed sources alone. The branch is being
retired, so this is recorded as a scar and needs no fix.
- **A failing test in the donor's July world.**
`ProjectionTests.CheckedInProjectionReportMatchesSampler` fails on Linux in
the July composite (169/170), and the same test passes on mainline. The most
likely cause is a platform difference in the regenerated report. It was not
chased, because the code is being retired.
- **CultMath's `HlslMirrorTests.cs:7-15`** is a negative spelling test. It
guards against planetary kernels returning to CultMath and is cited by Asura
as the ruling's enforcement. Keep it; after P1 its only threat is gone, but it
is cheap and names the boundary.
- **Stopgap note.** Composite multi-repo snapshots are how a Fensalir build
can be probed on Yggdrasil at all: `ygg-verify.sh` takes one repo, and
Fensalir needs sibling checkouts. The Idunn verify campaign should take a
multi-repo revision set rather than rely on this trick.

View file

@ -18,7 +18,11 @@ $liveProjectPath = if ([System.IO.Path]::IsPathRooted($ClientProject)) { $Client
$liveProjectPath = (Resolve-Path $liveProjectPath).Path $liveProjectPath = (Resolve-Path $liveProjectPath).Path
$liveAssemblyName = [System.IO.Path]::GetFileNameWithoutExtension($liveProjectPath) $liveAssemblyName = [System.IO.Path]::GetFileNameWithoutExtension($liveProjectPath)
$devRoot = Join-Path $repoRoot "artifacts\dev-reload" $devRoot = Join-Path $repoRoot "artifacts\dev-reload"
$slotRoot = Join-Path $devRoot "slots" # Everything the host may load as client code lives under $assemblyRoot (slots here, live-slots from dev-watch);
# it is the host's trusted root, so state, cache and logs in $devRoot are not part of it.
$assemblyRoot = Join-Path $devRoot "assemblies"
$slotRoot = Join-Path $assemblyRoot "slots"
$liveSlotRoot = Join-Path $assemblyRoot "live-slots"
$visibleStatePath = Join-Path $devRoot "state.clixml" $visibleStatePath = Join-Path $devRoot "state.clixml"
$headlessStatePath = Join-Path $devRoot "headless-state.clixml" $headlessStatePath = Join-Path $devRoot "headless-state.clixml"
$statePath = if ($Headless) { $headlessStatePath } else { $visibleStatePath } $statePath = if ($Headless) { $headlessStatePath } else { $visibleStatePath }
@ -79,9 +83,12 @@ function Remove-OldSlots {
return return
} }
$slots = Get-ChildItem -Path $slotRoot -Directory -ErrorAction SilentlyContinue | # Both roots hold client code the host may load; dev-watch adds a live slot per change and never prunes.
Sort-Object LastWriteTimeUtc -Descending | $slots = foreach ($root in @($slotRoot, $liveSlotRoot)) {
Select-Object -Skip $RetainSlots Get-ChildItem -Path $root -Directory -ErrorAction SilentlyContinue |
Sort-Object LastWriteTimeUtc -Descending |
Select-Object -Skip $RetainSlots
}
foreach ($slot in $slots) { foreach ($slot in $slots) {
try { try {
@ -195,7 +202,8 @@ function Start-AquariumProcess {
"--cache", $cultCachePath, "--cache", $cultCachePath,
"--shader-source", (Join-Path $SlotPath "Render\Shaders\D3D12HeightField.hlsl"), "--shader-source", (Join-Path $SlotPath "Render\Shaders\D3D12HeightField.hlsl"),
"--client-assembly", $LiveAssemblyPath, "--client-assembly", $LiveAssemblyPath,
"--client-reload-pointer", $liveReloadPointerPath "--client-reload-pointer", $liveReloadPointerPath,
"--client-trusted-root", $assemblyRoot
) )
if ($RunHeadless) { if ($RunHeadless) {
$arguments += "--headless" $arguments += "--headless"
@ -241,6 +249,17 @@ function Reopen-VisibleProcess {
$liveAssemblyPath = [string]$state.liveAssembly $liveAssemblyPath = [string]$state.liveAssembly
} }
# Stale state fails here, in words, instead of as a refused load inside the host.
$assemblyRootPrefix = [System.IO.Path]::GetFullPath($assemblyRoot).TrimEnd('\') + '\'
foreach ($recorded in @($slotPath, $liveAssemblyPath)) {
if (-not [System.IO.Path]::GetFullPath($recorded).StartsWith($assemblyRootPrefix, [System.StringComparison]::OrdinalIgnoreCase)) {
throw "Visible dev-reload state names '$recorded', outside the assemblies root '$assemblyRoot' (state from before the trusted-root layout, or the root moved). Run dev-reload without -Reopen to rebuild."
}
}
if (-not (Test-Path -LiteralPath $liveAssemblyPath)) {
throw "Visible dev-reload state names '$liveAssemblyPath', which no longer exists (pruned slot). Run dev-reload without -Reopen to rebuild."
}
$process = Start-AquariumProcess -SlotPath $slotPath -LiveAssemblyPath $liveAssemblyPath -RunHeadless:$false $process = Start-AquariumProcess -SlotPath $slotPath -LiveAssemblyPath $liveAssemblyPath -RunHeadless:$false
Wait-ForStartedAquarium -Process $process -ExpectWindow:$true Wait-ForStartedAquarium -Process $process -ExpectWindow:$true

View file

@ -20,7 +20,7 @@ $liveProjectPath = (Resolve-Path $liveProjectPath).Path
$liveAssemblyName = [System.IO.Path]::GetFileNameWithoutExtension($liveProjectPath) $liveAssemblyName = [System.IO.Path]::GetFileNameWithoutExtension($liveProjectPath)
$clientSourceRoot = Split-Path $liveProjectPath $clientSourceRoot = Split-Path $liveProjectPath
$watchLogPath = Join-Path $repoRoot "artifacts\dev-reload\watch.log" $watchLogPath = Join-Path $repoRoot "artifacts\dev-reload\watch.log"
$liveSlotRoot = Join-Path $repoRoot "artifacts\dev-reload\live-slots" $liveSlotRoot = Join-Path $repoRoot "artifacts\dev-reload\assemblies\live-slots"
$liveReloadPointerPath = Join-Path $repoRoot "artifacts\dev-reload\live-current.txt" $liveReloadPointerPath = Join-Path $repoRoot "artifacts\dev-reload\live-current.txt"
$shaderPath = Join-Path $repoRoot "src\Aquarium.Engine\Render\Shaders\Aquarium.hlsl" $shaderPath = Join-Path $repoRoot "src\Aquarium.Engine\Render\Shaders\Aquarium.hlsl"
$engineShaderRoot = Join-Path $repoRoot "src\Aquarium.Engine\Render\Shaders" $engineShaderRoot = Join-Path $repoRoot "src\Aquarium.Engine\Render\Shaders"
@ -455,12 +455,15 @@ function Wait-LiveReloadAcknowledged {
$stderrLog = if ($state.stderrLog) { [string]$state.stderrLog } else { $null } $stderrLog = if ($state.stderrLog) { [string]$state.stderrLog } else { $null }
$timeoutSeconds = [Math]::Max(1, $LiveReloadAckTimeoutSeconds) $timeoutSeconds = [Math]::Max(1, $LiveReloadAckTimeoutSeconds)
$deadline = (Get-Date).AddSeconds($timeoutSeconds) $deadline = (Get-Date).AddSeconds($timeoutSeconds)
$appliedLine = "Client runtime reload applied: $liveAssemblyPath" # The host logs the resolved path with backslashes doubled, which can differ from the path built here when the
# repo sits under a link. The slot directory name is unique, so match its leaf and the assembly name.
$slotLeaf = Split-Path -Leaf (Split-Path -Parent $liveAssemblyPath)
$appliedSuffix = ("$slotLeaf\" + (Split-Path -Leaf $liveAssemblyPath)).Replace("\", "\\")
while ((Get-Date) -lt $deadline) { while ((Get-Date) -lt $deadline) {
if (Test-Path $stdoutLog) { if (Test-Path $stdoutLog) {
$stdoutTail = (Get-Content -Path $stdoutLog -Tail 120 -ErrorAction SilentlyContinue) -join "`n" $stdoutTail = (Get-Content -Path $stdoutLog -Tail 120 -ErrorAction SilentlyContinue) -join "`n"
if ($stdoutTail.Contains($appliedLine)) { if ($stdoutTail -match ("(?m)^Client runtime reload applied: .*" + [regex]::Escape($appliedSuffix) + "\s*$")) {
Write-WatchLog "Live reload acknowledged by host: $liveAssemblyPath" Write-WatchLog "Live reload acknowledged by host: $liveAssemblyPath"
return return
} }

View file

@ -1,6 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<CultLibRoot Condition="'$(CultLibRoot)' == ''">$(MSBuildThisFileDirectory)..\..\..\CultLib</CultLibRoot>
<OutputType>WinExe</OutputType> <OutputType>WinExe</OutputType>
<TargetFramework>net10.0</TargetFramework> <TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
@ -22,7 +23,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\..\CultMath\src\CultMath\CultMath.csproj" /> <ProjectReference Include="$(CultLibRoot)\packages\cultmath\src\CultMath\CultMath.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View file

@ -18,8 +18,22 @@ public static class AquariumHost
ParseFieldReservoirMode(args), ParseFieldReservoirMode(args),
ParseFieldReservoirScale(args), ParseFieldReservoirScale(args),
ParseFieldReservoirSpatialReuseBudget(args)); ParseFieldReservoirSpatialReuseBudget(args));
using var runtimeLoader = new ClientRuntimeLoader(runtimeOptions, ParseClientAssemblyPath(args), ParseClientReloadPointerPath(args)); ClientRuntimeLoader? loader = null;
var runtime = runtimeLoader.Load(); IAquariumRuntime runtime;
try
{
loader = new ClientRuntimeLoader(runtimeOptions, ParseClientAssemblyPath(args), ParseClientReloadPointerPath(args), ParseClientTrustedRoot(args));
runtime = loader.Load();
}
catch (Exception error)
{
// Startup refusals carry raw, attacker-writable paths; the console gets them escaped, once, here.
Console.Error.WriteLine($"Client runtime failed to start ({ClientRuntimeLoader.Printable(error.GetType().FullName ?? error.GetType().Name)}). {ClientRuntimeLoader.Printable(error.Message)}");
loader?.Dispose();
return 1;
}
using var runtimeLoader = loader;
if (runtimeOptions.RenderDebugModeOverride is { } renderDebugModeOverride) if (runtimeOptions.RenderDebugModeOverride is { } renderDebugModeOverride)
{ {
runtime.GraphicsSettings = (runtime.GraphicsSettings with runtime.GraphicsSettings = (runtime.GraphicsSettings with
@ -258,6 +272,10 @@ public static class AquariumHost
?? Environment.GetEnvironmentVariable("AQUARIUM_LIVE_ASSEMBLY"); ?? Environment.GetEnvironmentVariable("AQUARIUM_LIVE_ASSEMBLY");
} }
private static readonly TrustedRootSetting TrustedRoot = TrustedRootSetting.FromProcessEnvironment();
private static string? ParseClientTrustedRoot(IReadOnlyCollection<string> args) => TrustedRoot.Resolve(args);
private static string? ParseClientReloadPointerPath(IReadOnlyCollection<string> args) private static string? ParseClientReloadPointerPath(IReadOnlyCollection<string> args)
{ {
var values = args.ToArray(); var values = args.ToArray();

View file

@ -8,17 +8,49 @@ public sealed class ClientRuntimeLoader : IDisposable
{ {
private readonly string? clientAssemblyPath; private readonly string? clientAssemblyPath;
private readonly string? clientReloadPointerPath; private readonly string? clientReloadPointerPath;
private readonly string? trustedRoot;
private readonly string? trustedRootAsGiven;
private readonly Stopwatch reloadClock = Stopwatch.StartNew(); private readonly Stopwatch reloadClock = Stopwatch.StartNew();
private readonly AquariumRuntimeOptions options; private readonly AquariumRuntimeOptions options;
private ReloadedRuntime? current; private ReloadedRuntime? current;
private TimeSpan lastReloadCheck; private TimeSpan lastReloadCheck;
private string? currentAssemblyPath; private string? currentAssemblyPath;
public ClientRuntimeLoader(AquariumRuntimeOptions options, string? clientAssemblyPath = null, string? clientReloadPointerPath = null) /// <summary>
/// Every assembly this loader runs, and every dependency or native library it resolves, must lie, links followed,
/// under <paramref name="trustedRoot"/> (default: the directory of the initial assembly). The root is resolved once
/// here and pinned; a volume root is refused. A relative initial path is taken against the working directory;
/// a relative or UNC reload target is refused. The boundary this enforces is the root directory's own ACLs.
/// </summary>
public ClientRuntimeLoader(
AquariumRuntimeOptions options,
string? clientAssemblyPath = null,
string? clientReloadPointerPath = null,
string? trustedRoot = null)
{ {
this.clientAssemblyPath = clientAssemblyPath; this.clientAssemblyPath = string.IsNullOrWhiteSpace(clientAssemblyPath) ? null : Path.GetFullPath(clientAssemblyPath);
this.clientReloadPointerPath = clientReloadPointerPath; this.clientReloadPointerPath = clientReloadPointerPath;
this.options = options; this.options = options;
var root = string.IsNullOrWhiteSpace(trustedRoot)
? this.clientAssemblyPath is null ? null : Path.GetDirectoryName(this.clientAssemblyPath)
: Path.GetFullPath(trustedRoot);
this.trustedRootAsGiven = root;
if (root is not null)
{
root = ResolveLinks(root);
if (string.Equals(
Path.TrimEndingDirectorySeparator(root),
Path.TrimEndingDirectorySeparator(Path.GetPathRoot(root) ?? root),
PathComparison))
{
throw new ArgumentException($"A drive or volume root cannot be the client runtime trusted root: {root}", nameof(trustedRoot));
}
Console.WriteLine($"Client runtime trusted root: {Printable(root)}");
}
this.trustedRoot = root;
} }
public IAquariumRuntime Runtime public IAquariumRuntime Runtime
@ -40,10 +72,13 @@ public sealed class ClientRuntimeLoader : IDisposable
return Runtime; return Runtime;
} }
public void Reload(string assemblyPath, AquariumRuntimeOptions options) public void Reload(string assemblyPath, AquariumRuntimeOptions options) =>
LoadResolved(ResolveTrusted(assemblyPath), options);
private void LoadResolved(string assemblyPath, AquariumRuntimeOptions options)
{ {
var previous = current; var previous = current;
var loadContext = new ClientAssemblyLoadContext(assemblyPath); var loadContext = new ClientAssemblyLoadContext(assemblyPath, trustedRoot!);
IAquariumRuntime? nextRuntime = null; IAquariumRuntime? nextRuntime = null;
try try
@ -103,25 +138,164 @@ public sealed class ClientRuntimeLoader : IDisposable
return; return;
} }
if (string.IsNullOrWhiteSpace(candidatePath) if (string.IsNullOrWhiteSpace(candidatePath))
|| string.Equals(candidatePath, currentAssemblyPath, StringComparison.OrdinalIgnoreCase)
|| !File.Exists(candidatePath))
{ {
return; return;
} }
try try
{ {
RequireLocalFullyQualified(candidatePath); // string rules first: no filesystem or network probe of a UNC path
RequireLexicallyUnderRoot(candidatePath); // and no probe of anything outside the root, whatever a link there points at
if (!File.Exists(candidatePath))
{
return;
}
var resolved = ResolveTrusted(candidatePath);
if (string.Equals(resolved, currentAssemblyPath, PathComparison))
{
return;
}
current?.Runtime.FlushState(); current?.Runtime.FlushState();
Reload(candidatePath, options); LoadResolved(resolved, options);
Console.WriteLine($"Client runtime reload applied: {candidatePath}"); Console.WriteLine($"Client runtime reload applied: {Printable(resolved)}");
} }
catch (Exception error) catch (Exception error)
{ {
Console.Error.WriteLine($"Client runtime reload failed; keeping previous runtime. {error.Message}"); Console.Error.WriteLine($"Client runtime reload failed; keeping previous runtime. {Printable(error.Message)}");
} }
} }
private static StringComparison PathComparison =>
OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
private string ResolveTrusted(string assemblyPath) =>
trustedRoot is null
? throw new InvalidOperationException("No trusted root for client runtime assemblies is set.")
: ResolveTrusted(trustedRoot, assemblyPath, trustedRootAsGiven);
private void RequireLexicallyUnderRoot(string path) =>
RequireLexicallyUnder(Path.GetFullPath(path), trustedRoot, trustedRootAsGiven);
// Pure string comparison against the root as resolved and as given: a path outside both is refused before any
// filesystem access, so a link there (to a UNC share, a mapped drive) is never followed or probed.
private static void RequireLexicallyUnder(string fullPath, params string?[] roots)
{
if (!roots.Any(root => root is not null && IsUnder(root, fullPath)))
{
throw new InvalidOperationException($"Client runtime path is outside the trusted root '{roots[0]}': {fullPath}");
}
}
private static bool IsUnder(string root, string path)
{
var relative = Path.GetRelativePath(root, path);
return !(relative == ".." || relative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal) || Path.IsPathRooted(relative));
}
// The final path of a local, fully qualified file under the already-resolved root; throws otherwise.
internal static string ResolveTrusted(string resolvedRoot, string path, string? rootAsGiven = null)
{
RequireLocalFullyQualified(path);
RequireLexicallyUnder(Path.GetFullPath(path), resolvedRoot, rootAsGiven);
var resolved = ResolveLinks(Path.GetFullPath(path));
if (!IsUnder(resolvedRoot, resolved))
{
throw new InvalidOperationException($"Client runtime path is outside the trusted root '{resolvedRoot}': {path}");
}
return resolved;
}
internal static void RequireLocalFullyQualified(string path)
{
if (!Path.IsPathFullyQualified(path) || (path.Length >= 2 && IsSeparator(path[0]) && IsSeparator(path[1])))
{
throw new InvalidOperationException($"Client runtime path must be local and fully qualified: {path}");
}
}
// Paths come from files other people can write. Exception messages carry them raw; every console write escapes
// them here, once: backslashes, control, format (bidi, zero-width, tag characters) and line/paragraph separator
// characters, by code point, and lone surrogates.
internal static string Printable(string text)
{
var builder = new System.Text.StringBuilder(text.Length);
for (var index = 0; index < text.Length;)
{
if (!System.Text.Rune.TryGetRuneAt(text, index, out var rune))
{
builder.Append($"\\u{(int)text[index]:x4}"); // a lone surrogate
index++;
continue;
}
index += rune.Utf16SequenceLength;
var category = System.Text.Rune.GetUnicodeCategory(rune);
if (rune.Value == '\\')
{
builder.Append("\\\\");
}
else if (category is System.Globalization.UnicodeCategory.Control or System.Globalization.UnicodeCategory.Format
or System.Globalization.UnicodeCategory.LineSeparator or System.Globalization.UnicodeCategory.ParagraphSeparator)
{
builder.Append(rune.Value switch
{
'\n' => "\\n",
'\r' => "\\r",
'\t' => "\\t",
<= 0xFFFF => $"\\u{rune.Value:x4}",
_ => $"\\U{rune.Value:x8}",
});
}
else
{
builder.Append(rune.ToString());
}
}
return builder.ToString();
}
private static bool IsSeparator(char c) => c is '/' or '\\';
// The path with every symlink or junction on it replaced by its final target.
internal static string ResolveLinks(string path, int depth = 0)
{
if (depth > 32)
{
throw new InvalidOperationException($"Too many links resolving {path}.");
}
for (var probe = path; probe is not null; probe = Path.GetDirectoryName(probe))
{
FileSystemInfo info = Directory.Exists(probe) ? new DirectoryInfo(probe) : new FileInfo(probe);
if (info.LinkTarget is null)
{
continue;
}
string target;
try
{
target = info.ResolveLinkTarget(returnFinalTarget: true)?.FullName
?? throw new InvalidOperationException($"Link does not resolve: {probe}");
}
catch (IOException error)
{
// Windows refuses to traverse a mount point made by a non-administrator ("untrusted mount point"):
// that is a refusal like any other, not a crash with a different type.
throw new InvalidOperationException($"Link cannot be resolved: {probe} ({error.GetType().Name})", error);
}
var rest = Path.GetRelativePath(probe, path);
return ResolveLinks(rest == "." ? target : Path.GetFullPath(Path.Combine(target, rest)), depth + 1);
}
return path;
}
private string RequireClientAssemblyPath() private string RequireClientAssemblyPath()
{ {
if (!string.IsNullOrWhiteSpace(clientAssemblyPath)) if (!string.IsNullOrWhiteSpace(clientAssemblyPath))
@ -150,7 +324,7 @@ public sealed class ClientRuntimeLoader : IDisposable
} }
} }
private sealed class ClientAssemblyLoadContext(string assemblyPath) : AssemblyLoadContext(isCollectible: true) private sealed class ClientAssemblyLoadContext(string assemblyPath, string trustedRoot) : AssemblyLoadContext(isCollectible: true)
{ {
private readonly AssemblyDependencyResolver resolver = new(assemblyPath); private readonly AssemblyDependencyResolver resolver = new(assemblyPath);
@ -162,13 +336,13 @@ public sealed class ClientRuntimeLoader : IDisposable
} }
var path = resolver.ResolveAssemblyToPath(assemblyName); var path = resolver.ResolveAssemblyToPath(assemblyName);
return path == null ? null : LoadFromAssemblyPath(path); return path == null ? null : LoadFromAssemblyPath(ResolveTrusted(trustedRoot, path));
} }
protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
{ {
var path = resolver.ResolveUnmanagedDllToPath(unmanagedDllName); var path = resolver.ResolveUnmanagedDllToPath(unmanagedDllName);
return path == null ? IntPtr.Zero : LoadUnmanagedDllFromPath(path); return path == null ? IntPtr.Zero : LoadUnmanagedDllFromPath(ResolveTrusted(trustedRoot, path));
} }
} }
} }

View file

@ -0,0 +1,48 @@
namespace Aquarium.Engine.Runtime;
/// <summary>
/// The client runtime trusted root as given on the command line or in AQUARIUM_CLIENT_TRUSTED_ROOT. The environment
/// value is taken (read and cleared) the first time anything is resolved, on every path, and cached: children do not
/// inherit it and a second resolution does not silently fall back to the default root. A blank flag value, a flag with
/// no value or a blank environment value is refused.
/// </summary>
internal sealed class TrustedRootSetting(Func<string?> takeEnvironment)
{
private const string Flag = "--client-trusted-root";
private const string Variable = "AQUARIUM_CLIENT_TRUSTED_ROOT";
private readonly Lazy<string?> fromEnvironment = new(takeEnvironment);
public static TrustedRootSetting FromProcessEnvironment() => new(() =>
{
var value = Environment.GetEnvironmentVariable(Variable);
Environment.SetEnvironmentVariable(Variable, null);
return value;
});
public string? Resolve(IReadOnlyCollection<string> args)
{
var environment = fromEnvironment.Value;
if (environment is not null && string.IsNullOrWhiteSpace(environment))
{
throw new ArgumentException($"{Variable} is set but empty; an empty value would fall back to the default root.");
}
var values = args.ToArray();
for (var index = 0; index < values.Length; index++)
{
if (!string.Equals(values[index], Flag, StringComparison.OrdinalIgnoreCase))
{
continue;
}
if (index + 1 >= values.Length || string.IsNullOrWhiteSpace(values[index + 1]))
{
throw new ArgumentException($"{Flag} needs a directory; an empty value would fall back to the default root.");
}
return values[index + 1];
}
return environment;
}
}

View file

@ -1,165 +0,0 @@
# Saga
**Planetary flow middleware for worlds that refuse to sit still.**
Saga is Fensalir's stochastic planetary flow organ: a cube-sphere native system
for streaming atmosphere, ocean, gas, debris, heat, and other transport fields
across whole planets at arbitrary level of detail.
It is built for studios that want living planets without hand-authoring a fake
weather loop, baking one heroic texture atlas, or stapling a particle system to
a skybox and calling it climate. Saga turns terrain, bathymetry, atmospheric
state, ocean reanalysis, arbitrary forcing sources, and learned stochastic
transport into compact flow packets the engine can stream, inspect, simulate,
and render.
No poles. No flat-Earth texture tricks. No private renderer arrows pretending
to be physics. Just a planet-scale flow field with provenance, uncertainty, and
enough teeth to survive a camera dive from orbit to coastline.
## The Pitch
Modern games and simulation tools can render planets. They rarely make them
move like planets.
Saga is the missing middleware layer between static world geometry and dynamic
planetary behavior:
```text
planet domain + relief + state + forcing + learned transport
-> stochastic advection packets
-> streaming flow pages, particles, weather, debris, clouds, currents, debug
```
Use it for:
- ocean surface currents and debris drift;
- atmospheric wind fields and gas-giant bands;
- volcanic, nuclear, magical, artificial, or stellar energy injection;
- multi-sun lighting and thermal forcing;
- tides, rotation, Coriolis-dominated flow, and exotic planetary regimes;
- gameplay-visible particles, clouds, smoke, spores, ash, foam, or pollutants;
- offline worldbuilding, cinematic previs, and realtime renderer guidance.
Saga is not a weather forecast API wearing a costume. It is a reusable engine
organ for representing and streaming stochastic flow over Fensalir's planetary
domains.
## What Makes It Different
### Cube-Sphere Native
Saga speaks Fensalir's optimized cube-sphere address space directly. Lat/lon
grids are source formats, not runtime truth. Every packet belongs to a tile,
LOD, projection, local tangent frame, and provenance chain.
### Stochastic By Design
Real flow is not one obedient arrow. Saga packets carry mean transport,
diffusivity/covariance, confidence, and optional transition kernels. Renderers
can draw clean vectors; simulations can keep the uncertainty instead of
throwing it into the sea and acting surprised later.
### Arbitrary Forcing
The evaluator is not Earth-locked. Saga conditions on explicit rotation and
Coriolis features plus variable-cardinality energy, mass, and momentum forcing
sources:
- one sun, binary suns, or no sun worth trusting;
- moons and tidal drivers;
- eruptions, impacts, reactors, orbital mirrors, industrial heat, spellstorms;
- gas-giant internal heat and extreme atmosphere bands;
- transient shock events and persistent planetary gradients.
Source count is data, not architecture.
### Built For Streaming
Saga is designed for camera-relative planet rendering:
- coarse flow far from the camera;
- refined flow where the player, shot, simulation, or uncertainty demands it;
- parent/child LOD consistency;
- cross-face seam continuity;
- explicit stale-page and model-version checks.
The renderer samples packets. It does not invent climate in a pixel shader
because the schedule got nervous.
## Architecture
Saga lives inside Fensalir because Fensalir already owns the machinery it needs:
- `CubeTileKey` and cube-sphere projection math;
- field evidence layers, especially `Transport`;
- selected cuts and residency planning;
- GPU resource pages and debug telemetry;
- renderer/simulation lowering boundaries.
Saga's live shape:
```text
source manifests
-> cube-sphere dataset bakes
-> training shards
-> FlowNet-S / FlowNet-M / optional FlowNet-T
-> Saga stochastic advection packets
-> Fensalir Transport field claims
-> GPU pages, particle advection, weather visuals, debug probes
```
## Model Line
Saga uses a staged neural architecture plan:
- `FlowNet-S`: 8-15M parameters, local baseline for ingestion, calibration, and
export.
- `FlowNet-M`: 40-60M parameters, first serious runtime/distillation model with
local tile encoders, a cube-sphere graph processor, and stochastic heads.
- `FlowNet-T`: 150-300M parameters, optional global teacher for offline
distillation and ensemble behavior.
The model emits stochastic advection parameters, not just velocity:
- tangent mean velocity;
- positive-semidefinite 2x2 covariance/diffusivity;
- calibrated confidence;
- optional neighbor transition logits;
- provenance and model identity.
## Data Spine
Saga's first research targets:
- ETOPO / GEBCO for relief and bathymetry;
- ERA5 for atmosphere;
- GLORYS / OSCAR / HYCOM candidates for ocean currents;
- PlasticAdrift and drifter transition matrices for stochastic debris
transport validation;
- synthetic analytic worlds for contract and seam tests before the ocean gets
expensive.
Every source needs a manifest. No manifest, no training shard. The altar wants
receipts.
## First Vertical Slice
1. Define the Saga packet contracts.
2. Bake a synthetic cube-sphere flow world.
3. Export Transport field pages.
4. Render/debug vectors, covariance ellipses, confidence, and selected LOD.
5. Train FlowNet-S on synthetic + tiny ERA5 wind.
6. Add ocean surface current targets.
7. Add PlasticAdrift transition validation.
8. Promote FlowNet-M when the baseline has failed in useful, measured ways.
## Boundary
Saga owns reusable planetary flow mechanics. Clients own meaning.
Fensalir clients may ask for currents, winds, debris drift, cloud motion, ash
transport, or gas-giant bands. They may not create a private flow authority that
bypasses Saga packets and Fensalir Transport claims.
That is the deal: the planet can be wild, but the authority has to be clean.

View file

@ -1,14 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\Aquarium.Engine.Contracts\Aquarium.Engine.Contracts.csproj" />
<ProjectReference Include="..\Aquarium.Engine.Fractal\Aquarium.Engine.Fractal.csproj" />
</ItemGroup>
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View file

@ -1,65 +0,0 @@
using Aquarium.Engine.Fractal;
using System.Numerics;
namespace Saga;
public static class SagaOrgan
{
public const string Name = "Saga";
public const string Description =
"Cube-sphere stochastic planetary flow for Fensalir Transport fields.";
}
public readonly record struct SagaFlowDomain(
string DomainId,
double PlanetRadiusMeters,
string ProjectionId,
string GridVersion);
public readonly record struct SagaFlowRequest(
SagaFlowDomain Domain,
CubeTileKey Tile,
int SampleResolution,
double TimeSeconds,
SagaCoriolisFrame Coriolis,
IReadOnlyList<SagaForcingSource> ForcingSources);
public readonly record struct SagaCoriolisFrame(
Vector3 RotationAxis,
double AngularVelocityRadiansPerSecond,
double LocalF,
Vector2 LocalBeta);
public readonly record struct SagaForcingSource(
string SourceId,
SagaForcingKind Kind,
SagaForcingGeometry Geometry,
Vector3 PlanetDirection,
Vector3 LocalTangentDirection,
double Intensity,
double RadiusMeters,
double Attenuation,
double TimePhase);
public readonly record struct SagaAdvectionSample(
Vector2 MeanVelocity,
SagaCovariance2D Diffusivity,
double Confidence);
public readonly record struct SagaCovariance2D(double C00, double C01, double C11);
public enum SagaForcingKind
{
Energy,
Mass,
Momentum,
}
public enum SagaForcingGeometry
{
Directional,
Point,
Area,
Volume,
}

View file

@ -21,12 +21,6 @@ current_model:
implementation: src/Aquarium.Engine.Fractal implementation: src/Aquarium.Engine.Fractal
tests: tests/Aquarium.Engine.Fractal.Tests tests: tests/Aquarium.Engine.Fractal.Tests
receipt_tool: tools/Aquarium.Fractal.Receipt receipt_tool: tools/Aquarium.Fractal.Receipt
saga:
implementation: src/Saga
purpose: >
Stochastic planetary flow middleware for cube-sphere Transport fields,
arbitrary forcing, explicit Coriolis/rotation conditioning, and learned
atmosphere/ocean/debris advection packets.
demos: demos:
fensalir_splash: src/Aquarium.Fensalir fensalir_splash: src/Aquarium.Fensalir
minimal: src/Aquarium.Sample.Minimal minimal: src/Aquarium.Sample.Minimal

View file

@ -1,18 +0,0 @@
# Fractal Surface Visible Slice
Objective: make the live Zyphos scene test authored fractal reservoir terrain instead of a decorative proxy.
Kept:
- GPU-resident 2M splat reservoir field.
- Separate SDF, PBR, and radiosity reservoir layers.
- `.aquageo` selected-cut program lowering.
Changed:
- Packed IFS transform rows now preserve cube-sphere tile face/level/x/y.
- Compute maps authored splats onto cube-sphere faces instead of a generic +Z cap.
- Visible splats render as tangent-frame surface patches, not camera-facing stickers.
- Zyphos camera targets the selected domain while keeping the parent as orbit anchor.
Still not good enough:
- The live view is fast and the reservoir is populated, but the current surface-consumption pass still reads too abstractly under the noisy starfield.
- Next coherent cut is a real clustered surface resolve or ray-query style splat surface pass, not more billboard cosmetics.

View file

@ -20,6 +20,7 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\src\Aquarium.Engine\Aquarium.Engine.csproj" /> <ProjectReference Include="..\..\src\Aquarium.Engine\Aquarium.Engine.csproj" />
<ProjectReference Include="..\..\src\Aquarium.Sample.Minimal\Aquarium.Sample.Minimal.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View file

@ -0,0 +1,485 @@
using System.Diagnostics;
using Aquarium.Engine;
using Aquarium.Engine.Input;
using Aquarium.Engine.Runtime;
namespace Aquarium.Engine.Tests;
/// <summary>Runs only where this process can create symbolic links; otherwise reported as skipped with the reason.</summary>
public sealed class SymlinkFactAttribute : FactAttribute
{
public SymlinkFactAttribute()
{
var probe = Path.Combine(Path.GetTempPath(), "aquarium-symlink-probe-" + Guid.NewGuid().ToString("N"));
try
{
File.CreateSymbolicLink(probe, Path.GetTempPath());
File.Delete(probe);
}
catch (Exception error) when (error is IOException or UnauthorizedAccessException)
{
Skip = "This account cannot create symbolic links: " + error.Message;
}
}
}
/// <summary>Junctions exist only on Windows.</summary>
public sealed class JunctionFactAttribute : FactAttribute
{
public JunctionFactAttribute()
{
if (!OperatingSystem.IsWindows())
{
Skip = "NTFS junctions exist only on Windows; run this test there.";
}
}
}
/// <summary>Windows file names cannot contain a newline, so this setup cannot be built there.</summary>
public sealed class NewlineInFileNameFactAttribute : FactAttribute
{
public NewlineInFileNameFactAttribute()
{
if (OperatingSystem.IsWindows())
{
Skip = "Windows file names cannot contain a newline; the escaping is covered by the Printable tests.";
}
}
}
public sealed class ClientRuntimeLoaderTrustTests : IDisposable
{
private static readonly AquariumRuntimeOptions Options = new(true, null);
private readonly string work = Path.Combine(Path.GetTempPath(), "aquarium-trust-" + Guid.NewGuid().ToString("N"));
private readonly string trusted;
private readonly string outside;
public ClientRuntimeLoaderTrustTests()
{
trusted = Directory.CreateDirectory(Path.Combine(work, "trusted")).FullName;
outside = Directory.CreateDirectory(Path.Combine(work, "outside")).FullName;
}
// A loaded assembly stays locked on Windows until its unloaded context is collected: tolerate that here.
public void Dispose()
{
for (var attempt = 0; attempt < 5; attempt++)
{
try
{
Directory.Delete(work, recursive: true);
return;
}
catch (Exception error) when (error is IOException or UnauthorizedAccessException)
{
GC.Collect();
GC.WaitForPendingFinalizers();
Thread.Sleep(100);
}
}
Console.Error.WriteLine($"Warning: test cleanup could not delete (locked loaded assembly?): {ClientRuntimeLoader.Printable(work)}");
}
// A real client assembly: the minimal sample, copied so its location is ours to choose.
private static string Copy(string directory, string name = "client.dll")
{
var path = Path.Combine(directory, name);
File.Copy(typeof(Aquarium.Sample.Minimal.MinimalRuntime).Assembly.Location, path);
return path;
}
[Fact]
public void AssemblyInsideTheTrustedRootLoadsAndReloads()
{
var first = Copy(trusted, "a.dll");
var second = Copy(Directory.CreateDirectory(Path.Combine(trusted, "slot2")).FullName);
using var loader = new ClientRuntimeLoader(Options, first);
loader.Load();
var before = loader.Runtime;
loader.Reload(second, Options);
Assert.NotSame(before, loader.Runtime);
}
[Fact]
public void SiblingDirectoryOfTheInitialAssemblyLoadsOnlyInsideTheExplicitRoot()
{
// dev-watch reloads from live-slots, a sibling of the slot the host started in.
var slot = Directory.CreateDirectory(Path.Combine(trusted, "slots", "s1")).FullName;
var live = Directory.CreateDirectory(Path.Combine(trusted, "live-slots", "s2")).FullName;
var sibling = Copy(live);
using var loader = new ClientRuntimeLoader(Options, Copy(slot), trustedRoot: trusted);
loader.Load();
loader.Reload(sibling, Options);
using var narrow = new ClientRuntimeLoader(Options, Path.Combine(slot, "client.dll"));
narrow.Load();
Assert.Throws<InvalidOperationException>(() => narrow.Reload(sibling, Options)); // default root is the initial directory
}
[Fact]
public void InitialAssemblyOutsideTheExplicitRootIsRefused()
{
using var loader = new ClientRuntimeLoader(Options, Copy(outside), trustedRoot: trusted);
Assert.Throws<InvalidOperationException>(() => loader.Load());
}
[Fact]
public void ReloadOutsideTheRootViaDotDotOrRelativePathIsRefused()
{
using var loader = new ClientRuntimeLoader(Options, Copy(trusted, "a.dll"));
loader.Load();
var escaped = Copy(outside);
Assert.Throws<InvalidOperationException>(() => loader.Reload(escaped, Options));
Assert.Throws<InvalidOperationException>(() => loader.Reload(Path.Combine(trusted, "..", "outside", "client.dll"), Options));
Assert.Throws<InvalidOperationException>(() => loader.Reload("a.dll", Options));
}
[Theory]
[InlineData("//host/share/client.dll")]
[InlineData(@"\\host\share\client.dll")]
[InlineData(@"\/host/share\client.dll")]
[InlineData(@"/\host\share/client.dll")]
public void UncPathsInAnySeparatorMixAreRefused(string path)
{
Assert.Throws<InvalidOperationException>(() => ClientRuntimeLoader.ResolveTrusted(trusted, path));
}
[Fact]
public void AVolumeRootCannotBeTheTrustedRoot()
{
Assert.Throws<ArgumentException>(() => new ClientRuntimeLoader(Options, Copy(trusted), trustedRoot: Path.GetPathRoot(trusted)));
}
[Fact]
public void ADependencyOrNativeLibraryOutsideTheRootIsRefused()
{
// The load context resolves dependencies through the same check; assert the check it calls.
var dependency = Path.Combine(outside, "dep.dll");
File.WriteAllText(dependency, "");
Assert.Throws<InvalidOperationException>(() => ClientRuntimeLoader.ResolveTrusted(ClientRuntimeLoader.ResolveLinks(trusted), dependency));
var inside = Path.Combine(trusted, "dep.so");
File.WriteAllText(inside, "");
Assert.Equal(inside, ClientRuntimeLoader.ResolveTrusted(ClientRuntimeLoader.ResolveLinks(trusted), inside));
}
[SymlinkFact]
public void SymlinkedFileOrDirectoryPointingOutsideTheRootIsRefused()
{
var fileLink = Path.Combine(trusted, "link.dll");
var dirLink = Path.Combine(trusted, "dirlink");
File.CreateSymbolicLink(fileLink, Copy(outside));
Directory.CreateSymbolicLink(dirLink, outside);
using var loader = new ClientRuntimeLoader(Options, Copy(trusted, "a.dll"));
loader.Load();
Assert.Throws<InvalidOperationException>(() => loader.Reload(fileLink, Options));
Assert.Throws<InvalidOperationException>(() => loader.Reload(Path.Combine(dirLink, "client.dll"), Options));
}
[JunctionFact]
public void JunctionPointingOutsideTheRootIsRefused()
{
var junction = Path.Combine(trusted, "junction");
Copy(outside);
var mklink = Process.Start(new ProcessStartInfo("cmd.exe", $"/c mklink /J \"{junction}\" \"{outside}\"") { UseShellExecute = false, CreateNoWindow = true })!;
mklink.WaitForExit();
Assert.Equal(0, mklink.ExitCode);
using var loader = new ClientRuntimeLoader(Options, Copy(trusted, "a.dll"));
loader.Load();
// Windows refuses an untrusted (non-administrator) mount point itself; the loader reports it as a refusal too.
Assert.ThrowsAny<InvalidOperationException>(() => loader.Reload(Path.Combine(junction, "client.dll"), Options));
}
[SymlinkFact]
public void ALoadedLinkIsStoredByItsResolvedPathSoThePointerDoesNotReloadItEveryPoll()
{
var real = Copy(Directory.CreateDirectory(Path.Combine(trusted, "real")).FullName);
var link = Path.Combine(trusted, "link.dll");
File.CreateSymbolicLink(link, real);
var pointer = Path.Combine(work, "pointer.txt");
File.WriteAllText(pointer, link);
using var loader = new ClientRuntimeLoader(Options, Copy(trusted, "a.dll"), pointer);
loader.Load();
Thread.Sleep(600); // the loader polls the pointer at most every 500 ms
loader.Update(0.01f, new InputState());
var afterFirst = loader.Runtime; // the link was loaded once, by its resolved path
Thread.Sleep(600);
loader.Update(0.01f, new InputState());
Assert.Same(afterFirst, loader.Runtime);
}
[SymlinkFact]
public void TheTrustedRootIsPinnedAtConstructionAndNotReResolved()
{
var first = Directory.CreateDirectory(Path.Combine(work, "first")).FullName;
var second = Directory.CreateDirectory(Path.Combine(work, "second")).FullName;
var rootLink = Path.Combine(work, "root");
Directory.CreateSymbolicLink(rootLink, first);
using var loader = new ClientRuntimeLoader(Options, Copy(first), trustedRoot: rootLink);
loader.Load();
Directory.Delete(rootLink);
Directory.CreateSymbolicLink(rootLink, second); // the root now names another directory
var elsewhere = Copy(second, "other.dll");
Assert.Throws<InvalidOperationException>(() => loader.Reload(Path.Combine(rootLink, "other.dll"), Options));
Assert.Throws<InvalidOperationException>(() => loader.Reload(elsewhere, Options));
}
[Fact]
public void PointerNamingAnAssemblyOutsideTheRootKeepsThePreviousRuntime()
{
var pointer = Path.Combine(work, "pointer.txt");
File.WriteAllText(pointer, Copy(outside));
using var loader = new ClientRuntimeLoader(Options, Copy(trusted, "a.dll"), pointer);
loader.Load();
var before = loader.Runtime;
Thread.Sleep(600);
loader.Update(0.01f, new InputState());
Assert.Same(before, loader.Runtime);
}
[Fact]
public void AnUncPointerIsRefusedAndReportedBeforeAnyFilesystemProbe()
{
var pointer = Path.Combine(work, "pointer.txt");
File.WriteAllText(pointer, "//no-such-host.invalid/share/client.dll");
using var loader = new ClientRuntimeLoader(Options, Copy(trusted, "a.dll"), pointer);
loader.Load();
var errors = CaptureError(() =>
{
Thread.Sleep(600);
loader.Update(0.01f, new InputState());
});
// File.Exists on this path would return false silently; the string rule must speak first.
Assert.Contains("local and fully qualified", errors);
}
[NewlineInFileNameFact]
public void ControlCharactersInAPointerTargetAreEscapedInTheLog()
{
var hostile = Path.Combine(outside, "a\nClient runtime reload applied: forged.dll");
File.Copy(typeof(Aquarium.Sample.Minimal.MinimalRuntime).Assembly.Location, hostile);
var pointer = Path.Combine(work, "pointer.txt");
File.WriteAllText(pointer, hostile);
using var loader = new ClientRuntimeLoader(Options, Copy(trusted, "a.dll"), pointer);
loader.Load();
var errors = CaptureError(() =>
{
Thread.Sleep(600);
loader.Update(0.01f, new InputState());
});
Assert.Contains("outside the trusted root", errors);
Assert.DoesNotContain("\nClient runtime reload applied", errors);
Assert.Contains("\\nClient runtime reload applied", errors);
Assert.Equal("a\\u0007b", ClientRuntimeLoader.Printable("a\u0007b"));
}
[Fact]
public void TheTrustedRootEnvironmentVariableIsTakenOnceOnEveryPathAndCached()
{
const string Name = "AQUARIUM_CLIENT_TRUSTED_ROOT";
Environment.SetEnvironmentVariable(Name, "/from/env");
var setting = TrustedRootSetting.FromProcessEnvironment();
Assert.Equal("/from/flag", setting.Resolve(["--client-trusted-root", "/from/flag"]));
Assert.Null(Environment.GetEnvironmentVariable(Name)); // cleared although the flag won
Assert.Equal("/from/env", setting.Resolve([])); // cached: a second resolution does not fall to the default root
}
[Theory]
[InlineData("")]
[InlineData(" ")]
public void ABlankEnvironmentValueIsRefusedLikeABlankFlag(string value)
{
Assert.Throws<ArgumentException>(() => new TrustedRootSetting(() => value).Resolve([]));
Assert.Throws<ArgumentException>(() => new TrustedRootSetting(() => null).Resolve(["--client-trusted-root", value]));
Assert.Throws<ArgumentException>(() => new TrustedRootSetting(() => null).Resolve(["--client-trusted-root"]));
}
[Fact]
public void APathOutsideTheRootIsRefusedBeforeAnyLinkOnItIsFollowed()
{
// A link loop outside the root: following it would throw "Too many links"; the string check must refuse first.
var a = Path.Combine(outside, "a");
var b = Path.Combine(outside, "b");
try
{
Directory.CreateSymbolicLink(a, b);
Directory.CreateSymbolicLink(b, a);
}
catch (Exception error) when (error is IOException or UnauthorizedAccessException)
{
// No links here: the check is still exercised by the nonexistent outside path below.
}
var error2 = Assert.Throws<InvalidOperationException>(
() => ClientRuntimeLoader.ResolveTrusted(ClientRuntimeLoader.ResolveLinks(trusted), Path.Combine(a, "client.dll")));
Assert.Contains("outside the trusted root", error2.Message);
}
[Fact]
public void ANonexistentPointerTargetOutsideTheRootIsRefusedAndReportedNotSilentlyIgnored()
{
var pointer = Path.Combine(work, "pointer.txt");
File.WriteAllText(pointer, Path.Combine(outside, "not-there.dll"));
using var loader = new ClientRuntimeLoader(Options, Copy(trusted, "a.dll"), pointer);
loader.Load();
var errors = CaptureError(() =>
{
Thread.Sleep(600);
loader.Update(0.01f, new InputState());
});
Assert.Contains("outside the trusted root", errors);
}
[SymlinkFact]
public void ARootReachedThroughALinkAsGivenStillAcceptsPathsUnderIt()
{
var real = Directory.CreateDirectory(Path.Combine(work, "real")).FullName;
var rootLink = Path.Combine(work, "rootlink");
Directory.CreateSymbolicLink(rootLink, real);
Copy(real, "a.dll");
var viaLink = Path.Combine(rootLink, "b.dll");
File.Copy(typeof(Aquarium.Sample.Minimal.MinimalRuntime).Assembly.Location, viaLink);
using var loader = new ClientRuntimeLoader(Options, Path.Combine(rootLink, "a.dll"), trustedRoot: rootLink);
loader.Load();
loader.Reload(viaLink, Options);
}
[Fact]
public void ABackslashInAPointerTargetIsEscapedExactlyOnceInTheLog()
{
if (OperatingSystem.IsWindows())
{
return; // a backslash is a separator in a Windows file name; the escaping itself is covered by the Printable tests
}
var hostile = Path.Combine(outside, "x\\y.dll");
File.Copy(typeof(Aquarium.Sample.Minimal.MinimalRuntime).Assembly.Location, hostile);
var pointer = Path.Combine(work, "pointer.txt");
File.WriteAllText(pointer, hostile);
using var loader = new ClientRuntimeLoader(Options, Copy(trusted, "a.dll"), pointer);
loader.Load();
var errors = CaptureError(() =>
{
Thread.Sleep(600);
loader.Update(0.01f, new InputState());
});
Assert.Contains("x\\\\y.dll", errors); // one literal backslash is shown as two characters
Assert.DoesNotContain("x\\\\\\\\y.dll", errors); // not four: the message is not escaped a second time
}
[Fact]
public void AStartupRefusalIsLoggedByTheHostAndExitsNonzero()
{
var volumeRoot = Path.GetPathRoot(Path.GetFullPath(work))!;
var exit = 0;
var errors = CaptureError(() => exit = AquariumHost.Run(["--headless", "--client-trusted-root", volumeRoot]));
Assert.Equal(1, exit);
Assert.Contains("Client runtime failed to start (System.ArgumentException).", errors);
Assert.Contains("cannot be the client runtime trusted root", errors);
}
[Fact]
public void ALoadedClientSeesItsOwnFilePathAsAssemblyLocation()
{
var path = Copy(trusted, "a.dll");
using var loader = new ClientRuntimeLoader(Options, path);
loader.Load();
Assert.Equal(ClientRuntimeLoader.ResolveLinks(path), loader.Runtime.GetType().Assembly.Location);
}
[Fact]
public void LoggedPathsEscapeAstralFormatCharactersAndLoneSurrogatesByCodePoint()
{
Assert.Equal("a\\U000e0001b", ClientRuntimeLoader.Printable("a\U000E0001b")); // language tag
Assert.Equal("a\\U000e0041b", ClientRuntimeLoader.Printable("a\U000E0041b")); // tag letter
Assert.Equal("a\\U0001d173b", ClientRuntimeLoader.Printable("a\U0001D173b")); // musical begin beam
Assert.Equal("a\\ud800b", ClientRuntimeLoader.Printable("a\ud800b")); // lone high surrogate
Assert.Equal("a\\udc00b", ClientRuntimeLoader.Printable("a\udc00b")); // lone low surrogate
Assert.Equal("a\\ud800\\ud800b", ClientRuntimeLoader.Printable("a\ud800\ud800b")); // two highs in a row
Assert.Equal("a\U0001F600b", ClientRuntimeLoader.Printable("a\U0001F600b")); // an ordinary astral character is kept
}
[Fact]
public void LoggedPathsEscapeBackslashesLineSeparatorsAndBidiAndZeroWidthControls()
{
Assert.Equal("a\\\\b", ClientRuntimeLoader.Printable("a\\b"));
Assert.Equal("a\\u2028b", ClientRuntimeLoader.Printable("a\u2028b"));
Assert.Equal("a\\u2029b", ClientRuntimeLoader.Printable("a\u2029b"));
Assert.Equal("a\\u202eb", ClientRuntimeLoader.Printable("a\u202eb"));
Assert.Equal("a\\u200bb", ClientRuntimeLoader.Printable("a\u200bb"));
Assert.Equal("plain-name.dll", ClientRuntimeLoader.Printable("plain-name.dll"));
}
[Fact]
public void DevScriptsKeepEverythingLoadableUnderOneAssembliesRootThatIsNotTheWholeDevRoot()
{
var scripts = Path.Combine(RepositoryRoot(), "scripts");
var reload = File.ReadAllText(Path.Combine(scripts, "dev-reload.ps1"));
var watch = File.ReadAllText(Path.Combine(scripts, "dev-watch.ps1"));
Assert.Contains("\"--client-trusted-root\", $assemblyRoot", reload);
Assert.DoesNotContain("\"--client-trusted-root\", $devRoot", reload);
Assert.Contains("$slotRoot = Join-Path $assemblyRoot \"slots\"", reload);
Assert.Contains("artifacts\\dev-reload\\assemblies\\live-slots", watch);
}
[Fact]
public void DevScriptsMatchTheHostAckByItsUniqueSlotLeafPruneLiveSlotsAndRejectStaleReopenState()
{
var scripts = Path.Combine(RepositoryRoot(), "scripts");
var reload = File.ReadAllText(Path.Combine(scripts, "dev-reload.ps1"));
var watch = File.ReadAllText(Path.Combine(scripts, "dev-watch.ps1"));
Assert.Contains(".Replace(\"\\\", \"\\\\\")", watch); // the host logs backslashes doubled
Assert.DoesNotContain("Contains($appliedLine)", watch);
Assert.Contains("@($slotRoot, $liveSlotRoot)", reload);
Assert.Contains("outside the assemblies root", reload);
Assert.Contains("no longer exists (pruned slot)", reload);
}
private static string CaptureError(Action action)
{
var original = Console.Error;
using var captured = new StringWriter();
Console.SetError(captured);
try
{
action();
}
finally
{
Console.SetError(original);
}
return captured.ToString();
}
private static string RepositoryRoot()
{
var directory = new DirectoryInfo(AppContext.BaseDirectory);
while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Fensalir.sln")))
{
directory = directory.Parent;
}
return directory?.FullName ?? throw new InvalidOperationException("Fensalir.sln not found above the test binaries.");
}
}