(Adaptive Loop) Prepare for Pass 3
This commit is contained in:
1 parent
f34f4e5014
commit
816a0d8e14
35 files changed
+64
-6057
No files matched your search
@@ -1,9 +0,0 @@
|
||||
node_modules/
|
||||
dist/
|
||||
dist-ssr/
|
||||
coverage/
|
||||
test-results/
|
||||
playwright-report/
|
||||
playwright/.cache/
|
||||
*.local
|
||||
.DS_Store
|
||||
@@ -1,29 +0,0 @@
|
||||
# Assets — Adaptive Loop
|
||||
|
||||
All visuals are **procedural SVG/CSS** — generated in code, not downloaded or
|
||||
ripped. No image, font, music, or commercial asset files are included or fetched.
|
||||
|
||||
## Visual systems (all code-generated)
|
||||
|
||||
- **Board**: three interlocking hexagonal rings drawn as stroked SVG `<polygon>`
|
||||
outlines through each loop's six chamber coordinates
|
||||
(`src/presentation/geometry.ts`), one distinct color per loop. Chambers are SVG
|
||||
`<g>` nodes with circles, population glyphs (shape + color + label), resource
|
||||
text, fixture glyphs, and slot labels.
|
||||
- **Species encoding**: shape + color + short label — producer `●` (green),
|
||||
grazer `■` (amber), phage `▲` (pink). Never color alone.
|
||||
- **Pressure encoding**: glyph + color + numeric track (0–3) + adapted `✓` tag.
|
||||
- **Flow direction**: a dot on each owner-loop edge indicating current flow.
|
||||
- **Typography**: system UI font stack only (`ui-sans-serif, system-ui, …`).
|
||||
- **Motion**: a single subtle chamber transform; fully suppressed under
|
||||
`prefers-reduced-motion` via CSS.
|
||||
|
||||
## Generated asset files created during the run
|
||||
|
||||
None. No raster images, sprites, or icon files were generated. If a future run
|
||||
produces an allowed generated asset, record its provenance here.
|
||||
|
||||
## Dependencies
|
||||
|
||||
Runtime: none (browser-only, no network after install). Dev-only:
|
||||
`vite`, `typescript`, `vitest`, `@playwright/test` (see `package.json`).
|
||||
@@ -1,96 +0,0 @@
|
||||
# Context Manifest — Adaptive Loop
|
||||
|
||||
This manifest closes the disclosure boundary for the Agentic Labs one-prompt run.
|
||||
It records the private prompt source, every staged local context file, the
|
||||
effective launch configuration, and the loaded extensions/packages.
|
||||
|
||||
## Private prompt source
|
||||
|
||||
- **Authoritative private prompt path:** `/Users/alex/Projects/scripting/agentic-labs-challenge/adaptive-loop/PROMPT.md`
|
||||
- The prompt is supplied privately and is **not** copied into this public game
|
||||
repository. Per competition rules it is DM'd with the submission unless the
|
||||
operator deliberately chooses publication.
|
||||
- The first line of `PROMPT.md` is the `/goal ...` kickoff; the remainder is the
|
||||
human-authored one prompt. No other human message is expected in-session.
|
||||
|
||||
## Staged local context (human-authored, preserved at original paths)
|
||||
|
||||
| Path | Role |
|
||||
|---|---|
|
||||
| `PROMPT.md` | The one prompt (private; see above). |
|
||||
| `SPEC.md` | Authoritative implementation specification. |
|
||||
| `docs/board-layout.md` | Binding rendering reference for the three interlocking hexagonal rings. |
|
||||
| `docs/brainstorming-summary.md` | Product/design outcome summary. |
|
||||
| `.agents/skills/pi-game-factory/SKILL.md` | Orchestration methodology. |
|
||||
| `.agents/skills/deterministic-game-core/SKILL.md` | Deterministic-simulation methodology. |
|
||||
| `.agents/skills/game-ui-proof/SKILL.md` | UI/accessibility methodology. |
|
||||
|
||||
All four staged files (`PROMPT.md`, `SPEC.md`, `docs/board-layout.md`,
|
||||
`docs/brainstorming-summary.md`) and the three steering skills remain at their
|
||||
original project-local paths; no game code edits target them.
|
||||
|
||||
## Initial tree (pre-implementation)
|
||||
|
||||
Confirmed working tree contains only the permitted human-authored context plus
|
||||
harness state — no prior game source, no generated artifacts:
|
||||
|
||||
```
|
||||
PROMPT.md
|
||||
SPEC.md
|
||||
docs/board-layout.md
|
||||
docs/brainstorming-summary.md
|
||||
.agents/skills/{pi-game-factory,deterministic-game-core,game-ui-proof}/SKILL.md
|
||||
.pi/ (harness state: subagent artifacts/missions from prior orchestrator passes)
|
||||
```
|
||||
|
||||
This run is one pass of an iterative orchestrator: the parent repository
|
||||
`agentic-labs-challenge` builds three games (Underdepths, Body Snatcher,
|
||||
Adaptive Loop) across passes. Each pass rebuilds a game from the (possibly
|
||||
refined) spec, then the orchestrator reviews, refines the spec, deletes all
|
||||
generated code ("Prepare for Pass N+1"), and relaunches. The prior Pass-1
|
||||
Adaptive Loop build was deleted before this pass; its completed read-only review
|
||||
artifacts under `.pi/subagents/artifacts/` were read for guidance only.
|
||||
|
||||
## Effective launch configuration
|
||||
|
||||
- **Harness:** Pi `0.84.1`.
|
||||
- **Goal extension:** `@narumitw/pi-goal` (one `/goal` kickoff; later in-session
|
||||
user entries are Goal-owned continuations, not human follow-ups).
|
||||
- **Todo extension:** `@juicesharp/rpiv-todo`.
|
||||
- **Subagent extension:** `pi-subagents` (used only for bounded fresh-context
|
||||
read-only reviews; one writer applies all fixes).
|
||||
- **Computer-use extension:** `@injaneity/pi-computer-use`.
|
||||
- Ambient context files, global skills, prompt templates, and themes are
|
||||
disabled for the run; only the three disclosed local `.agents/skills` are
|
||||
loaded as steering context.
|
||||
- **Effective model/provider/reasoning:** supplied by the launch config; this
|
||||
agent does not mutate it. (Operator post-exit step records the exact
|
||||
`provider/model/reasoning` from the session JSONL.)
|
||||
|
||||
## PI_SESSION_FILE (recorded; never copied live)
|
||||
|
||||
```
|
||||
/Users/alex/.pi/agent/sessions/--Users-alex-Projects-scripting-agentic-labs-challenge-adaptive-loop--/2026-08-12T20-34-00-927Z_019ff7ae-925f-7bd4-8cad-e5884ba195d5.jsonl
|
||||
```
|
||||
|
||||
Per SPEC Gate 0, the live session log is **not** copied or parsed during the
|
||||
run. Copying, parsing (provenance classification of `role:user` entries into
|
||||
`pi-goal-prompt` vs `pi-goal-continuation`), and hashing is an operator-owned
|
||||
**post-exit** submission step (see README "Post-exit" section).
|
||||
|
||||
## Repository / git boundary
|
||||
|
||||
- The `adaptive-loop/` directory is a tracked subdirectory of the parent
|
||||
repository `agentic-labs-challenge` (git toplevel
|
||||
`/Users/alex/Projects/scripting/agentic-labs-challenge`).
|
||||
- This agent does **not** initialize a separate git repo or commit; the parent
|
||||
orchestrator owns commits. The final freeze therefore records a deterministic
|
||||
**file manifest + per-file hashes** rather than a commit hash (SPEC Gate 8
|
||||
permits this when no commit is appropriate).
|
||||
|
||||
## Dependencies (locked)
|
||||
|
||||
Runtime: none (browser-only, procedural SVG/CSS, no network after install).
|
||||
Dev: `vite`, `typescript`, `vitest`, `@playwright/test` (see `package.json` /
|
||||
`package-lock.json` for exact pinned versions). No game engine, no downloaded
|
||||
art/fonts/music, no backend.
|
||||
@@ -1,65 +0,0 @@
|
||||
# Freeze Manifest — Adaptive Loop
|
||||
|
||||
Generated (UTC): 2026-08-13T00:42:04Z
|
||||
|
||||
No commit is made in this orchestrator pass (the parent repository owns git),
|
||||
so per SPEC Gate 8 this records a deterministic file manifest + SHA-256 hashes
|
||||
over the game source/test/config/doc tree. Excludes generated/harness dirs
|
||||
(`node_modules`, `dist`, `test-results`, `playwright-report`, `.pi`, `.git`).
|
||||
|
||||
## Aggregate
|
||||
|
||||
Total source/test/config/doc files (excluding generated/harness dirs and this manifest): 40
|
||||
|
||||
## Per-file SHA-256
|
||||
|
||||
```
|
||||
e63356c9ccb28a9d62d8266b788019df2bc266a378b7a8d771998e179bce824b .agents/skills/deterministic-game-core/SKILL.md
|
||||
57fe82d82ee98751b0fd648d6bfc463a9153befb88cfa984d8a0a7390dc44d95 .agents/skills/game-ui-proof/SKILL.md
|
||||
b44005242a71ee2a8c087c6f13ca51f8675f31c99e8d55dc5a9db1f5245969a6 .agents/skills/pi-game-factory/SKILL.md
|
||||
bf17a1d11f410d827fd27991211e869346aa3a22f120cc59204375d3676471e2 .gitignore
|
||||
8ba361db44e1605a4cd1c27d337a2bda6283e09cefe9b9e44c29561f887bed93 ASSETS.md
|
||||
d7248f78431cdcc6f6ff0fd91c893b253a3dad825919c312cc637c0f2d503d2c CONTEXT-MANIFEST.md
|
||||
9213907e43f48452cd1aca384e62ce15767230d1a44df56f84f710b58c565cce docs/board-layout.md
|
||||
46a2ed3d76ea9436077319891b54049ff4b359429fb32fa8f08710a7cc40585d docs/brainstorming-summary.md
|
||||
12d85e0a55d76f29f26328b38421ed232effca31462215c28aef18edd8a7d376 docs/scenario-tuning.md
|
||||
00a708d7e741ee20509edcc9bf4e51853dba667d9b14d7e0689291baccf11ea7 e2e/smoke.spec.ts
|
||||
48c95d7e3e15c88c0534d4771bffb36a76d383bbf581be85330b32c8db76a07d index.html
|
||||
67ae81700749158f465d41bdcba156bbb77fe9b6129e90a1b9642148de2b1d38 package-lock.json
|
||||
8d962f3bcf59204245582fbbb88d5f8eff168b21a79e43fcad259a8f21e0ac3b package.json
|
||||
a54ac28a4ce1fa0153e067a4a167324c23debbd45da2f0f9785bb72cd899d6e5 playwright.config.ts
|
||||
987eacf8265016eb5e04671eedd6cec369961d38171aa765ac9b5e2fe5dab11f PROMPT.md
|
||||
ce89b8b71fb781f2aad439af918b9eac88476be3ae7b064bf2cb822627167548 README.md
|
||||
c0965a39d83c1f583ed8842fb0a99e60b2a100b8218fc23a2a4401d8eecad3eb RECORDING.md
|
||||
9fcd1dc6e5e91a6ed9c7a38fa1280ad1fd95818ec81f4828020f64d54038c156 scripts/gen-solver-fixtures.ts
|
||||
88215757de248bae4d24402a8699227c17cd96e4300611038ade03154327c4a3 SPEC.md
|
||||
32f4f95fc8b5cc11f2ad9e9bb796a98761136702ca059a8535d3b9d676efb423 src/content/scenarios.ts
|
||||
3e407cb8573c869118c929890401fc40ed1b6ef81bc1d649612c4ff4246828c3 src/domain/constants.ts
|
||||
218ba25b5ac3e9274098b1e1165b0dc99c49d72dcdd377719e7bfb9e2c41e414 src/domain/derived.ts
|
||||
f813e76654bfe6425959abbf0082ed4200b04c2629765a8983b61afc7813b5e7 src/domain/pipeline.ts
|
||||
c48c8e9d4494fea06e2fc904029818dd89373a22b9ef07a2785c6390028448dc src/domain/scenario.ts
|
||||
06e088f298ffbc098e8ba718b809d54c81757757a6dd3244005becf60aae51a5 src/domain/serialize.ts
|
||||
f473a9c0052b2ce43745a0fe2c6d37d05adf7995e95415b7d9d57d7a9d2fe775 src/domain/solver.ts
|
||||
663ac7ff38c148866f6c4b59a0a05c580301fcb03036989ef5526c56e71996b0 src/domain/types.ts
|
||||
1d4ed36551bcd7fad43ce659d6aa6f304fa4f6e2c20bd4e7ed0a239197ed8372 src/main.ts
|
||||
2f12f42a25d29206ac3e0e9174c991d04bc5161201cb5ec9fdfe4ca32ac96d04 src/persistence/save.ts
|
||||
183e4276eab47a850cb9fc377066eb24c8302ef99a46d6ae61ae6fbc7e89f441 src/presentation/geometry.ts
|
||||
eecfb20fef3b3f9c0595ac2e54628c5fff967bba86c873b1a7102013034d8804 src/session.ts
|
||||
bc14e844c80c6173c95ec9313040f1bc7a2fa63bf972eccca57fa513b6e370a0 src/styles.css
|
||||
656944433978b1e5ef917a971122846becbd4deb59989f9fe41a4afd4316d61f tests/fixtures/solver-results.json
|
||||
0f02efdeb875d265e8e8e9889936c5800e47eb758295881314967c01192414bf tests/helpers.ts
|
||||
ca427fffdb2986e5c2d93e6ae7e86a1db91aceb8c515d5138c874bf24a403e08 tests/persistence.test.ts
|
||||
8dfebd74cf9fbe420b61d7f96539b66bfaee210256cb7e588b2305f2a3be0a8b tests/solver.test.ts
|
||||
1ee589e7858d8ac3c32f062a074c7d1898dfbfcda0ef957cf564c227892f7b29 tests/truth.test.ts
|
||||
9f89a5d3124c3dd72764a11a80102680256d0f82b017cc014d756afdb2e46092 tsconfig.json
|
||||
2b2a5a541184291b92310c7b82ba92d14e108d9417e29b544af07d61133377ec vite.config.ts
|
||||
986990819d6771c6d295c39a057149c82efe4996f1dde207bd01d19fd1f211a8 vitest.config.ts
|
||||
```
|
||||
|
||||
## Verification (final aggregate gate, after the last code edit)
|
||||
|
||||
```
|
||||
npm run verify = tsc --noEmit + vitest (53 tests) + vite build + playwright (11 tests)
|
||||
result: ALL GREEN (typecheck clean, 53 unit/behavior/solver/replay/persistence pass,
|
||||
production build 36 kB JS / 5.5 kB CSS, 11 black-box browser tests pass)
|
||||
```
|
||||
@@ -1,94 +0,0 @@
|
||||
# Adaptive Loop
|
||||
|
||||
A calm deterministic microfluidic strategy puzzle. Rotate three overlapping
|
||||
hexagonal loops to move culture chambers and redirect nutrient/toxin flow; each
|
||||
tick resolves growth, feeding, migration, evolution, and environmental pressure
|
||||
in a fixed order. Provoke adaptations, then exploit their costs. Five handcrafted
|
||||
scenarios form one campaign with persistent lineage traits (gifts and burdens).
|
||||
|
||||
Deterministic: no runtime randomness. One pure serializable transition
|
||||
`nextState(state, action)` owns every rule and is shared identically by preview
|
||||
and commit. Exact save/load and action-replay reproduction are proven by tests.
|
||||
|
||||
## Stack
|
||||
|
||||
Vite + TypeScript + Vitest + Playwright. No backend, no game engine, no
|
||||
downloaded assets, no network after install. Procedural SVG/CSS only.
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm approve-scripts esbuild # one-time: allow esbuild's postinstall (vite needs it)
|
||||
```
|
||||
|
||||
## Run / play
|
||||
|
||||
```bash
|
||||
npm run dev # dev server (Vite), open the printed URL
|
||||
# or production:
|
||||
npm run build && npm run preview # serves dist at http://127.0.0.1:4173
|
||||
```
|
||||
|
||||
**Controls**: select a loop rotation (click / focus / hover / tap) to preview
|
||||
exactly one turn, then press **Commit** (or Enter on Commit). The selection
|
||||
persists until you commit, pick a different rotation, or cancel (Escape).
|
||||
Keyboard, touch, and mouse all work.
|
||||
|
||||
## Build / typecheck / test
|
||||
|
||||
```bash
|
||||
npm run build # tsc --noEmit, then vite build → dist/
|
||||
npm run typecheck # tsc --noEmit
|
||||
npm run test # vitest: behavior + solver/replay + persistence (fast)
|
||||
npm run test:e2e # Playwright black-box browser tests against the prod build
|
||||
npm run verify # typecheck + unit tests + build + e2e (the aggregate gate)
|
||||
```
|
||||
|
||||
The unit suite is fast and deterministic. The heavy offline solver search runs
|
||||
once via `NODE_OPTIONS="--max-old-space-size=6144" npx tsx scripts/gen-solver-fixtures.ts`
|
||||
and its results are stored in `tests/fixtures/solver-results.json`; the solver
|
||||
test replays those routes to re-verify them.
|
||||
|
||||
## Project layout
|
||||
|
||||
```
|
||||
src/domain/ types, constants (board topology), serialize, derived, pipeline (nextState), scenario, solver
|
||||
src/content/ declarative scenarios + species/pressure tables
|
||||
src/persistence/ versioned save/load + replay (localStorage adapter + in-memory for tests)
|
||||
src/presentation/ board geometry (three interlocking hexagonal rings)
|
||||
src/main.ts presentation controller (views, preview/commit, controls, a11y)
|
||||
src/styles.css procedural dark-lab aesthetic; responsive + reduced-motion
|
||||
tests/ behavior (truth), solver, persistence (+ fixtures/)
|
||||
e2e/ Playwright black-box browser proof
|
||||
scripts/ one-shot solver-fixture generator
|
||||
docs/ board-layout, scenario-tuning, brainstorming-summary
|
||||
```
|
||||
|
||||
## Scenario tuning & residual risk
|
||||
|
||||
Some baselines/inheritance combos were solver-proven impossible and tuned within
|
||||
SPEC §9's permitted knobs (starting resources, fixture locations, ±1 thresholds).
|
||||
Every change is documented in `docs/scenario-tuning.md`, including one documented
|
||||
residual-risk class (inheriting producer Dormancy into the finale overgrows
|
||||
producers past the sustained ceiling).
|
||||
|
||||
## Post-exit (operator-owned — not part of the in-session freeze)
|
||||
|
||||
The authoritative session JSONL is **not** copied or parsed during the run. After
|
||||
exit, the operator:
|
||||
|
||||
1. Records/links one uncut take following `RECORDING.md`.
|
||||
2. DMs `PROMPT.md` per competition rules.
|
||||
3. Copies the session JSONL from the path in `CONTEXT-MANIFEST.md`, then parses
|
||||
every `role:user` entry to classify provenance: one initial `pi-goal-prompt`
|
||||
kickoff reconstructs `PROMPT.md` (its `goal-state.text` byte-equals the file
|
||||
without the leading `/goal `), and every later user entry must be a matching
|
||||
disclosed `pi-goal-continuation` for the same objective/goal id (not a human
|
||||
follow-up). Verifies no `parentSession`. Hashes prompt and log copy.
|
||||
|
||||
## Steering context
|
||||
|
||||
Authoritative spec: `SPEC.md`. Steering skills and the binding board-layout
|
||||
reference remain at their original project-local paths under `.agents/skills/`
|
||||
and `docs/`.
|
||||
@@ -1,42 +0,0 @@
|
||||
# Recording Route — Adaptive Loop
|
||||
|
||||
This route is generated from **verified** solver and browser routes (in
|
||||
`tests/fixtures/solver-results.json` and the passing Playwright suite), not
|
||||
invented prose. Automated tests validate all five scenarios and campaign victory;
|
||||
the recording need not play every scenario. No game state or localStorage is
|
||||
injected — every step is a public control (select rotation → Commit).
|
||||
|
||||
## One continuous take (script)
|
||||
|
||||
Open the production build (`npm run preview`) and follow this sequence. It is
|
||||
short and exercises the required mechanics.
|
||||
|
||||
| # | Beat (SPEC §16) | Action |
|
||||
|---|---|---|
|
||||
| 1 | Title / campaign start | Click **New Campaign** (scenario 1, *Cultivation Quota*). |
|
||||
| 2 | Exact preview of a rotation | Hover/focus **Loop A ↻**; the board shows per-chamber deltas and the event panel previews the tick. |
|
||||
| 3 | Rotation causing movement + flow | **Commit** A↻. Chambers move along loop A and a flow dot appears on the reclaimed owner edge. |
|
||||
| 4 | Pressure causing an adaptation | Continue the verified winning route **A↻ ×5 more, then B↻, C↺** (8 turns total). Around the turns where a pressure track reaches 3, a trait unlocks and a global response activates (visible in the Pressures & traits panel and the tick events). |
|
||||
| 5 | Adaptation benefit / cost / spillover | While adapted, the tick events attribute the prevented loss (benefit), the carrier cost, and the ecological spillover. |
|
||||
| 6 | Global pressure response strengthening a fixture | With a response active, the matching fixture adds more per turn (e.g. heat source +3 instead of +2); the tick events attribute the strengthened fixture. |
|
||||
| 7 | Ecosystem collapse and retry | From the title, **New Campaign** again and repeat a single rotation (e.g. A↻) to the turn limit or until biomass hits zero → **Retry** restores the scenario. |
|
||||
| 8 | A scenario win and preserved lineage choice | Finishing the route in step 4 wins scenario 1 and offers **Preserve a trait** (or Decline). |
|
||||
| 9 | Save & Quit | In any scenario, click **Save & Quit**. |
|
||||
| 10 | Page/tab close and reopen | Close the tab; reopen the build. |
|
||||
| 11 | Continue restoring exact state | Click **Continue** — the exact turn, board, pressures, and action log return. |
|
||||
| 12 | Visible access to multiple scenarios | Click **Replay Standalone** to see all five scenarios; enter any. |
|
||||
|
||||
## Verified routes (solver-proven, replayed by tests)
|
||||
|
||||
| Scenario | Winning route (loop-direction) | Outcome |
|
||||
|---|---|---|
|
||||
| 1 Cultivation Quota | A↻, A↻, A↻, A↻, A↻, A↻, B↻, C↺ | won (8 turns; uses ownership + unlocks an adaptation) |
|
||||
| 2 Endurance | see `solver-results.json` (10 turns) | won |
|
||||
| 3 Cleansing | see fixture (8 turns) | won |
|
||||
| 4 Escort | see fixture (8 turns) | won |
|
||||
| 5 Stable Equilibrium | see fixture (12 turns) | won |
|
||||
|
||||
A deterministic **losing** route per scenario (repeat a single rotation to the
|
||||
turn limit or until collapse) is stored in the same fixture and replayed by the
|
||||
solver test. Run `npm run test` to re-verify all of them; run `npm run test:e2e`
|
||||
to re-verify the browser beats above through public controls only.
|
||||
@@ -1,88 +1,85 @@
|
||||
# Board Layout — three interlocking hexagonal rings
|
||||
# Board Layout — three concentric hexagonal rings
|
||||
|
||||
This document is the rendering reference for the Adaptive Loop board (SPEC §4
|
||||
"Board layout (rendering)"). The topology (12 slots, 3 loops, 6 shared slots) is
|
||||
authoritative and unchanged; this file prescribes **how to draw it as three
|
||||
interlocking hexagonal rings**, not as a network of connected spheres or a
|
||||
numbered wiring diagram.
|
||||
"Board topology and legal actions"). It prescribes **how to draw the board as
|
||||
three concentric hexagonal rings connected by six radial gates**, not as a
|
||||
network of connected spheres or a numbered wiring diagram.
|
||||
|
||||
## Why the obvious drawings fail
|
||||
## Topology (authoritative, from SPEC §4)
|
||||
|
||||
The three loops pairwise share *edges* (A∩B = slots {2,3}; A∩C = {4,5};
|
||||
B∩C = {8,9}). In a flat hexagonal *tiling*, three mutually edge-adjacent hexagons
|
||||
meet at a single triple vertex and yield only 4 shared vertices — not the 6 this
|
||||
topology requires. So the board **cannot** be drawn as three regular hexagons
|
||||
that geometrically share edges in the plane. It must be drawn as three
|
||||
**interlocking rings** (like chain links): hexagonal outlines that overlap, with
|
||||
the six shared chambers sitting at the six overlap/crossing points.
|
||||
- **Inner ring** (radius 1): 6 tiles `I0..I5` — `I0` at top, clockwise.
|
||||
- **Middle ring** (radius 2): 12 tiles `M0..M11` — `M0` at top, clockwise.
|
||||
- **Outer ring** (radius 3): 18 tiles `O0..O17` — `O0` at top, clockwise.
|
||||
- 36 tiles total. The outer ring has more tiles than the middle, which has more
|
||||
than the inner.
|
||||
|
||||
Six **gates** `g0..g5` sit at the six hex vertices (clockwise from the top). A
|
||||
tile is **on a gate** when its current ring position is that vertex:
|
||||
|
||||
- Inner: `I_g` is on gate `g` (every inner tile is always on a gate).
|
||||
- Middle: `M_{2g}` is on gate `g` (every second middle tile).
|
||||
- Outer: `O_{3g}` is on gate `g` (every third outer tile).
|
||||
|
||||
The three on-gate tiles at the same gate (inner + middle + outer) form a radial
|
||||
channel. Rotating a ring shifts payloads around the track, so **which payloads
|
||||
sit on the gates changes** — this is what reconnects the rings each turn.
|
||||
|
||||
## Requirements (binding)
|
||||
|
||||
1. Each loop is a **regular six-sided hexagon** (pointy-top), drawn as a stroked
|
||||
`<polygon>` with a distinct per-loop color (A, B, C).
|
||||
2. The three rings are arranged in a **symmetric trefoil** (centers at the
|
||||
corners of an equilateral triangle) so each pair overlaps and the rings read
|
||||
as interlocked.
|
||||
3. At each of the six ring crossings use a consistent **over/under weave**
|
||||
(break one ring's stroke where the other passes over it) so no ring outline is
|
||||
visually broken and the "interlocking" reads clearly.
|
||||
4. Chambers are circular nodes placed **on the rings at the hexagon vertices**,
|
||||
in each loop's clockwise cyclic order:
|
||||
- Loop A: `0 → 1 → 2 → 3 → 4 → 5 → 0`
|
||||
- Loop B: `2 → 3 → 6 → 7 → 8 → 9 → 2`
|
||||
- Loop C: `4 → 5 → 10 → 11 → 8 → 9 → 4`
|
||||
5. A shared chamber belongs to two rings; render it **once** and route **both**
|
||||
ring outlines through that single node (it is the visible overlap point).
|
||||
6. Label each chamber with its slot index; mark shared chambers with the loops
|
||||
that own them (e.g. `2 ⓪ⓑ`). Rotation moves payloads along the chosen loop's
|
||||
cyclic order above; channel-flow arrows are drawn along the owner loop's edges
|
||||
in its current direction.
|
||||
1. Render the board as **three concentric hexagonal rings** of regular pointy-top
|
||||
hex tiles, clearly nested around a common center.
|
||||
2. Each ring has a **distinct color** (inner / middle / outer).
|
||||
3. Draw the **six gates as luminous radial connectors** between the rings at the
|
||||
six vertices, so the player can see which tiles are currently linked across
|
||||
rings.
|
||||
4. Keep the clockwise cyclic tile order per ring (`I0→I1→…`, `M0→M1→…`,
|
||||
`O0→O1→…`) so rotation direction reads correctly.
|
||||
5. Tiles are hexagonal nodes; label each with its ring index (`I0`, `M0`, `O0`).
|
||||
On-gate tiles are visually emphasized (e.g., a gate-aligned glow).
|
||||
|
||||
## Construction (recommended)
|
||||
|
||||
Define the 12 chamber coordinates, then draw each loop as the polygon through its
|
||||
6 chambers in cyclic order. Because a shared chamber is one coordinate used by two
|
||||
loops' polygons, shared vertices **coincide by construction** and each loop is a
|
||||
genuine 6-gon. Place the chambers so the three resulting 6-gons form a clean
|
||||
trefoil (tune spacing/rotation until each ring reads as a distinct hexagon and
|
||||
the six shared nodes sit at clear crossings).
|
||||
Place the three rings concentrically. For a pointy-top hex grid, the tiles of
|
||||
ring radius `r` lie on a hexagonal perimeter at distance `r·tileSpacing` from the
|
||||
center, with:
|
||||
|
||||
A pointy-top hexagon of radius `R` centered at `C` has vertex offsets (clockwise
|
||||
from top): `(0,-R)`, `(R·√3/2,-R/2)`, `(R·√3/2,R/2)`, `(0,R)`, `(-R·√3/2,R/2)`,
|
||||
`(-R·√3/2,-R/2)`.
|
||||
- Inner `r=1`: 6 perimeter tiles at the 6 vertex directions.
|
||||
- Middle `r=2`: 12 tiles — one at each vertex plus one midway along each edge.
|
||||
- Outer `r=3`: 18 tiles — one at each vertex plus two along each edge.
|
||||
|
||||
### Reference starting coordinates (viewBox 440×400, tune for legibility)
|
||||
Index each ring clockwise from the top vertex (`I0`, `M0`, `O0` at top). With this
|
||||
construction the gate vertices line up exactly: the top vertex holds `I0`, `M0`,
|
||||
`O0` (gate `g0`); the next vertex clockwise holds `I1`, `M2`, `O3` (gate `g1`);
|
||||
and so on, matching the `M_{2g}` / `O_{3g}` gate rule.
|
||||
|
||||
Three pointy-top hexagons, `R = 68`, trefoil centers `A=(220,114)`,
|
||||
`B=(145,243)`, `C=(295,243)`. Generate each loop's six vertex positions from its
|
||||
center, assign chambers in the cyclic order above, then for the six **shared**
|
||||
chambers use a single coordinate at the overlap of the two loops that own them
|
||||
(the midpoint of the two loops' nearest vertices is a fine starting point; nudge
|
||||
so it lands on a clean crossing). Unique chambers keep their own vertex
|
||||
coordinates. The implementer **must** visually/DOM-verify the result is three
|
||||
distinct interlocking hexagons and adjust spacing if any ring collapses into a
|
||||
tangle.
|
||||
Tile size may decrease slightly for the inner ring (fewer, larger tiles) and
|
||||
increase count for the outer ring — whatever keeps all 36 tiles legible. The
|
||||
implementer **must** visually/DOM-verify the result is three distinct nested
|
||||
hexagonal rings with six clear radial gates and adjust spacing if any ring
|
||||
collapses or overlaps illegibly.
|
||||
|
||||
## ASCII schematic (topology only — not to scale)
|
||||
|
||||
`` Loop A
|
||||
0─────1
|
||||
/ \
|
||||
5 2 ──┐ shared A∩B
|
||||
│ C │ │
|
||||
4─────────3 │ Loop B
|
||||
\ │ / │
|
||||
11 10 6────7
|
||||
\ │ / │
|
||||
\ │ / │
|
||||
9─8 ──────┘ shared B∩C
|
||||
↑ ↑
|
||||
shared A∩C (4,5) and B∩C (8,9) and A∩B (2,3)
|
||||
`` g0 (top)
|
||||
I0 M0 O0
|
||||
I5 I1
|
||||
O17 M11 M1 O1
|
||||
g5 ┌─────┬─────┬─────┐ g1
|
||||
│ │ I·· │ │
|
||||
O16 │ M10 │ │ M2 │ O2
|
||||
│ │ │ │
|
||||
g5 └─────┴─────┴─────┘ g1
|
||||
O15 M9 M3 O3
|
||||
I4 I2
|
||||
I3 M6 O9
|
||||
g3 (bottom)
|
||||
|
||||
gates g0..g5 at the 6 vertices connect I·/M·/O· on the same spoke
|
||||
```
|
||||
|
||||
Each loop is a hexagon; shared slots (2,3 / 4,5 / 8,9) are the chambers where two
|
||||
rings cross. Draw rings as stroked hexagons with an over/under weave at these six
|
||||
crossings.
|
||||
Each ring is a closed hexagon of tiles; the six gates are the radial spokes that
|
||||
link the three rings. Rotation moves payloads around a ring; the gate spokes are
|
||||
fixed in space, so rotation changes which tiles the spokes touch.
|
||||
|
||||
## Interaction note (see SPEC §13)
|
||||
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
# Scenario Tuning — Adaptive Loop
|
||||
|
||||
`SPEC.md` (§9) is authoritative. Board topology, turn order, caps, trait
|
||||
semantics, and objective types are unchanged. Where the bounded solver proved a
|
||||
baseline scenario (or a reachable inheritance combination) impossible, the SPEC
|
||||
explicitly permits adjusting only **starting populations/resources, fixture
|
||||
locations, or numeric objective thresholds by at most 1 per tuning pass**. Every
|
||||
adjustment is listed here; all solver tests were rerun after each.
|
||||
|
||||
## Tunings applied
|
||||
|
||||
| Scenario | Change (SPEC §9 knob) | Reason (solver-proven) |
|
||||
|---|---|---|
|
||||
| s3 Cleansing | Removed toxin inlet at slot 9 (fixture-location change) | With two toxin inlets (+4 toxin/turn) the win (total toxin ≤ 2 by turn 6–9) was unreachable within the search budget; a single inlet at slot 3 keeps the detox-routing puzzle intact. |
|
||||
| s4 Escort | phage@11 objective threshold relaxed 1 → 0 (numeric objective threshold) | Escorting a phage to sanctuary alongside 3 grazers within 8 turns was unreachable; grazer escort + producer survival remains the taught objective. `winDescription` updated to match. |
|
||||
| s5 Stable Equilibrium | Assay occupancy threshold relaxed 2 → 1 (numeric objective threshold) | Holding producer+grazer ≥ 2 in all three assay chambers for two consecutive turns while immune nodes culled populations was unreachable; ≥ 1 keeps the multi-chamber equilibrium objective. |
|
||||
| s5 Stable Equilibrium | Removed toxin inlet at slot 3 (fixture-location change) | With a continuous toxin inlet and a single drain, total toxin stayed above the ≤ 6 sustained ceiling in every reachable state; the start toxin (3, 9) + drain @9 still teaches toxin routing. |
|
||||
| s5 Stable Equilibrium | Removed both immune nodes (fixture-location change) | With immune nodes present, inheriting Cloak from s4 (a reachable campaign choice) made s5 unwinnable: the carrier cost destabilized the equilibrium. s4 already teaches immunity; s5 converges heat/hunger/toxin + inheritance without immune targeting. |
|
||||
|
||||
## Invariants preserved
|
||||
|
||||
Unchanged across all tunings: 12-slot / 3-loop topology, shared-slot ownership
|
||||
rule, the fixed 8-phase turn order, integer caps (0–6 populations/resources,
|
||||
0–3 pressure tracks), the four adaptation semantics (benefit + carrier cost +
|
||||
spillover + global response), universal collapse (producer + grazer = 0), and
|
||||
terminal precedence (collapse > win > expire).
|
||||
|
||||
## Reachability verification
|
||||
|
||||
`scripts/gen-solver-fixtures.ts` enumerates every cumulative inheritance set
|
||||
reachable by preserving 0 or 1 newly-unlocked trait after each scenario and
|
||||
confirms each is solvable. Result: **all reachable combinations are solvable
|
||||
except a documented residual-risk class** (below).
|
||||
|
||||
## Documented residual risk
|
||||
|
||||
Eight reachable combinations inherit **producer Dormancy** (the hunger trait)
|
||||
into the convergence scenario. Dormancy removes the natural starvation that
|
||||
bounds producers, so they overgrow past the sustained 8–14 producer ceiling,
|
||||
making the equilibrium bounded-search-unsolvable (verified unsolvable within
|
||||
15 000 000 explored states). SPEC §9's ±1-per-pass tuning budget cannot bound
|
||||
that runaway growth without distorting the scenario, so these combinations are
|
||||
recorded as a residual risk in `tests/fixtures/solver-results.json`
|
||||
(`reachability.residualRiskCombos`) rather than forced. Normal play is unaffected
|
||||
— a player who inherits Dormancy into the finale can still decline/retry; all
|
||||
other inheritance paths complete the campaign.
|
||||
@@ -1,151 +0,0 @@
|
||||
// Gate 6 — black-box browser proof against the production build. Public controls
|
||||
// only: we click rotation buttons + Commit, never inject domain state or localStorage.
|
||||
// Deterministic routes come from the solver fixture so outcomes are guaranteed.
|
||||
|
||||
import { test, expect, type Page } from "@playwright/test";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
const fixture = JSON.parse(readFileSync(new URL("../tests/fixtures/solver-results.json", import.meta.url), "utf8"));
|
||||
|
||||
const BASE = "http://127.0.0.1:4173";
|
||||
|
||||
async function startCampaign(page: Page) {
|
||||
await page.goto(BASE);
|
||||
await page.click("#new-campaign-btn");
|
||||
await expect(page.locator("#board")).toBeVisible();
|
||||
}
|
||||
|
||||
async function commitAction(page: Page, loop: string, dir: string) {
|
||||
await page.click(`.rotate-btn[data-loop="${loop}"][data-dir="${dir}"]`);
|
||||
await expect(page.locator("#commit-btn")).toBeEnabled();
|
||||
await page.click("#commit-btn");
|
||||
}
|
||||
|
||||
async function turnText(page: Page): Promise<string> {
|
||||
return (await page.locator('[data-region="objective"] .stat').first().textContent()) ?? "";
|
||||
}
|
||||
|
||||
test("starts a campaign and renders the three-ring board with no console errors", async ({ page }) => {
|
||||
const errors: string[] = [];
|
||||
page.on("console", (m) => { if (m.type() === "error") errors.push(m.text()); });
|
||||
await startCampaign(page);
|
||||
await expect(page.locator("h1")).toContainText("Cultivation Quota");
|
||||
// three interlocking hexagonal rings (one polygon per loop), 12 chamber nodes
|
||||
await expect(page.locator("#board polygon.ring")).toHaveCount(3);
|
||||
await expect(page.locator("#board g.chamber")).toHaveCount(12);
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
test("preview enables Commit and persists until commit; commit advances the turn", async ({ page }) => {
|
||||
await startCampaign(page);
|
||||
// selecting a rotation enables Commit
|
||||
await page.click('.rotate-btn[data-loop="A"][data-dir="cw"]');
|
||||
await expect(page.locator("#commit-btn")).toBeEnabled();
|
||||
// moving focus away does NOT disable Commit (selection persists)
|
||||
await page.locator("#commit-btn").focus();
|
||||
await expect(page.locator("#commit-btn")).toBeEnabled();
|
||||
await page.click("#commit-btn");
|
||||
await expect(await turnText(page)).toContain("Turn 1");
|
||||
});
|
||||
|
||||
test("rotation causes chamber movement + channel flow interaction", async ({ page }) => {
|
||||
await startCampaign(page);
|
||||
// capture a chamber's population text, commit, confirm the board changed
|
||||
const before = await page.locator("#board").innerHTML();
|
||||
await commitAction(page, "A", "cw");
|
||||
const after = await page.locator("#board").innerHTML();
|
||||
expect(after).not.toBe(before);
|
||||
// flow dots are rendered along owner edges
|
||||
await expect(page.locator("#board .flow-dot").first()).toBeVisible();
|
||||
});
|
||||
|
||||
test("a full win route wins scenario 1 and offers a trait choice (adaptation exploited)", async ({ page }) => {
|
||||
await startCampaign(page);
|
||||
const route = fixture.scenarios.find((s: any) => s.id === "s1-heat").win.actions as { loop: string; direction: string }[];
|
||||
for (const a of route) await commitAction(page, a.loop, a.direction === "cw" ? "cw" : "ccw");
|
||||
// win -> scenario complete affordance
|
||||
await expect(page.locator("#continue-win-btn")).toBeVisible();
|
||||
// the route unlocked an adaptation (a pressure cell is marked adapted at some point)
|
||||
const adapted = await page.locator('[data-region="pressures"] .pcell.adapted').count();
|
||||
expect(adapted).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("a fixed bad sequence loses (expire or collapse), then retry restarts the scenario", async ({ page }) => {
|
||||
await startCampaign(page);
|
||||
// drive to a terminal by repeating a single rotation; stop once a terminal affordance appears
|
||||
const sc = fixture.scenarios.find((s: any) => s.id === "s1-heat");
|
||||
for (let i = 0; i < sc.turnLimit + 1; i++) {
|
||||
if (await page.locator("#retry-btn").count() > 0) break;
|
||||
await commitAction(page, "A", "cw");
|
||||
}
|
||||
// a terminal retry affordance appears (collapse or expire)
|
||||
await expect(page.locator("#retry-btn")).toBeVisible();
|
||||
await page.click("#retry-btn");
|
||||
await expect(await turnText(page)).toContain("Turn 0");
|
||||
});
|
||||
|
||||
test("Save & Quit then close/reopen/Continue restores exact state", async ({ page }) => {
|
||||
await startCampaign(page);
|
||||
await commitAction(page, "A", "cw");
|
||||
await commitAction(page, "B", "ccw");
|
||||
const saved = await turnText(page);
|
||||
await page.click("#save-quit-btn");
|
||||
await expect(page.locator("h1")).toContainText("Adaptive Loop"); // back to title
|
||||
// close/reopen
|
||||
await page.goto(BASE);
|
||||
await expect(page.locator("#continue-btn")).toBeEnabled();
|
||||
await page.click("#continue-btn");
|
||||
await expect(await turnText(page)).toBe(saved);
|
||||
});
|
||||
|
||||
test("core actions operable by keyboard", async ({ page }) => {
|
||||
await startCampaign(page);
|
||||
await page.keyboard.press("Tab"); // focus into the page
|
||||
// focus a rotation control, select it, then commit via keyboard on Commit
|
||||
await page.locator('.rotate-btn[data-loop="C"][data-dir="cw"]').focus();
|
||||
await expect(page.locator("#commit-btn")).toBeEnabled();
|
||||
await page.locator("#commit-btn").focus();
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(await turnText(page)).toContain("Turn 1");
|
||||
// Escape cancels a fresh preview
|
||||
await page.locator('.rotate-btn[data-loop="A"][data-dir="ccw"]').focus();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(page.locator("#commit-btn")).toBeDisabled();
|
||||
});
|
||||
|
||||
test("narrow viewport (390px) has no horizontal scroll and reachable controls", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await startCampaign(page);
|
||||
await commitAction(page, "A", "cw");
|
||||
const scrollWidth = await page.evaluate(() => document.documentElement.scrollWidth);
|
||||
expect(scrollWidth).toBeLessThanOrEqual(410);
|
||||
await expect(page.locator("#commit-btn")).toBeVisible();
|
||||
await expect(page.locator("#save-quit-btn")).toBeVisible();
|
||||
});
|
||||
|
||||
test("200% zoom (2x device pixel ratio) keeps the board and controls usable", async ({ browser }) => {
|
||||
const context = await browser.newContext({ viewport: { width: 512, height: 800 }, deviceScaleFactor: 2 });
|
||||
const page = await context.newPage();
|
||||
await startCampaign(page);
|
||||
await commitAction(page, "B", "cw");
|
||||
await expect(page.locator("#board")).toBeVisible();
|
||||
await expect(page.locator(".rotate-btn").first()).toBeVisible();
|
||||
await context.close();
|
||||
});
|
||||
|
||||
test("reduced-motion emulation renders without animation reliance", async ({ browser }) => {
|
||||
const context = await browser.newContext({ reducedMotion: "reduce" });
|
||||
const page = await context.newPage();
|
||||
await startCampaign(page);
|
||||
await commitAction(page, "C", "cw");
|
||||
await expect(page.locator("#board")).toBeVisible();
|
||||
await context.close();
|
||||
});
|
||||
|
||||
test("multiple scenarios are reachable via Replay Standalone", async ({ page }) => {
|
||||
await page.goto(BASE);
|
||||
await page.click("#standalone-btn");
|
||||
await expect(page.locator(".scenario-pick")).toHaveCount(5);
|
||||
await page.click('.scenario-pick[data-scenario="s3-toxin"]');
|
||||
await expect(page.locator("h1")).toContainText("Cleansing");
|
||||
});
|
||||
@@ -1,15 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="color-scheme" content="dark" />
|
||||
<title>Adaptive Loop</title>
|
||||
<link rel="stylesheet" href="./src/styles.css" />
|
||||
</head>
|
||||
<body>
|
||||
<a class="skip-link" href="#main">Skip to game</a>
|
||||
<div id="app" aria-label="Adaptive Loop"></div>
|
||||
<script type="module" src="./src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
-1561
File diff suppressed because it is too large.
Load diff
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"name": "adaptive-loop",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Adaptive Loop — a calm deterministic microfluidic strategy puzzle.",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"preview": "vite preview --port 4173 --host 127.0.0.1",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"test:e2e": "playwright test",
|
||||
"verify": "npm run typecheck && npm run test && npm run build && npm run test:e2e"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.58.2",
|
||||
"typescript": "^5.6.3",
|
||||
"vite": "^5.4.10",
|
||||
"vitest": "^2.1.4"
|
||||
},
|
||||
"allowScripts": {
|
||||
"esbuild@0.21.5": true
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
import { defineConfig, devices } from "@playwright/test";
|
||||
|
||||
export default defineConfig({
|
||||
testDir: "./e2e",
|
||||
fullyParallel: false,
|
||||
workers: 1,
|
||||
retries: 0,
|
||||
reporter: [["list"]],
|
||||
use: {
|
||||
baseURL: "http://127.0.0.1:4173",
|
||||
actionTimeout: 10_000,
|
||||
trace: "retain-on-failure",
|
||||
},
|
||||
projects: [
|
||||
{ name: "chromium", use: { ...devices["Desktop Chrome"] } },
|
||||
],
|
||||
webServer: {
|
||||
command: "npm run preview",
|
||||
url: "http://127.0.0.1:4173",
|
||||
reuseExistingServer: !process.env.CI,
|
||||
timeout: 60_000,
|
||||
},
|
||||
});
|
||||
@@ -1,73 +0,0 @@
|
||||
// One-shot generator: runs the bounded solver for every scenario and inheritance
|
||||
// combination, writes results to tests/fixtures/solver-results.json. Run with a
|
||||
// large heap: NODE_OPTIONS="--max-old-space-size=6144" npx tsx scripts/gen-solver-fixtures.ts
|
||||
// The solver test then validates the stored routes by replay (fast, deterministic).
|
||||
|
||||
import { writeFileSync, mkdirSync } from "node:fs";
|
||||
import { findWin, findLose, findWinAvoidingAdaptation, verifyReachableInheritance, routeProperties, type Route } from "../src/domain/solver";
|
||||
import { SCENARIOS } from "../src/content/scenarios";
|
||||
|
||||
const CAPS: Record<string, number> = {
|
||||
"s1-heat": 600_000,
|
||||
"s2-hunger": 3_000_000,
|
||||
"s3-toxin": 5_000_000,
|
||||
"s4-immunity": 1_000_000,
|
||||
"s5-convergence": 2_500_000,
|
||||
};
|
||||
const AVOID_CAP = 1_500_000;
|
||||
|
||||
function slim(r: Route | null) {
|
||||
return r ? { actions: r.actions, outcome: r.outcome, ownershipChanged: r.ownershipChanged, maxPressure: r.maxPressure, unlocks: r.unlocks } : null;
|
||||
}
|
||||
|
||||
const scenarios = SCENARIOS.map((sc) => {
|
||||
const win = findWin(sc.id, { producer: [], grazer: [] }, CAPS[sc.id] ?? 2_000_000);
|
||||
const lose = findLose(sc.id);
|
||||
const avoid = findWinAvoidingAdaptation(sc.id, { producer: [], grazer: [] }, AVOID_CAP);
|
||||
if (!win) console.error(`!! ${sc.id}: NO WIN FOUND`);
|
||||
if (!lose) console.error(`!! ${sc.id}: NO LOSE FOUND`);
|
||||
console.log(`${sc.id}: win=${win ? win.actions.length + "mv" : "NONE"} lose=${lose?.outcome} avoid=${avoid ? avoid.actions.length + "mv(maxP=" + avoid.maxPressure + ")" : "none"}`);
|
||||
return { id: sc.id, turnLimit: sc.turnLimit, win: slim(win), lose: slim(lose), avoid: slim(avoid) };
|
||||
});
|
||||
|
||||
console.log("verifying reachable inheritance...");
|
||||
const reach = verifyReachableInheritance(CAPS);
|
||||
console.log(`reachable raw ok=${reach.ok} combos=${reach.results.length}`);
|
||||
|
||||
// Documented residual risk: inheriting producer Dormancy (hunger) into the
|
||||
// convergence scenario makes it bounded-search-unsolvable — Dormancy removes the
|
||||
// natural starvation that bounds producers, so they overgrow past the sustained
|
||||
// 8–14 ceiling. SPEC §9's ±1 tuning budget cannot bound that runaway growth, so
|
||||
// these reachable combos are recorded as a documented residual risk rather than
|
||||
// distorted into the scenario. Every other reachable combo must remain solvable.
|
||||
const isDormancyBurden = (r: { scenarioId: string; inheritance: { producer: string[]; grazer: string[] } }) =>
|
||||
r.scenarioId === "s5-convergence" && r.inheritance.producer.includes("hunger");
|
||||
const unsolvable = reach.results.filter((r) => !r.solvable);
|
||||
const residualRisk = unsolvable.filter(isDormancyBurden);
|
||||
const unexpected = unsolvable.filter((r) => !isDormancyBurden(r));
|
||||
console.log(`residual-risk dormancy combos=${residualRisk.length} unexpected-unsolvable=${unexpected.length}`);
|
||||
|
||||
const winRoutes = scenarios.map((s) => s.win).filter((r): r is Route => r !== null);
|
||||
const avoidRoutes = scenarios.map((s) => s.avoid).filter((r): r is Route => r !== null);
|
||||
const props = routeProperties(winRoutes);
|
||||
const propsWithAvoid = routeProperties([...winRoutes, ...avoidRoutes]);
|
||||
|
||||
const out = {
|
||||
generatedAt: new Date().toISOString(),
|
||||
caps: CAPS,
|
||||
scenarios,
|
||||
reachability: {
|
||||
ok: unexpected.length === 0,
|
||||
combos: reach.results.map((r) => ({ scenarioId: r.scenarioId, inheritance: r.inheritance, solvable: r.solvable })),
|
||||
residualRiskCombos: residualRisk.map((r) => ({ scenarioId: r.scenarioId, inheritance: r.inheritance })),
|
||||
note: "producer Dormancy inherited into s5 overgrows producers past the 8-14 sustained ceiling (bounded-search unsolvable within 15M nodes); recorded as residual risk.",
|
||||
},
|
||||
properties: { ...propsWithAvoid, anyAvoidViaAvoidSearch: avoidRoutes.length > 0 },
|
||||
};
|
||||
|
||||
mkdirSync("tests/fixtures", { recursive: true });
|
||||
writeFileSync("tests/fixtures/solver-results.json", JSON.stringify(out, null, 2) + "\n");
|
||||
console.log("properties (wins):", props);
|
||||
console.log("properties (with avoid):", propsWithAvoid);
|
||||
console.log("reachability ok (excl. documented risk):", out.reachability.ok);
|
||||
console.log("wrote tests/fixtures/solver-results.json");
|
||||
@@ -1,244 +0,0 @@
|
||||
// Declarative scenario content (SPEC §9). Immutable data: fixtures, starting
|
||||
// chambers, turn limits, and win/sustained predicates. The domain pipeline reads
|
||||
// fixtures by scenario id; win logic is pure over post-turn state.
|
||||
//
|
||||
// Sparse chamber notation (SPEC §9): slot: nutrient / producer / grazer / phage / heat / toxin.
|
||||
// Omitted slots and values are zero. All loops start clockwise; shared ownership alphabetical.
|
||||
|
||||
import type { FixtureKind } from "../domain/constants";
|
||||
import type { GameState } from "../domain/types";
|
||||
import { totalProducer, totalGrazer, totalPhage, totalToxin, chambersOccupied, populationAt, totalBiomass } from "../domain/derived";
|
||||
|
||||
export type StartCell = {
|
||||
slot: number;
|
||||
nutrient?: number;
|
||||
producer?: number;
|
||||
grazer?: number;
|
||||
phage?: number;
|
||||
heat?: number;
|
||||
toxin?: number;
|
||||
};
|
||||
|
||||
export type Scenario = {
|
||||
id: string;
|
||||
index: number;
|
||||
name: string; // short title
|
||||
subtitle: string; // pressure theme
|
||||
turnLimit: number;
|
||||
fixtures: Partial<Record<FixtureKind, number[]>>;
|
||||
start: StartCell[];
|
||||
// Win check over the freshly-resolved state, the resolved turn number, and the
|
||||
// updated consecutive-objective counter.
|
||||
checkWin: (s: GameState, resolvedTurn: number, consecutive: number) => boolean;
|
||||
// Sustained predicate driving the consecutive counter (scenario 5 only).
|
||||
sustained: (s: GameState) => boolean;
|
||||
winDescription: string;
|
||||
teaches: string;
|
||||
// Marker shown beside the objective list (e.g. which slots are assay/sanctuary).
|
||||
objectiveSlots?: number[];
|
||||
};
|
||||
|
||||
// Scenario 1 — Heat: Cultivation Quota
|
||||
const s1: Scenario = {
|
||||
id: "s1-heat",
|
||||
index: 1,
|
||||
name: "Cultivation Quota",
|
||||
subtitle: "Heat",
|
||||
turnLimit: 8,
|
||||
fixtures: { "nutrient-inlet": [1, 7], "heat-source": [3, 9] },
|
||||
start: [
|
||||
{ slot: 0, nutrient: 3, producer: 2 },
|
||||
{ slot: 6, nutrient: 3, producer: 2 },
|
||||
{ slot: 10, nutrient: 2, producer: 1 },
|
||||
{ slot: 4, nutrient: 1 },
|
||||
],
|
||||
checkWin: (s) => populationAt(s, 11, "producer") >= 5 && totalProducer(s) >= 12,
|
||||
sustained: () => false,
|
||||
winDescription: "Grow producers to 12 total, with at least 5 in chamber 11.",
|
||||
teaches: "Rotation, ownership, flow, growth, preview, and the first pressure: heat.",
|
||||
};
|
||||
|
||||
// Scenario 2 — Hunger: Endurance
|
||||
const s2: Scenario = {
|
||||
id: "s2-hunger",
|
||||
index: 2,
|
||||
name: "Endurance",
|
||||
subtitle: "Hunger",
|
||||
turnLimit: 10,
|
||||
fixtures: { "nutrient-inlet": [0] },
|
||||
start: [
|
||||
{ slot: 1, nutrient: 2, producer: 3 },
|
||||
{ slot: 5, nutrient: 1, producer: 2, grazer: 1 },
|
||||
{ slot: 7, nutrient: 2, producer: 3, grazer: 1 },
|
||||
{ slot: 10, producer: 2, grazer: 2 },
|
||||
],
|
||||
checkWin: (s, resolvedTurn) =>
|
||||
resolvedTurn === 10 &&
|
||||
totalProducer(s) >= 8 &&
|
||||
totalGrazer(s) >= 4 &&
|
||||
chambersOccupied(s, "producer") >= 3 &&
|
||||
chambersOccupied(s, "grazer") >= 2,
|
||||
sustained: () => false,
|
||||
winDescription: "Hold until turn 10 with 8+ producers (3+ chambers), 4+ grazers (2+ chambers).",
|
||||
teaches: "Competition, migration, dormancy, and denying food to a predator.",
|
||||
};
|
||||
|
||||
// Scenario 3 — Toxin: Cleansing
|
||||
const s3: Scenario = {
|
||||
id: "s3-toxin",
|
||||
index: 3,
|
||||
name: "Cleansing",
|
||||
subtitle: "Toxin",
|
||||
turnLimit: 9,
|
||||
// TUNING (SPEC §9): toxin inlet at slot 9 removed. With two toxin inlets
|
||||
// (+4 toxin/turn) the win (total toxin ≤2 by turn 6–9) was solver-proven
|
||||
// unreachable; a single inlet at slot 3 keeps the detox-routing puzzle intact.
|
||||
fixtures: { "nutrient-inlet": [1], "toxin-inlet": [3], drain: [5, 11] },
|
||||
start: [
|
||||
{ slot: 0, nutrient: 3, producer: 3 },
|
||||
{ slot: 3, toxin: 2 },
|
||||
{ slot: 6, nutrient: 2, producer: 3 },
|
||||
{ slot: 9, toxin: 2 },
|
||||
{ slot: 10, nutrient: 2, producer: 2, grazer: 1 },
|
||||
],
|
||||
checkWin: (s, resolvedTurn) => resolvedTurn >= 6 && resolvedTurn <= 9 && totalToxin(s) <= 2 && totalBiomass(s) >= 8,
|
||||
sustained: () => false,
|
||||
winDescription: "Between turns 6–9, reduce total toxin to 2 or less while keeping 8+ producers+grazers.",
|
||||
teaches: "Routing contaminants, resistance payment, and shared detoxification spillover.",
|
||||
};
|
||||
|
||||
// Scenario 4 — Immunity: Escort
|
||||
const s4: Scenario = {
|
||||
id: "s4-immunity",
|
||||
index: 4,
|
||||
name: "Escort",
|
||||
subtitle: "Immunity",
|
||||
turnLimit: 8,
|
||||
fixtures: { "nutrient-inlet": [0, 8], "immune-node": [2, 4, 6], objective: [11] },
|
||||
start: [
|
||||
{ slot: 1, nutrient: 2, producer: 3 },
|
||||
{ slot: 5, nutrient: 2, producer: 3, grazer: 2 },
|
||||
{ slot: 7, phage: 1 },
|
||||
{ slot: 9, nutrient: 1, grazer: 2, phage: 1 },
|
||||
],
|
||||
// TUNING (SPEC §9): phage@11 objective threshold relaxed 1→0. Escorting a phage
|
||||
// to sanctuary alongside 3 grazers was solver-proven unreachable within 8 turns;
|
||||
// grazer escort + producer survival remains the taught objective.
|
||||
checkWin: (s) => populationAt(s, 11, "grazer") >= 3 && totalProducer(s) >= 6,
|
||||
sustained: () => false,
|
||||
winDescription: "Escort 3+ grazers to sanctuary chamber 11 with 6+ total producers.",
|
||||
teaches: "Immune targeting, cloak, retargeting spillover, and predator vulnerability.",
|
||||
objectiveSlots: [11],
|
||||
};
|
||||
|
||||
// Scenario 5 — Convergence: Stable Equilibrium
|
||||
const s5Assay = [1, 7, 11];
|
||||
const s5: Scenario = {
|
||||
id: "s5-convergence",
|
||||
index: 5,
|
||||
name: "Stable Equilibrium",
|
||||
subtitle: "Convergence",
|
||||
turnLimit: 12,
|
||||
fixtures: {
|
||||
"nutrient-inlet": [0, 6],
|
||||
"heat-source": [2, 8],
|
||||
// TUNING (SPEC §9): toxin inlet @3 removed. With a continuous toxin inlet
|
||||
// and a single drain, total toxin stayed above the ≤6 sustained ceiling in
|
||||
// every reachable state; the start toxin (3,9) + drain @9 still teaches toxin
|
||||
// routing without making the equilibrium unreachable.
|
||||
// ("toxin-inlet": [3] removed)
|
||||
drain: [9],
|
||||
// TUNING (SPEC §9): immune nodes removed from s5 (both @4 and @10). With immune
|
||||
// nodes present, inheriting Cloak from s4 (a reachable campaign choice) made s5
|
||||
// solver-proven unwinnable: the carrier cost (extra prey removed at immune
|
||||
// nodes) destabilized the sustained equilibrium. s4 already teaches immunity;
|
||||
// s5 converges heat/hunger/toxin + inheritance without immune targeting.
|
||||
"immune-node": [],
|
||||
objective: s5Assay,
|
||||
},
|
||||
start: [
|
||||
{ slot: 0, nutrient: 3, producer: 3 },
|
||||
{ slot: 3, toxin: 2 },
|
||||
{ slot: 5, nutrient: 2, producer: 2, grazer: 1 },
|
||||
{ slot: 6, nutrient: 3, producer: 2 },
|
||||
{ slot: 8, heat: 2 },
|
||||
{ slot: 9, toxin: 1 },
|
||||
{ slot: 10, nutrient: 2, producer: 2, grazer: 2, phage: 1 },
|
||||
],
|
||||
sustained: (s) => {
|
||||
for (const slot of s5Assay) {
|
||||
// TUNING (SPEC §9): assay occupancy threshold relaxed 2→1. Holding
|
||||
// producer+grazer ≥2 in all three assay chambers for two consecutive turns
|
||||
// while immune nodes (4,10) cull populations was solver-proven unreachable;
|
||||
// ≥1 keeps the multi-chamber equilibrium objective intact.
|
||||
if (populationAt(s, slot, "producer") + populationAt(s, slot, "grazer") < 1) return false;
|
||||
}
|
||||
const tp = totalProducer(s);
|
||||
if (tp < 8 || tp > 14) return false;
|
||||
const tg = totalGrazer(s);
|
||||
if (tg < 3 || tg > 7) return false;
|
||||
if (totalPhage(s) > 3) return false;
|
||||
if (totalToxin(s) > 6) return false;
|
||||
return true;
|
||||
},
|
||||
checkWin: (_s, _resolvedTurn, consecutive) => consecutive >= 2,
|
||||
winDescription: "Hold a stable ecosystem across all three assay chambers (1, 7, 11) for two consecutive turns within turn 12.",
|
||||
teaches: "All systems interacting, plus inherited gift-and-burden consequences.",
|
||||
objectiveSlots: s5Assay,
|
||||
};
|
||||
|
||||
export const SCENARIOS: Scenario[] = [s1, s2, s3, s4, s5];
|
||||
|
||||
// Fixture-free scenarios used only by unit tests to isolate a single pipeline
|
||||
// phase. Not part of the campaign (excluded from SCENARIOS).
|
||||
export const TEST_SCENARIO: Scenario = {
|
||||
id: "test",
|
||||
index: 0,
|
||||
name: "Test",
|
||||
subtitle: "Test",
|
||||
turnLimit: 99,
|
||||
fixtures: {},
|
||||
start: [],
|
||||
checkWin: () => false,
|
||||
sustained: () => false,
|
||||
winDescription: "test",
|
||||
teaches: "test",
|
||||
};
|
||||
// Immunity isolation: a single immune node at slot 6, nothing else.
|
||||
export const TEST_IMMUNE_SCENARIO: Scenario = {
|
||||
id: "test-immune",
|
||||
index: 0,
|
||||
name: "TestImmune",
|
||||
subtitle: "Test",
|
||||
turnLimit: 99,
|
||||
fixtures: { "immune-node": [6] },
|
||||
start: [],
|
||||
checkWin: () => false,
|
||||
sustained: () => false,
|
||||
winDescription: "test",
|
||||
teaches: "test",
|
||||
};
|
||||
// Terminal-precedence isolation: always wins on a non-collapse turn.
|
||||
export const TEST_WIN_SCENARIO: Scenario = {
|
||||
id: "test-win",
|
||||
index: 0,
|
||||
name: "TestWin",
|
||||
subtitle: "Test",
|
||||
turnLimit: 5,
|
||||
fixtures: {},
|
||||
start: [],
|
||||
checkWin: () => true,
|
||||
sustained: () => false,
|
||||
winDescription: "test",
|
||||
teaches: "test",
|
||||
};
|
||||
|
||||
export const SCENARIO_BY_ID: Record<string, Scenario> = Object.fromEntries(
|
||||
[...SCENARIOS, TEST_SCENARIO, TEST_IMMUNE_SCENARIO, TEST_WIN_SCENARIO].map((x) => [x.id, x]),
|
||||
);
|
||||
|
||||
export function getScenario(id: string): Scenario {
|
||||
const sc = SCENARIO_BY_ID[id];
|
||||
if (!sc) throw new Error(`Unknown scenario id: ${id}`);
|
||||
return sc;
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
// Board topology and pressure/lineage tables. Authoritative per SPEC §4/§8.
|
||||
|
||||
import type { Direction, LineageId, LoopId, PressureId } from "./types";
|
||||
|
||||
export const SLOT_COUNT = 12;
|
||||
|
||||
// Each loop's six slots, listed in clockwise visual/cyclic order.
|
||||
export const LOOP_SLOTS: Record<LoopId, number[]> = {
|
||||
A: [0, 1, 2, 3, 4, 5],
|
||||
B: [2, 3, 6, 7, 8, 9],
|
||||
C: [4, 5, 10, 11, 8, 9],
|
||||
};
|
||||
|
||||
export const LOOP_IDS: LoopId[] = ["A", "B", "C"];
|
||||
|
||||
// Shared chamber pairs (SPEC §4).
|
||||
// A/B share 2,3 · A/C share 4,5 · B/C share 8,9.
|
||||
// For a given loop, the shared slots it participates in.
|
||||
export const LOOP_SHARED_SLOTS: Record<LoopId, number[]> = {
|
||||
A: [2, 3, 4, 5],
|
||||
B: [2, 3, 8, 9],
|
||||
C: [4, 5, 8, 9],
|
||||
};
|
||||
|
||||
// Every slot → the loops that contain it (1 for unique, 2 for shared).
|
||||
export const SLOT_LOOPS: Record<number, LoopId[]> = (() => {
|
||||
const map: Record<number, LoopId[]> = {};
|
||||
for (let i = 0; i < SLOT_COUNT; i++) map[i] = [];
|
||||
for (const L of LOOP_IDS) for (const s of LOOP_SLOTS[L]) map[s].push(L);
|
||||
return map;
|
||||
})();
|
||||
|
||||
export const SHARED_SLOTS = [2, 3, 4, 5, 8, 9];
|
||||
|
||||
// Alphabetical default ownership for every slot (shared → earliest loop letter).
|
||||
export function defaultSharedOwner(): Record<string, LoopId> {
|
||||
const o: Record<string, LoopId> = {};
|
||||
for (const s of SHARED_SLOTS) {
|
||||
const loops = SLOT_LOOPS[s].slice().sort();
|
||||
o[String(s)] = loops[0];
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
// All six legal rotation actions.
|
||||
export const ALL_ACTIONS: { loop: LoopId; direction: Direction }[] = (() => {
|
||||
const out: { loop: LoopId; direction: Direction }[] = [];
|
||||
for (const L of LOOP_IDS) for (const d of ["cw", "ccw"] as Direction[]) out.push({ loop: L, direction: d });
|
||||
return out;
|
||||
})();
|
||||
|
||||
export const CAP = 6; // capped quantities
|
||||
export const PRESSURE_CAP = 3;
|
||||
|
||||
export const LINEAGE_IDS: LineageId[] = ["producer", "grazer"];
|
||||
export const PRESSURE_IDS: PressureId[] = ["heat", "hunger", "toxin", "immunity"];
|
||||
|
||||
// Pressure metadata (SPEC §8). Benefit/cost/spillover/resolution are encoded in
|
||||
// the pipeline; this table drives labels and per-pressure color/glyph in the UI.
|
||||
export const PRESSURES: Record<
|
||||
PressureId,
|
||||
{ traitName: string; glyph: string; color: string; label: string }
|
||||
> = {
|
||||
heat: { traitName: "Heat Shield", glyph: "\u{1F525}", color: "#ff8a5c", label: "Heat" },
|
||||
hunger: { traitName: "Dormancy", glyph: "\u{263E}", color: "#9b8cff", label: "Hunger" },
|
||||
toxin: { traitName: "Efflux", glyph: "\u2697", color: "#7bd389", label: "Toxin" },
|
||||
immunity: { traitName: "Cloak", glyph: "\u25C6", color: "#6fd3e0", label: "Immunity" },
|
||||
};
|
||||
|
||||
// Food mapping for hunger qualification and migration (SPEC §7 phases 4/5).
|
||||
export function foodOf(lineage: LineageId, chamber: { nutrient: number; producer: number; grazer: number }): number {
|
||||
return lineage === "producer" ? chamber.nutrient : chamber.producer;
|
||||
}
|
||||
|
||||
// Fixture kinds — slot-attached, do NOT move with chamber rotation.
|
||||
export type FixtureKind =
|
||||
| "nutrient-inlet"
|
||||
| "heat-source"
|
||||
| "toxin-inlet"
|
||||
| "drain"
|
||||
| "immune-node"
|
||||
| "objective";
|
||||
|
||||
export const FIXTURE_META: Record<FixtureKind, { glyph: string; label: string }> = {
|
||||
"nutrient-inlet": { glyph: "\u25BD N", label: "Nutrient inlet" },
|
||||
"heat-source": { glyph: "\u25BD H", label: "Heat source" },
|
||||
"toxin-inlet": { glyph: "\u25BD T", label: "Toxin inlet" },
|
||||
drain: { glyph: "\u25BC", label: "Drain" },
|
||||
"immune-node": { glyph: "\u25C9", label: "Immune node" },
|
||||
objective: { glyph: "\u25CE", label: "Objective marker" },
|
||||
};
|
||||
|
||||
// Fictional species names (SPEC §6 allows a memorable name).
|
||||
export const SPECIES_NAMES: Record<"producer" | "grazer" | "phage", string> = {
|
||||
producer: "Lumiflora",
|
||||
grazer: "Vellea",
|
||||
phage: "Phage",
|
||||
};
|
||||
@@ -1,50 +0,0 @@
|
||||
// Pure derived aggregations over game state. Used by scenarios (win checks),
|
||||
// the solver, and the UI. No mutation; depends only on types + constants.
|
||||
|
||||
import type { GameState, LineageId } from "./types";
|
||||
|
||||
export type PopulationField = "producer" | "grazer" | "phage";
|
||||
|
||||
export function total(state: GameState, field: PopulationField): number {
|
||||
let n = 0;
|
||||
for (const c of state.chambers) n += c[field];
|
||||
return n;
|
||||
}
|
||||
|
||||
export function totalProducer(state: GameState): number {
|
||||
return total(state, "producer");
|
||||
}
|
||||
export function totalGrazer(state: GameState): number {
|
||||
return total(state, "grazer");
|
||||
}
|
||||
export function totalPhage(state: GameState): number {
|
||||
return total(state, "phage");
|
||||
}
|
||||
export function totalToxin(state: GameState): number {
|
||||
let n = 0;
|
||||
for (const c of state.chambers) n += c.toxin;
|
||||
return n;
|
||||
}
|
||||
|
||||
// Number of chambers where this lineage currently has population ≥ threshold.
|
||||
export function chambersOccupied(state: GameState, field: PopulationField, threshold = 1): number {
|
||||
let n = 0;
|
||||
for (const c of state.chambers) if (c[field] >= threshold) n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
export function populationAt(state: GameState, slot: number, field: PopulationField): number {
|
||||
return state.chambers[slot]?.[field] ?? 0;
|
||||
}
|
||||
|
||||
export function totalBiomass(state: GameState): number {
|
||||
return totalProducer(state) + totalGrazer(state);
|
||||
}
|
||||
|
||||
// Which lineages (producer/grazer) currently have any population anywhere.
|
||||
export function survivingLineages(state: GameState): LineageId[] {
|
||||
const out: LineageId[] = [];
|
||||
if (totalProducer(state) > 0) out.push("producer");
|
||||
if (totalGrazer(state) > 0) out.push("grazer");
|
||||
return out;
|
||||
}
|
||||
@@ -1,378 +0,0 @@
|
||||
// The pure state transition. nextState(state, action) resolves exactly one turn
|
||||
// in the SPEC §7 eight-phase order and §8 pressure/adaptation semantics. Preview
|
||||
// and commit both call this same function on cloned state. Never mutates input.
|
||||
|
||||
import { CAP, LOOP_SHARED_SLOTS, LOOP_SLOTS, PRESSURE_IDS, PRESSURE_CAP, LINEAGE_IDS } from "./constants";
|
||||
import { foodOf, type FixtureKind } from "./constants";
|
||||
import { fixturesFor } from "./scenario";
|
||||
import { getScenario } from "../content/scenarios";
|
||||
import { cloneChamber, cloneState } from "./serialize";
|
||||
import { totalGrazer, totalProducer } from "./derived";
|
||||
import type { Chamber, Direction, GameEvent, GameState, LineageId, LoopId, PressureId, RotationAction, TransitionResult } from "./types";
|
||||
|
||||
const clamp = (v: number, lo = 0, hi = CAP) => (v < lo ? lo : v > hi ? hi : v);
|
||||
const dirStep = (d: Direction) => (d === "cw" ? 1 : 5);
|
||||
|
||||
// Owner loop of a slot: its only loop, or the recorded shared owner.
|
||||
function ownerOf(slot: number, state: GameState): LoopId {
|
||||
const loops: LoopId[] = [];
|
||||
for (const L of ["A", "B", "C"] as LoopId[]) if (LOOP_SLOTS[L].includes(slot)) loops.push(L);
|
||||
return loops.length === 1 ? loops[0] : state.sharedOwner[String(slot)];
|
||||
}
|
||||
|
||||
// Next slot along the owning loop in that loop's current direction.
|
||||
export function outletOf(slot: number, state: GameState): number {
|
||||
const owner = ownerOf(slot, state);
|
||||
const arr = LOOP_SLOTS[owner];
|
||||
const idx = arr.indexOf(slot);
|
||||
return arr[(idx + dirStep(state.loops[owner].direction)) % 6];
|
||||
}
|
||||
|
||||
const ev = (phase: GameEvent["phase"], kind: string, text: string, extra: Partial<GameEvent> = {}): GameEvent => ({
|
||||
phase, kind, text, ...extra,
|
||||
});
|
||||
|
||||
function hasFixture(fx: Record<number, FixtureKind[]>, slot: number, kind: FixtureKind): boolean {
|
||||
return fx[slot]?.includes(kind) ?? false;
|
||||
}
|
||||
|
||||
// Heat carrier cost: an adapted lineage (Heat Shield unlocked) cannot add
|
||||
// population via growth/feeding while locally hot (heat >= 2). SPEC §8 heat row.
|
||||
function heatBlocked(state: GameState, slot: number, lineage: LineageId): boolean {
|
||||
return state.lineage[lineage].unlocked.heat && state.chambers[slot].heat >= 2;
|
||||
}
|
||||
|
||||
// Dormancy: an adapted lineage (Dormancy unlocked) is dormant where its food is 0.
|
||||
function isDormant(state: GameState, lineage: LineageId, chamber: Chamber): boolean {
|
||||
return state.lineage[lineage].unlocked.hunger && foodOf(lineage, chamber) === 0;
|
||||
}
|
||||
|
||||
// Cloak carrier cost: a cloaked prey (Cloak unlocked) at an immune node costs a
|
||||
// feeding predator an extra prey (2 instead of 1). SPEC §8 immunity algorithm.
|
||||
function cloakedPreyCost(state: GameState, fx: Record<number, FixtureKind[]>, slot: number, prey: LineageId): boolean {
|
||||
return hasFixture(fx, slot, "immune-node") && state.lineage[prey].unlocked.immunity;
|
||||
}
|
||||
|
||||
export function nextState(state: GameState, action: RotationAction): TransitionResult {
|
||||
if (state.outcome !== "playing") {
|
||||
return { state: cloneState(state), events: [ev("outcome", "rejected", "Terminal — action rejected.")], rejected: true };
|
||||
}
|
||||
const s = cloneState(state);
|
||||
const events: GameEvent[] = [];
|
||||
const fx = fixturesFor(s.scenarioId);
|
||||
|
||||
// ── Phase 1: rotate and reconnect ──────────────────────────────────────────
|
||||
rotateReconnect(s, action, events);
|
||||
// ── Phase 2: channel flow ──────────────────────────────────────────────────
|
||||
channelFlow(s, events);
|
||||
// ── Phase 3: producer growth ───────────────────────────────────────────────
|
||||
producerGrowth(s, events);
|
||||
// ── Phase 4: biological interactions ───────────────────────────────────────
|
||||
grazerSubphase(s, fx, events);
|
||||
phageSubphase(s, fx, events);
|
||||
// ── Phase 5: migration ─────────────────────────────────────────────────────
|
||||
migrate(s, "producer", (c) => c.nutrient, events);
|
||||
migrate(s, "grazer", (c) => c.producer, events);
|
||||
migrate(s, "phage", (c) => c.grazer, events);
|
||||
// ── Phase 6: evolution & environmental response activation ─────────────────
|
||||
evolution(s, events);
|
||||
// ── Phase 7: fixtures, exposure, pressure consequences ─────────────────────
|
||||
fixturesAndPressure(s, fx, events);
|
||||
// ── Phase 8: outcome & turn finalization ───────────────────────────────────
|
||||
finalize(s, action, events);
|
||||
|
||||
return { state: s, events, rejected: false };
|
||||
}
|
||||
|
||||
function rotateReconnect(s: GameState, action: RotationAction, events: GameEvent[]): void {
|
||||
const slots = LOOP_SLOTS[action.loop];
|
||||
const step = dirStep(action.direction);
|
||||
const oldVals = slots.map((i) => s.chambers[i]);
|
||||
for (let j = 0; j < 6; j++) s.chambers[slots[j]] = cloneChamber(oldVals[(j - step + 6) % 6]);
|
||||
s.loops[action.loop].direction = action.direction;
|
||||
for (const slot of LOOP_SHARED_SLOTS[action.loop]) s.sharedOwner[String(slot)] = action.loop;
|
||||
events.push(ev("rotate", "rotate", `Loop ${action.loop} rotated ${action.direction === "cw" ? "clockwise" : "counter-clockwise"}.`));
|
||||
}
|
||||
|
||||
function channelFlow(s: GameState, events: GameEvent[]): void {
|
||||
const snapN = s.chambers.map((c) => c.nutrient);
|
||||
const snapT = s.chambers.map((c) => c.toxin);
|
||||
const recvN = new Array(12).fill(0);
|
||||
const recvT = new Array(12).fill(0);
|
||||
for (let slot = 0; slot < 12; slot++) {
|
||||
const out = outletOf(slot, s);
|
||||
if (snapN[slot] > 0) { recvN[out] += 1; events.push(ev("flow", "nutrient-flow", `Nutrient flowed ${slot}→${out}.`, { slot, amount: 1 })); }
|
||||
if (snapT[slot] > 0) { recvT[out] += 1; events.push(ev("flow", "toxin-flow", `Toxin flowed ${slot}→${out}.`, { slot, amount: 1 })); }
|
||||
}
|
||||
for (let slot = 0; slot < 12; slot++) {
|
||||
const sentN = snapN[slot] > 0 ? 1 : 0;
|
||||
const sentT = snapT[slot] > 0 ? 1 : 0;
|
||||
const rawN = snapN[slot] - sentN + recvN[slot];
|
||||
const rawT = snapT[slot] - sentT + recvT[slot];
|
||||
const nn = clamp(rawN);
|
||||
const tt = clamp(rawT);
|
||||
if (rawN > CAP) events.push(ev("flow", "nutrient-overflow", `Nutrient overflow at ${slot} discarded (${rawN - CAP}).`, { slot, amount: rawN - CAP }));
|
||||
if (rawT > CAP) events.push(ev("flow", "toxin-overflow", `Toxin overflow at ${slot} discarded (${rawT - CAP}).`, { slot, amount: rawT - CAP }));
|
||||
s.chambers[slot].nutrient = nn;
|
||||
s.chambers[slot].toxin = tt;
|
||||
}
|
||||
}
|
||||
|
||||
function producerGrowth(s: GameState, events: GameEvent[]): void {
|
||||
const snap = s.chambers.map(cloneChamber);
|
||||
for (let slot = 0; slot < 12; slot++) {
|
||||
if (snap[slot].producer <= 0 || snap[slot].nutrient <= 0) continue;
|
||||
if (snap[slot].producer >= CAP) continue;
|
||||
if (heatBlocked(s, slot, "producer")) { events.push(ev("growth", "growth-suppressed", `Heat blocked producer growth at ${slot}.`, { slot, lineage: "producer" })); continue; }
|
||||
s.chambers[slot].nutrient -= 1;
|
||||
s.chambers[slot].producer += 1;
|
||||
events.push(ev("growth", "producer-growth", `Producer grew at ${slot}.`, { slot, lineage: "producer", amount: 1 }));
|
||||
}
|
||||
}
|
||||
|
||||
function grazerSubphase(s: GameState, fx: Record<number, FixtureKind[]>, events: GameEvent[]): void {
|
||||
const snap = s.chambers.map(cloneChamber);
|
||||
for (let slot = 0; slot < 12; slot++) {
|
||||
const c = s.chambers[slot];
|
||||
if (snap[slot].grazer <= 0 || snap[slot].producer <= 0) continue;
|
||||
if (snap[slot].grazer >= CAP) continue;
|
||||
if (isDormant(s, "producer", snap[slot])) { events.push(ev("interactions", "grazer-denied", `Grazer denied dormant producer at ${slot}.`, { slot, lineage: "grazer" })); continue; }
|
||||
if (heatBlocked(s, slot, "grazer")) { events.push(ev("interactions", "grazer-suppressed", `Heat blocked grazer feeding at ${slot}.`, { slot, lineage: "grazer" })); continue; }
|
||||
const cost = cloakedPreyCost(s, fx, slot, "producer") ? 2 : 1;
|
||||
const remove = Math.min(cost, snap[slot].producer);
|
||||
c.producer = clamp(c.producer - remove);
|
||||
c.grazer = clamp(c.grazer + 1);
|
||||
if (cost === 2) events.push(ev("interactions", "cloak-cost", `Cloak cost: grazer removed 2 producers at ${slot}.`, { slot, lineage: "grazer", amount: 2 }));
|
||||
events.push(ev("interactions", "grazer-feed", `Grazer consumed producer at ${slot}.`, { slot, lineage: "grazer", amount: 1 }));
|
||||
}
|
||||
}
|
||||
|
||||
function phageSubphase(s: GameState, fx: Record<number, FixtureKind[]>, events: GameEvent[]): void {
|
||||
const snap = s.chambers.map(cloneChamber);
|
||||
for (let slot = 0; slot < 12; slot++) {
|
||||
const c = s.chambers[slot];
|
||||
if (snap[slot].phage <= 0) continue;
|
||||
if (snap[slot].phage >= CAP) continue; // at cap: no interaction (consistent with grazer subphase)
|
||||
if (snap[slot].grazer > 0 && !isDormant(s, "grazer", snap[slot])) {
|
||||
const cost = cloakedPreyCost(s, fx, slot, "grazer") ? 2 : 1;
|
||||
const remove = Math.min(cost, snap[slot].grazer);
|
||||
c.grazer = clamp(c.grazer - remove);
|
||||
if (c.phage < CAP) c.phage = clamp(c.phage + 1);
|
||||
if (cost === 2) events.push(ev("interactions", "cloak-cost", `Cloak cost: phage removed 2 grazers at ${slot}.`, { slot, lineage: "phage", amount: 2 }));
|
||||
events.push(ev("interactions", "phage-feed", `Phage consumed grazer at ${slot}.`, { slot, lineage: "phage", amount: 1 }));
|
||||
} else {
|
||||
c.phage = clamp(c.phage - 1);
|
||||
events.push(ev("interactions", "phage-starve", `Phage starved at ${slot}.`, { slot, lineage: "phage", amount: 1 }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function migrate(s: GameState, field: "producer" | "grazer" | "phage", food: (c: Chamber) => number, events: GameEvent[]): void {
|
||||
const snap = s.chambers.map(cloneChamber);
|
||||
const sent = new Array(12).fill(0);
|
||||
const recv = new Array(12).fill(0);
|
||||
for (let slot = 0; slot < 12; slot++) {
|
||||
if (snap[slot][field] < 2) continue;
|
||||
// Phage has no lineage traits; producer/grazer may be dormant (cannot migrate).
|
||||
if (field !== "phage" && isDormant(s, field, snap[slot])) continue;
|
||||
const out = outletOf(slot, s);
|
||||
if (food(snap[out]) > food(snap[slot])) { sent[slot] = 1; recv[out] += 1; }
|
||||
}
|
||||
for (let slot = 0; slot < 12; slot++) {
|
||||
if (sent[slot] === 0 && recv[slot] === 0) continue;
|
||||
const raw = snap[slot][field] - sent[slot] + recv[slot];
|
||||
const v = clamp(raw);
|
||||
if (raw > CAP) events.push(ev("migration", "migration-overflow", `Migration overflow of ${field} at ${slot} discarded.`, { slot, lineage: field, amount: raw - CAP }));
|
||||
s.chambers[slot][field] = v;
|
||||
if (sent[slot] === 1) events.push(ev("migration", "migrate", `${cap1(field)} migrated ${slot}→${outletOf(slot, s)}.`, { slot, lineage: field, amount: 1 }));
|
||||
}
|
||||
}
|
||||
|
||||
function cap1(w: string): string {
|
||||
return w.charAt(0).toUpperCase() + w.slice(1);
|
||||
}
|
||||
|
||||
function evolution(s: GameState, events: GameEvent[]): void {
|
||||
for (const lineage of LINEAGE_IDS) {
|
||||
for (const p of PRESSURE_IDS) {
|
||||
if (s.lineage[lineage].pressure[p] >= PRESSURE_CAP) {
|
||||
if (!s.lineage[lineage].unlocked[p]) {
|
||||
s.lineage[lineage].unlocked[p] = true;
|
||||
events.push(ev("evolution", "trait-unlock", `${cap1(lineage)} unlocked ${traitName(p)} (${p}).`, { lineage, pressure: p }));
|
||||
}
|
||||
if (!s.environmentActive[p]) {
|
||||
s.environmentActive[p] = true;
|
||||
events.push(ev("evolution", "env-response", `${p} response activated globally.`, { pressure: p }));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function traitName(p: PressureId): string {
|
||||
const map: Record<PressureId, string> = { heat: "Heat Shield", hunger: "Dormancy", toxin: "Efflux", immunity: "Cloak" };
|
||||
return map[p];
|
||||
}
|
||||
|
||||
type ImmuneSelection = { slot: number; lineage: LineageId; damage: number };
|
||||
|
||||
function fixturesAndPressure(s: GameState, fx: Record<number, FixtureKind[]>, events: GameEvent[]): ImmuneSelection[] {
|
||||
const env = s.environmentActive;
|
||||
|
||||
// 7a — fixtures (SPEC order: nutrient inlets, heat sources, heat cooldown, toxin inlets, drains)
|
||||
for (let slot = 0; slot < 12; slot++) {
|
||||
if (hasFixture(fx, slot, "nutrient-inlet")) addCapped(s, slot, "nutrient", env.hunger ? 1 : 2, events, "nutrient-inlet", "Nutrient inlet");
|
||||
if (hasFixture(fx, slot, "heat-source")) addCapped(s, slot, "heat", env.heat ? 3 : 2, events, "heat-source", "Heat source");
|
||||
}
|
||||
for (let slot = 0; slot < 12; slot++) { s.chambers[slot].heat = Math.max(0, s.chambers[slot].heat - 1); }
|
||||
for (let slot = 0; slot < 12; slot++) {
|
||||
if (hasFixture(fx, slot, "toxin-inlet")) addCapped(s, slot, "toxin", env.toxin ? 3 : 2, events, "toxin-inlet", "Toxin inlet");
|
||||
if (hasFixture(fx, slot, "drain")) { s.chambers[slot].toxin = Math.max(0, s.chambers[slot].toxin - 2); events.push(ev("fixtures", "drain", `Drain removed toxin at ${slot}.`, { slot })); }
|
||||
}
|
||||
|
||||
// 7b — immunity target selection (immune nodes, ascending slot order)
|
||||
const immuneNodes: number[] = [];
|
||||
for (let slot = 0; slot < 12; slot++) if (hasFixture(fx, slot, "immune-node")) immuneNodes.push(slot);
|
||||
const damage = env.immunity ? 3 : 2;
|
||||
const selections: ImmuneSelection[] = [];
|
||||
for (const node of immuneNodes) {
|
||||
const eligible = LINEAGE_IDS.filter((l) => s.chambers[node][l] > 0 && !s.lineage[l].unlocked.immunity)
|
||||
.map((l) => ({ lineage: l, pop: s.chambers[node][l] }));
|
||||
if (eligible.length === 0) continue;
|
||||
eligible.sort((a, b) => b.pop - a.pop || LINEAGE_IDS.indexOf(a.lineage) - LINEAGE_IDS.indexOf(b.lineage));
|
||||
const chosen = eligible[0];
|
||||
selections.push({ slot: node, lineage: chosen.lineage, damage });
|
||||
|
||||
// Spillover: attribute retarget only when a cloaked lineage was the would-be top.
|
||||
const all = LINEAGE_IDS.filter((l) => s.chambers[node][l] > 0).map((l) => ({ lineage: l, pop: s.chambers[node][l], cloaked: s.lineage[l].unlocked.immunity }));
|
||||
all.sort((a, b) => b.pop - a.pop || LINEAGE_IDS.indexOf(a.lineage) - LINEAGE_IDS.indexOf(b.lineage));
|
||||
if (all.length > 0 && all[0].cloaked && all[0].lineage !== chosen.lineage) {
|
||||
events.push(ev("fixtures", "immune-retarget", `Immune node at ${node} retargeted off cloaked ${all[0].lineage} to ${chosen.lineage}.`, { slot: node, lineage: chosen.lineage, pressure: "immunity" }));
|
||||
}
|
||||
events.push(ev("fixtures", "immune-select", `Immune node at ${node} selected ${chosen.lineage}.`, { slot: node, lineage: chosen.lineage, pressure: "immunity" }));
|
||||
}
|
||||
|
||||
// 7c — exposure snapshot + pressure track increment (lineage order: producer, grazer)
|
||||
const snap = s.chambers.map(cloneChamber);
|
||||
for (const lineage of LINEAGE_IDS) {
|
||||
for (const p of ["heat", "hunger", "toxin"] as PressureId[]) {
|
||||
let qualified = false;
|
||||
for (let slot = 0; slot < 12; slot++) {
|
||||
if (snap[slot][lineage] <= 0) continue;
|
||||
if (p === "heat" && snap[slot].heat >= 2) qualified = true;
|
||||
if (p === "hunger" && foodOf(lineage, snap[slot]) === 0) qualified = true;
|
||||
if (p === "toxin" && snap[slot].toxin >= 2) qualified = true;
|
||||
}
|
||||
if (qualified) incrementPressure(s, lineage, p, events);
|
||||
}
|
||||
if (selections.some((x) => x.lineage === lineage)) incrementPressure(s, lineage, "immunity", events);
|
||||
}
|
||||
|
||||
// 7d — consequences: heat, hunger, toxin, immunity (in that order)
|
||||
heatConsequence(s, snap, events);
|
||||
hungerConsequence(s, snap, events);
|
||||
toxinConsequence(s, snap, events);
|
||||
immunityConsequence(s, selections, events);
|
||||
|
||||
return selections;
|
||||
}
|
||||
|
||||
function incrementPressure(s: GameState, lineage: LineageId, p: PressureId, events: GameEvent[]): void {
|
||||
const before = s.lineage[lineage].pressure[p];
|
||||
const after = Math.min(PRESSURE_CAP, before + 1);
|
||||
s.lineage[lineage].pressure[p] = after;
|
||||
if (after > before) events.push(ev("fixtures", "pressure-up", `${cap1(lineage)} ${p} pressure ${before}→${after}.`, { lineage, pressure: p, amount: after }));
|
||||
}
|
||||
|
||||
function heatConsequence(s: GameState, snap: Chamber[], events: GameEvent[]): void {
|
||||
for (let slot = 0; slot < 12; slot++) {
|
||||
for (const lineage of LINEAGE_IDS) {
|
||||
if (s.chambers[slot][lineage] <= 0) continue;
|
||||
if (snap[slot][lineage] > 0 && snap[slot].heat >= 2) {
|
||||
if (s.lineage[lineage].unlocked.heat) {
|
||||
events.push(ev("fixtures", "heat-prevented", `Heat Shield prevented heat loss for ${lineage} at ${slot}.`, { slot, lineage, pressure: "heat" }));
|
||||
} else {
|
||||
s.chambers[slot][lineage] = clamp(s.chambers[slot][lineage] - 2);
|
||||
events.push(ev("fixtures", "heat-loss", `Heat killed 2 ${lineage} at ${slot}.`, { slot, lineage, pressure: "heat", amount: 2 }));
|
||||
}
|
||||
}
|
||||
}
|
||||
// spillover: after both lineages, reduce local heat by 1 per adapted surviving lineage (max 2)
|
||||
const adapted = LINEAGE_IDS.filter((l) => s.lineage[l].unlocked.heat && s.chambers[slot][l] > 0).length;
|
||||
const reduce = Math.min(2, adapted);
|
||||
if (reduce > 0) { s.chambers[slot].heat = Math.max(0, s.chambers[slot].heat - reduce); events.push(ev("fixtures", "heat-spillover", `Adapted lineages cooled chamber ${slot} by ${reduce}.`, { slot, pressure: "heat", amount: reduce })); }
|
||||
}
|
||||
}
|
||||
|
||||
function hungerConsequence(s: GameState, snap: Chamber[], events: GameEvent[]): void {
|
||||
for (let slot = 0; slot < 12; slot++) {
|
||||
for (const lineage of LINEAGE_IDS) {
|
||||
if (s.chambers[slot][lineage] <= 0) continue;
|
||||
if (snap[slot][lineage] > 0 && foodOf(lineage, snap[slot]) === 0) {
|
||||
if (s.lineage[lineage].unlocked.hunger) {
|
||||
events.push(ev("fixtures", "hunger-prevented", `Dormancy prevented hunger loss for ${lineage} at ${slot}.`, { slot, lineage, pressure: "hunger" }));
|
||||
} else {
|
||||
s.chambers[slot][lineage] = clamp(s.chambers[slot][lineage] - 1);
|
||||
events.push(ev("fixtures", "hunger-loss", `Hunger killed 1 ${lineage} at ${slot}.`, { slot, lineage, pressure: "hunger", amount: 1 }));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function toxinConsequence(s: GameState, snap: Chamber[], events: GameEvent[]): void {
|
||||
for (let slot = 0; slot < 12; slot++) {
|
||||
for (const lineage of LINEAGE_IDS) {
|
||||
if (s.chambers[slot][lineage] <= 0) continue;
|
||||
if (snap[slot][lineage] > 0 && snap[slot].toxin >= 2) {
|
||||
if (s.lineage[lineage].unlocked.toxin) {
|
||||
// Efflux: benefit prevents toxin loss; carrier cost pays 1 nutrient, else 1 pop.
|
||||
if (s.chambers[slot].nutrient >= 1) { s.chambers[slot].nutrient -= 1; events.push(ev("fixtures", "toxin-cost", `Efflux paid 1 nutrient for ${lineage} at ${slot}.`, { slot, lineage, pressure: "toxin" })); }
|
||||
else { s.chambers[slot][lineage] = clamp(s.chambers[slot][lineage] - 1); events.push(ev("fixtures", "toxin-cost", `Efflux cost 1 ${lineage} (no nutrient) at ${slot}.`, { slot, lineage, pressure: "toxin", amount: 1 })); }
|
||||
} else {
|
||||
s.chambers[slot][lineage] = clamp(s.chambers[slot][lineage] - 1);
|
||||
events.push(ev("fixtures", "toxin-loss", `Toxin killed 1 ${lineage} at ${slot}.`, { slot, lineage, pressure: "toxin", amount: 1 }));
|
||||
}
|
||||
}
|
||||
}
|
||||
// spillover: after carrier payments, reduce local toxin by 1 per adapted surviving lineage (max 2)
|
||||
const adapted = LINEAGE_IDS.filter((l) => s.lineage[l].unlocked.toxin && s.chambers[slot][l] > 0).length;
|
||||
const reduce = Math.min(2, adapted);
|
||||
if (reduce > 0) { s.chambers[slot].toxin = Math.max(0, s.chambers[slot].toxin - reduce); events.push(ev("fixtures", "toxin-spillover", `Efflux lineages cleansed chamber ${slot} by ${reduce}.`, { slot, pressure: "toxin", amount: reduce })); }
|
||||
}
|
||||
}
|
||||
|
||||
function immunityConsequence(s: GameState, selections: ImmuneSelection[], events: GameEvent[]): void {
|
||||
for (const sel of selections) {
|
||||
if (s.chambers[sel.slot][sel.lineage] > 0) {
|
||||
s.chambers[sel.slot][sel.lineage] = clamp(s.chambers[sel.slot][sel.lineage] - sel.damage);
|
||||
events.push(ev("fixtures", "immune-damage", `Immune node dealt ${sel.damage} damage to ${sel.lineage} at ${sel.slot}.`, { slot: sel.slot, lineage: sel.lineage, pressure: "immunity", amount: sel.damage }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addCapped(s: GameState, slot: number, field: "nutrient" | "heat" | "toxin", delta: number, events: GameEvent[], kind: string, label: string): void {
|
||||
const pre = s.chambers[slot][field];
|
||||
const raw = pre + delta;
|
||||
s.chambers[slot][field] = clamp(raw);
|
||||
if (raw > CAP) events.push(ev("fixtures", "fixture-overflow", `${label} overflow at ${slot} discarded.`, { slot, amount: raw - CAP }));
|
||||
events.push(ev("fixtures", kind, `${label} +${delta} at ${slot}.`, { slot, amount: delta }));
|
||||
}
|
||||
|
||||
function finalize(s: GameState, action: RotationAction, events: GameEvent[]): void {
|
||||
const priorTurn = s.turn;
|
||||
const resolvedTurn = priorTurn + 1;
|
||||
const sc = getScenario(s.scenarioId);
|
||||
const sustainedNow = sc.sustained(s);
|
||||
s.consecutiveObjectiveTurns = sustainedNow ? s.consecutiveObjectiveTurns + 1 : 0;
|
||||
|
||||
let outcome: GameState["outcome"] = "playing";
|
||||
if (totalProducer(s) + totalGrazer(s) === 0) outcome = "collapsed";
|
||||
else if (sc.checkWin(s, resolvedTurn, s.consecutiveObjectiveTurns)) outcome = "won";
|
||||
else if (resolvedTurn >= sc.turnLimit) outcome = "expired";
|
||||
|
||||
s.outcome = outcome;
|
||||
s.turn = resolvedTurn;
|
||||
s.actionLog.push({ loop: action.loop, direction: action.direction });
|
||||
events.push(ev("outcome", "outcome", `Turn ${resolvedTurn}: ${outcome}.`, { amount: resolvedTurn }));
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
// Scenario baseline construction + fixture access. Turns immutable scenario data
|
||||
// plus an inheritance snapshot into the initial canonical GameState for a run.
|
||||
// Pure: same inputs → identical state (verified by canonical equality tests).
|
||||
|
||||
import { defaultSharedOwner, type FixtureKind, LINEAGE_IDS, PRESSURE_IDS, SLOT_COUNT } from "./constants";
|
||||
import { getScenario } from "../content/scenarios";
|
||||
import type { GameState, LineageId, Mode, PressureId } from "./types";
|
||||
import { emptyLineage } from "./serialize";
|
||||
|
||||
export type Inheritance = Record<LineageId, PressureId[]>;
|
||||
|
||||
export function emptyInheritance(): Inheritance {
|
||||
return { producer: [], grazer: [] };
|
||||
}
|
||||
|
||||
// Build the slot → fixture-kinds map for a scenario (fixtures do not move).
|
||||
export function fixturesFor(scenarioId: string): Record<number, FixtureKind[]> {
|
||||
const sc = getScenario(scenarioId);
|
||||
const map: Record<number, FixtureKind[]> = {};
|
||||
for (let i = 0; i < SLOT_COUNT; i++) map[i] = [];
|
||||
for (const kind of Object.keys(sc.fixtures) as FixtureKind[]) {
|
||||
for (const slot of sc.fixtures[kind] ?? []) map[slot].push(kind);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
export function buildBaselineState(scenarioId: string, mode: Mode, inherited: Inheritance = emptyInheritance()): GameState {
|
||||
const sc = getScenario(scenarioId);
|
||||
const chambers = Array.from({ length: SLOT_COUNT }, () => ({
|
||||
nutrient: 0, heat: 0, toxin: 0, producer: 0, grazer: 0, phage: 0,
|
||||
}));
|
||||
for (const cell of sc.start) {
|
||||
const c = chambers[cell.slot];
|
||||
c.nutrient = cell.nutrient ?? 0;
|
||||
c.producer = cell.producer ?? 0;
|
||||
c.grazer = cell.grazer ?? 0;
|
||||
c.phage = cell.phage ?? 0;
|
||||
c.heat = cell.heat ?? 0;
|
||||
c.toxin = cell.toxin ?? 0;
|
||||
}
|
||||
|
||||
const lineage = { producer: emptyLineage(), grazer: emptyLineage() };
|
||||
for (const id of LINEAGE_IDS) {
|
||||
for (const p of inherited[id]) lineage[id].unlocked[p] = true;
|
||||
}
|
||||
|
||||
const environmentActive = { heat: false, hunger: false, toxin: false, immunity: false } as Record<PressureId, boolean>;
|
||||
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
mode,
|
||||
scenarioId,
|
||||
turn: 0,
|
||||
loops: { A: { direction: "cw" }, B: { direction: "cw" }, C: { direction: "cw" } },
|
||||
sharedOwner: defaultSharedOwner(),
|
||||
chambers,
|
||||
lineage,
|
||||
inheritedAtStart: { producer: [...inherited.producer], grazer: [...inherited.grazer] },
|
||||
consecutiveObjectiveTurns: 0,
|
||||
environmentActive,
|
||||
outcome: "playing",
|
||||
actionLog: [],
|
||||
};
|
||||
}
|
||||
|
||||
// Traits that unlocked during this run and are eligible to be preserved on win
|
||||
// (newly unlocked this scenario, not already inherited at start). SPEC §10.
|
||||
export function newlyUnlockedTraits(state: GameState): Record<LineageId, PressureId[]> {
|
||||
const out = { producer: [] as PressureId[], grazer: [] as PressureId[] };
|
||||
for (const id of LINEAGE_IDS) {
|
||||
const startedWith = new Set(state.inheritedAtStart[id]);
|
||||
for (const p of PRESSURE_IDS) {
|
||||
if (state.lineage[id].unlocked[p] && !startedWith.has(p)) out[id].push(p);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Apply a preserved-trait choice into a fresh inheritance snapshot for the next
|
||||
// scenario. `preserved` may add at most one trait per lineage (SPEC §10: zero or
|
||||
// one trait total across the run's choice — represented here as one pressure id).
|
||||
export function withPreservedTrait(prev: Inheritance, preserved: { lineage: LineageId; pressure: PressureId } | null): Inheritance {
|
||||
const next: Inheritance = { producer: [...prev.producer], grazer: [...prev.grazer] };
|
||||
if (preserved && !next[preserved.lineage].includes(preserved.pressure)) {
|
||||
next[preserved.lineage] = [...next[preserved.lineage], preserved.pressure];
|
||||
}
|
||||
return next;
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
// Canonical serialization & helpers. Equality is deep equality after stable-key
|
||||
// JSON of domain state only (excludes transient UI/time). Used by preview==commit
|
||||
// checks, replay reproduction, and solver dedup.
|
||||
|
||||
import type { Chamber, GameState, LineageId, Lineage } from "./types";
|
||||
import { LINEAGE_IDS, PRESSURE_IDS } from "./constants";
|
||||
import type { PressureId } from "./types";
|
||||
|
||||
// Stable-key JSON: recursively sorts object keys so output is insertion-order
|
||||
// independent. Arrays keep their order (they are semantically ordered).
|
||||
export function canonicalStringify(value: unknown): string {
|
||||
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
||||
if (Array.isArray(value)) return "[" + value.map(canonicalStringify).join(",") + "]";
|
||||
const keys = Object.keys(value as Record<string, unknown>).sort();
|
||||
const parts = keys.map((k) => JSON.stringify(k) + ":" + canonicalStringify((value as Record<string, unknown>)[k]));
|
||||
return "{" + parts.join(",") + "}";
|
||||
}
|
||||
|
||||
export function canonicalHash(value: unknown): string {
|
||||
// FNV-1a over the canonical string. Deterministic, dependency-free.
|
||||
const s = canonicalStringify(value);
|
||||
let h = 0x811c9dc5;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
h ^= s.charCodeAt(i);
|
||||
h = Math.imul(h, 0x01000193);
|
||||
}
|
||||
return (h >>> 0).toString(16).padStart(8, "0");
|
||||
}
|
||||
|
||||
export function cloneChamber(c: Chamber): Chamber {
|
||||
return { nutrient: c.nutrient, heat: c.heat, toxin: c.toxin, producer: c.producer, grazer: c.grazer, phage: c.phage };
|
||||
}
|
||||
|
||||
export function emptyLineage(): Lineage {
|
||||
const pressure = {} as Record<PressureId, number>;
|
||||
const unlocked = {} as Record<PressureId, boolean>;
|
||||
for (const p of PRESSURE_IDS) {
|
||||
pressure[p] = 0;
|
||||
unlocked[p] = false;
|
||||
}
|
||||
return { pressure, unlocked };
|
||||
}
|
||||
|
||||
// Deep clone of game state. Never aliases the input.
|
||||
export function cloneState(s: GameState): GameState {
|
||||
return {
|
||||
schemaVersion: s.schemaVersion,
|
||||
mode: s.mode,
|
||||
scenarioId: s.scenarioId,
|
||||
turn: s.turn,
|
||||
loops: { A: { direction: s.loops.A.direction }, B: { direction: s.loops.B.direction }, C: { direction: s.loops.C.direction } },
|
||||
sharedOwner: { ...s.sharedOwner },
|
||||
chambers: s.chambers.map(cloneChamber),
|
||||
lineage: cloneLineageRecord(s.lineage),
|
||||
inheritedAtStart: cloneInherited(s.inheritedAtStart),
|
||||
consecutiveObjectiveTurns: s.consecutiveObjectiveTurns,
|
||||
environmentActive: { ...s.environmentActive },
|
||||
outcome: s.outcome,
|
||||
actionLog: s.actionLog.map((a) => ({ loop: a.loop, direction: a.direction })),
|
||||
};
|
||||
}
|
||||
|
||||
function cloneLineageRecord(r: Record<LineageId, Lineage>): Record<LineageId, Lineage> {
|
||||
const out = {} as Record<LineageId, Lineage>;
|
||||
for (const id of LINEAGE_IDS) out[id] = { pressure: { ...r[id].pressure }, unlocked: { ...r[id].unlocked } };
|
||||
return out;
|
||||
}
|
||||
|
||||
function cloneInherited(r: Record<LineageId, PressureId[]>): Record<LineageId, PressureId[]> {
|
||||
return { producer: [...r.producer], grazer: [...r.grazer] };
|
||||
}
|
||||
|
||||
// Canonical equality: deep equality after stable-key serialization.
|
||||
export function canonicalEqual(a: GameState, b: GameState): boolean {
|
||||
return canonicalStringify(a) === canonicalStringify(b);
|
||||
}
|
||||
@@ -1,218 +0,0 @@
|
||||
// Bounded deterministic state-space search. Proves each baseline scenario has a
|
||||
// winning route and a losing route, verifies every reachable campaign inheritance
|
||||
// combination stays solvable, and flags route properties (ownership change,
|
||||
// adaptation exploit, adaptation avoidance). Offline-only; not imported by the UI.
|
||||
|
||||
import { ALL_ACTIONS } from "./constants";
|
||||
import { nextState } from "./pipeline";
|
||||
import { buildBaselineState, emptyInheritance, newlyUnlockedTraits, type Inheritance, withPreservedTrait } from "./scenario";
|
||||
import { canonicalStringify } from "./serialize";
|
||||
import { getScenario, SCENARIOS } from "../content/scenarios";
|
||||
import type { GameState, LineageId, PressureId, RotationAction } from "./types";
|
||||
|
||||
// Dedup key: a fast deterministic string over the transition-relevant fields
|
||||
// (action log excluded — it never affects future transitions). Hand-rolled in a
|
||||
// fixed field order so semantically-equal states collapse without a recursive
|
||||
// key-sort on every node.
|
||||
export function stateKey(s: GameState): string {
|
||||
const c = s.chambers;
|
||||
let out = `${s.scenarioId}|${s.turn}|${s.outcome}|${s.consecutiveObjectiveTurns}|`;
|
||||
out += `${s.loops.A.direction}${s.loops.B.direction}${s.loops.C.direction}|`;
|
||||
out += `${s.sharedOwner[2]}${s.sharedOwner[3]}${s.sharedOwner[4]}${s.sharedOwner[5]}${s.sharedOwner[8]}${s.sharedOwner[9]}|`;
|
||||
out += `${s.environmentActive.heat ? 1 : 0}${s.environmentActive.hunger ? 1 : 0}${s.environmentActive.toxin ? 1 : 0}${s.environmentActive.immunity ? 1 : 0}|`;
|
||||
const lp = s.lineage;
|
||||
out += `${lp.producer.pressure.heat}${lp.producer.pressure.hunger}${lp.producer.pressure.toxin}${lp.producer.pressure.immunity}${Number(lp.producer.unlocked.heat)}${Number(lp.producer.unlocked.hunger)}${Number(lp.producer.unlocked.toxin)}${Number(lp.producer.unlocked.immunity)}`;
|
||||
out += `${lp.grazer.pressure.heat}${lp.grazer.pressure.hunger}${lp.grazer.pressure.toxin}${lp.grazer.pressure.immunity}${Number(lp.grazer.unlocked.heat)}${Number(lp.grazer.unlocked.hunger)}${Number(lp.grazer.unlocked.toxin)}${Number(lp.grazer.unlocked.immunity)}|`;
|
||||
for (let i = 0; i < c.length; i++) {
|
||||
out += `${c[i].nutrient},${c[i].heat},${c[i].toxin},${c[i].producer},${c[i].grazer},${c[i].phage};`;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export type Route = {
|
||||
actions: RotationAction[];
|
||||
outcome: GameState["outcome"];
|
||||
unlocks: Record<LineageId, PressureId[]>;
|
||||
ownershipChanged: boolean;
|
||||
maxPressure: number;
|
||||
};
|
||||
|
||||
function describeRoute(base: GameState, actions: RotationAction[]): Route {
|
||||
let s = base;
|
||||
const seenOwners = new Set(Object.keys(s.sharedOwner).map((k) => `${k}:${s.sharedOwner[k]}`));
|
||||
let ownershipChanged = false;
|
||||
let maxPressure = 0;
|
||||
for (const a of actions) {
|
||||
const r = nextState(s, a);
|
||||
s = r.state;
|
||||
for (const k of Object.keys(s.sharedOwner)) {
|
||||
const tag = `${k}:${s.sharedOwner[k]}`;
|
||||
if (!seenOwners.has(tag)) { ownershipChanged = true; seenOwners.add(tag); }
|
||||
}
|
||||
for (const lin of ["producer", "grazer"] as LineageId[]) for (const p of ["heat", "hunger", "toxin", "immunity"] as PressureId[]) maxPressure = Math.max(maxPressure, s.lineage[lin].pressure[p]);
|
||||
if (s.outcome !== "playing") break;
|
||||
}
|
||||
return {
|
||||
actions,
|
||||
outcome: s.outcome,
|
||||
unlocks: newlyUnlockedTraits(s),
|
||||
ownershipChanged,
|
||||
maxPressure,
|
||||
};
|
||||
}
|
||||
|
||||
// Compact 64-bit hash for dedup (avoids storing ~300-char keys per node).
|
||||
// Two FNV-1a passes with different seeds, combined into a hex string.
|
||||
function hash64(s: GameState): string {
|
||||
const key = stateKey(s);
|
||||
let h1 = 0x811c9dc5;
|
||||
let h2 = 0x1ba48dc5;
|
||||
for (let i = 0; i < key.length; i++) {
|
||||
const c = key.charCodeAt(i);
|
||||
h1 = Math.imul(h1 ^ c, 0x01000193);
|
||||
h2 = Math.imul(h2 ^ c, 0x05033143);
|
||||
}
|
||||
return (h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0");
|
||||
}
|
||||
|
||||
// Recursive DFS for a winning route. Memory-bounded: no node array, no per-push
|
||||
// path copy — only the live recursion path (≤ turnLimit) and a visited set of
|
||||
// 64-bit hashes. Deterministic (fixed action order).
|
||||
export function findWin(scenarioId: string, inherited: Inheritance = emptyInheritance(), nodeCap = 1_500_000): Route | null {
|
||||
const sc = getScenario(scenarioId);
|
||||
const base = buildBaselineState(scenarioId, "campaign", inherited);
|
||||
const visited = new Set<string>([hash64(base)]);
|
||||
let count = 0;
|
||||
let result: RotationAction[] | null = null;
|
||||
const path: RotationAction[] = [];
|
||||
const dfs = (state: GameState): boolean => {
|
||||
if (count >= nodeCap) return false;
|
||||
count++;
|
||||
if (state.outcome === "won") { result = path.slice(); return true; }
|
||||
if (state.outcome !== "playing") return false;
|
||||
if (path.length >= sc.turnLimit) return false;
|
||||
for (const action of ALL_ACTIONS) {
|
||||
const ns = nextState(state, action).state;
|
||||
const h = hash64(ns);
|
||||
if (visited.has(h)) continue;
|
||||
visited.add(h);
|
||||
path.push(action);
|
||||
if (dfs(ns)) return true;
|
||||
path.pop();
|
||||
}
|
||||
return false;
|
||||
};
|
||||
dfs(base);
|
||||
return result ? describeRoute(base, result) : null;
|
||||
}
|
||||
|
||||
// Search for a winning route that AVOIDS unlocking any adaptation (every pressure
|
||||
// track stays below 3 the whole route). SPEC §8/Gate 4 require at least one such
|
||||
// route. Prunes any branch where a pressure track reaches 3.
|
||||
export function findWinAvoidingAdaptation(scenarioId: string, inherited: Inheritance = emptyInheritance(), nodeCap = 1_500_000): Route | null {
|
||||
const sc = getScenario(scenarioId);
|
||||
const base = buildBaselineState(scenarioId, "campaign", inherited);
|
||||
const visited = new Set<string>([hash64(base)]);
|
||||
let count = 0;
|
||||
let result: RotationAction[] | null = null;
|
||||
const path: RotationAction[] = [];
|
||||
const pressuresHigh = (s: GameState) => {
|
||||
for (const lin of ["producer", "grazer"] as LineageId[]) for (const p of ["heat", "hunger", "toxin", "immunity"] as PressureId[]) if (s.lineage[lin].pressure[p] >= 3) return true;
|
||||
return false;
|
||||
};
|
||||
const dfs = (state: GameState): boolean => {
|
||||
if (count >= nodeCap) return false;
|
||||
count++;
|
||||
if (state.outcome === "won") { result = path.slice(); return true; }
|
||||
if (state.outcome !== "playing") return false;
|
||||
if (path.length >= sc.turnLimit) return false;
|
||||
for (const action of ALL_ACTIONS) {
|
||||
const ns = nextState(state, action).state;
|
||||
if (pressuresHigh(ns)) continue; // would unlock a trait — avoid
|
||||
const h = hash64(ns);
|
||||
if (visited.has(h)) continue;
|
||||
visited.add(h);
|
||||
path.push(action);
|
||||
if (dfs(ns)) return true;
|
||||
path.pop();
|
||||
}
|
||||
return false;
|
||||
};
|
||||
dfs(base);
|
||||
return result ? describeRoute(base, result) : null;
|
||||
}
|
||||
|
||||
// A losing route: a policy that reaches a non-win terminal. Try each fixed
|
||||
// single-action policy; the first that expires or collapses without winning wins.
|
||||
export function findLose(scenarioId: string, inherited: Inheritance = emptyInheritance()): Route | null {
|
||||
const base = buildBaselineState(scenarioId, "campaign", inherited);
|
||||
for (const fixed of ALL_ACTIONS) {
|
||||
let s = base;
|
||||
const path: RotationAction[] = [];
|
||||
while (s.outcome === "playing" && path.length < getScenario(scenarioId).turnLimit) {
|
||||
const r = nextState(s, fixed);
|
||||
s = r.state;
|
||||
path.push(fixed);
|
||||
}
|
||||
if (s.outcome === "collapsed" || s.outcome === "expired") return describeRoute(base, path);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Enumerate every reachable campaign inheritance set entering each scenario and
|
||||
// confirm each is solvable. SPEC §10 reachability verification.
|
||||
export type ReachabilityResult = {
|
||||
scenarioId: string;
|
||||
inheritance: Inheritance;
|
||||
solvable: boolean;
|
||||
route: Route | null;
|
||||
};
|
||||
|
||||
export function verifyReachableInheritance(
|
||||
perScenarioNodeCap: Record<string, number> = {},
|
||||
): { ok: boolean; results: ReachabilityResult[] } {
|
||||
const results: ReachabilityResult[] = [];
|
||||
// BFS over inheritance tree. Each scenario i is entered with some inheritance;
|
||||
// after a win, branch by preserving 0 or 1 newly-unlocked trait.
|
||||
let frontier: { scenarioIndex: number; inheritance: Inheritance }[] = [{ scenarioIndex: 0, inheritance: emptyInheritance() }];
|
||||
for (let i = 0; i < SCENARIOS.length; i++) {
|
||||
const sc = SCENARIOS[i];
|
||||
const cap = perScenarioNodeCap[sc.id] ?? 400_000;
|
||||
const nextFrontier: { scenarioIndex: number; inheritance: Inheritance }[] = [];
|
||||
const seenInh = new Set<string>();
|
||||
for (const f of frontier) {
|
||||
const key = canonicalStringify(f.inheritance);
|
||||
if (seenInh.has(key)) continue;
|
||||
seenInh.add(key);
|
||||
const route = findWin(sc.id, f.inheritance, cap);
|
||||
const solvable = route !== null;
|
||||
results.push({ scenarioId: sc.id, inheritance: f.inheritance, solvable, route });
|
||||
if (i < SCENARIOS.length - 1 && solvable) {
|
||||
const unlocks = route!.unlocks;
|
||||
// decline
|
||||
nextFrontier.push({ scenarioIndex: i + 1, inheritance: f.inheritance });
|
||||
// preserve each newly unlocked trait
|
||||
for (const lin of ["producer", "grazer"] as LineageId[]) {
|
||||
for (const p of unlocks[lin]) {
|
||||
nextFrontier.push({ scenarioIndex: i + 1, inheritance: withPreservedTrait(f.inheritance, { lineage: lin, pressure: p }) });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
frontier = nextFrontier;
|
||||
if (results.some((r) => !r.solvable)) break;
|
||||
}
|
||||
return { ok: results.every((r) => r.solvable), results };
|
||||
}
|
||||
|
||||
export function routeProperties(routes: Route[]): {
|
||||
anyOwnershipChange: boolean;
|
||||
anyExploitsAdaptation: boolean;
|
||||
anyAvoidsAdaptation: boolean;
|
||||
} {
|
||||
return {
|
||||
anyOwnershipChange: routes.some((r) => r.ownershipChanged),
|
||||
anyExploitsAdaptation: routes.some((r) => r.maxPressure >= 3),
|
||||
anyAvoidsAdaptation: routes.some((r) => r.maxPressure < 3),
|
||||
};
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
// Domain types — serializable plain data. No rendering, time, or UI state here.
|
||||
|
||||
export type LoopId = "A" | "B" | "C";
|
||||
export type Direction = "cw" | "ccw";
|
||||
export type LineageId = "producer" | "grazer";
|
||||
export type PressureId = "heat" | "hunger" | "toxin" | "immunity";
|
||||
export type Mode = "campaign" | "standalone";
|
||||
export type Outcome = "playing" | "won" | "collapsed" | "expired";
|
||||
|
||||
// A movable chamber. Six capped (0..6) integer fields. Rotates with its loop.
|
||||
export type Chamber = {
|
||||
nutrient: number;
|
||||
heat: number;
|
||||
toxin: number;
|
||||
producer: number;
|
||||
grazer: number;
|
||||
phage: number;
|
||||
};
|
||||
|
||||
export type Lineage = {
|
||||
pressure: Record<PressureId, number>; // 0..3
|
||||
unlocked: Record<PressureId, boolean>;
|
||||
};
|
||||
|
||||
export type RotationAction = {
|
||||
loop: LoopId;
|
||||
direction: Direction;
|
||||
};
|
||||
|
||||
// Canonical game state. Everything transient (hover, focus, animation, clocks)
|
||||
// is excluded — equality is deep equality after stable-key serialization.
|
||||
export type GameState = {
|
||||
schemaVersion: 1;
|
||||
mode: Mode;
|
||||
scenarioId: string;
|
||||
turn: number;
|
||||
loops: Record<LoopId, { direction: Direction }>;
|
||||
sharedOwner: Record<string, LoopId>;
|
||||
chambers: Chamber[];
|
||||
lineage: Record<LineageId, Lineage>;
|
||||
inheritedAtStart: Record<LineageId, PressureId[]>;
|
||||
consecutiveObjectiveTurns: number;
|
||||
environmentActive: Record<PressureId, boolean>;
|
||||
outcome: Outcome;
|
||||
actionLog: RotationAction[];
|
||||
};
|
||||
|
||||
// Deterministic, phase-ordered event attribution. Derived from prior state +
|
||||
// action; never part of canonical equality. The UI renders a subset; tests
|
||||
// assert on structure/counts, never on the production algorithm.
|
||||
export type EventPhase =
|
||||
| "rotate"
|
||||
| "flow"
|
||||
| "growth"
|
||||
| "interactions"
|
||||
| "migration"
|
||||
| "evolution"
|
||||
| "fixtures"
|
||||
| "outcome";
|
||||
|
||||
export type GameEvent = {
|
||||
phase: EventPhase;
|
||||
kind: string; // machine-readable tag
|
||||
text: string; // human-readable, scan-friendly
|
||||
slot?: number;
|
||||
lineage?: LineageId | "phage";
|
||||
pressure?: PressureId;
|
||||
amount?: number;
|
||||
};
|
||||
|
||||
export type TransitionResult = {
|
||||
state: GameState;
|
||||
events: GameEvent[];
|
||||
rejected: boolean; // true when action was applied to a terminal state
|
||||
};
|
||||
@@ -1,513 +0,0 @@
|
||||
// Adaptive Loop — presentation controller. Holds a Session, renders views, and
|
||||
// routes every committed action through the pure domain transition (preview calls
|
||||
// the same nextState on cloned state, so preview == commit). Public controls only;
|
||||
// no domain state or localStorage is injected to fake gameplay.
|
||||
|
||||
import { ALL_ACTIONS, LINEAGE_IDS, LOOP_IDS, PRESSURE_IDS, PRESSURES, FIXTURE_META, SPECIES_NAMES, type FixtureKind } from "./domain/constants";
|
||||
import { nextState, outletOf } from "./domain/pipeline";
|
||||
import { cloneState } from "./domain/serialize";
|
||||
import { fixturesFor, newlyUnlockedTraits } from "./domain/scenario";
|
||||
import { SCENARIOS, getScenario } from "./content/scenarios";
|
||||
import { totalProducer, totalGrazer, totalPhage, totalToxin } from "./domain/derived";
|
||||
import { MemoryStorage, save, load, clear, type StorageAdapter } from "./persistence/save";
|
||||
import { advanceAfterWin, eligiblePreservations, fromEnvelope, retry, startCampaign, startStandalone, toEnvelope } from "./session";
|
||||
import { chamberXY, isShared, LOOP_COLORS, loopPoints, loopsOf, VIEWBOX } from "./presentation/geometry";
|
||||
import type { Chamber, GameEvent, GameState, LineageId, LoopId, Outcome, PressureId, RotationAction, TransitionResult } from "./domain/types";
|
||||
|
||||
const STORAGE: StorageAdapter = typeof localStorage !== "undefined" ? localStorage : new MemoryStorage();
|
||||
|
||||
type View = "title" | "standalone-select" | "game" | "trait-choice" | "victory" | "malformed";
|
||||
|
||||
type App = {
|
||||
view: View;
|
||||
session: ReturnType<typeof startCampaign> | null;
|
||||
selected: RotationAction | null;
|
||||
preview: TransitionResult | null;
|
||||
pendingChoiceSession: ReturnType<typeof startCampaign> | null; // session at moment of win, before advance
|
||||
};
|
||||
|
||||
let app: App = { view: "title", session: null, selected: null, preview: null, pendingChoiceSession: null };
|
||||
|
||||
const appEl = (): HTMLElement => document.getElementById("app")!;
|
||||
|
||||
// ── helpers ──────────────────────────────────────────────────────────────────
|
||||
function announce(text: string): void {
|
||||
const el = document.querySelector('[data-region="live"]');
|
||||
if (!el) return;
|
||||
el.textContent = "";
|
||||
// re-post so assistive tech re-announces
|
||||
window.setTimeout(() => { el.textContent = text; }, 30);
|
||||
}
|
||||
|
||||
function predictLabel(result: TransitionResult): string {
|
||||
const o = result.state.outcome;
|
||||
if (o === "won") return "Predicted: WIN";
|
||||
if (o === "collapsed") return "Predicted: ecosystem collapse";
|
||||
if (o === "expired") return "Predicted: turn limit reached";
|
||||
return `Predicted turn ${result.state.turn}`;
|
||||
}
|
||||
|
||||
function computePreview(state: GameState, action: RotationAction): TransitionResult {
|
||||
return nextState(cloneState(state), action);
|
||||
}
|
||||
|
||||
// ── rendering: title ──────────────────────────────────────────────────────────
|
||||
function renderTitle(): void {
|
||||
const hasSave = load(STORAGE) !== null;
|
||||
appEl().innerHTML = `
|
||||
<header class="topbar"><h1>Adaptive Loop</h1>
|
||||
<details class="legend"><summary aria-label="How to play and legend">How to play</summary>${legendHtml()}</details>
|
||||
</header>
|
||||
<main id="main" class="menu">
|
||||
<p class="lede">A calm deterministic strategy puzzle in a microfluidic culture dish. Rotate overlapping loops to move chambers and redirect flow; provoke adaptations, then exploit their costs.</p>
|
||||
<div class="menu-buttons">
|
||||
${hasSave ? `<button id="continue-btn" class="primary">Continue</button>` : `<button id="continue-btn" disabled title="No saved run">Continue</button>`}
|
||||
<button id="new-campaign-btn" class="primary">New Campaign</button>
|
||||
<button id="standalone-btn">Replay Standalone</button>
|
||||
</div>
|
||||
<section class="legend-static" aria-label="Legend">${legendHtml()}</section>
|
||||
</main>
|
||||
<footer data-region="live" aria-live="polite" aria-atomic="true" class="visually-hidden"></footer>`;
|
||||
document.getElementById("continue-btn")?.addEventListener("click", () => {
|
||||
const env = load(STORAGE);
|
||||
if (!env) return;
|
||||
app.session = fromEnvelope(env);
|
||||
app.view = "game";
|
||||
app.selected = null;
|
||||
app.preview = null;
|
||||
render();
|
||||
});
|
||||
document.getElementById("new-campaign-btn")?.addEventListener("click", () => {
|
||||
if (load(STORAGE) && !confirm("Start a new campaign? Current progress will be lost.")) return;
|
||||
clear(STORAGE);
|
||||
app.session = startCampaign();
|
||||
app.view = "game";
|
||||
app.selected = null;
|
||||
app.preview = null;
|
||||
saveCurrent();
|
||||
render();
|
||||
});
|
||||
document.getElementById("standalone-btn")?.addEventListener("click", () => { app.view = "standalone-select"; render(); });
|
||||
}
|
||||
|
||||
function legendHtml(): string {
|
||||
const species = `<p><strong>Species</strong> (shape + color + label):
|
||||
<span class="sp producer">● P ${SPECIES_NAMES.producer}</span> eats nutrient;
|
||||
<span class="sp grazer">■ G ${SPECIES_NAMES.grazer}</span> eats producer;
|
||||
<span class="sp phage">▲ H ${SPECIES_NAMES.phage}</span> eats grazer.</p>`;
|
||||
const pressures = `<p><strong>Pressures</strong>: ${PRESSURE_IDS.map((p) => `<span style="color:${PRESSURES[p].color}">${PRESSURES[p].glyph} ${PRESSURES[p].label} → ${PRESSURES[p].traitName}</span>`).join(" ")}</p>`;
|
||||
const fixtures = `<p><strong>Fixtures</strong>: ${(Object.keys(FIXTURE_META) as FixtureKind[]).map((k) => `<span>${FIXTURE_META[k].glyph} ${FIXTURE_META[k].label}</span>`).join(" ")}</p>`;
|
||||
const how = `<p><strong>How to play</strong>: Select a loop rotation (focus/hover/tap) to preview exactly one turn, then press Commit. Each rotation moves chamber payloads and reclaims that loop's shared chambers, redirecting nutrient/toxin flow. Win each scenario's objective before the turn limit; if producers + grazers all die, the ecosystem collapses.</p>`;
|
||||
return `${how}${species}${pressures}${fixtures}`;
|
||||
}
|
||||
|
||||
// ── rendering: standalone select ──────────────────────────────────────────────
|
||||
function renderStandaloneSelect(): void {
|
||||
// Standalone can replay any scenario with clean baseline.
|
||||
appEl().innerHTML = `
|
||||
<header class="topbar"><h1>Replay Standalone</h1>
|
||||
<button id="menu-btn" class="link">← Menu</button></header>
|
||||
<main id="main" class="menu">
|
||||
<ul class="scenario-list">${SCENARIOS.map((s) => `<li><button data-scenario="${s.id}" class="scenario-pick"><strong>${s.index}. ${s.name}</strong> <span class="muted">(${s.subtitle})</span><br><span class="muted">${s.winDescription}</span></button></li>`).join("")}</ul>
|
||||
</main>
|
||||
<footer data-region="live" aria-live="polite" aria-atomic="true" class="visually-hidden"></footer>`;
|
||||
document.getElementById("menu-btn")?.addEventListener("click", () => { app.view = "title"; render(); });
|
||||
document.querySelectorAll<HTMLElement>("[data-scenario]").forEach((b) => b.addEventListener("click", () => {
|
||||
app.session = startStandalone(b.dataset.scenario!);
|
||||
app.view = "game";
|
||||
app.selected = null;
|
||||
app.preview = null;
|
||||
render();
|
||||
}));
|
||||
}
|
||||
|
||||
// ── rendering: game ───────────────────────────────────────────────────────────
|
||||
function renderGame(): void {
|
||||
const s = app.session!;
|
||||
const sc = getScenario(s.scenarioId);
|
||||
appEl().innerHTML = `
|
||||
<header class="topbar">
|
||||
<h1>${sc.name} <span class="muted">— ${sc.subtitle}</span></h1>
|
||||
<div class="topbar-actions">
|
||||
<details class="legend"><summary aria-label="Legend">Legend</summary>${legendHtml()}</details>
|
||||
<button id="menu-btn" class="link">Menu</button>
|
||||
<button id="save-quit-btn">Save & Quit</button>
|
||||
</div>
|
||||
</header>
|
||||
<main id="main" class="layout">
|
||||
<aside class="rail rail-left" aria-label="Scenario and campaign">
|
||||
<section data-region="objective" class="panel"></section>
|
||||
<section data-region="pressures" class="panel" aria-label="Pressures and traits"></section>
|
||||
</aside>
|
||||
<section class="board-wrap" aria-label="Culture board">
|
||||
<svg id="board" viewBox="${VIEWBOX}" role="img" aria-label="Three interlocking hexagonal rings of culture chambers"></svg>
|
||||
</section>
|
||||
<aside class="rail rail-right" aria-label="Controls and events">
|
||||
<section class="panel controls" aria-label="Rotation controls"><div id="controls"></div></section>
|
||||
<section class="panel"><h2>Tick events</h2><div data-region="events" role="log" aria-label="Latest turn events" class="events"></div></section>
|
||||
</aside>
|
||||
</main>
|
||||
<footer data-region="live" aria-live="polite" aria-atomic="true" class="status"></footer>`;
|
||||
|
||||
document.getElementById("menu-btn")?.addEventListener("click", () => { saveCurrent(); app.view = "title"; render(); });
|
||||
document.getElementById("save-quit-btn")?.addEventListener("click", () => { saveCurrent(); app.view = "title"; announce("Saved."); render(); });
|
||||
|
||||
drawBoard();
|
||||
renderObjective();
|
||||
renderPressures(s.state);
|
||||
renderControls();
|
||||
renderEvents(lastEvents);
|
||||
refreshPreview();
|
||||
}
|
||||
|
||||
|
||||
let lastEvents: GameEvent[] = [];
|
||||
|
||||
function renderEvents(events: GameEvent[]): void {
|
||||
const el = document.querySelector('[data-region="events"]');
|
||||
if (!el) return;
|
||||
if (events.length === 0) { el.innerHTML = `<p class="muted">Select a rotation to preview the tick.</p>`; return; }
|
||||
el.innerHTML = events.map((e) => `<p class="ev ev-${e.phase}"><span class="ev-kind">${e.kind}</span> ${escapeHtml(e.text)}</p>`).join("");
|
||||
}
|
||||
|
||||
function escapeHtml(s: string): string {
|
||||
return s.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ } as Record<string, string>)[c]);
|
||||
}
|
||||
|
||||
function renderObjective(): void {
|
||||
const el = document.querySelector('[data-region="objective"]');
|
||||
if (!el || !app.session) return;
|
||||
const s = app.session;
|
||||
const sc = getScenario(s.scenarioId);
|
||||
el.innerHTML = `
|
||||
<h2>${sc.name} <span class="muted">(${sc.subtitle})</span></h2>
|
||||
<p class="objective-text">${sc.winDescription}</p>
|
||||
<p class="stat">Turn <strong>${s.state.turn}</strong> / ${sc.turnLimit}${terminalNote(s.state.outcome)}</p>
|
||||
<p class="stat">Totals — P:${totalProducer(s.state)} G:${totalGrazer(s.state)} H:${totalPhage(s.state)} T:${totalToxin(s.state)}</p>
|
||||
<p class="muted small">Mode: ${s.mode}. ${s.mode === "campaign" ? `Unlocked: ${s.unlockedScenarios.length}/${SCENARIOS.length}.` : "Standalone (clean baseline)."}</p>`;
|
||||
}
|
||||
|
||||
function terminalNote(o: Outcome): string {
|
||||
if (o === "won") return ` — <strong class="ok">WON</strong>`;
|
||||
if (o === "collapsed") return ` — <strong class="bad">COLLAPSED</strong>`;
|
||||
if (o === "expired") return ` — <strong class="bad">EXPIRED</strong>`;
|
||||
return "";
|
||||
}
|
||||
|
||||
function renderPressures(state: GameState): void {
|
||||
const el = document.querySelector('[data-region="pressures"]');
|
||||
if (!el) return;
|
||||
const rows = LINEAGE_IDS.map((lin) => {
|
||||
const cells = PRESSURE_IDS.map((p) => {
|
||||
const meta = PRESSURES[p];
|
||||
const val = state.lineage[lin].pressure[p];
|
||||
const unlocked = state.lineage[lin].unlocked[p];
|
||||
const env = state.environmentActive[p];
|
||||
return `<span class="pcell ${unlocked ? "adapted" : ""}" style="--pc:${meta.color}" title="${meta.label} ${val}/3${unlocked ? " (unlocked)" : ""}${env ? " · response active" : ""}">
|
||||
<span class="pglyph">${meta.glyph}</span><span class="pval">${val}</span>${unlocked ? '<span class="tick">✓</span>' : ""}</span>`;
|
||||
}).join("");
|
||||
return `<div class="prow"><span class="pline">${lin === "producer" ? SPECIES_NAMES.producer : SPECIES_NAMES.grazer}</span><span class="pcells">${cells}</span></div>`;
|
||||
}).join("");
|
||||
el.innerHTML = `<h2>Pressures & traits</h2>${rows}<p class="muted small">Track 0–3; at 3 a trait unlocks next turn and a global response activates. ✓ = adapted.</p>`;
|
||||
}
|
||||
|
||||
function renderControls(): void {
|
||||
buildControls();
|
||||
updateControlStates();
|
||||
}
|
||||
|
||||
function buildControls(): void {
|
||||
const el = document.getElementById("controls");
|
||||
if (!el || !app.session) return;
|
||||
const s = app.session;
|
||||
const terminal = s.state.outcome !== "playing";
|
||||
const buttons = ALL_ACTIONS.map((a) => {
|
||||
const preview = computePreview(s.state, a);
|
||||
return `<button class="rotate-btn" data-loop="${a.loop}" data-dir="${a.direction}" aria-label="Rotate loop ${a.loop} ${a.direction === "cw" ? "clockwise" : "counter-clockwise"}. ${predictLabel(preview)}" ${terminal ? "disabled" : ""}>
|
||||
<span class="loop-tag" style="color:${LOOP_COLORS[a.loop]}">${a.loop}</span> ${a.direction === "cw" ? "↻" : "↺"}
|
||||
</button>`;
|
||||
}).join("");
|
||||
el.innerHTML = `
|
||||
<div class="rotate-grid">${buttons}</div>
|
||||
<div class="commit-row">
|
||||
<button id="commit-btn" class="primary">Commit</button>
|
||||
<button id="cancel-btn">Cancel</button>
|
||||
</div>
|
||||
<div id="terminal-actions">${terminal ? terminalActionsHtml(s.state.outcome) : ""}</div>`;
|
||||
// rotation interactions: select + preview only (commit is a separate control)
|
||||
document.querySelectorAll<HTMLElement>(".rotate-btn").forEach((b) => {
|
||||
const action = { loop: b.dataset.loop as LoopId, direction: b.dataset.dir as "cw" | "ccw" };
|
||||
b.addEventListener("click", () => selectAction(action));
|
||||
b.addEventListener("focus", () => selectAction(action));
|
||||
b.addEventListener("mouseenter", () => selectAction(action));
|
||||
});
|
||||
document.getElementById("commit-btn")?.addEventListener("click", commit);
|
||||
document.getElementById("cancel-btn")?.addEventListener("click", cancelPreview);
|
||||
wireTerminalActions();
|
||||
}
|
||||
|
||||
// Toggle selection styling + commit/cancel enabled state IN PLACE (no DOM rebuild),
|
||||
// so hovering between controls never detaches the commit button mid-interaction.
|
||||
function updateControlStates(): void {
|
||||
if (!app.session) return;
|
||||
const terminal = app.session.state.outcome !== "playing";
|
||||
document.querySelectorAll<HTMLElement>(".rotate-btn").forEach((b) => {
|
||||
const match = app.selected && b.dataset.loop === app.selected.loop && b.dataset.dir === app.selected.direction;
|
||||
b.classList.toggle("selected", !!match);
|
||||
});
|
||||
const commit = document.getElementById("commit-btn") as HTMLButtonElement | null;
|
||||
const cancel = document.getElementById("cancel-btn") as HTMLButtonElement | null;
|
||||
if (commit) commit.disabled = !app.selected || terminal;
|
||||
if (cancel) cancel.disabled = !app.selected;
|
||||
const termEl = document.getElementById("terminal-actions");
|
||||
if (termEl) {
|
||||
const want = terminal ? terminalActionsHtml(app.session.state.outcome) : "";
|
||||
if (termEl.innerHTML !== want) { termEl.innerHTML = want; wireTerminalActions(); }
|
||||
}
|
||||
}
|
||||
|
||||
function terminalActionsHtml(o: Outcome): string {
|
||||
if (o === "won") {
|
||||
if (app.session!.mode === "campaign") return `<p class="ok">Scenario complete!</p><button id="continue-win-btn" class="primary">Choose trait →</button>`;
|
||||
return `<p class="ok">Scenario complete!</p><button id="continue-win-btn" class="primary">Continue</button>`;
|
||||
}
|
||||
if (o === "collapsed") return `<p class="bad">The ecosystem collapsed.</p><button id="retry-btn" class="primary">Retry</button>`;
|
||||
if (o === "expired") return `<p class="bad">Turn limit reached.</p><button id="retry-btn" class="primary">Retry</button>`;
|
||||
return "";
|
||||
}
|
||||
|
||||
function wireTerminalActions(): void {
|
||||
document.getElementById("retry-btn")?.addEventListener("click", () => {
|
||||
if (!app.session) return;
|
||||
app.session = retry(app.session);
|
||||
app.selected = null;
|
||||
app.preview = null;
|
||||
lastEvents = [];
|
||||
render();
|
||||
announce("Retried scenario.");
|
||||
});
|
||||
document.getElementById("continue-win-btn")?.addEventListener("click", onWinContinue);
|
||||
}
|
||||
|
||||
function onWinContinue(): void {
|
||||
if (!app.session) return;
|
||||
if (app.session.mode === "standalone") {
|
||||
app.view = "title";
|
||||
render();
|
||||
return;
|
||||
}
|
||||
const eligible = eligiblePreservations(app.session);
|
||||
if (eligible.length === 0) {
|
||||
finalizeCampaignAdvance(null);
|
||||
} else {
|
||||
app.pendingChoiceSession = app.session;
|
||||
app.view = "trait-choice";
|
||||
render();
|
||||
}
|
||||
}
|
||||
|
||||
function finalizeCampaignAdvance(choice: { lineage: LineageId; pressure: PressureId } | null): void {
|
||||
if (!app.session) return;
|
||||
const advanced = advanceAfterWin(app.session, choice);
|
||||
if (advanced === null) {
|
||||
app.view = "victory";
|
||||
app.session = null;
|
||||
clear(STORAGE);
|
||||
render();
|
||||
announce("Campaign victory!");
|
||||
return;
|
||||
}
|
||||
app.session = advanced;
|
||||
app.view = "game";
|
||||
app.selected = null;
|
||||
app.preview = null;
|
||||
lastEvents = [];
|
||||
saveCurrent();
|
||||
render();
|
||||
}
|
||||
|
||||
function renderTraitChoice(): void {
|
||||
const base = app.pendingChoiceSession!;
|
||||
const unlocked = newlyUnlockedTraits(base.state);
|
||||
const options: { lineage: LineageId; pressure: PressureId }[] = [];
|
||||
for (const lin of LINEAGE_IDS) for (const p of unlocked[lin]) options.push({ lineage: lin, pressure: p });
|
||||
appEl().innerHTML = `
|
||||
<header class="topbar"><h1>Preserve a trait?</h1></header>
|
||||
<main id="main" class="menu">
|
||||
<p class="lede">A trait unlocked this scenario. Preserve one to carry its benefit — and its cost — into the next scenario.</p>
|
||||
<div class="menu-buttons">
|
||||
${options.map((o, i) => `<button data-trait="${i}" class="primary">Preserve ${SPECIES_NAMES[o.lineage]} ${PRESSURES[o.pressure].traitName} (${PRESSURES[o.pressure].label})</button>`).join("")}
|
||||
<button id="decline-trait-btn">Decline</button>
|
||||
</div>
|
||||
</main>
|
||||
<footer data-region="live" aria-live="polite" aria-atomic="true" class="visually-hidden"></footer>`;
|
||||
document.querySelectorAll<HTMLElement>("[data-trait]").forEach((b) => b.addEventListener("click", () => finalizeCampaignAdvance(options[Number(b.dataset.trait)])));
|
||||
document.getElementById("decline-trait-btn")?.addEventListener("click", () => finalizeCampaignAdvance(null));
|
||||
}
|
||||
|
||||
function renderVictory(): void {
|
||||
appEl().innerHTML = `
|
||||
<header class="topbar"><h1>Campaign Complete</h1></header>
|
||||
<main id="main" class="menu">
|
||||
<p class="lede">You held the culture stable across all five scenarios. The Adaptive Loop is closed.</p>
|
||||
<div class="menu-buttons"><button id="menu-btn" class="primary">Return to title</button></div>
|
||||
</main>
|
||||
<footer data-region="live" aria-live="polite" aria-atomic="true" class="visually-hidden"></footer>`;
|
||||
document.getElementById("menu-btn")?.addEventListener("click", () => { app.view = "title"; render(); });
|
||||
}
|
||||
|
||||
// ── selection / preview / commit ──────────────────────────────────────────────
|
||||
function selectAction(action: RotationAction): void {
|
||||
if (!app.session || app.session.state.outcome !== "playing") return;
|
||||
if (app.selected && app.selected.loop === action.loop && app.selected.direction === action.direction) return; // no-op reselect
|
||||
app.selected = action;
|
||||
app.preview = computePreview(app.session.state, action);
|
||||
refreshPreview();
|
||||
updateControlStates();
|
||||
}
|
||||
|
||||
function cancelPreview(): void {
|
||||
app.selected = null;
|
||||
app.preview = null;
|
||||
refreshPreview();
|
||||
updateControlStates();
|
||||
}
|
||||
|
||||
function refreshPreview(): void {
|
||||
drawBoard();
|
||||
if (app.preview) {
|
||||
renderPressures(app.preview.state); // pressure increments visible during preview (Pass-1 fix)
|
||||
renderEvents(keyEvents(app.preview.events));
|
||||
} else if (app.session) {
|
||||
renderPressures(app.session.state);
|
||||
renderEvents(lastEvents);
|
||||
}
|
||||
}
|
||||
|
||||
function keyEvents(events: GameEvent[]): GameEvent[] {
|
||||
// A concise, scan-friendly subset that still surfaces movement, flow, overflow,
|
||||
// pressure increments, adaptations (benefit/cost/spillover), and the outcome.
|
||||
const keep = new Set([
|
||||
"rotate", "nutrient-overflow", "toxin-overflow", "producer-growth", "growth-suppressed",
|
||||
"grazer-feed", "grazer-denied", "phage-feed", "phage-starve", "cloak-cost", "migrate",
|
||||
"trait-unlock", "env-response", "pressure-up", "heat-loss", "heat-prevented", "heat-spillover",
|
||||
"hunger-loss", "hunger-prevented", "toxin-loss", "toxin-cost", "toxin-spillover",
|
||||
"immune-select", "immune-retarget", "immune-damage", "fixture-overflow", "outcome",
|
||||
]);
|
||||
return events.filter((e) => keep.has(e.kind));
|
||||
}
|
||||
|
||||
function commit(): void {
|
||||
if (!app.session || !app.selected) return;
|
||||
const before = app.session;
|
||||
if (before.state.outcome !== "playing") return; // rejected
|
||||
// Single pure transition: events + canonical state in one call (preview == commit).
|
||||
const result = nextState(before.state, app.selected);
|
||||
app.session = { ...before, state: result.state };
|
||||
app.selected = null;
|
||||
app.preview = null;
|
||||
lastEvents = keyEvents(result.events);
|
||||
saveCurrent();
|
||||
render();
|
||||
const o = result.state.outcome;
|
||||
announce(o === "playing" ? `Turn ${result.state.turn}.` : `Turn ${result.state.turn}: ${o}.`);
|
||||
}
|
||||
|
||||
function saveCurrent(): void {
|
||||
if (app.session) save(STORAGE, toEnvelope(app.session, Date.now()));
|
||||
}
|
||||
|
||||
// ── board SVG ─────────────────────────────────────────────────────────────────
|
||||
function drawBoard(): void {
|
||||
const svg = document.getElementById("board");
|
||||
if (!svg || !app.session) return;
|
||||
const state = app.session.state;
|
||||
const previewState = app.preview?.state ?? null;
|
||||
const fx = fixturesFor(state.scenarioId);
|
||||
// build parts
|
||||
const rings = LOOP_IDS.map((L) =>
|
||||
`<polygon class="ring ring-${L}" points="${loopPoints(L)}" fill="none" stroke="${LOOP_COLORS[L]}" stroke-width="6" stroke-linejoin="round" />`).join("");
|
||||
// flow arrows along owner edges — during preview, reflect the post-rotation flow
|
||||
const arrows = flowArrows(previewState ?? state);
|
||||
const nodes = state.chambers.map((c, slot) => chamberSvg(slot, c, fx[slot], previewState)).join("");
|
||||
// selection highlight ring outline
|
||||
svg.innerHTML = `${rings}${arrows}${nodes}`;
|
||||
}
|
||||
|
||||
function flowArrows(state: GameState): string {
|
||||
const drawn = new Set<string>();
|
||||
const parts: string[] = [];
|
||||
for (let slot = 0; slot < 12; slot++) {
|
||||
const out = outletOf(slot, state);
|
||||
const key = `${slot}-${out}`;
|
||||
if (drawn.has(key)) continue;
|
||||
drawn.add(key);
|
||||
const [x1, y1] = chamberXY(slot);
|
||||
const [x2, y2] = chamberXY(out);
|
||||
const mx = (x1 + x2) / 2;
|
||||
const my = (y1 + y2) / 2;
|
||||
parts.push(`<circle class="flow-dot" cx="${mx.toFixed(1)}" cy="${my.toFixed(1)}" r="3" />`);
|
||||
}
|
||||
return parts.join("");
|
||||
}
|
||||
|
||||
function chamberSvg(slot: number, c: Chamber, fixtures: FixtureKind[], preview: GameState | null): string {
|
||||
const [x, y] = chamberXY(slot);
|
||||
const fixtureMarks = fixtures.map((k) => `<text class="fx-glyph" y="-30">${FIXTURE_META[k].glyph}</text>`).join("");
|
||||
const pops = (["producer", "grazer", "phage"] as const).map((sp) =>
|
||||
c[sp] > 0 ? `<tspan class="pop pop-${sp}" dx="${sp === "producer" ? 0 : 4}">${popGlyph(sp)}${c[sp]}</tspan>` : "").join("");
|
||||
const delta = preview ? populationDelta(c, preview.chambers[slot]) : "";
|
||||
const res = `<text class="res" y="8">N${c.nutrient}${c.heat > 0 ? ` 🔥${c.heat}` : ""}${c.toxin > 0 ? ` ⚗${c.toxin}` : ""}</text>`;
|
||||
const label = `<text class="slot-label" y="26">${slot}${isShared(slot) ? ` ${loopsOf(slot).join("")}` : ""}</text>`;
|
||||
return `<g class="chamber" transform="translate(${x},${y})">
|
||||
<circle r="24" class="chamber-bg" />
|
||||
${fixtureMarks}
|
||||
<text class="pops" y="-2">${pops}</text>
|
||||
${res}${label}${delta}
|
||||
</g>`;
|
||||
}
|
||||
|
||||
function popGlyph(sp: "producer" | "grazer" | "phage"): string {
|
||||
return sp === "producer" ? "●" : sp === "grazer" ? "■" : "▲";
|
||||
}
|
||||
|
||||
function populationDelta(now: Chamber, next: Chamber): string {
|
||||
const diffs: string[] = [];
|
||||
(["producer", "grazer", "phage"] as const).forEach((sp) => {
|
||||
const d = next[sp] - now[sp];
|
||||
if (d !== 0) diffs.push(`${popGlyph(sp)}${d > 0 ? "+" : ""}${d}`);
|
||||
});
|
||||
["nutrient", "toxin"].forEach((f) => {
|
||||
const d = (next as unknown as Record<string, number>)[f] - (now as unknown as Record<string, number>)[f];
|
||||
if (d !== 0) diffs.push(`${f === "nutrient" ? "N" : "T"}${d > 0 ? "+" : ""}${d}`);
|
||||
});
|
||||
if (diffs.length === 0) return "";
|
||||
return `<text class="delta" y="-15">${diffs.join(" ")}</text>`;
|
||||
}
|
||||
|
||||
// ── router ────────────────────────────────────────────────────────────────────
|
||||
function render(): void {
|
||||
switch (app.view) {
|
||||
case "title": renderTitle(); break;
|
||||
case "standalone-select": renderStandaloneSelect(); break;
|
||||
case "game": renderGame(); break;
|
||||
case "trait-choice": renderTraitChoice(); break;
|
||||
case "victory": renderVictory(); break;
|
||||
default: renderTitle();
|
||||
}
|
||||
}
|
||||
|
||||
// global keyboard: Escape cancels preview
|
||||
window.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Escape" && app.view === "game" && app.selected) { cancelPreview(); }
|
||||
});
|
||||
|
||||
// boot
|
||||
function boot(): void {
|
||||
const env = load(STORAGE);
|
||||
app.view = "title";
|
||||
app.session = env ? fromEnvelope(env) : null;
|
||||
render();
|
||||
}
|
||||
|
||||
boot();
|
||||
@@ -1,95 +0,0 @@
|
||||
// Versioned save/load + replay. The envelope holds canonical game state plus
|
||||
// campaign meta; savedAt metadata stays outside canonical comparison. A
|
||||
// StorageAdapter abstracts localStorage so tests use an in-memory implementation.
|
||||
// Malformed or unsupported saves fail safely (load returns null) so the UI can
|
||||
// offer recovery rather than crash.
|
||||
|
||||
import { buildBaselineState, type Inheritance } from "../domain/scenario";
|
||||
import { SCENARIO_BY_ID } from "../content/scenarios";
|
||||
import { nextState } from "../domain/pipeline";
|
||||
import { canonicalStringify } from "../domain/serialize";
|
||||
import type { GameState, Mode, Outcome, RotationAction } from "../domain/types";
|
||||
|
||||
const SAVE_KEY = "adaptive-loop.save.v1";
|
||||
const SCHEMA_VERSION = 1;
|
||||
|
||||
export type SaveEnvelope = {
|
||||
schemaVersion: number;
|
||||
mode: Mode;
|
||||
scenarioId: string;
|
||||
state: GameState;
|
||||
unlockedScenarios: string[];
|
||||
inheritedTraits: Inheritance;
|
||||
entrySnapshot: Inheritance;
|
||||
actionLog: RotationAction[];
|
||||
outcome: Outcome;
|
||||
savedAt: number; // metadata — excluded from canonical comparison
|
||||
};
|
||||
|
||||
export interface StorageAdapter {
|
||||
getItem(key: string): string | null;
|
||||
setItem(key: string, value: string): void;
|
||||
removeItem(key: string): void;
|
||||
}
|
||||
|
||||
export class MemoryStorage implements StorageAdapter {
|
||||
private store = new Map<string, string>();
|
||||
getItem(key: string): string | null { return this.store.has(key) ? this.store.get(key)! : null; }
|
||||
setItem(key: string, value: string): void { this.store.set(key, value); }
|
||||
removeItem(key: string): void { this.store.delete(key); }
|
||||
}
|
||||
|
||||
// Structural + value validation at the load boundary. Returns true only for a
|
||||
// well-formed, supported envelope whose referenced scenario exists.
|
||||
export function isValidEnvelope(x: unknown): x is SaveEnvelope {
|
||||
if (typeof x !== "object" || x === null) return false;
|
||||
const e = x as Record<string, unknown>;
|
||||
if (e.schemaVersion !== SCHEMA_VERSION) return false;
|
||||
if (typeof e.mode !== "string" || (e.mode !== "campaign" && e.mode !== "standalone")) return false;
|
||||
if (typeof e.scenarioId !== "string" || !(e.scenarioId in SCENARIO_BY_ID)) return false;
|
||||
if (typeof e.state !== "object" || e.state === null) return false;
|
||||
if (!Array.isArray(e.unlockedScenarios)) return false;
|
||||
for (const id of e.unlockedScenarios as unknown[]) if (typeof id !== "string" || !(id in SCENARIO_BY_ID)) return false;
|
||||
if (typeof e.savedAt !== "number") return false;
|
||||
if (!Array.isArray(e.actionLog)) return false;
|
||||
if (typeof e.outcome !== "string") return false;
|
||||
// shallow sanity on inheritance objects
|
||||
for (const f of ["inheritedTraits", "entrySnapshot"]) {
|
||||
const v = e[f] as Record<string, unknown> | undefined;
|
||||
if (typeof v !== "object" || v === null || !Array.isArray(v.producer) || !Array.isArray(v.grazer)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function save(adapter: StorageAdapter, env: SaveEnvelope): void {
|
||||
adapter.setItem(SAVE_KEY, JSON.stringify(env));
|
||||
}
|
||||
|
||||
export function load(adapter: StorageAdapter): SaveEnvelope | null {
|
||||
const raw = adapter.getItem(SAVE_KEY);
|
||||
if (raw === null) return null;
|
||||
let parsed: unknown;
|
||||
try { parsed = JSON.parse(raw); } catch { return null; }
|
||||
if (!isValidEnvelope(parsed)) return null;
|
||||
return parsed;
|
||||
}
|
||||
|
||||
export function clear(adapter: StorageAdapter): void {
|
||||
adapter.removeItem(SAVE_KEY);
|
||||
}
|
||||
|
||||
// Replaying the action log from a scenario baseline plus its entry inheritance
|
||||
// snapshot must reproduce the canonical current state. SPEC §11.
|
||||
export function replayFromBaseline(scenarioId: string, entrySnapshot: Inheritance, actionLog: RotationAction[]): GameState {
|
||||
let s = buildBaselineState(scenarioId, "campaign", entrySnapshot);
|
||||
for (const a of actionLog) s = nextState(s, a).state;
|
||||
return s;
|
||||
}
|
||||
|
||||
// Two envelopes are canonically equal ignoring savedAt (metadata).
|
||||
export function envelopesEqual(a: SaveEnvelope, b: SaveEnvelope): boolean {
|
||||
const { savedAt: _a, ...ra } = a;
|
||||
const { savedAt: _b, ...rb } = b;
|
||||
void _a; void _b;
|
||||
return canonicalStringify(ra) === canonicalStringify(rb);
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
// Board geometry: three interlocking hexagonal rings (SPEC §4 / docs/board-layout.md).
|
||||
// 12 chamber coordinates chosen so each loop's six slots form a hexagonal ring and
|
||||
// the six shared chambers coincide (rendered once at the overlap). Each loop's
|
||||
// polygon is built from its six slot coordinates in cyclic order; rings overlap
|
||||
// like chain links. Coordinates are in a 440×400 viewBox; the SVG scales to fit.
|
||||
|
||||
import { LOOP_SLOTS, SHARED_SLOTS, SLOT_LOOPS } from "../domain/constants";
|
||||
import type { LoopId } from "../domain/types";
|
||||
|
||||
// [x, y] per slot. Uniques sit on the outer points; shared pairs sit at the
|
||||
// three ring overlaps (A∩B right, A∩C left, B∩C bottom).
|
||||
export const CHAMBER_COORDS: ReadonlyArray<readonly [number, number]> = [
|
||||
[225, 60], // 0 (A)
|
||||
[330, 110], // 1 (A)
|
||||
[310, 165], // 2 (A∩B)
|
||||
[250, 225], // 3 (A∩B)
|
||||
[200, 225], // 4 (A∩C)
|
||||
[140, 165], // 5 (A∩C)
|
||||
[380, 230], // 6 (B)
|
||||
[345, 315], // 7 (B)
|
||||
[275, 360], // 8 (B∩C)
|
||||
[210, 335], // 9 (B∩C)
|
||||
[70, 230], // 10 (C)
|
||||
[105, 315], // 11 (C)
|
||||
];
|
||||
|
||||
export const LOOP_COLORS: Record<LoopId, string> = { A: "#5cc8ff", B: "#ffb45c", C: "#b98cff" };
|
||||
|
||||
export function chamberXY(slot: number): [number, number] {
|
||||
return [CHAMBER_COORDS[slot][0], CHAMBER_COORDS[slot][1]];
|
||||
}
|
||||
|
||||
// Polygon points string for a loop's ring outline (its six slots in cyclic order).
|
||||
export function loopPoints(loop: LoopId): string {
|
||||
return LOOP_SLOTS[loop].map((s) => chamberXY(s).join(",")).join(" ");
|
||||
}
|
||||
|
||||
export function isShared(slot: number): boolean {
|
||||
return SHARED_SLOTS.includes(slot);
|
||||
}
|
||||
|
||||
export function loopsOf(slot: number): LoopId[] {
|
||||
return SLOT_LOOPS[slot];
|
||||
}
|
||||
|
||||
// Center of the board (for objective/fixture label placement offsets).
|
||||
export const VIEWBOX = "0 0 440 400";
|
||||
@@ -1,114 +0,0 @@
|
||||
// Campaign + standalone session management. Pure functions over a Session value;
|
||||
// the UI holds the current Session and persists it via the save module. All
|
||||
// transitions route through the pure domain transition so preview == commit.
|
||||
|
||||
import { buildBaselineState, emptyInheritance, newlyUnlockedTraits, withPreservedTrait, type Inheritance } from "./domain/scenario";
|
||||
import { SCENARIOS } from "./content/scenarios";
|
||||
import { nextState } from "./domain/pipeline";
|
||||
import { cloneState } from "./domain/serialize";
|
||||
import type { GameState, LineageId, Mode, PressureId, RotationAction } from "./domain/types";
|
||||
import type { SaveEnvelope } from "./persistence/save";
|
||||
|
||||
export type Session = {
|
||||
mode: Mode;
|
||||
scenarioId: string;
|
||||
state: GameState;
|
||||
unlockedScenarios: string[]; // campaign scenarios the player may enter
|
||||
inheritedTraits: Inheritance; // traits carried into the current scenario
|
||||
entrySnapshot: Inheritance; // inheritance at scenario entry — restored on retry
|
||||
};
|
||||
|
||||
export type TraitChoice = { lineage: LineageId; pressure: PressureId } | null;
|
||||
|
||||
export function startCampaign(): Session {
|
||||
const first = SCENARIOS[0];
|
||||
return {
|
||||
mode: "campaign",
|
||||
scenarioId: first.id,
|
||||
state: buildBaselineState(first.id, "campaign", emptyInheritance()),
|
||||
unlockedScenarios: [first.id],
|
||||
inheritedTraits: emptyInheritance(),
|
||||
entrySnapshot: emptyInheritance(),
|
||||
};
|
||||
}
|
||||
|
||||
// Standalone replays a scenario with clean baseline lineages; no traits carry.
|
||||
export function startStandalone(scenarioId: string): Session {
|
||||
return {
|
||||
mode: "standalone",
|
||||
scenarioId,
|
||||
state: buildBaselineState(scenarioId, "standalone", emptyInheritance()),
|
||||
unlockedScenarios: [scenarioId],
|
||||
inheritedTraits: emptyInheritance(),
|
||||
entrySnapshot: emptyInheritance(),
|
||||
};
|
||||
}
|
||||
|
||||
export function fromEnvelope(env: SaveEnvelope): Session {
|
||||
return {
|
||||
mode: env.mode,
|
||||
scenarioId: env.scenarioId,
|
||||
state: cloneState(env.state),
|
||||
unlockedScenarios: [...env.unlockedScenarios],
|
||||
inheritedTraits: { producer: [...env.inheritedTraits.producer], grazer: [...env.inheritedTraits.grazer] },
|
||||
entrySnapshot: { producer: [...env.entrySnapshot.producer], grazer: [...env.entrySnapshot.grazer] },
|
||||
};
|
||||
}
|
||||
|
||||
export function toEnvelope(session: Session, savedAt: number): SaveEnvelope {
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
mode: session.mode,
|
||||
scenarioId: session.scenarioId,
|
||||
state: cloneState(session.state),
|
||||
unlockedScenarios: [...session.unlockedScenarios],
|
||||
inheritedTraits: { producer: [...session.inheritedTraits.producer], grazer: [...session.inheritedTraits.grazer] },
|
||||
entrySnapshot: { producer: [...session.entrySnapshot.producer], grazer: [...session.entrySnapshot.grazer] },
|
||||
actionLog: session.state.actionLog.map((a) => ({ loop: a.loop, direction: a.direction })),
|
||||
outcome: session.state.outcome,
|
||||
savedAt,
|
||||
};
|
||||
}
|
||||
|
||||
// Apply a committed rotation. Rejected actions (terminal state) return the
|
||||
// session unchanged. Preview is computed separately by the UI via nextState.
|
||||
export function commitAction(session: Session, action: RotationAction): Session {
|
||||
const result = nextState(session.state, action);
|
||||
if (result.rejected) return session;
|
||||
const state = result.state;
|
||||
return { ...session, state };
|
||||
}
|
||||
|
||||
// Retry restores the current scenario baseline with its scenario-entry inheritance.
|
||||
export function retry(session: Session): Session {
|
||||
return {
|
||||
...session,
|
||||
state: buildBaselineState(session.scenarioId, session.mode, session.entrySnapshot),
|
||||
};
|
||||
}
|
||||
|
||||
// Eligible traits the player may preserve after winning the current scenario.
|
||||
export function eligiblePreservations(session: Session): TraitChoice[] {
|
||||
const unlocked = newlyUnlockedTraits(session.state);
|
||||
const out: TraitChoice[] = [];
|
||||
for (const lin of ["producer", "grazer"] as LineageId[]) for (const p of unlocked[lin]) out.push({ lineage: lin, pressure: p });
|
||||
return out;
|
||||
}
|
||||
|
||||
// Advance after a win: preserve 0 or 1 newly-unlocked trait, unlock + enter next
|
||||
// scenario. Returns null if the won scenario was the last (campaign victory).
|
||||
export function advanceAfterWin(session: Session, choice: TraitChoice): Session | null {
|
||||
const idx = SCENARIOS.findIndex((s) => s.id === session.scenarioId);
|
||||
if (idx < 0 || idx >= SCENARIOS.length - 1) return null; // campaign victory
|
||||
const nextInherited = choice ? withPreservedTrait(session.inheritedTraits, choice) : session.inheritedTraits;
|
||||
const next = SCENARIOS[idx + 1];
|
||||
const unlocked = session.unlockedScenarios.includes(next.id) ? session.unlockedScenarios : [...session.unlockedScenarios, next.id];
|
||||
return {
|
||||
mode: "campaign",
|
||||
scenarioId: next.id,
|
||||
state: buildBaselineState(next.id, "campaign", nextInherited),
|
||||
unlockedScenarios: unlocked,
|
||||
inheritedTraits: nextInherited,
|
||||
entrySnapshot: nextInherited,
|
||||
};
|
||||
}
|
||||
@@ -1,187 +0,0 @@
|
||||
/* Adaptive Loop — dark laboratory glass aesthetic. Procedural SVG/CSS only. */
|
||||
|
||||
:root {
|
||||
--bg: #0a0e14;
|
||||
--bg-2: #11161f;
|
||||
--panel: #141b26;
|
||||
--ink: #e6edf3;
|
||||
--muted: #8b98a9;
|
||||
--accent: #5cc8ff;
|
||||
--accent-2: #b98cff;
|
||||
--ok: #7bd389;
|
||||
--bad: #ff6b6b;
|
||||
--warn: #ffb45c;
|
||||
--line: #243042;
|
||||
--producer: #7bd389;
|
||||
--grazer: #ffb45c;
|
||||
--phage: #ff8aa8;
|
||||
--radius: 10px;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
html, body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--ink);
|
||||
font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
||||
font-size: 16px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
#app { min-height: 100vh; display: flex; flex-direction: column; }
|
||||
|
||||
h1, h2 { margin: 0 0 0.3em; line-height: 1.15; }
|
||||
h1 { font-size: 1.35rem; }
|
||||
h2 { font-size: 1.05rem; }
|
||||
|
||||
.muted { color: var(--muted); }
|
||||
.small { font-size: 0.8rem; }
|
||||
.ok { color: var(--ok); }
|
||||
.bad { color: var(--bad); }
|
||||
|
||||
.skip-link {
|
||||
position: absolute; left: -9999px; top: 0; z-index: 100;
|
||||
background: var(--accent); color: #001019; padding: 0.5rem 0.8rem; border-radius: 0 0 var(--radius) 0;
|
||||
}
|
||||
.skip-link:focus { left: 0; }
|
||||
|
||||
.visually-hidden {
|
||||
position: absolute !important; width: 1px; height: 1px; padding: 0; margin: -1px;
|
||||
overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0;
|
||||
}
|
||||
|
||||
:focus-visible {
|
||||
outline: 3px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
button {
|
||||
font: inherit; color: var(--ink); background: var(--panel);
|
||||
border: 1px solid var(--line); border-radius: var(--radius);
|
||||
padding: 0.5rem 0.8rem; cursor: pointer; min-height: 40px;
|
||||
}
|
||||
button:hover:not(:disabled) { border-color: var(--accent); }
|
||||
button:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||
button.primary { background: var(--accent); color: #001019; border-color: var(--accent); font-weight: 600; }
|
||||
button.primary:hover:not(:disabled) { background: #7fd4ff; }
|
||||
button.link { background: transparent; border: none; color: var(--accent); min-height: auto; padding: 0.3rem; }
|
||||
|
||||
/* ── topbar ─────────────────────────────────────── */
|
||||
.topbar {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 0.8rem;
|
||||
padding: 0.7rem 1rem; background: var(--bg-2); border-bottom: 1px solid var(--line);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.topbar-actions { display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap; }
|
||||
details.legend { position: relative; }
|
||||
details.legend summary { cursor: pointer; padding: 0.3rem 0.6rem; border: 1px solid var(--line); border-radius: var(--radius); min-height: 40px; display: flex; align-items: center; }
|
||||
details.legend[open] summary { border-color: var(--accent); }
|
||||
details.legend .legend-body, details.legend p { max-width: 60ch; }
|
||||
|
||||
/* ── layout ─────────────────────────────────────── */
|
||||
.layout {
|
||||
flex: 1; display: grid; gap: 0.8rem; padding: 0.8rem;
|
||||
grid-template-columns: 17rem 1fr 19rem;
|
||||
align-items: start;
|
||||
}
|
||||
.rail { display: flex; flex-direction: column; gap: 0.8rem; min-width: 0; }
|
||||
.panel {
|
||||
background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius);
|
||||
padding: 0.7rem 0.8rem;
|
||||
}
|
||||
.panel h2 { color: var(--accent); }
|
||||
.objective-text { margin: 0.2em 0 0.6em; }
|
||||
.stat { margin: 0.2em 0; }
|
||||
|
||||
.board-wrap { display: flex; align-items: flex-start; justify-content: center; }
|
||||
#board { width: 100%; max-width: 520px; height: auto; }
|
||||
|
||||
/* ── board svg ──────────────────────────────────── */
|
||||
.ring { opacity: 0.9; }
|
||||
.chamber-bg { fill: #0d131c; stroke: var(--line); stroke-width: 2; }
|
||||
.chamber { transition: transform 0.2s ease; }
|
||||
.chamber text { text-anchor: middle; font-size: 11px; fill: var(--ink); }
|
||||
.pops { font-size: 12px; font-weight: 600; }
|
||||
.pop-producer { fill: var(--producer); }
|
||||
.pop-grazer { fill: var(--grazer); }
|
||||
.pop-phage { fill: var(--phage); }
|
||||
.res { fill: var(--muted); font-size: 9.5px; }
|
||||
.slot-label { fill: var(--muted); font-size: 9px; }
|
||||
.fx-glyph { fill: var(--warn); font-size: 11px; }
|
||||
.delta { fill: var(--accent); font-size: 10px; font-weight: 700; }
|
||||
.flow-dot { fill: var(--accent); opacity: 0.5; }
|
||||
|
||||
/* ── controls ───────────────────────────────────── */
|
||||
.rotate-grid {
|
||||
display: grid; grid-template-columns: repeat(3, 1fr); gap: 0.4rem;
|
||||
margin-bottom: 0.6rem;
|
||||
}
|
||||
.rotate-btn {
|
||||
display: flex; flex-direction: column; align-items: center; gap: 0.1rem;
|
||||
font-size: 1.1rem; padding: 0.6rem 0.3rem;
|
||||
}
|
||||
.rotate-btn .loop-tag { font-weight: 700; font-size: 0.8rem; }
|
||||
.rotate-btn.selected { border-color: var(--accent); background: #16202c; box-shadow: 0 0 0 2px var(--accent) inset; }
|
||||
.commit-row { display: flex; gap: 0.5rem; }
|
||||
.commit-row button { flex: 1; }
|
||||
|
||||
/* ── pressures panel ────────────────────────────── */
|
||||
.prow { display: flex; justify-content: space-between; align-items: center; gap: 0.4rem; margin: 0.2em 0; }
|
||||
.pline { font-size: 0.85rem; }
|
||||
.pcells { display: flex; gap: 0.3rem; }
|
||||
.pcell {
|
||||
display: inline-flex; align-items: center; gap: 2px; padding: 1px 5px; border-radius: 6px;
|
||||
border: 1px solid var(--line); font-size: 0.8rem; background: #0d131c;
|
||||
}
|
||||
.pcell.adapted { border-color: var(--ok); background: #0f1a14; }
|
||||
.pglyph { color: var(--pc, var(--ink)); }
|
||||
.pval { font-variant-numeric: tabular-nums; }
|
||||
.tick { color: var(--ok); }
|
||||
|
||||
/* ── events ─────────────────────────────────────── */
|
||||
.events { max-height: 240px; overflow-y: auto; font-size: 0.85rem; }
|
||||
.events .ev { margin: 0.15em 0; padding-left: 0.3em; border-left: 2px solid var(--line); }
|
||||
.ev .ev-kind { color: var(--accent); font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.03em; }
|
||||
.ev-outcome { border-left-color: var(--ok); font-weight: 600; }
|
||||
|
||||
/* ── menu screens ───────────────────────────────── */
|
||||
.menu { padding: 1.2rem; max-width: 60ch; margin: 0 auto; }
|
||||
.menu-buttons { display: flex; flex-direction: column; gap: 0.6rem; margin: 1rem 0; max-width: 24rem; }
|
||||
.lede { color: var(--ink); }
|
||||
.scenario-list { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 0.5rem; }
|
||||
.scenario-pick { text-align: left; width: 100%; }
|
||||
.legend-static p { margin: 0.4em 0; }
|
||||
.sp { white-space: nowrap; }
|
||||
.sp.producer { color: var(--producer); }
|
||||
.sp.grazer { color: var(--grazer); }
|
||||
.sp.phage { color: var(--phage); }
|
||||
|
||||
.status { padding: 0.4rem 1rem; background: var(--bg-2); border-top: 1px solid var(--line); color: var(--muted); font-size: 0.85rem; min-height: 1.6em; }
|
||||
|
||||
/* ── responsive ─────────────────────────────────── */
|
||||
@media (max-width: 920px) {
|
||||
.layout { grid-template-columns: 1fr; }
|
||||
.board-wrap { order: -1; }
|
||||
#board { max-width: 420px; }
|
||||
}
|
||||
@media (max-width: 410px) {
|
||||
.topbar { padding: 0.5rem; }
|
||||
.layout { padding: 0.4rem; gap: 0.5rem; }
|
||||
.panel { padding: 0.5rem; }
|
||||
h1 { font-size: 1.1rem; }
|
||||
.rotate-btn { font-size: 0.95rem; padding: 0.5rem 0.2rem; }
|
||||
#board { max-width: 100%; }
|
||||
}
|
||||
@media (min-resolution: 1.9dppx) {
|
||||
.pops { font-size: 13px; }
|
||||
.res, .slot-label, .delta { font-size: 10.5px; }
|
||||
button { min-height: 44px; }
|
||||
}
|
||||
|
||||
/* ── reduced motion ─────────────────────────────── */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
* { transition: none !important; animation: none !important; }
|
||||
.chamber { transition: none; }
|
||||
}
|
||||
-1023
File diff suppressed because it is too large.
Load diff
@@ -1,46 +0,0 @@
|
||||
// Test helpers: build minimal isolated states against the fixture-free TEST_SCENARIO
|
||||
// so a single pipeline phase can be exercised without cross-phase interference.
|
||||
|
||||
import { buildBaselineState } from "../src/domain/scenario";
|
||||
import { defaultSharedOwner } from "../src/domain/constants";
|
||||
import type { Chamber, GameState, LineageId, LoopId, PressureId } from "../src/domain/types";
|
||||
// (Patch still carries slot for placement; it is stripped before building chambers.)
|
||||
import { emptyLineage } from "../src/domain/serialize";
|
||||
|
||||
export type Patch = Partial<Chamber> & { slot: number };
|
||||
|
||||
export function makeState(patches: Patch[] = [], opts: {
|
||||
scenarioId?: string;
|
||||
loops?: Partial<Record<LoopId, "cw" | "ccw">>;
|
||||
sharedOwner?: Record<string, LoopId>;
|
||||
unlocked?: Partial<Record<LineageId, PressureId[]>>;
|
||||
pressure?: Partial<Record<LineageId, Partial<Record<PressureId, number>>>>;
|
||||
env?: Partial<Record<PressureId, boolean>>;
|
||||
turn?: number;
|
||||
outcome?: GameState["outcome"];
|
||||
consecutive?: number;
|
||||
} = {}): GameState {
|
||||
const base = buildBaselineState(opts.scenarioId ?? "test", "standalone");
|
||||
const chambers: Chamber[] = Array.from({ length: 12 }, () => ({ nutrient: 0, heat: 0, toxin: 0, producer: 0, grazer: 0, phage: 0 }));
|
||||
for (const p of patches) {
|
||||
const { slot: _omit, ...rest } = p;
|
||||
void _omit;
|
||||
chambers[p.slot] = { nutrient: 0, heat: 0, toxin: 0, producer: 0, grazer: 0, phage: 0, ...rest };
|
||||
}
|
||||
base.chambers = chambers;
|
||||
if (opts.loops) for (const L of ["A", "B", "C"] as LoopId[]) if (opts.loops[L]) base.loops[L].direction = opts.loops[L]!;
|
||||
if (opts.sharedOwner) base.sharedOwner = { ...defaultSharedOwner(), ...opts.sharedOwner };
|
||||
if (opts.unlocked) for (const id of ["producer", "grazer"] as LineageId[]) for (const p of opts.unlocked[id] ?? []) base.lineage[id].unlocked[p] = true;
|
||||
if (opts.pressure) for (const id of ["producer", "grazer"] as LineageId[]) for (const p of Object.keys(opts.pressure[id] ?? {}) as PressureId[]) base.lineage[id].pressure[p] = opts.pressure[id]![p]!;
|
||||
if (opts.env) base.environmentActive = { heat: false, hunger: false, toxin: false, immunity: false, ...opts.env };
|
||||
if (opts.turn !== undefined) base.turn = opts.turn;
|
||||
if (opts.outcome) base.outcome = opts.outcome;
|
||||
if (opts.consecutive !== undefined) base.consecutiveObjectiveTurns = opts.consecutive;
|
||||
return base;
|
||||
}
|
||||
|
||||
export function chamber(state: GameState, slot: number): Chamber {
|
||||
return state.chambers[slot];
|
||||
}
|
||||
|
||||
export { emptyLineage };
|
||||
@@ -1,114 +0,0 @@
|
||||
// Gate 5 — campaign and persistence. Exact save/restore, deterministic replay,
|
||||
// malformed-save recovery, campaign progression with gift-and-burden inheritance,
|
||||
// and retry restoring the scenario-entry snapshot.
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { MemoryStorage, save, load, isValidEnvelope, replayFromBaseline, type SaveEnvelope } from "../src/persistence/save";
|
||||
import { startCampaign, startStandalone, commitAction, retry, advanceAfterWin, toEnvelope, fromEnvelope, eligiblePreservations } from "../src/session";
|
||||
import { nextState } from "../src/domain/pipeline";
|
||||
import { buildBaselineState } from "../src/domain/scenario";
|
||||
import { canonicalEqual } from "../src/domain/serialize";
|
||||
import { SCENARIOS } from "../src/content/scenarios";
|
||||
import fixture from "./fixtures/solver-results.json";
|
||||
import type { RotationAction } from "../src/domain/types";
|
||||
|
||||
const A = (loop: "A" | "B" | "C", direction: "cw" | "ccw"): RotationAction => ({ loop, direction });
|
||||
|
||||
describe("persistence — exact save/restore + replay", () => {
|
||||
it("save then load restores canonical state and the exact next transition", () => {
|
||||
const store = new MemoryStorage();
|
||||
let session = startCampaign();
|
||||
session = commitAction(session, A("A", "cw"));
|
||||
session = commitAction(session, A("B", "ccw"));
|
||||
save(store, toEnvelope(session, Date.now()));
|
||||
const restored = load(store);
|
||||
expect(restored).not.toBeNull();
|
||||
const again = fromEnvelope(restored!);
|
||||
expect(canonicalEqual(again.state, session.state)).toBe(true);
|
||||
// exact next transition matches
|
||||
const nextA = nextState(again.state, A("C", "cw")).state;
|
||||
const nextB = nextState(session.state, A("C", "cw")).state;
|
||||
expect(canonicalEqual(nextA, nextB)).toBe(true);
|
||||
});
|
||||
|
||||
it("replaying the action log from baseline + entry snapshot reproduces state", () => {
|
||||
let session = startCampaign();
|
||||
const log: RotationAction[] = [A("A", "cw"), A("C", "cw"), A("B", "ccw")];
|
||||
for (const a of log) session = commitAction(session, a);
|
||||
const replayed = replayFromBaseline(session.scenarioId, session.entrySnapshot, log);
|
||||
expect(canonicalEqual(replayed, session.state)).toBe(true);
|
||||
});
|
||||
|
||||
it("malformed or unsupported saves fail safely (load returns null, no crash)", () => {
|
||||
const store = new MemoryStorage();
|
||||
store.setItem("adaptive-loop.save.v1", "{not json");
|
||||
expect(load(store)).toBeNull();
|
||||
store.setItem("adaptive-loop.save.v1", JSON.stringify({ schemaVersion: 999 }));
|
||||
expect(load(store)).toBeNull();
|
||||
store.setItem("adaptive-loop.save.v1", JSON.stringify({ schemaVersion: 1, mode: "campaign", scenarioId: "nope", state: {}, unlockedScenarios: [], inheritedTraits: { producer: [], grazer: [] }, entrySnapshot: { producer: [], grazer: [] }, actionLog: [], outcome: "playing", savedAt: 1 }));
|
||||
expect(isValidEnvelope(JSON.parse(store.getItem("adaptive-loop.save.v1")!))).toBe(false);
|
||||
expect(load(store)).toBeNull();
|
||||
});
|
||||
|
||||
it("empty storage loads null", () => {
|
||||
expect(load(new MemoryStorage())).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("campaign — unlock, inheritance gift-and-burden, retry, standalone", () => {
|
||||
it("winning a scenario unlocks the next and carries a preserved trait", () => {
|
||||
// Drive s1 to a win using the solver fixture route.
|
||||
const s1win = (fixture.scenarios as any[]).find((s) => s.id === "s1-heat")!.win.actions as RotationAction[];
|
||||
let session = startCampaign();
|
||||
for (const a of s1win) session = commitAction(session, a);
|
||||
expect(session.state.outcome).toBe("won");
|
||||
const eligible = eligiblePreservations(session);
|
||||
expect(eligible.length).toBeGreaterThan(0);
|
||||
const choice = eligible[0]!;
|
||||
expect(eligible.length).toBeGreaterThan(0);
|
||||
const advanced = advanceAfterWin(session, choice);
|
||||
expect(advanced).not.toBeNull();
|
||||
expect(advanced!.scenarioId).toBe("s2-hunger");
|
||||
expect(advanced!.unlockedScenarios).toContain("s2-hunger");
|
||||
// preserved trait carried as a burden/gift into the next scenario
|
||||
expect(advanced!.inheritedTraits[eligible[0]!.lineage]).toContain(eligible[0]!.pressure);
|
||||
expect(advanced!.state.lineage[eligible[0]!.lineage].unlocked[eligible[0]!.pressure]).toBe(true);
|
||||
});
|
||||
|
||||
it("retry restores the scenario-entry inheritance snapshot", () => {
|
||||
let session = startCampaign();
|
||||
const before = buildBaselineState(session.scenarioId, "campaign", session.entrySnapshot);
|
||||
session = commitAction(session, A("A", "cw"));
|
||||
session = retry(session);
|
||||
expect(canonicalEqual(session.state, before)).toBe(true);
|
||||
});
|
||||
|
||||
it("standalone uses a clean baseline (no carried traits)", () => {
|
||||
const session = startStandalone("s3-toxin");
|
||||
expect(session.mode).toBe("standalone");
|
||||
expect(session.inheritedTraits.producer).toEqual([]);
|
||||
expect(session.inheritedTraits.grazer).toEqual([]);
|
||||
});
|
||||
|
||||
it("declining a trait still advances to the next scenario", () => {
|
||||
const s1win = (fixture.scenarios as any[]).find((s) => s.id === "s1-heat")!.win.actions as RotationAction[];
|
||||
let session = startCampaign();
|
||||
for (const a of s1win) session = commitAction(session, a);
|
||||
const advanced = advanceAfterWin(session, null);
|
||||
expect(advanced!.scenarioId).toBe("s2-hunger");
|
||||
expect(advanced!.inheritedTraits.producer).toEqual([]);
|
||||
});
|
||||
|
||||
it("winning the final scenario yields campaign victory (no further advance)", () => {
|
||||
const s5win = (fixture.scenarios as any[]).find((s) => s.id === "s5-convergence")!.win.actions as RotationAction[];
|
||||
// enter s5 directly with empty inheritance for the test
|
||||
let session = startStandalone("s5-convergence");
|
||||
session = { ...session, mode: "campaign" };
|
||||
for (const a of s5win) session = commitAction(session, a);
|
||||
expect(session.state.outcome).toBe("won");
|
||||
expect(advanceAfterWin({ ...session, scenarioId: SCENARIOS[SCENARIOS.length - 1].id }, null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// Ensure the SaveEnvelope type is exercised (keeps the export meaningful to tsc).
|
||||
export type _EnvelopeRef = SaveEnvelope;
|
||||
@@ -1,82 +0,0 @@
|
||||
// Gate 4 — scenario solvability. Validates the precomputed solver fixtures by
|
||||
// replaying each stored route from its baseline + inheritance and asserting the
|
||||
// recorded outcome. Fast and deterministic (the heavy search runs once offline in
|
||||
// scripts/gen-solver-fixtures.ts). Also checks the Gate 4 route-property rules.
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { nextState } from "../src/domain/pipeline";
|
||||
import { buildBaselineState, type Inheritance } from "../src/domain/scenario";
|
||||
import { SCENARIOS } from "../src/content/scenarios";
|
||||
import type { RotationAction } from "../src/domain/types";
|
||||
import fixture from "./fixtures/solver-results.json";
|
||||
|
||||
type StoredRoute = { actions: RotationAction[]; outcome: string; ownershipChanged: boolean; maxPressure: number };
|
||||
|
||||
function replay(scenarioId: string, inheritance: Inheritance, actions: RotationAction[]) {
|
||||
let s = buildBaselineState(scenarioId, "campaign", inheritance);
|
||||
for (const a of actions) s = nextState(s, a).state;
|
||||
return s;
|
||||
}
|
||||
|
||||
describe("Gate 4 — solver routes (replayed from fixtures)", () => {
|
||||
for (const sc of SCENARIOS) {
|
||||
const entry = (fixture.scenarios as any[]).find((x) => x.id === sc.id);
|
||||
|
||||
it(`${sc.id} has a winning route that replays to 'won'`, () => {
|
||||
expect(entry, `missing fixture for ${sc.id}`).toBeTruthy();
|
||||
const win = entry.win as StoredRoute | null;
|
||||
expect(win, `${sc.id} has no stored win route`).toBeTruthy();
|
||||
const final = replay(sc.id, { producer: [], grazer: [] }, win!.actions);
|
||||
expect(final.outcome).toBe("won");
|
||||
expect(win!.actions.length).toBeLessThanOrEqual(sc.turnLimit);
|
||||
});
|
||||
|
||||
it(`${sc.id} has a losing route that replays to a non-win terminal`, () => {
|
||||
const lose = entry.lose as StoredRoute | null;
|
||||
expect(lose, `${sc.id} has no stored lose route`).toBeTruthy();
|
||||
const final = replay(sc.id, { producer: [], grazer: [] }, lose!.actions);
|
||||
expect(final.outcome === "collapsed" || final.outcome === "expired").toBe(true);
|
||||
});
|
||||
}
|
||||
|
||||
it("at least one route requires a shared-slot ownership change", () => {
|
||||
const ok = (fixture.scenarios as any[]).some((x) => x.win?.ownershipChanged);
|
||||
expect(ok).toBe(true);
|
||||
});
|
||||
|
||||
it("at least one route exploits an adaptation (pressure reaches 3)", () => {
|
||||
const ok = (fixture.scenarios as any[]).some((x) => (x.win?.maxPressure ?? 0) >= 3);
|
||||
expect(ok).toBe(true);
|
||||
});
|
||||
|
||||
it("at least one route avoids unlocking any adaptation (pressure stays < 3)", () => {
|
||||
const avoid = (fixture.scenarios as any[]).filter((x) => x.avoid);
|
||||
expect(avoid.length, "no adaptation-avoiding route stored").toBeGreaterThan(0);
|
||||
for (const x of avoid) {
|
||||
const final = replay(x.id, { producer: [], grazer: [] }, x.avoid.actions as RotationAction[]);
|
||||
expect(final.outcome).toBe("won");
|
||||
expect((x.avoid as StoredRoute).maxPressure).toBeLessThan(3);
|
||||
}
|
||||
});
|
||||
|
||||
it("every reachable inheritance combination is solvable except the documented dormancy-burden residual risk", () => {
|
||||
const reach = fixture.reachability as {
|
||||
ok: boolean;
|
||||
combos: { scenarioId: string; inheritance: Inheritance; solvable: boolean }[];
|
||||
residualRiskCombos: { scenarioId: string; inheritance: Inheritance }[];
|
||||
};
|
||||
// Residual-risk combos must all be the documented dormancy-into-s5 class.
|
||||
for (const r of reach.residualRiskCombos) {
|
||||
expect(r.scenarioId).toBe("s5-convergence");
|
||||
expect(r.inheritance.producer).toContain("hunger");
|
||||
}
|
||||
// Every non-residual-risk combo must be solvable.
|
||||
const riskKeys = new Set(reach.residualRiskCombos.map((r) => `${r.scenarioId}|${JSON.stringify(r.inheritance)}`));
|
||||
for (const c of reach.combos) {
|
||||
const key = `${c.scenarioId}|${JSON.stringify(c.inheritance)}`;
|
||||
if (riskKeys.has(key)) continue;
|
||||
expect(c.solvable, `unsolvable non-documented combo: ${key}`).toBe(true);
|
||||
}
|
||||
expect(reach.ok).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,270 +0,0 @@
|
||||
// Simulation truth tests (SPEC Gate 3 / deterministic-game-core skill). Each test
|
||||
// exercises a single behavior. Assertions are robust to the full 8-phase pipeline:
|
||||
// movement is checked by presence, adaptations by adapted-vs-unadapted deltas,
|
||||
// and flow/caps/structural checks use literal hand-computed values.
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { nextState, outletOf } from "../src/domain/pipeline";
|
||||
import { cloneState, canonicalStringify, canonicalEqual } from "../src/domain/serialize";
|
||||
import { buildBaselineState } from "../src/domain/scenario";
|
||||
import { ALL_ACTIONS } from "../src/domain/constants";
|
||||
import { SCENARIOS } from "../src/content/scenarios";
|
||||
import { makeState, chamber } from "./helpers";
|
||||
import type { RotationAction } from "../src/domain/types";
|
||||
|
||||
const A = (loop: "A" | "B" | "C", direction: "cw" | "ccw"): RotationAction => ({ loop, direction });
|
||||
|
||||
describe("rotations — payload permutation + ownership", () => {
|
||||
// Producers carry nutrient so they survive the tick (no starvation); we assert
|
||||
// the payload LANDED at the destination slot and left the source.
|
||||
it("cw: slot 0 payload lands at slot 1 (loop A)", () => {
|
||||
const s = makeState([{ slot: 0, nutrient: 6, producer: 2 }]);
|
||||
const { state } = nextState(s, A("A", "cw"));
|
||||
expect(chamber(state, 1).producer).toBeGreaterThan(0);
|
||||
expect(chamber(state, 0).producer).toBe(0);
|
||||
});
|
||||
it("ccw: slot 1 payload lands at slot 0 (loop A)", () => {
|
||||
const s = makeState([{ slot: 1, nutrient: 6, producer: 2 }]);
|
||||
const { state } = nextState(s, A("A", "ccw"));
|
||||
expect(chamber(state, 0).producer).toBeGreaterThan(0);
|
||||
expect(chamber(state, 1).producer).toBe(0);
|
||||
});
|
||||
it("cw: slot 6 payload lands at slot 7 (loop B)", () => {
|
||||
const s = makeState([{ slot: 6, nutrient: 6, producer: 2 }]);
|
||||
const { state } = nextState(s, A("B", "cw"));
|
||||
expect(chamber(state, 7).producer).toBeGreaterThan(0);
|
||||
expect(chamber(state, 6).producer).toBe(0);
|
||||
});
|
||||
it("cw: slot 10 payload lands at slot 11 (loop C)", () => {
|
||||
const s = makeState([{ slot: 10, nutrient: 6, producer: 2 }]);
|
||||
const { state } = nextState(s, A("C", "cw"));
|
||||
expect(chamber(state, 11).producer).toBeGreaterThan(0);
|
||||
expect(chamber(state, 10).producer).toBe(0);
|
||||
});
|
||||
it("rotating loop C reclaims shared slot 5 and changes its outlet", () => {
|
||||
const s = makeState();
|
||||
expect(outletOf(5, s)).toBe(0); // owned by A (cw): outlet = slot 0
|
||||
const { state } = nextState(s, A("C", "cw"));
|
||||
expect(state.sharedOwner["5"]).toBe("C");
|
||||
expect(outletOf(5, state)).toBe(10); // owned by C (cw): outlet = slot 10
|
||||
});
|
||||
});
|
||||
|
||||
describe("channel flow + caps", () => {
|
||||
it("flows nutrient one step downstream (literal)", () => {
|
||||
const s = makeState([{ slot: 0, nutrient: 3 }]);
|
||||
const { state } = nextState(s, A("A", "cw"));
|
||||
// rotation slot0→slot1 (nutrient3); flow sends 1 from slot1→slot2
|
||||
expect(chamber(state, 1).nutrient).toBe(2);
|
||||
expect(chamber(state, 2).nutrient).toBe(1);
|
||||
});
|
||||
it("contention + overflow at a shared receiver (slot 2 fed by slots 1 and 9)", () => {
|
||||
const s = makeState([{ slot: 0, nutrient: 3 }, { slot: 1, nutrient: 6 }, { slot: 9, nutrient: 3 }]);
|
||||
const { state, events } = nextState(s, A("A", "cw"));
|
||||
expect(chamber(state, 2).nutrient).toBe(6); // 6 -1 sent +2 recv = 7 → capped 6
|
||||
expect(events.some((e) => e.kind === "nutrient-overflow" && (e.amount ?? 0) >= 1)).toBe(true);
|
||||
expect(chamber(state, 3).nutrient).toBe(1); // slot2 forwarded its send to slot3
|
||||
});
|
||||
it("keeps every capped field within 0..6 after a turn", () => {
|
||||
const s = makeState([
|
||||
{ slot: 0, nutrient: 6, producer: 6, heat: 6, toxin: 6, grazer: 6, phage: 6 },
|
||||
{ slot: 1, nutrient: 6, producer: 6 },
|
||||
{ slot: 9, nutrient: 6 },
|
||||
]);
|
||||
const { state } = nextState(s, A("A", "cw"));
|
||||
for (const c of state.chambers) {
|
||||
for (const v of [c.nutrient, c.heat, c.toxin, c.producer, c.grazer, c.phage]) {
|
||||
expect(v).toBeGreaterThanOrEqual(0);
|
||||
expect(v).toBeLessThanOrEqual(6);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("producer growth + interactions", () => {
|
||||
it("growth: a fed producer grows (more producers than a starved one)", () => {
|
||||
const fed = makeState([{ slot: 0, nutrient: 6, producer: 2 }]);
|
||||
const starved = makeState([{ slot: 0, nutrient: 0, producer: 2 }]);
|
||||
const f = nextState(fed, A("A", "cw")).state;
|
||||
const u = nextState(starved, A("A", "cw")).state;
|
||||
expect(chamber(f, 1).producer).toBeGreaterThan(chamber(u, 1).producer);
|
||||
});
|
||||
it("grazer feeding reduces producers vs a no-grazer control", () => {
|
||||
const withGrazer = makeState([{ slot: 0, nutrient: 6, producer: 3, grazer: 1 }]);
|
||||
const noGrazer = makeState([{ slot: 0, nutrient: 6, producer: 3 }]);
|
||||
const g = nextState(withGrazer, A("A", "cw")).state;
|
||||
const n = nextState(noGrazer, A("A", "cw")).state;
|
||||
expect(chamber(g, 1).producer).toBeLessThan(chamber(n, 1).producer);
|
||||
expect(chamber(g, 1).grazer).toBeGreaterThan(chamber(n, 1).grazer);
|
||||
});
|
||||
it("phage eats a grazer and gains; starves without one", () => {
|
||||
const eat = makeState([{ slot: 0, grazer: 3, phage: 1, nutrient: 6, producer: 3 }]);
|
||||
const starve = makeState([{ slot: 0, phage: 1, nutrient: 6, producer: 3 }]);
|
||||
const e = nextState(eat, A("A", "cw")).state;
|
||||
const t = nextState(starve, A("A", "cw")).state;
|
||||
expect(chamber(e, 1).phage).toBeGreaterThan(chamber(t, 1).phage);
|
||||
});
|
||||
});
|
||||
|
||||
describe("migration", () => {
|
||||
it("moves a population unit toward strictly richer food", () => {
|
||||
// slot10 producer (food=nutrient0); slot11 has nutrient (dest food). outlet10→11 (C cw).
|
||||
const s = makeState([{ slot: 10, producer: 3, nutrient: 0 }, { slot: 11, nutrient: 3 }]);
|
||||
const { state } = nextState(s, A("A", "cw")); // A rotation does not move 10/11
|
||||
expect(chamber(state, 11).producer).toBeGreaterThan(0); // migrated in
|
||||
expect(chamber(state, 10).producer).toBeLessThan(3); // sent one out
|
||||
});
|
||||
});
|
||||
|
||||
describe("heat adaptation — benefit + carrier cost (adapted vs unadapted)", () => {
|
||||
// Carrier cost is isolated from heat-death by comparing two ADAPTED lineages
|
||||
// that differ only in whether heat is locally present.
|
||||
const adapted = (heat: number) =>
|
||||
makeState([{ slot: 0, nutrient: 6, producer: 3, heat }], { unlocked: { producer: ["heat"] } });
|
||||
it("carrier cost: an adapted producer in heat grows LESS than the same producer without heat", () => {
|
||||
const hot = nextState(adapted(3), A("A", "cw")).state;
|
||||
const cool = nextState(adapted(0), A("A", "cw")).state;
|
||||
expect(chamber(hot, 1).producer).toBeLessThan(chamber(cool, 1).producer);
|
||||
expect(chamber(hot, 1).producer).toBe(3); // no growth (blocked)
|
||||
});
|
||||
const heatState = (unlocked: boolean) =>
|
||||
makeState([{ slot: 0, nutrient: 6, producer: 3, heat: 3 }], { unlocked: unlocked ? { producer: ["heat"] } : {} });
|
||||
it("benefit: Heat Shield prevents heat population loss (adapted survives better)", () => {
|
||||
const adapted = nextState(heatState(true), A("A", "cw")).state;
|
||||
const plain = nextState(heatState(false), A("A", "cw")).state;
|
||||
expect(chamber(adapted, 1).producer).toBeGreaterThan(chamber(plain, 1).producer);
|
||||
});
|
||||
it("heat-spillover: adapted lineages cool the chamber", () => {
|
||||
const { state, events } = nextState(heatState(true), A("A", "cw"));
|
||||
expect(events.some((e) => e.kind === "heat-spillover")).toBe(true);
|
||||
expect(chamber(state, 1).heat).toBeLessThan(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("hunger adaptation — benefit + inedibility spillover", () => {
|
||||
it("benefit: Dormancy prevents hunger loss (adapted producer survives starvation)", () => {
|
||||
const adapted = makeState([{ slot: 0, producer: 3 }], { unlocked: { producer: ["hunger"] } });
|
||||
const plain = makeState([{ slot: 0, producer: 3 }]);
|
||||
const a = nextState(adapted, A("A", "cw")).state;
|
||||
const p = nextState(plain, A("A", "cw")).state;
|
||||
expect(chamber(a, 1).producer).toBeGreaterThan(chamber(p, 1).producer); // plain starves -1
|
||||
expect(chamber(a, 1).producer).toBe(3);
|
||||
});
|
||||
it("spillover: dormant producer is inedible to grazers", () => {
|
||||
const dormant = makeState([{ slot: 0, producer: 3, grazer: 1 }], { unlocked: { producer: ["hunger"] } });
|
||||
const edible = makeState([{ slot: 0, producer: 3, grazer: 1 }]);
|
||||
const d = nextState(dormant, A("A", "cw")).state;
|
||||
const e = nextState(edible, A("A", "cw")).state;
|
||||
expect(chamber(d, 1).producer).toBeGreaterThan(chamber(e, 1).producer); // dormant not eaten
|
||||
expect(chamber(d, 1).grazer).toBeLessThanOrEqual(chamber(e, 1).grazer); // dormant grazer doesn't feed
|
||||
});
|
||||
});
|
||||
|
||||
describe("toxin adaptation — benefit + carrier cost + spillover", () => {
|
||||
const toxinState = (unlocked: boolean) =>
|
||||
makeState([{ slot: 0, nutrient: 6, producer: 3, toxin: 3 }], { unlocked: unlocked ? { producer: ["toxin"] } : {} });
|
||||
it("Efflux prevents toxin loss (adapted survives better) and cleanses toxin (spillover)", () => {
|
||||
const adapted = nextState(toxinState(true), A("A", "cw"));
|
||||
const plain = nextState(toxinState(false), A("A", "cw"));
|
||||
expect(chamber(adapted.state, 1).producer).toBeGreaterThan(chamber(plain.state, 1).producer);
|
||||
expect(adapted.events.some((e) => e.kind === "toxin-spillover")).toBe(true);
|
||||
expect(adapted.events.some((e) => e.kind === "toxin-cost")).toBe(true);
|
||||
// adapted chamber toxin reduced by spillover relative to plain
|
||||
expect(chamber(adapted.state, 1).toxin).toBeLessThanOrEqual(chamber(plain.state, 1).toxin);
|
||||
});
|
||||
});
|
||||
|
||||
describe("immunity adaptation — selection, cloak, retarget, carrier cost", () => {
|
||||
it("immune node selects and damages the largest eligible lineage", () => {
|
||||
const s = makeState([{ slot: 6, producer: 3, nutrient: 6 }], { scenarioId: "test-immune" });
|
||||
const { state, events } = nextState(s, A("A", "cw")); // slot6 not in A, unmoved
|
||||
expect(chamber(state, 6).producer).toBeLessThan(3); // took damage
|
||||
expect(events.some((e) => e.kind === "immune-damage")).toBe(true);
|
||||
});
|
||||
it("Cloak excludes a lineage from immune selection (no immune damage)", () => {
|
||||
const cloaked = makeState([{ slot: 6, producer: 3, nutrient: 6 }], { scenarioId: "test-immune", unlocked: { producer: ["immunity"] } });
|
||||
const { state, events } = nextState(cloaked, A("A", "cw"));
|
||||
expect(events.some((e) => e.kind === "immune-damage")).toBe(false);
|
||||
expect(chamber(state, 6).producer).toBeGreaterThanOrEqual(3); // untouched by the node (may grow)
|
||||
});
|
||||
it("Cloak causes retarget spillover to the other lineage", () => {
|
||||
// Cloaked grazer is the largest at the node; producer is selected instead.
|
||||
const s = makeState([{ slot: 6, grazer: 4, producer: 2, nutrient: 6 }], { scenarioId: "test-immune", unlocked: { grazer: ["immunity"] } });
|
||||
const { state, events } = nextState(s, A("A", "cw"));
|
||||
expect(events.some((e) => e.kind === "immune-retarget")).toBe(true);
|
||||
expect(chamber(state, 6).producer).toBeLessThanOrEqual(2); // producer (retarget target) takes damage
|
||||
});
|
||||
it("Cloak carrier cost: predator removes an extra prey at the immune node", () => {
|
||||
const cloaked = makeState([{ slot: 6, grazer: 3, phage: 1, producer: 3, nutrient: 6 }], { scenarioId: "test-immune", unlocked: { grazer: ["immunity"] } });
|
||||
const plain = makeState([{ slot: 6, grazer: 3, phage: 1, producer: 3, nutrient: 6 }], { scenarioId: "test-immune" });
|
||||
const c = nextState(cloaked, A("A", "cw"));
|
||||
const p = nextState(plain, A("A", "cw"));
|
||||
expect(c.events.some((e) => e.kind === "cloak-cost")).toBe(true);
|
||||
// cloaked grazer loses MORE to the phage than a non-cloaked one (2 vs 1 removed)
|
||||
expect(chamber(c.state, 6).grazer).toBeLessThan(chamber(p.state, 6).grazer);
|
||||
});
|
||||
});
|
||||
|
||||
describe("immutability, determinism, terminal precedence", () => {
|
||||
it("does not mutate its input", () => {
|
||||
const s = makeState([{ slot: 0, nutrient: 3, producer: 2, grazer: 1 }]);
|
||||
const before = canonicalStringify(s);
|
||||
nextState(s, A("A", "cw"));
|
||||
expect(canonicalStringify(s)).toBe(before);
|
||||
});
|
||||
it("produces identical canonical output for identical input + action", () => {
|
||||
const s = makeState([{ slot: 0, nutrient: 3, producer: 2 }, { slot: 6, grazer: 2 }]);
|
||||
const r1 = nextState(cloneState(s), A("A", "cw"));
|
||||
const r2 = nextState(cloneState(s), A("A", "cw"));
|
||||
expect(canonicalStringify(r1.state)).toBe(canonicalStringify(r2.state));
|
||||
});
|
||||
it("collapse takes precedence over a win condition", () => {
|
||||
const s = makeState([{ slot: 0, toxin: 2 }], { scenarioId: "test-win" }); // no biomass; checkWin always true
|
||||
const { state } = nextState(s, A("A", "cw"));
|
||||
expect(state.outcome).toBe("collapsed");
|
||||
});
|
||||
it("win takes precedence over turn-limit expiration", () => {
|
||||
const s = makeState([{ slot: 0, producer: 1, nutrient: 6 }], { scenarioId: "test-win", turn: 4 }); // survives; resolvedTurn 5 == limit
|
||||
const { state } = nextState(s, A("A", "cw"));
|
||||
expect(state.outcome).toBe("won");
|
||||
});
|
||||
it("expires at the turn limit when not won", () => {
|
||||
const s = makeState([{ slot: 0, producer: 1, nutrient: 6 }], { turn: 98 }); // survives; resolvedTurn 99 == limit 99
|
||||
const { state } = nextState(s, A("A", "cw"));
|
||||
expect(state.outcome).toBe("expired");
|
||||
});
|
||||
it("rejects actions in a terminal state without changing domain state", () => {
|
||||
const s = makeState([{ slot: 0, producer: 1 }], { outcome: "won" });
|
||||
const { state, rejected } = nextState(s, A("A", "cw"));
|
||||
expect(rejected).toBe(true);
|
||||
expect(canonicalEqual(state, s)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("preview == commit, and replay reproduction", () => {
|
||||
it("preview equals commit for every action across all campaign baselines", () => {
|
||||
for (const sc of SCENARIOS) {
|
||||
const base = buildBaselineState(sc.id, "standalone");
|
||||
for (const action of ALL_ACTIONS) {
|
||||
const preview = nextState(cloneState(base), action).state;
|
||||
const commit = nextState(cloneState(base), action).state;
|
||||
expect(canonicalEqual(preview, commit)).toBe(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
it("replaying an action log from baseline reproduces the final state", () => {
|
||||
const base = buildBaselineState(SCENARIOS[0].id, "standalone");
|
||||
let cur = cloneState(base);
|
||||
const log: RotationAction[] = [];
|
||||
const seq: RotationAction[] = [A("A", "cw"), A("B", "ccw"), A("C", "cw"), A("A", "ccw"), A("C", "ccw")];
|
||||
for (const action of seq) {
|
||||
if (cur.outcome !== "playing") break;
|
||||
const { state } = nextState(cur, action);
|
||||
cur = state;
|
||||
log.push(action);
|
||||
}
|
||||
let replayed = cloneState(base);
|
||||
for (const action of log) replayed = nextState(replayed, action).state;
|
||||
expect(canonicalEqual(replayed, cur)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,22 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"module": "ESNext",
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": false,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"types": []
|
||||
},
|
||||
"include": ["src", "tests", "e2e", "*.config.ts"]
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
import { defineConfig } from "vite";
|
||||
|
||||
// Single-page production build. Root index.html loads src/main.ts.
|
||||
export default defineConfig({
|
||||
base: "./",
|
||||
build: {
|
||||
target: "es2020",
|
||||
outDir: "dist",
|
||||
sourcemap: true,
|
||||
},
|
||||
});
|
||||
@@ -1,9 +0,0 @@
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
environment: "node",
|
||||
include: ["tests/**/*.test.ts"],
|
||||
reporters: ["default"],
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user