(Adaptive Loop) Pass 4

This commit is contained in:
AlexKucera committed 2026-08-15 19:22:22 +02:00
1 parent 91f8562ab6
commit 360c0992ce
36 files changed
+12943

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
node_modules/
dist/
test-results/
playwright-report/
.DS_Store
PROMPT.md
+32
View File
@@ -0,0 +1,32 @@
# Assets Disclosure
**All visuals in Adaptive Loop are procedural SVG/CSS generated in code.** No image, font, music,
or other binary art asset is downloaded, bundled, or imported. SPEC §3 (Forbidden) and §13
(Entity art) are satisfied entirely by code.
## Procedural asset sources
| Asset | Source | Location |
|---|---|---|
| Board geometry (three concentric hexagonal rings, six radial gates, pointy-top hex tiles) | computed at runtime from ring radius / vertex math | `src/ui/geom.ts` |
| Species glyphs (Lumiflora producer = 6-petal diatom; Vellea grazer = ciliated crescent; Phage = lunar-lander virus) | procedural SVG path/ellipse/polygon builders | `src/ui/svg.ts` |
| Fixture glyphs (nutrient inlet pipette, heat coiled filament, toxin dropper, drain funnel, immune sentinel eye, objective reticle) | procedural SVG | `src/ui/svg.ts` |
| Pressure iconography (heat sun-rays, hunger crescent, toxin skull-drop, immunity shield) | procedural SVG, each with a distinct color | `src/ui/svg.ts` |
| Tile state rendering (nutrient liquid level, toxin level, heat rim glow, on-gate ring-color stroke) | SVG `clip-path` rectangles + strokes | `src/ui/board.ts` |
| Layout, theme, focus states, reduced-motion | CSS only | `src/style.css` |
## Generated image assets
**None.** No raster images were generated or used during the run. The `image_generate` capability
was not invoked; the deliverable is fully vector/CSS.
## Fonts
Uses only the operating-system UI font stack (`-apple-system, BlinkMacSystemFont, "Segoe UI",
system-ui, sans-serif`) and the monospace stack for pressure-track glyphs. No web fonts are loaded.
## Third-party packages
Runtime has **zero** third-party dependencies. Dev-only: `vite`, `typescript`, `vitest`,
`@playwright/test` (declared in `package.json` `devDependencies`). None ship art or fonts into the
game bundle.
+77
View File
@@ -0,0 +1,77 @@
# Context Manifest
## Authoritative private prompt
- Source/effective path: `/Users/alex/Projects/scripting/agentic-labs-challenge/adaptive-loop/PROMPT.md`
- SHA-256: `9e75d9260db550160797f40416ea083fef15e8119a46b9b39623b0415d05ad61`
- Disclosure: retained at its private submitted path and excluded from the public repository by `.gitignore`; DM it with the submission.
## Staged steering context
| File | SHA-256 |
|---|---|
| `SPEC.md` | `99968f6c12715be2c091f471abc98dab283c7729cce521316b1a05a955906801` |
| `.agents/skills/pi-game-factory/SKILL.md` | `b44005242a71ee2a8c087c6f13ca51f8675f31c99e8d55dc5a9db1f5245969a6` |
| `.agents/skills/deterministic-game-core/SKILL.md` | `9c81c93e471cb620c3c9bb53beed287b674bfa2be1d3b9b03c38d484fa62d11b` |
| `.agents/skills/game-ui-proof/SKILL.md` | `f51ad6794ddb1051fdf703d48c9fc6d02ba76ceaacdc9bedd110642e4f536bba` |
| `docs/board-layout.md` | `2db689a2d35a356380d2d517861872954be070d94e447977625e64e19e15c47a` |
| `docs/brainstorming-summary.md` | `b9830ba45cab4145f189182405590e0642744fea877e9882fd3bd2478236a6e1` |
## Preflight evidence
- Recorded before implementation: the directory contained `PROMPT.md`, `SPEC.md`, the three skill files, `docs/board-layout.md`, `docs/brainstorming-summary.md`, and ignored `.DS_Store` files.
- The requested isolated four-file launch condition was **not** the state presented to this run: two additional disclosed docs and the private prompt were present, and the directory was nested inside the existing Git worktree `/Users/alex/Projects/scripting/agentic-labs-challenge` at parent commit `91f8562`.
- A fresh nested repository was initialized before final project tracking so the public game repository has its own history and excludes the private prompt.
- `PI_SESSION_FILE`: `/Users/alex/.pi/agent/sessions/--Users-alex-Projects-scripting-agentic-labs-challenge-adaptive-loop--/2026-08-14T07-58-52-011Z_019fff47-ee6b-74f4-92c2-244425aae2c3.jsonl`
- The live JSONL was inspected in place and not copied. It begins with session id `019fff47-ee6b-74f4-92c2-244425aae2c3`, initial `zai/glm-5.2`, reasoning `high`, then switches to effective `openai-codex/gpt-5.6-sol` before the Goal state and first user entry.
- Provenance warning: the first user entry is the harness-rendered “Goal mode is active” continuation for objective `@PROMPT.md`; this session does not contain a byte-for-byte `pi-goal-prompt` kickoff containing the private prompt. This launch-time property cannot be repaired in game code and must not be concealed in post-exit validation.
## Effective model and reasoning
- Provider/model: `openai-codex/gpt-5.6-sol`
- Reasoning: `high`
- Initial model event before Goal kickoff: `zai/glm-5.2`
## Requested isolated harness versus effective harness
Requested launch flags/effects: disable ambient context, skills, prompt templates, themes, and extensions; load only the four packages below. The current host session did not honor that isolation: user/project context, 107 discovered skills, theme `dark`, and the packages from the user settings were available. No project-scoped agent files or chains were discovered; executable built-ins were `delegate`, `oracle`, `researcher`, `reviewer`, `scout`, and `worker`.
| Requested package | Requested | Installed/effective | Package hash |
|---|---:|---:|---|
| `@narumitw/pi-goal` | `0.51.0` | `0.51.0` | `bac4d54866730844e9dff6eec114f7385d9bb234d83c8b72cdf446af3553354d` |
| `@juicesharp/rpiv-todo` | `2.4.0` | `2.5.0` | `02566f838ecf2b7ed75306523ce9e80022a1084d720a6cefb641c2c7823b4d3f` |
| `pi-subagents` | `0.47.1` | `0.49.0` | `20413c4d15094847c6978e856cf2d244292e82bdc934a57638a780f2434f0bbd` |
| `@injaneity/pi-computer-use` | `0.5.0` | `0.5.0` | `5cc83cdcea5393f50118906069dac31e7bedda7887e9f6cf00c7176b0c5f9f94` |
User settings hash: `23785494b192151263fa86ef1a2a4a687422f490ec53be87ce2c567893e577b1`. Effective settings selected `openai-codex/gpt-5.6-sol`, reasoning `high`, theme `dark`, and 23 configured packages: `pi-gitnexus`, `pi-mcp-adapter`, `pi-subagents`, `rpiv-ask-user-question`, `pi-review-loop`, `pi-web-access`, `pi-powerline-footer`, `pi-context-usage`, `pi-lcm`, `pi-intercom`, `pi-hashline-readmap`, `pi-dcp`, `pi-computer-use`, `rpiv-todo`, `pi-design-deck`, `pi-nous-portal-provider`, `ponytail`, `pi-image-gen`, `pi-hermes-memory`, `pi-guardrails`, `glimpseui`, `pi-prompt-template-model`, and `pi-goal`.
## Runtime and hooks
- Node `v26.5.1`; npm `11.17.0`; Git `2.50.1`.
- MCP servers: none connected.
- Subagent project agents/chains: none. Built-in fresh-context, read-only reviewers were used; final focused review run `3d3b5453` returned `No issues found`.
- No generated raster assets, downloaded art, backend, analytics, network dependency, or game engine.
## Freeze evidence
- Final aggregate command: `npm run check`.
- Result after the last game-code edit: TypeScript passed; production build passed; 76 Vitest tests passed; 21 Playwright tests passed.
- `SHA256SUMS` is the deterministic tracked-file manifest; verify with `shasum -a 256 -c SHA256SUMS`.
- The final commit and tree hashes are printed at submission time with `git rev-parse HEAD HEAD^{tree}`.
## Post-exit ownership
Authoritative live session path:
`/Users/alex/.pi/agent/sessions/--Users-alex-Projects-scripting-agentic-labs-challenge-adaptive-loop--/2026-08-14T07-58-52-011Z_019fff47-ee6b-74f4-92c2-244425aae2c3.jsonl`
After Pi exits, copy—not move—and validate it with:
```sh
SESSION='/Users/alex/.pi/agent/sessions/--Users-alex-Projects-scripting-agentic-labs-challenge-adaptive-loop--/2026-08-14T07-58-52-011Z_019fff47-ee6b-74f4-92c2-244425aae2c3.jsonl'
cp -- "$SESSION" adaptive-loop-session.jsonl
node -e 'const fs=require("fs");const text=fs.readFileSync("adaptive-loop-session.jsonl","utf8");const rows=text.trim().split("\n").map(JSON.parse);if(rows.some(r=>r.parentSession))throw Error("parentSession found");if(!text.includes("@PROMPT.md"))throw Error("goal marker missing");console.log(`validated ${rows.length} JSONL records; kickoff byte-equivalence remains explicitly disclaimed in CONTEXT-MANIFEST.md`)'
shasum -a 256 PROMPT.md adaptive-loop-session.jsonl
```
Do not claim kickoff byte equality: the provenance warning above remains authoritative.
+92
View File
@@ -0,0 +1,92 @@
# Adaptive Loop
A calm, deterministic microfluidic strategy puzzle. Rotate three concentric glass rings to
align six radial gates, route nutrient inward, grow a microbial ecosystem, and provoke — then
exploit — its counter-adaptations. Built for the Agentic Labs one-prompt challenge.
- **Stack:** Vite + TypeScript + Vitest + Playwright (the smallest boring stack that satisfies SPEC §14).
- **Determinism:** one pure transition `nextState(state, action)` owns every rule; preview and
commit call the same function on a cloned state. No runtime randomness, no floating-point
simulation — all quantities are capped integers.
- **No backend, no engine, no downloaded assets.** All visuals are procedural SVG/CSS.
## Play
Open the built game in a browser, or run the dev server:
```sh
npm install
npm run dev # http://localhost:5173
```
Or build and preview the production bundle:
```sh
npm run build
npm run preview # http://localhost:4173
```
### Controls
- **Mouse/touch:** click a rotation control (Inner/Middle/Outer ⟳/⟲) to **preview** the exact
one-turn outcome, then **Commit**. The selection persists until you commit, pick a different
rotation, or press **Esc** — Commit never greys out just because the pointer left the control.
- **Keyboard:** `1`–`6` select the six rotations, `Enter`/`Space` commits, `Esc` cancels.
- **Menu:** New Campaign, Continue (resume exact saved run), Replay Standalone (any unlocked
scenario with clean baseline lineages), Save & Quit, Retry, Help/Legend.
### Objective loop
Each scenario has a specific win condition (see the objective panel) and the universal loss
conditions: **ecosystem collapse** (total producer + grazer = 0) or **turn-limit expiry**.
Collapse takes precedence over win, which takes precedence over expiry. Win a scenario to unlock
the next and preserve **one** newly-unlocked lineage trait (a gift *and* a cost) for later scenarios.
## Develop & verify
```sh
npm run typecheck # tsc --noEmit
npm test # vitest unit + behavior + solver/replay + campaign tests
npm run build && npm run e2e # Playwright black-box tests against the production build
```
The full aggregate (typecheck + build + unit tests + e2e) is the freeze gate.
### Tests
- `test/behavior.test.ts` — literal worked tests for every pipeline phase, both rotation
directions on all rings, gate alignment, tangential + radial flow, caps, all four adaptations
(benefit/cost/spillover), immutability, canonical determinism, terminal precedence,
preview/commit equality, replay.
- `test/solver-fixtures.test.ts` — replays verified winning and losing routes, checks actual
adaptation benefit/cost/spillover and matching-adaptation avoidance, and proves campaign
reachability across all 302 conservative inheritance sets.
- `test/campaign.test.ts` — campaign progression, inheritance carry, retry snapshot, standalone
baseline.
- `tests/e2e.spec.ts` — black-box browser proof via public controls only.
## Repository layout
```
src/domain/ types, core (canonical/clone/gates), scenarios, transition (nextState), solver
src/persistence/ versioned localStorage save/load + validation
src/ui/ board geometry, procedural SVG glyphs, render, app (views/controls/preview)
test/ vitest suites tests/ Playwright e2e
SPEC.md authoritative spec docs/ board-layout + brainstorming context
CONTEXT-MANIFEST.md disclosure boundary (prompt, context, versions, session log path)
TUNING.md documented §9 scenario-data adjustments
ASSETS.md procedural-asset disclosure
RECORDING.md deterministic recording route from verified solver actions
```
## Scenario tuning
Three scenarios required minimal SPEC §9 data adjustments to be provably solvable under the
deterministic 1-unit/phase flow/migration model; no simulation rules were changed. See
[`TUNING.md`](./TUNING.md) for the exact changes, reasons, and preserved invariants.
## Session / submission
The authoritative prompt and session-log boundary are recorded in
[`CONTEXT-MANIFEST.md`](./CONTEXT-MANIFEST.md). The exact session JSONL is an operator-owned
post-exit artifact and is not copied during the run.
+33
View File
@@ -0,0 +1,33 @@
# Recording Route — deterministic, verified actions
The routes come from `test/solver-fixtures.json` and black-box browser tests. Drive the production build through public controls only; do not inject state or localStorage.
Run `npm run build && npm run preview`, then open http://localhost:4173.
## Verified action sequences
- **Scenario 1 win (8 turns):** `Inner cw → Inner ccw → Middle ccw ×4 → Middle cw → Outer cw`
- **Scenario 1 collapse (5 turns):** `Inner cw → Middle ccw → Outer cw → Outer cw → Inner cw`
- **Scenario 2 win (10 turns):** `Inner cw → Inner cw → Middle cw → Inner cw → Inner ccw → Outer cw → Middle cw → Middle cw → Middle ccw → Middle ccw`
- **Scenario 5 win (3 turns):** `Middle ccw → Inner cw → Middle cw`
## Uncut recording script (SPEC §16)
| # | Beat | Action and visible proof |
|---|------|--------------------------|
| 1 | Title / campaign start | Click **New Campaign**. Show the 36-tile board, three rings, six gates, objective, traits, event panel, and six rotation controls. |
| 2 | Exact preview | Focus or click **Inner ⟳**. Open **Payload destinations** and show `I0→I1`; show predicted objective progress, exact resource/species deltas, board highlights, and enabled **Commit**. |
| 3 | Movement + flow | Commit. Show turn 1, moved payloads, flow arrows, and `Flow` events. |
| 4 | Pressure causes adaptation | Follow the Scenario 1 win route through turn 4. Show `Lumiflora unlocked Dormancy`, its 3/3 pressure track, adapted tile borders/✓ tags, and the Hunger response. |
| 5 | Benefit + carrier cost | Continue the route. Show `Benefit active: hunger loss prevented` and `Cost active: dormant producer could not migrate` in the event panel. |
| 6 | Strengthened global response | Show `Hunger response active`; nutrient inlets now add 1 instead of 2. |
| 7 | Collapse + retry | Use **Save & Quit → New Campaign** for a clean Scenario 1, then play the five-turn collapse route. Show **Ecosystem collapsed**, click **Retry**, and show turn 0 restored. |
| 8 | Win + preserved lineage choice | Play the eight-turn win route. Show **Objective achieved**, then explicitly preserve **Lumiflora · Dormancy** to enter Scenario 2. |
| 9 | Benefit / cost / spillover together | Commit the first Scenario 2 action. Show inherited Dormancy and the actual `Benefit active`, `Cost active`, and `Spillover active: dormant producer was inedible` events. |
| 10 | Save & Quit | Click **Save & Quit** and show **Continue** on the title. |
| 11 | Close | Close the browser tab/window on screen. Do not substitute reload. |
| 12 | Reopen | Open a new tab/window and navigate back to http://localhost:4173. |
| 13 | Exact Continue | Click **Continue**. Show Scenario 2 at the same turn, board values, inherited traits, and action history. |
| 14 | Multiple scenarios | Save & Quit, choose **Replay Standalone**, and show the unlocked Scenario 1 and Scenario 2 entries. |
Automated proof covers all five scenarios, all 302 conservative campaign inheritance sets, a legal baseline route that provokes and triggers adaptation benefit/cost/spillover, persistence, retry, accessibility, and preview/commit equality. The recording need not play the full campaign.
+41
View File
@@ -0,0 +1,41 @@
9c81c93e471cb620c3c9bb53beed287b674bfa2be1d3b9b03c38d484fa62d11b .agents/skills/deterministic-game-core/SKILL.md
f51ad6794ddb1051fdf703d48c9fc6d02ba76ceaacdc9bedd110642e4f536bba .agents/skills/game-ui-proof/SKILL.md
b44005242a71ee2a8c087c6f13ca51f8675f31c99e8d55dc5a9db1f5245969a6 .agents/skills/pi-game-factory/SKILL.md
2cd017c88a0ca6799462021defa84a7b4ffe7f038d2a65b32058af06048558b6 .gitignore
76f1468371f8c02c9557f31bce9291e5b596466e80181f4decac7a7c091cff61 ASSETS.md
4d5c96b1f867179d0d69f82394a6203c15926de5275100c48beda1650f54b2f4 CONTEXT-MANIFEST.md
aea86fb4fdfb799e3a03d9bdbd7cffeb4d76dbd56f26d819122f60af7d02f2e7 README.md
ff40e374426a66876474f1f1ef2ab6d4695d153b22775fe8561a16187dd6bbef RECORDING.md
99968f6c12715be2c091f471abc98dab283c7729cce521316b1a05a955906801 SPEC.md
2cf727f7f7dc77acb812265928daef3ac6408f333caff46cdb9428a192dab9b3 TUNING.md
2db689a2d35a356380d2d517861872954be070d94e447977625e64e19e15c47a docs/board-layout.md
b9830ba45cab4145f189182405590e0642744fea877e9882fd3bd2478236a6e1 docs/brainstorming-summary.md
fc415b46fe80a806f11932d248fd8d1646b3d2542d115fc1306055f6bd4cb2da index.html
67ae81700749158f465d41bdcba156bbb77fe9b6129e90a1b9642148de2b1d38 package-lock.json
55a07069ea300999f6d2b687152040ea62eaa01ba116159c27b1ce371452dcf8 package.json
465a2f764cd053ac82e466ecc54195e9e0f83f24d29887b1c4f9f9b352731ad0 playwright.config.ts
61c39326b3c40846d356914dd440213ca28dcff708c2a2adf84a993fc6af6e7f src/domain/core.ts
f6ce956126b58723ed3b98c8ea5064f8fb476e92e10b8e4f5f674567153f269c src/domain/scenarios.ts
5a3280d57a0b1a1b31e4457029abbf3b1bcc9a12cc0e6b9ed51bb1f9a864f1c1 src/domain/solver.ts
23556eeee71af00445f4480570556b2175a57114339291f555202710de995c4a src/domain/transition.ts
c44d78553cb722bc38b05a68ecb05397a40523c50d3fe07bbd16bc309d79c401 src/domain/types.ts
f481aa368faa86815d4fa012d435b3485767ac33966bee5f7c45f9b593c19dcd src/main.ts
34170a1d9804004e1c5c7e038f10a88fdac6e46d11a381d5b88a70e2406c9c58 src/persistence/save.ts
991e0b2b2554c71336093fe63998a3d271c2f38891fa2ad8a36d83282427ea36 src/solver/gen-fixtures.ts
ab1ccf7ee344564ffa8ebb756a4ae37e801c69b73164fa5af14b6727877beaa0 src/style.css
fb258ef3cf157ec1bf149127ca366ee458a22d95b566f651da5a8fee7ad12ec4 src/ui/app.ts
94571b60d51301ddde602609af5a6bb2d0bfa17f1a1a9e5438ddfd40307fca64 src/ui/board.ts
69e74578539f5f16c333845d0c2c846c010415dba7da003d2025d8b87d13777c src/ui/geom.ts
0230b373d59eebee838367fa8f6243e9e2d14915190e8ae3d4b599662ee42d63 src/ui/svg.ts
4ee1beda44bf323b4b458d9aef1728eed95b625828de3f5b162e90407ad17506 test/behavior.test.ts
632d59889dbcc23756cb32bee2d1718ed47887e63c81528dcd6cdb5bb4dbf27e test/campaign.test.ts
8b0d96118ebe09a9adf715a35812f76ac547f7d7479114a56e093493e5afa9ec test/persistence.test.ts
262ace520c0c6f35d5fd35d80c631504008d44aee04f5f37a71090f96af9fd9f test/scenario1.test.ts
2842f874183e14f5cd9f67ce2ed5fafc993b9edeed6d03e4c7772583079c8589 test/smoke.test.ts
ee672267357eaf6a16c889a3d39e6a9cbe11b1353a5526f18807e590a2e8ed85 test/solver-fixtures.json
68ef9705efed39575e5ec3e7bff8313254356e38a1d13ec17a952aa737a22ed7 test/solver-fixtures.test.ts
8a2740cc59ce0caaffc16f007db592508174daa62dff6e7b3bd16c2ef5e7164c test/solver.test.ts
ef88d8ae5d6102057d0399810a233745cf95855e0b2f3a5f2f3c695b7568dbaf test/truth-extra.test.ts
e4c5f8b6c08c957b70c1867e2c1ddf743bee8bb0f90073b771e122ff9ef902e2 tests/e2e.spec.ts
62c12215a807775bc7c759d27c140dbc15448ba56b2d64899d1b7a03b134e320 tsconfig.json
98486ad5378a839173deb55cb83ee6a3355110c733d261c22510fe1077e82e6b vite.config.ts
+69
View File
@@ -0,0 +1,69 @@
# Scenario Tuning Log (SPEC §9)
Only permitted declarative knobs changed: starting populations/resources, fixture locations, and numeric objective thresholds. Each numeric change below is a sequence of ±1 passes. Board topology, actions, turn order, caps, adaptation rules, objective types, and terminal precedence are unchanged.
## Scenario 1 — Heat
No tuning.
## Scenario 2 — Hunger
No tuning.
## Scenario 3 — Toxin
The required permanent toxin inlets outpaced localized drains after tangential and radial spreading.
1. Move the `O3` toxin inlet to the `I1` drain; keep it present. Raise `O3` starting toxin `2→3` (`+1`).
2. Move the `O9` toxin inlet to the `I3` drain; keep it present. Raise `O9` starting toxin `2→3` (`+1`).
3. Relax the total-toxin ceiling `2→3→4→5→6→7→8` (six `+1` passes).
Bounded searches failed at each lower ceiling and first found a winning route at `8` during turns 6–9 with both ongoing inlets retained. The route must still control contamination while preserving at least eight producers plus grazers. Efflux benefit, cost, and detoxification spillover are unchanged.
## Scenario 4 — Immunity
The original grazers could not reach sanctuary `I0` within eight one-unit migrations. Add a gate-0 escort path:
1. `M0`: nutrient `0→1`, producer `0→1`, grazer `0→1`; `I0`: producer `0→1`, grazer `0→1`; `I5`: nutrient `0→1`, producer `0→1`, grazer `0→1`.
2. `M0`: nutrient `1→2`, producer `1→2`; `I0`: producer `1→2`; `I5`: nutrient `1→2`, producer `1→2`, grazer `1→2`.
3. `M0`: nutrient `2→3`, producer `2→3`.
4. Harden sanctuary from `I0 grazer ≥3` to `≥4` (`+1`).
Immune nodes, phage, target selection, Cloak exclusion, predator cost, and retarget spillover are unchanged. The baseline solver win still takes eight turns.
## Scenario 5 — Convergence
The original assay could not stay occupied through forced rotations. Permanent toxin input also made the toxin band unreachable.
Starting-data passes:
- `O1`, `O17`: producer `0→1`.
- `M0`: nutrient `0→1→2`, producer `0→1→2`, grazer `0→1`.
- `M1`, `M11`: producer `0→1`.
- `I1`, `I5`: producer `0→1`.
- `I4`: nutrient `0→1→2→3`, producer `0→1→2`; this second clockwise predecessor keeps `I0` occupied after a cross-ring move.
- Original `O6: 3 nutrient / 2 producer` remains unchanged.
- Move the required `O2` toxin inlet to the `I3` drain; keep `O2` starting toxin `2`.
`I0` deliberately starts empty, so the scenario does **not** begin inside its objective. The stored three-turn win rotates both inner and middle rings.
Numeric-range passes:
- producer floor `8→7→6→5→4`; ceiling `16→17→…→32`;
- grazer floor `3→2→1`; ceiling `7→8→9→10→11`;
- phage ceiling `3→4→5`;
- toxin ceiling `6→7→8`.
The sustained objective type is unchanged: `I0`, `M0`, and `O0` must all be occupied, population/toxin bands must hold, and the predicate must remain true for two consecutive turns. Heat sources, toxin inlet, drain, immune node, phage, and inherited gift-and-burden effects remain present.
## Solver evidence
`npm run solver:generate` deterministically stores:
- one winning and one losing route for every baseline scenario;
- a winning route for all **302** inheritance sets in a conservative campaign superset;
- a winning campaign route whose events prove adaptation benefit, cost, and spillover;
- a baseline route that avoids its matching adaptation;
- a route where changed gate alignment produces radial flow.
`npm run solver` replays every stored route and fails on mismatch. See `test/solver-fixtures.json` and `test/solver-fixtures.test.ts`.
+13
View File
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Adaptive Loop</title>
<link rel="stylesheet" href="./src/style.css" />
</head>
<body>
<div id="app"></div>
<script type="module" src="./src/main.ts"></script>
</body>
</html>
+1561
View File
File diff suppressed because it is too large. Load diff
+24
View File
@@ -0,0 +1,24 @@
{
"name": "adaptive-loop",
"version": "1.0.0",
"description": "Adaptive Loop — a calm deterministic microfluidic strategy puzzle (Agentic Labs one-prompt build).",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview --port 4173",
"test": "vitest run",
"test:watch": "vitest",
"solver": "vitest run test/solver-fixtures.test.ts test/campaign.test.ts",
"solver:generate": "node --experimental-strip-types src/solver/gen-fixtures.ts",
"e2e": "playwright test",
"typecheck": "tsc --noEmit",
"check": "npm run typecheck && npm run build && npm test && npm run e2e"
},
"devDependencies": {
"@playwright/test": "^1.58.2",
"typescript": "^5.6.3",
"vite": "^5.4.10",
"vitest": "^2.1.4"
}
}
+18
View File
@@ -0,0 +1,18 @@
import { defineConfig } from "@playwright/test";
export default defineConfig({
testDir: "./tests",
timeout: 60000,
retries: 0,
use: {
headless: true,
viewport: { width: 1280, height: 900 },
actionTimeout: 8000,
},
webServer: {
command: "npm run preview",
port: 4173,
reuseExistingServer: true,
timeout: 30000,
},
});
+106
View File
@@ -0,0 +1,106 @@
// Core helpers: clamp, clone, canonical serialization, equality, gate topology.
import type { Chamber, Direction, GameState, RingId } from "./types.ts";
import { RING_SIZES } from "./types.ts";
export const CAP = 6;
export const PRESSURE_CAP = 3;
export function clamp(n: number, lo: number, hi: number): number {
return n < lo ? lo : n > hi ? hi : n;
}
export function emptyChamber(): Chamber {
return { nutrient: 0, heat: 0, toxin: 0, producer: 0, grazer: 0, phage: 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 cloneState(s: GameState): GameState {
return {
schemaVersion: 1,
mode: s.mode,
scenarioId: s.scenarioId,
turn: s.turn,
rings: {
inner: { direction: s.rings.inner.direction, tiles: s.rings.inner.tiles.map(cloneChamber) },
middle: { direction: s.rings.middle.direction, tiles: s.rings.middle.tiles.map(cloneChamber) },
outer: { direction: s.rings.outer.direction, tiles: s.rings.outer.tiles.map(cloneChamber) },
},
lineage: {
producer: {
pressure: { ...s.lineage.producer.pressure },
unlocked: { ...s.lineage.producer.unlocked },
},
grazer: {
pressure: { ...s.lineage.grazer.pressure },
unlocked: { ...s.lineage.grazer.unlocked },
},
},
inheritedAtStart: {
producer: [...s.inheritedAtStart.producer],
grazer: [...s.inheritedAtStart.grazer],
},
consecutiveObjectiveTurns: s.consecutiveObjectiveTurns,
environmentActive: { ...s.environmentActive },
outcome: s.outcome,
actionLog: s.actionLog.map((a) => ({ ring: a.ring, dir: a.dir })),
};
}
/** Canonical recursive stable-key JSON serialization (state contains no transient fields). */
export function canonical(state: unknown): string {
return JSON.stringify(stable(state));
}
function stable(value: unknown): unknown {
if (Array.isArray(value)) return value.map(stable);
if (value && typeof value === "object") {
return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, child]) => [key, stable(child)]));
}
return value;
}
export function canonicalEqual(a: GameState, b: GameState): boolean {
return canonical(a) === canonical(b);
}
/** Next tile index in a ring's current direction. */
export function nextIndex(index: number, size: number, dir: Direction): number {
return dir === "cw" ? (index + 1) % size : (index + size - 1) % size;
}
/** Rotate an array of payloads by one position. cw: payload i -> (i+1)%size. */
export function rotatePayloads<T>(tiles: T[], dir: Direction): T[] {
const size = tiles.length;
const out = new Array<T>(size);
for (let i = 0; i < size; i++) {
const dest = dir === "cw" ? (i + 1) % size : (i + size - 1) % size;
out[dest] = tiles[i];
}
return out;
}
/** On-gate track index for a ring at gate g (0..5). inner=g, middle=2g, outer=3g. */
export function gateIndex(ring: RingId, g: number): number {
if (ring === "inner") return g;
if (ring === "middle") return (2 * g) % RING_SIZES.middle;
return (3 * g) % RING_SIZES.outer;
}
/** Is this track index on a gate? */
export function isOnGate(ring: RingId, index: number): boolean {
if (ring === "inner") return index >= 0 && index < 6;
if (ring === "middle") return index % 2 === 0 && index < RING_SIZES.middle;
return index % 3 === 0 && index < RING_SIZES.outer;
}
/** Which gate (0..5) is this on-gate tile on, or -1 if mid-arc. */
export function gateOf(ring: RingId, index: number): number {
if (ring === "inner") return index;
if (ring === "middle") return index % 2 === 0 ? index / 2 : -1;
return index % 3 === 0 ? index / 3 : -1;
}
+346
View File
@@ -0,0 +1,346 @@
// Immutable species/trait tables and declarative scenarios (SPEC §6, §8, §9).
import type {
GameState,
Lineage,
LineageId,
Mode,
PressureId,
RingId,
Scenario,
ScenarioStart,
} from "./types.ts";
import { LINEAGES, PRESSURES } from "./types.ts";
import { cloneChamber, emptyChamber } from "./core.ts";
import type { Chamber, ScenarioFixture } from "./types.ts";
function parseLabel(label: string): { ring: RingId; index: number } {
const ringChar = label[0];
const ring = ringChar === "I" ? "inner" : ringChar === "M" ? "middle" : "outer";
return { ring, index: parseInt(label.slice(1), 10) };
}
/** Build a start from a SPEC sparse line "I0: 3/2/0/0/0/0" = nutrient/producer/grazer/phage/heat/toxin. */
function start(label: string, n: number, prod: number, gr: number, ph: number, heat: number, tox: number): ScenarioStart {
return { ...parseLabel(label), chamber: { nutrient: n, producer: prod, grazer: gr, phage: ph, heat, toxin: tox } };
}
const SCENARIOS_RAW: Omit<Scenario, "sustained" | "win">[] = [
{
id: "s1-heat",
index: 1,
name: "Cultivation Quota",
subtitle: "Heat",
turnLimit: 8,
starts: [
start("O0", 3, 2, 0, 0, 0, 0),
start("O6", 3, 2, 0, 0, 0, 0),
start("M2", 2, 1, 0, 0, 0, 0),
start("I0", 1, 0, 0, 0, 0, 0),
],
fixtures: [
{ kind: "nutrientInlet", ...parseLabel("O0") },
{ kind: "nutrientInlet", ...parseLabel("O6") },
{ kind: "heatSource", ...parseLabel("O3") },
{ kind: "heatSource", ...parseLabel("O9") },
],
teaches: "Ring rotation, gate alignment, inward nutrient flow, growth, preview, and the first pressure: heat.",
},
{
id: "s2-hunger",
index: 2,
name: "Endurance",
subtitle: "Hunger",
turnLimit: 10,
starts: [
start("O0", 2, 3, 0, 0, 0, 0),
start("M2", 1, 2, 1, 0, 0, 0),
start("M8", 2, 3, 1, 0, 0, 0),
start("I4", 0, 2, 2, 0, 0, 0),
],
fixtures: [{ kind: "nutrientInlet", ...parseLabel("O0") }],
teaches: "Competition, migration through gates, dormancy, and denying predator food.",
},
{
id: "s3-toxin",
index: 3,
name: "Cleansing",
subtitle: "Toxin",
turnLimit: 9,
// TUNING: both toxin inlets were relocated onto the I1/I3 drain chambers so ongoing
// contamination remains present without outpacing the deterministic one-unit routing model.
starts: [
start("O0", 3, 3, 0, 0, 0, 0),
start("O3", 0, 0, 0, 0, 0, 3),
start("M4", 2, 3, 0, 0, 0, 0),
start("O9", 0, 0, 0, 0, 0, 3),
start("I5", 2, 2, 1, 0, 0, 0),
],
fixtures: [
{ kind: "nutrientInlet", ...parseLabel("O0") },
// TUNING: required toxin inlets relocated from O3/O9 to the drain chambers.
{ kind: "toxinInlet", ...parseLabel("I1") },
{ kind: "toxinInlet", ...parseLabel("I3") },
{ kind: "drain", ...parseLabel("I1") },
{ kind: "drain", ...parseLabel("I3") },
],
teaches: "Routing contaminants inward to drains, resistance payment, and shared detoxification spillover.",
},
{
id: "s4-immunity",
index: 4,
name: "Escort",
subtitle: "Immunity",
turnLimit: 8,
// TUNING: seeded the gate-0 spoke (M0) and the sanctuary (I0) so grazers can actually
// reach I0 within 8 turns under the 1-unit/phase migration model. Original starts left all
// grazers off the gate-0 path (max reachable grazer at I0 was 0). Teaching intent preserved.
starts: [
start("M2", 2, 3, 0, 0, 0, 0),
start("M8", 2, 3, 2, 0, 0, 0),
start("M0", 3, 3, 1, 0, 0, 0),
start("I0", 0, 2, 1, 0, 0, 0),
// TUNING passes 3–4: seed I5 by +1 twice so clockwise entry can escort a viable grazer cohort.
start("I5", 2, 2, 2, 0, 0, 0),
start("O5", 0, 0, 0, 1, 0, 0),
start("O11", 1, 0, 2, 1, 0, 0),
],
fixtures: [
{ kind: "nutrientInlet", ...parseLabel("O0") },
{ kind: "nutrientInlet", ...parseLabel("O2") },
{ kind: "immuneNode", ...parseLabel("I1") },
{ kind: "immuneNode", ...parseLabel("I3") },
{ kind: "objective", ...parseLabel("I0"), label: "sanctuary" },
],
teaches: "Immune targeting, cloak, retargeting spillover, and predator vulnerability.",
},
{
id: "s5-convergence",
index: 5,
name: "Stable Equilibrium",
subtitle: "Convergence",
turnLimit: 12,
// TUNING: seeded the gate-0 assay spoke (I0, M0) so the sustained predicate's assay
// condition (I0/M0/O0 each occupied) is reachable. Under the 1-unit/phase migration model
// organisms could not reach I0/M0, so sustained was never satisfiable. Pressures (heat,
// toxin inlet, immune node) still force active management of the population/toxin ranges.
// See TUNING.md.
// TUNING: seeded the gate-0 assay spoke AND its rotational neighbors (I1/I5, M1/M11, O1/O17)
// so a single ring rotation keeps the spoke occupied (the cw/ccw neighbor rotates in). Under
// the 1-unit/phase migration model organisms could not reach I0/M0 and a bare spoke emptied on
// the first rotation, so sustained-for-2-consecutive-turns was unprovable. Heat sources, toxin,
// immune node, and phage keep all systems present. See TUNING.md.
starts: [
start("O0", 3, 3, 0, 0, 0, 0),
start("O6", 3, 2, 0, 0, 0, 0),
start("O1", 0, 1, 0, 0, 0, 0),
start("O17", 0, 1, 0, 0, 0, 0),
start("O2", 0, 0, 0, 0, 0, 2),
start("O8", 0, 0, 0, 0, 2, 0),
start("M0", 2, 2, 1, 0, 0, 0),
start("M1", 0, 1, 0, 0, 0, 0),
start("M11", 0, 1, 0, 0, 0, 0),
start("M2", 2, 2, 1, 0, 0, 0),
start("M8", 2, 2, 2, 1, 0, 0),
start("I1", 0, 1, 0, 0, 0, 0),
start("I3", 0, 0, 0, 0, 0, 1),
// TUNING: second clockwise predecessor keeps I0 occupied after a cross-ring alignment move.
start("I4", 3, 2, 0, 0, 0, 0),
start("I5", 0, 1, 0, 0, 0, 0),
],
fixtures: [
{ kind: "nutrientInlet", ...parseLabel("O0") },
{ kind: "nutrientInlet", ...parseLabel("O6") },
{ kind: "heatSource", ...parseLabel("O3") },
{ kind: "heatSource", ...parseLabel("O9") },
// TUNING: required O2 toxin inlet relocated onto the I3 drain chamber.
{ kind: "toxinInlet", ...parseLabel("I3") },
{ kind: "drain", ...parseLabel("I3") },
{ kind: "immuneNode", ...parseLabel("I2") },
{ kind: "objective", ...parseLabel("I0"), label: "assay" },
{ kind: "objective", ...parseLabel("M0"), label: "assay" },
{ kind: "objective", ...parseLabel("O0"), label: "assay" },
],
teaches: "All systems plus inherited gift-and-burden consequences.",
},
];
function freshLineage(inherited: PressureId[]): Lineage {
const pressure = { heat: 0, hunger: 0, toxin: 0, immunity: 0 } as Record<PressureId, number>;
const unlocked = { heat: false, hunger: false, toxin: false, immunity: false } as Record<PressureId, boolean>;
for (const p of inherited) unlocked[p] = true;
return { pressure, unlocked };
}
export function buildInitialState(
scenario: Scenario,
mode: Mode,
inherited: Record<LineageId, PressureId[]> = { producer: [], grazer: [] },
): GameState {
const rings = {
inner: { direction: "cw" as const, tiles: Array.from({ length: 6 }, () => emptyChamber()) },
middle: { direction: "cw" as const, tiles: Array.from({ length: 12 }, () => emptyChamber()) },
outer: { direction: "cw" as const, tiles: Array.from({ length: 18 }, () => emptyChamber()) },
};
for (const s of scenario.starts) {
const base = rings[s.ring].tiles[s.index];
rings[s.ring].tiles[s.index] = { ...cloneChamber(base), ...s.chamber };
}
return {
schemaVersion: 1,
mode,
scenarioId: scenario.id,
turn: 0,
rings,
lineage: {
producer: freshLineage(inherited.producer),
grazer: freshLineage(inherited.grazer),
},
inheritedAtStart: { producer: [...inherited.producer], grazer: [...inherited.grazer] },
consecutiveObjectiveTurns: 0,
environmentActive: { heat: false, hunger: false, toxin: false, immunity: false },
outcome: "playing",
actionLog: [],
};
}
// ---- Win / sustained predicates ----
function tile(state: GameState, label: string) {
const { ring, index } = parseLabel(label);
return state.rings[ring].tiles[index];
}
function totalProducer(s: GameState): number {
let n = 0;
for (const r of ["inner", "middle", "outer"] as RingId[]) for (const t of s.rings[r].tiles) n += t.producer;
return n;
}
function totalGrazer(s: GameState): number {
let n = 0;
for (const r of ["inner", "middle", "outer"] as RingId[]) for (const t of s.rings[r].tiles) n += t.grazer;
return n;
}
function totalPhage(s: GameState): number {
let n = 0;
for (const r of ["inner", "middle", "outer"] as RingId[]) for (const t of s.rings[r].tiles) n += t.phage;
return n;
}
function totalToxin(s: GameState): number {
let n = 0;
for (const r of ["inner", "middle", "outer"] as RingId[]) for (const t of s.rings[r].tiles) n += t.toxin;
return n;
}
function occupiedTiles(s: GameState, field: "producer" | "grazer"): number {
let n = 0;
for (const r of ["inner", "middle", "outer"] as RingId[]) for (const t of s.rings[r].tiles) if (t[field] > 0) n++;
return n;
}
export const SCENARIOS: Scenario[] = SCENARIOS_RAW.map((raw) => {
const base: Scenario = {
...raw,
sustained: () => false,
win: () => false,
};
if (raw.id === "s1-heat") {
base.win = ({ state }) => tile(state, "I0").producer >= 4 && totalProducer(state) >= 12;
} else if (raw.id === "s2-hunger") {
base.win = ({ state, resolvedTurn }) =>
resolvedTurn === 10 &&
totalProducer(state) >= 8 &&
totalGrazer(state) >= 4 &&
occupiedTiles(state, "producer") >= 3 &&
occupiedTiles(state, "grazer") >= 2;
} else if (raw.id === "s3-toxin") {
base.win = ({ state, resolvedTurn }) =>
resolvedTurn >= 6 &&
resolvedTurn <= 9 &&
// TUNING: with required ongoing toxin inlets relocated onto drains, the bounded solver
// first finds a route at ceiling 8 across turns 6–9. See TUNING.md.
totalToxin(state) <= 8 &&
totalProducer(state) + totalGrazer(state) >= 8;
} else if (raw.id === "s4-immunity") {
base.win = ({ state }) => tile(state, "I0").grazer >= 4 && totalProducer(state) >= 6;
} else if (raw.id === "s5-convergence") {
base.sustained = (state) => {
const i0 = tile(state, "I0"), m0 = tile(state, "M0"), o0 = tile(state, "O0");
// TUNING: seeded the spoke and its clockwise predecessors so all three assay tiles can
// remain occupied for two turns; the original all-three assay objective type is preserved.
const assayOk = [i0, m0, o0].every((chamber) => chamber.producer + chamber.grazer >= 1);
const tp = totalProducer(state);
const tg = totalGrazer(state);
// TUNING: ranges widened. The seeded ecosystem is volatile under predation (producers crash
// fast), so the original tight bands (prod 8-16, graz 3-7) could not hold for 2 turns.
// TUNING: ranges widened. Producers crash fast under predation (low floor) but OVERGROW when
// an inherited Dormancy makes them inedible (high ceiling), so the band is wide. The
// verified win completes within 2 turns before either extreme is reached.
return assayOk && tp >= 4 && tp <= 32 && tg >= 1 && tg <= 11 && totalPhage(state) <= 5 && totalToxin(state) <= 8;
};
base.win = ({ resolvedTurn, consecutive }) => consecutive >= 2 && resolvedTurn <= 12;
}
return base;
});
export function getScenario(id: string): Scenario {
const s = SCENARIOS.find((x) => x.id === id) ?? TEST_SCENARIOS[id];
if (!s) throw new Error(`Unknown scenario: ${id}`);
return s;
}
/** Test-only scenarios (no fixtures unless specified) for literal behavior tests. */
export const TEST_SCENARIOS: Record<string, Scenario> = {
test: { id: "test", index: 0, name: "Test", subtitle: "", turnLimit: 99, starts: [], fixtures: [], sustained: () => false, win: () => false, teaches: "" },
};
/** Build a state for tests: custom tile chambers, lineage unlocks, fixtures (via a test scenario id). */
export function buildTestState(
opts: {
tiles?: { ring: RingId; index: number; chamber: Partial<Chamber> }[];
unlocked?: Record<LineageId, PressureId[]>;
environmentActive?: PressureId[];
scenarioId?: string;
fixtures?: ScenarioFixture[];
turnLimit?: number;
win?: (ctx: import("./types.ts").ScenarioWinCtx) => boolean;
sustained?: (state: GameState, ctx: import("./types.ts").ScenarioWinCtx) => boolean;
} = {},
): GameState {
const sid = opts.scenarioId ?? "test";
TEST_SCENARIOS[sid] = {
id: sid,
index: 0,
name: "Test",
subtitle: "",
turnLimit: opts.turnLimit ?? 99,
starts: [],
fixtures: opts.fixtures ?? [],
sustained: opts.sustained ?? (() => false),
win: opts.win ?? (() => false),
teaches: "",
};
const scenario = TEST_SCENARIOS[sid];
const st = buildInitialState(scenario, "campaign", {
producer: opts.unlocked?.producer ?? [],
grazer: opts.unlocked?.grazer ?? [],
});
st.scenarioId = sid;
for (const t of opts.tiles ?? []) {
st.rings[t.ring].tiles[t.index] = { ...st.rings[t.ring].tiles[t.index], ...t.chamber };
}
if (opts.environmentActive) for (const p of opts.environmentActive) st.environmentActive[p] = true;
return st;
}
/** Fixtures indexed by tile for a scenario. */
export function fixturesByTile(scenario: Scenario): Map<string, { kind: string; label?: string }[]> {
const m = new Map<string, { kind: string; label?: string }[]>();
for (const f of scenario.fixtures) {
const key = `${f.ring}:${f.index}`;
if (!m.has(key)) m.set(key, []);
m.get(key)!.push({ kind: f.kind, label: f.label });
}
return m;
}
export { parseLabel };
export { totalProducer, totalGrazer, totalPhage, totalToxin, occupiedTiles };
+127
View File
@@ -0,0 +1,127 @@
// Bounded deterministic solver (SPEC §9, Gate 4). Pure search, no randomness.
import type { GameState, LineageId, Mode, PressureId, RotationAction, Scenario } from "./types.ts";
import { nextState } from "./transition.ts";
import { buildInitialState } from "./scenarios.ts";
import { canonical } from "./core.ts";
/** Collision-free canonical position key. Action history is excluded because it does not affect future transitions. */
export function hashState(state: GameState): string {
const { actionLog: _actionLog, ...position } = state;
return canonical(position);
}
const ACTIONS: RotationAction[] = [
{ ring: "inner", dir: "cw" },
{ ring: "inner", dir: "ccw" },
{ ring: "middle", dir: "cw" },
{ ring: "middle", dir: "ccw" },
{ ring: "outer", dir: "cw" },
{ ring: "outer", dir: "ccw" },
];
export type Inherited = Record<LineageId, PressureId[]>;
/** DFS for a winning action sequence within the scenario turn limit. Returns null if none
* found within the node/time budget. */
export function solveWin(
scenario: Scenario,
inherited: Inherited = { producer: [], grazer: [] },
opts: { nodeBudget?: number; timeMs?: number } = {},
): RotationAction[] | null {
const start = buildInitialState(scenario, "campaign", inherited);
const visited = new Set<string>();
const path: RotationAction[] = [];
let nodes = 0;
const nodeBudget = opts.nodeBudget ?? 3_000_000;
let timedOut = false;
function dfs(state: GameState): RotationAction[] | null {
if (state.outcome !== "playing") return null;
nodes++;
if (nodes > nodeBudget) { timedOut = true; return null; }
const pk = hashState(state);
if (visited.has(pk)) return null;
visited.add(pk);
for (const a of ACTIONS) {
path.push(a);
const nx = nextState(state, a);
if (nx.outcome === "won") return [...path];
if (nx.outcome === "playing") {
const r = dfs(nx);
if (r) return r;
}
path.pop();
}
return null;
}
const result = dfs(start);
lastWinTimedOut = timedOut;
return result;
}
/** True if the most recent solveWin hit its time/node budget (inconclusive), false if it exhausted the space. */
export let lastWinTimedOut = false;
/** DFS for any losing terminal (collapse or expiry). */
export function solveLoss(scenario: Scenario, inherited: Inherited = { producer: [], grazer: [] }): RotationAction[] | null {
const start = buildInitialState(scenario, "campaign", inherited);
const visited = new Set<string>();
const path: RotationAction[] = [];
let nodes = 0;
const nodeBudget = 2_000_000;
function dfs(state: GameState): RotationAction[] | null {
nodes++;
if (nodes > nodeBudget) return null;
const pk = hashState(state);
if (visited.has(pk)) return null;
visited.add(pk);
for (const a of ACTIONS) {
path.push(a);
const nx = nextState(state, a);
if (nx.outcome === "collapsed" || nx.outcome === "expired") return [...path];
if (nx.outcome === "playing") {
const r = dfs(nx);
if (r) return r;
}
path.pop();
}
return null;
}
return dfs(start);
}
/**
* Enumerate a conservative superset of campaign inheritance sets at scenario entry.
* After N prior scenarios the campaign can preserve at most N distinct trait slots.
* Proving every subset of the eight lineage/pressure slots up to that size is stronger
* than proving only the route-dependent reachable subset.
*/
export function reachableInheritanceAt(scenarioIndex: number): Inherited[] {
const maxTraits = Math.max(0, Math.min(4, scenarioIndex - 1));
const slots = (["producer", "grazer"] as LineageId[]).flatMap((lineage) =>
(["heat", "hunger", "toxin", "immunity"] as PressureId[]).map((pressure) => ({ lineage, pressure })),
);
const out: Inherited[] = [];
function visit(index: number, chosen: typeof slots): void {
const inherited: Inherited = { producer: [], grazer: [] };
for (const { lineage, pressure } of chosen) inherited[lineage].push(pressure);
out.push(inherited);
if (chosen.length === maxTraits) return;
for (let i = index; i < slots.length; i++) visit(i + 1, [...chosen, slots[i]]);
}
visit(0, []);
return out;
}
export function inheritanceKey(inherited: Inherited): string {
return `P:${inherited.producer.join(",")}|G:${inherited.grazer.join(",")}`;
}
export function replay(scenario: Scenario, inherited: Inherited, actions: RotationAction[], mode: Mode = "campaign"): GameState {
let state = buildInitialState(scenario, mode, inherited);
for (const action of actions) state = nextState(state, action);
return state;
}
+508
View File
@@ -0,0 +1,508 @@
// The single pure transition: nextState(state, action). SPEC §7 pipeline.
// Preview and commit both call resolve() on a clone. Input is never mutated.
import type {
Chamber,
FixtureKind,
GameState,
LineageId,
PressureId,
RingId,
RotationAction,
Scenario,
} from "./types.ts";
import { CAP, clamp, cloneState, gateIndex, gateOf, nextIndex, rotatePayloads } from "./core.ts";
import { getScenario } from "./scenarios.ts";
export type GameEvent =
| { phase: "rotate"; ring: RingId; dir: string }
| { phase: "flow"; ring: RingId; index: number; field: "nutrient" | "toxin"; delta: number; tangential: number; radial: number }
| { phase: "growth"; ring: RingId; index: number; gained: number; suppressed: boolean }
| { phase: "feed"; ring: RingId; index: number; predator: "grazer" | "phage"; preyRemoved: number; gained: boolean; suppressed?: boolean; phageStarve?: boolean }
| { phase: "migrate"; from: string; to: string; species: "producer" | "grazer" | "phage" }
| { phase: "overflow"; ring: RingId; index: number; field: keyof Chamber; amount: number }
| { phase: "evolution"; lineage: LineageId; pressure: PressureId; unlocked: boolean }
| { phase: "env"; pressure: PressureId; active: boolean }
| { phase: "fixture"; ring: RingId; index: number; kind: FixtureKind; field: string; delta: number }
| { phase: "fixtureGlobal"; field: "heat"; delta: number }
| { phase: "immuneSelect"; ring: RingId; index: number; lineage: LineageId; damage: number; retarget: boolean }
| { phase: "pressureInc"; lineage: LineageId; pressure: PressureId; to: number }
| { phase: "consequence"; ring: RingId; index: number; lineage: LineageId; pressure: PressureId; kind: "loss" | "prevented" | "payNutrient" | "payPop"; amount: number }
| { phase: "spillover"; ring: RingId; index: number; pressure: PressureId; field: "heat" | "toxin"; reduced: number }
| { phase: "adaptation"; ring: RingId; index: number; lineage: LineageId; pressure: PressureId; effect: "cost" | "spillover" }
| { phase: "outcome"; outcome: GameState["outcome"]; turn: number };
export type ResolveResult = { state: GameState; events: GameEvent[] };
const RING_ORDER: RingId[] = ["outer", "middle", "inner"];
const NOPE: GameEvent[] = []; // sentinel reused when events are not collected
function foodForTile(tile: Chamber, species: "producer" | "grazer" | "phage"): number {
if (species === "producer") return tile.nutrient;
if (species === "grazer") return tile.producer;
return tile.grazer;
}
function fixturesFor(scenario: Scenario): (ring: RingId, index: number) => FixtureKind[] {
const m = new Map<string, FixtureKind[]>();
for (const f of scenario.fixtures) {
const key = `${f.ring}:${f.index}`;
if (!m.has(key)) m.set(key, []);
m.get(key)!.push(f.kind);
}
return (ring: RingId, index: number) => m.get(`${ring}:${index}`) ?? EMPTY;
}
const EMPTY: FixtureKind[] = [];
export function resolve(state: GameState, action: RotationAction, collectEvents = true): ResolveResult {
if (state.outcome !== "playing") return { state: cloneState(state), events: [] };
const scenario = getScenario(state.scenarioId);
const w = cloneState(state);
const events: GameEvent[] = collectEvents ? [] : NOPE;
const push = (e: GameEvent) => { if (collectEvents) events.push(e); };
const fixturesAt = fixturesFor(scenario);
// ---- Phase 1: Rotate ----
w.rings[action.ring].tiles = rotatePayloads(w.rings[action.ring].tiles, action.dir);
w.rings[action.ring].direction = action.dir;
push({ phase: "rotate", ring: action.ring, dir: action.dir });
// ---- Phase 2: Channel flow (nutrient + toxin) ----
for (const field of ["nutrient", "toxin"] as const) {
const snap: Record<RingId, number[]> = {
inner: w.rings.inner.tiles.map((t) => t[field]),
middle: w.rings.middle.tiles.map((t) => t[field]),
outer: w.rings.outer.tiles.map((t) => t[field]),
};
const sent: Record<RingId, number[]> = { inner: [0, 0, 0, 0, 0, 0], middle: arr(12), outer: arr(18) };
const recv: Record<RingId, number[]> = { inner: [0, 0, 0, 0, 0, 0], middle: arr(12), outer: arr(18) };
const sentTan: Record<RingId, number[]> = { inner: [0, 0, 0, 0, 0, 0], middle: arr(12), outer: arr(18) };
// tangential
for (const r of RING_ORDER) {
const size = snap[r].length;
const dir = w.rings[r].direction;
for (let i = 0; i < size; i++) {
if (snap[r][i] >= 1) {
const j = nextIndex(i, size, dir);
sent[r][i] += 1;
sentTan[r][i] += 1;
recv[r][j] += 1;
}
}
}
// radial inward through gates
for (let g = 0; g < 6; g++) {
const oi = gateIndex("outer", g);
const mi = gateIndex("middle", g);
const ii = gateIndex("inner", g);
if (snap.outer[oi] >= 1) {
sent.outer[oi] += 1;
recv.middle[mi] += 1;
}
if (snap.middle[mi] >= 1) {
sent.middle[mi] += 1;
recv.inner[ii] += 1;
}
}
// commit
for (const r of RING_ORDER) {
for (let i = 0; i < snap[r].length; i++) {
const start = snap[r][i];
const raw = start - sent[r][i] + recv[r][i];
const nv = clamp(raw, 0, CAP);
w.rings[r].tiles[i][field] = nv;
if (sent[r][i] || recv[r][i]) {
push({ phase: "flow", ring: r, index: i, field, delta: nv - start, tangential: sentTan[r][i], radial: sent[r][i] - sentTan[r][i] });
}
if (raw > CAP) push({ phase: "overflow", ring: r, index: i, field, amount: raw - CAP });
}
}
}
// ---- Phase 3: Producer growth ----
for (const r of RING_ORDER) {
for (let i = 0; i < w.rings[r].tiles.length; i++) {
const t = w.rings[r].tiles[i];
if (t.producer >= 1 && t.nutrient >= 1) {
const heatSuppress = w.lineage.producer.unlocked.heat && t.heat >= 2;
t.nutrient -= 1;
const before = t.producer;
if (!heatSuppress) t.producer = clamp(t.producer + 1, 0, CAP);
push({ phase: "growth", ring: r, index: i, gained: t.producer - before, suppressed: heatSuppress });
if (!heatSuppress && before === CAP) push({ phase: "overflow", ring: r, index: i, field: "producer", amount: 1 });
}
}
}
// ---- Phase 4: Biological interactions ----
// Grazer subphase
{
const snapProd = snapField(w, "producer");
const snapGrazer = snapField(w, "grazer");
for (const r of RING_ORDER) {
for (let i = 0; i < w.rings[r].tiles.length; i++) {
const t = w.rings[r].tiles[i];
if (snapGrazer[r][i] >= 1) {
const dormantProd = w.lineage.producer.unlocked.hunger && t.nutrient === 0;
const edible = snapProd[r][i] >= 1 && !dormantProd;
if (snapProd[r][i] >= 1 && dormantProd) push({ phase: "adaptation", ring: r, index: i, lineage: "producer", pressure: "hunger", effect: "spillover" });
const heatSuppressFeed = w.lineage.grazer.unlocked.heat && t.heat >= 2;
if (edible) {
const onImmune = fixturesAt(r, i).includes("immuneNode");
const cloaked = w.lineage.producer.unlocked.immunity && onImmune;
const remove = Math.min(cloaked ? 2 : 1, t.producer);
t.producer = clamp(t.producer - remove, 0, CAP);
const before = t.grazer;
if (!heatSuppressFeed) t.grazer = clamp(t.grazer + 1, 0, CAP);
push({ phase: "feed", ring: r, index: i, predator: "grazer", preyRemoved: remove, gained: t.grazer > before, suppressed: heatSuppressFeed });
if (!heatSuppressFeed && before === CAP) push({ phase: "overflow", ring: r, index: i, field: "grazer", amount: 1 });
}
}
}
}
}
// Phage subphase
{
const snapGrazer = snapField(w, "grazer");
const snapPhage = snapField(w, "phage");
for (const r of RING_ORDER) {
for (let i = 0; i < w.rings[r].tiles.length; i++) {
const t = w.rings[r].tiles[i];
if (snapPhage[r][i] >= 1) {
const dormantGraz = w.lineage.grazer.unlocked.hunger && t.producer === 0;
const edible = snapGrazer[r][i] >= 1 && !dormantGraz;
if (snapGrazer[r][i] >= 1 && dormantGraz) push({ phase: "adaptation", ring: r, index: i, lineage: "grazer", pressure: "hunger", effect: "spillover" });
if (edible) {
const onImmune = fixturesAt(r, i).includes("immuneNode");
const cloaked = w.lineage.grazer.unlocked.immunity && onImmune;
const remove = Math.min(cloaked ? 2 : 1, t.grazer);
t.grazer = clamp(t.grazer - remove, 0, CAP);
const before = t.phage;
t.phage = clamp(t.phage + 1, 0, CAP);
push({ phase: "feed", ring: r, index: i, predator: "phage", preyRemoved: remove, gained: t.phage > before });
if (before === CAP) push({ phase: "overflow", ring: r, index: i, field: "phage", amount: 1 });
} else {
t.phage = clamp(t.phage - 1, 0, CAP);
push({ phase: "feed", ring: r, index: i, predator: "phage", preyRemoved: 0, gained: false, phageStarve: true });
}
}
}
}
}
// ---- Phase 5: Migration ----
for (const species of ["producer", "grazer", "phage"] as const) {
const snapSp = snapField(w, species);
const movers: { from: RingId; fi: number; toRing: RingId; toIndex: number }[] = [];
for (const r of RING_ORDER) {
const size = w.rings[r].tiles.length;
const dir = w.rings[r].direction;
for (let i = 0; i < size; i++) {
if (snapSp[r][i] < 2) continue;
const lin = species === "producer" ? w.lineage.producer : species === "grazer" ? w.lineage.grazer : null;
const food = foodForTile(w.rings[r].tiles[i], species);
const dormant = lin ? lin.unlocked.hunger && food === 0 : false;
// candidate neighbors: tangential (one step in ring direction), then radial through a
// gate to the ADJACENT ring only (SPEC §7.5: outer<->middle, middle<->inner; never outer<->inner).
const cands: { ring: RingId; index: number }[] = [];
cands.push({ ring: r, index: nextIndex(i, size, dir) });
const g = gateOf(r, i);
if (g >= 0) {
const radialRings: RingId[] = r === "inner" ? ["middle"] : r === "outer" ? ["middle"] : ["inner", "outer"];
for (const rr of radialRings) cands.push({ ring: rr, index: gateIndex(rr, g) });
}
if (dormant) {
if (cands.some((candidate) => foodForTile(w.rings[candidate.ring].tiles[candidate.index], species) > food)) {
push({ phase: "adaptation", ring: r, index: i, lineage: species as LineageId, pressure: "hunger", effect: "cost" });
}
continue;
}
let best: { ring: RingId; index: number; food: number } | null = null;
for (const c of cands) {
const cf = foodForTile(w.rings[c.ring].tiles[c.index], species);
if (cf > food) {
if (!best || cf > best.food) best = { ring: c.ring, index: c.index, food: cf };
}
}
if (best) movers.push({ from: r, fi: i, toRing: best.ring, toIndex: best.index });
}
}
// commit aggregate SIMULTANEOUSLY per tile: clamp(start - sent + sum(received), 0, CAP) (SPEC §7.5)
const delta: Record<string, number> = {};
const keyOf = (ring: RingId, i: number) => `${ring}:${i}`;
for (const m of movers) {
delta[keyOf(m.from, m.fi)] = (delta[keyOf(m.from, m.fi)] ?? 0) - 1;
delta[keyOf(m.toRing, m.toIndex)] = (delta[keyOf(m.toRing, m.toIndex)] ?? 0) + 1;
push({ phase: "migrate", from: keyOf(m.from, m.fi), to: keyOf(m.toRing, m.toIndex), species });
}
for (const [k, d] of Object.entries(delta)) {
const [ring, iStr] = k.split(":");
const r = ring as RingId;
const i = +iStr;
const t = w.rings[r].tiles[i];
const raw = t[species] + d;
t[species] = clamp(raw, 0, CAP);
if (raw > CAP) push({ phase: "overflow", ring: r, index: i, field: species, amount: raw - CAP });
}
}
// ---- Phase 6: Evolution & environmental response activation ----
for (const lin of ["producer", "grazer"] as LineageId[]) {
for (const p of ["heat", "hunger", "toxin", "immunity"] as PressureId[]) {
if (w.lineage[lin].pressure[p] >= 3 && !w.lineage[lin].unlocked[p]) {
w.lineage[lin].unlocked[p] = true;
push({ phase: "evolution", lineage: lin, pressure: p, unlocked: true });
}
}
}
for (const p of ["heat", "hunger", "toxin", "immunity"] as PressureId[]) {
const active = w.lineage.producer.pressure[p] >= 3 || w.lineage.grazer.pressure[p] >= 3;
if (active && !w.environmentActive[p]) {
w.environmentActive[p] = true;
push({ phase: "env", pressure: p, active: true });
}
}
// ---- Phase 7: Fixtures, exposure, pressure consequences ----
// (a) fixtures in SPEC order: nutrient, heat, cooldown, toxin, drains.
for (const r of RING_ORDER) for (let i = 0; i < w.rings[r].tiles.length; i++) {
if (!fixturesAt(r, i).includes("nutrientInlet")) continue;
const tile = w.rings[r].tiles[i];
const add = w.environmentActive.hunger ? 1 : 2;
const before = tile.nutrient;
tile.nutrient = clamp(before + add, 0, CAP);
if (tile.nutrient !== before) push({ phase: "fixture", ring: r, index: i, kind: "nutrientInlet", field: "nutrient", delta: tile.nutrient - before });
if (before + add > CAP) push({ phase: "overflow", ring: r, index: i, field: "nutrient", amount: before + add - CAP });
}
for (const r of RING_ORDER) for (let i = 0; i < w.rings[r].tiles.length; i++) {
if (!fixturesAt(r, i).includes("heatSource")) continue;
const tile = w.rings[r].tiles[i];
const add = w.environmentActive.heat ? 3 : 2;
const before = tile.heat;
tile.heat = clamp(before + add, 0, CAP);
if (tile.heat !== before) push({ phase: "fixture", ring: r, index: i, kind: "heatSource", field: "heat", delta: tile.heat - before });
if (before + add > CAP) push({ phase: "overflow", ring: r, index: i, field: "heat", amount: before + add - CAP });
}
for (const r of RING_ORDER) for (let i = 0; i < w.rings[r].tiles.length; i++) {
const tile = w.rings[r].tiles[i];
if (tile.heat > 0) {
tile.heat -= 1;
push({ phase: "fixtureGlobal", field: "heat", delta: -1 });
}
}
for (const r of RING_ORDER) for (let i = 0; i < w.rings[r].tiles.length; i++) {
if (!fixturesAt(r, i).includes("toxinInlet")) continue;
const tile = w.rings[r].tiles[i];
const add = w.environmentActive.toxin ? 3 : 2;
const before = tile.toxin;
tile.toxin = clamp(before + add, 0, CAP);
if (tile.toxin !== before) push({ phase: "fixture", ring: r, index: i, kind: "toxinInlet", field: "toxin", delta: tile.toxin - before });
if (before + add > CAP) push({ phase: "overflow", ring: r, index: i, field: "toxin", amount: before + add - CAP });
}
for (const r of RING_ORDER) for (let i = 0; i < w.rings[r].tiles.length; i++) {
if (!fixturesAt(r, i).includes("drain")) continue;
const tile = w.rings[r].tiles[i];
const before = tile.toxin;
tile.toxin = clamp(before - 2, 0, CAP);
if (tile.toxin !== before) push({ phase: "fixture", ring: r, index: i, kind: "drain", field: "toxin", delta: tile.toxin - before });
}
// (b) immunity algorithm: select target per immune node
const immuneSchedule: { ring: RingId; index: number; lineage: LineageId; damage: number }[] = [];
for (const r of RING_ORDER) {
for (let i = 0; i < w.rings[r].tiles.length; i++) {
if (!fixturesAt(r, i).includes("immuneNode")) continue;
const t = w.rings[r].tiles[i];
const all: { lin: LineageId; pop: number; cloaked: boolean }[] = [];
if (t.producer >= 1) all.push({ lin: "producer", pop: t.producer, cloaked: w.lineage.producer.unlocked.immunity });
if (t.grazer >= 1) all.push({ lin: "grazer", pop: t.grazer, cloaked: w.lineage.grazer.unlocked.immunity });
const rank = <T extends { lin: LineageId; pop: number }>(a: T, b: T) => (b.pop - a.pop) || (a.lin === "producer" ? -1 : 1);
all.sort(rank);
const candidates = all.filter((candidate) => !candidate.cloaked).sort(rank);
if (candidates.length === 0) continue;
const chosen = candidates[0].lin;
const damage = w.environmentActive.immunity ? 3 : 2;
immuneSchedule.push({ ring: r, index: i, lineage: chosen, damage });
push({ phase: "immuneSelect", ring: r, index: i, lineage: chosen, damage, retarget: all[0].cloaked && all[0].lin !== chosen });
}
}
// (c) snapshot qualification + occupied
const qualify: Record<LineageId, Record<PressureId, Set<string>>> = {
producer: { heat: new Set(), hunger: new Set(), toxin: new Set(), immunity: new Set() },
grazer: { heat: new Set(), hunger: new Set(), toxin: new Set(), immunity: new Set() },
};
for (const r of RING_ORDER) {
for (let i = 0; i < w.rings[r].tiles.length; i++) {
const t = w.rings[r].tiles[i];
const key = `${r}:${i}`;
if (t.producer >= 1) {
if (t.heat >= 2) qualify.producer.heat.add(key);
if (t.nutrient === 0) qualify.producer.hunger.add(key);
if (t.toxin >= 2) qualify.producer.toxin.add(key);
}
if (t.grazer >= 1) {
if (t.heat >= 2) qualify.grazer.heat.add(key);
if (t.producer === 0) qualify.grazer.hunger.add(key);
if (t.toxin >= 2) qualify.grazer.toxin.add(key);
}
}
}
for (const s of immuneSchedule) {
qualify[s.lineage].immunity.add(`${s.ring}:${s.index}`);
}
// (d) increment pressure tracks
for (const lin of ["producer", "grazer"] as LineageId[]) {
for (const p of ["heat", "hunger", "toxin", "immunity"] as PressureId[]) {
if (qualify[lin][p].size >= 1) {
const before = w.lineage[lin].pressure[p];
w.lineage[lin].pressure[p] = Math.min(3, before + 1);
if (w.lineage[lin].pressure[p] !== before) {
push({ phase: "pressureInc", lineage: lin, pressure: p, to: w.lineage[lin].pressure[p] });
}
}
}
}
// (e) consequences: heat, hunger, toxin, immunity
// HEAT (producer then grazer, then spillover)
for (const lin of ["producer", "grazer"] as LineageId[]) {
for (const key of qualify[lin].heat) {
const [r, iStr] = key.split(":");
const i = +iStr;
const t = w.rings[r as RingId].tiles[i];
const popField = lin === "producer" ? "producer" : "grazer";
if (t[popField] <= 0) continue;
if (w.lineage[lin].unlocked.heat) {
push({ phase: "consequence", ring: r as RingId, index: i, lineage: lin, pressure: "heat", kind: "prevented", amount: 0 });
} else {
const before = t[popField];
t[popField] = clamp(t[popField] - 2, 0, CAP);
push({ phase: "consequence", ring: r as RingId, index: i, lineage: lin, pressure: "heat", kind: "loss", amount: before - t[popField] });
}
}
}
// heat spillover: reduce local heat by 1 per adapted surviving lineage, max 2
for (const key of unionKeys([qualify.producer.heat, qualify.grazer.heat])) {
const [r, iStr] = key.split(":");
const r2 = r as RingId;
const i = +iStr;
const t = w.rings[r2].tiles[i];
let count = 0;
if (w.lineage.producer.unlocked.heat && t.producer > 0) count++;
if (w.lineage.grazer.unlocked.heat && t.grazer > 0) count++;
const reduce = Math.min(2, count);
if (reduce > 0 && t.heat > 0) {
const before = t.heat;
t.heat = clamp(t.heat - reduce, 0, CAP);
push({ phase: "spillover", ring: r2, index: i, pressure: "heat", field: "heat", reduced: before - t.heat });
}
}
// HUNGER
for (const lin of ["producer", "grazer"] as LineageId[]) {
for (const key of qualify[lin].hunger) {
const [r, iStr] = key.split(":");
const i = +iStr;
const t = w.rings[r as RingId].tiles[i];
const popField = lin === "producer" ? "producer" : "grazer";
if (t[popField] <= 0) continue;
if (w.lineage[lin].unlocked.hunger) {
push({ phase: "consequence", ring: r as RingId, index: i, lineage: lin, pressure: "hunger", kind: "prevented", amount: 0 });
} else {
const before = t[popField];
t[popField] = clamp(t[popField] - 1, 0, CAP);
push({ phase: "consequence", ring: r as RingId, index: i, lineage: lin, pressure: "hunger", kind: "loss", amount: before - t[popField] });
}
}
}
// TOXIN: carrier payments producer then grazer per tile, then spillover
for (const key of unionKeys([qualify.producer.toxin, qualify.grazer.toxin])) {
const [r, iStr] = key.split(":");
const r2 = r as RingId;
const i = +iStr;
const t = w.rings[r2].tiles[i];
for (const lin of ["producer", "grazer"] as LineageId[]) {
const popField = lin === "producer" ? "producer" : "grazer";
if (t[popField] <= 0) continue;
if (!qualify[lin].toxin.has(`${r2}:${i}`)) continue;
if (w.lineage[lin].unlocked.toxin) {
// Efflux: pay 1 nutrient, else lose 1 pop
if (t.nutrient >= 1) {
t.nutrient -= 1;
push({ phase: "consequence", ring: r2, index: i, lineage: lin, pressure: "toxin", kind: "payNutrient", amount: 1 });
} else {
const before = t[popField];
t[popField] = clamp(t[popField] - 1, 0, CAP);
push({ phase: "consequence", ring: r2, index: i, lineage: lin, pressure: "toxin", kind: "payPop", amount: before - t[popField] });
}
} else {
const before = t[popField];
t[popField] = clamp(t[popField] - 1, 0, CAP);
push({ phase: "consequence", ring: r2, index: i, lineage: lin, pressure: "toxin", kind: "loss", amount: before - t[popField] });
}
}
// toxin spillover: reduce local toxin by 1 per adapted surviving lineage, max 2
let count = 0;
if (w.lineage.producer.unlocked.toxin && t.producer > 0) count++;
if (w.lineage.grazer.unlocked.toxin && t.grazer > 0) count++;
const reduce = Math.min(2, count);
if (reduce > 0 && t.toxin > 0) {
const before = t.toxin;
t.toxin = clamp(t.toxin - reduce, 0, CAP);
push({ phase: "spillover", ring: r2, index: i, pressure: "toxin", field: "toxin", reduced: before - t.toxin });
}
}
// IMMUNITY: apply scheduled damage if target still has population
for (const s of immuneSchedule) {
const t = w.rings[s.ring].tiles[s.index];
const popField = s.lineage === "producer" ? "producer" : "grazer";
if (t[popField] <= 0) continue;
const before = t[popField];
t[popField] = clamp(t[popField] - s.damage, 0, CAP);
push({ phase: "consequence", ring: s.ring, index: s.index, lineage: s.lineage, pressure: "immunity", kind: "loss", amount: before - t[popField] });
}
// ---- Phase 8: Outcome ----
const resolvedTurn = state.turn + 1;
const sustained = scenario.sustained(w, { state: w, resolvedTurn, consecutive: 0, fixturesByTile: () => [] });
const consecutive = sustained ? state.consecutiveObjectiveTurns + 1 : 0;
w.consecutiveObjectiveTurns = consecutive;
w.turn = resolvedTurn;
w.actionLog = [...w.actionLog, action];
let total = 0;
for (const r of RING_ORDER) for (const t of w.rings[r].tiles) total += t.producer + t.grazer;
if (total === 0) {
w.outcome = "collapsed";
} else if (scenario.win({ state: w, resolvedTurn, consecutive, fixturesByTile: () => [] })) {
w.outcome = "won";
} else if (resolvedTurn >= scenario.turnLimit) {
w.outcome = "expired";
} else {
w.outcome = "playing";
}
push({ phase: "outcome", outcome: w.outcome, turn: resolvedTurn });
return { state: w, events: collectEvents ? events : [] };
}
export function nextState(state: GameState, action: RotationAction): GameState {
return resolve(state, action, false).state;
}
// ---- helpers ----
function arr(n: number): number[] {
return new Array(n).fill(0);
}
function snapField(w: GameState, field: keyof Chamber): Record<RingId, number[]> {
return {
inner: w.rings.inner.tiles.map((t) => t[field]),
middle: w.rings.middle.tiles.map((t) => t[field]),
outer: w.rings.outer.tiles.map((t) => t[field]),
};
}
function unionKeys(sets: Set<string>[]): string[] {
const u = new Set<string>();
for (const s of sets) for (const k of s) u.add(k);
return [...u].sort();
}
+111
View File
@@ -0,0 +1,111 @@
// Adaptive Loop — domain types (SPEC §5). Serializable plain data only.
export type RingId = "inner" | "middle" | "outer";
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";
export type SpeciesId = "producer" | "grazer" | "phage";
/** Movable tile payload (rotates with the ring, flows in channel phase). */
export type Chamber = {
nutrient: number; // 0..6
heat: number; // 0..6
toxin: number; // 0..6
producer: number; // 0..6
grazer: number; // 0..6
phage: number; // 0..6
};
export type Ring = {
direction: Direction;
tiles: Chamber[]; // clockwise track order; tiles[0] at top
};
export type Lineage = {
pressure: Record<PressureId, number>; // 0..3
unlocked: Record<PressureId, boolean>;
};
export type RotationAction = { ring: RingId; dir: Direction };
export type GameState = {
schemaVersion: 1;
mode: Mode;
scenarioId: string;
turn: number;
rings: Record<RingId, Ring>;
lineage: Record<LineageId, Lineage>;
inheritedAtStart: Record<LineageId, PressureId[]>;
consecutiveObjectiveTurns: number;
environmentActive: Record<PressureId, boolean>;
outcome: Outcome;
actionLog: RotationAction[];
};
/** Fixed fixtures (SPEC §6). Static per scenario, derived from scenario data. */
export type FixtureKind =
| "nutrientInlet"
| "heatSource"
| "toxinInlet"
| "drain"
| "immuneNode"
| "objective";
export type RingTileRef = { ring: RingId; index: number };
export type ScenarioStart = { ring: RingId; index: number; chamber: Partial<Chamber> };
export type ScenarioFixture = { kind: FixtureKind; ring: RingId; index: number; label?: string };
export type ScenarioWinCtx = {
state: GameState;
resolvedTurn: number;
consecutive: number;
fixturesByTile: (ring: RingId, index: number) => FixtureKind[];
};
export type Scenario = {
id: string;
index: number; // campaign order 1..5
name: string;
subtitle: string;
turnLimit: number;
starts: ScenarioStart[];
fixtures: ScenarioFixture[];
/** sustained predicate true => consecutiveObjectiveTurns increments; else resets. */
sustained: (state: GameState, ctx: ScenarioWinCtx) => boolean;
/** win check (evaluated before turn-limit expiry). */
win: (ctx: ScenarioWinCtx) => boolean;
/** lose-by-expiry human hint */
teaches: string;
};
export const RING_SIZES: Record<RingId, number> = { inner: 6, middle: 12, outer: 18 };
export const RING_IDS: RingId[] = ["inner", "middle", "outer"];
export const PRESSURES: PressureId[] = ["heat", "hunger", "toxin", "immunity"];
export const LINEAGES: LineageId[] = ["producer", "grazer"];
export const TRAIT_NAME: Record<PressureId, string> = {
heat: "Heat Shield",
hunger: "Dormancy",
toxin: "Efflux",
immunity: "Cloak",
};
export const SPECIES_NAME: Record<SpeciesId, string> = {
producer: "Lumiflora",
grazer: "Vellea",
phage: "Phage",
};
export const PRESSURE_META: Record<
PressureId,
{ label: string; color: string; icon: string; trait: string; response: string }
> = {
heat: { label: "Heat", color: "#ff8a4c", icon: "sun", trait: "Heat Shield", response: "Heat sources add 3" },
hunger: { label: "Hunger", color: "#b388ff", icon: "crescent", trait: "Dormancy", response: "Nutrient inlets add 1" },
toxin: { label: "Toxin", color: "#7fd66b", icon: "skull", trait: "Efflux", response: "Toxin inlets add 3" },
immunity: { label: "Immunity", color: "#5fd0ff", icon: "shield", trait: "Cloak", response: "Immune damage 3" },
};
+5
View File
@@ -0,0 +1,5 @@
import { mount } from "./ui/app.ts";
const el = document.getElementById("app");
if (!el) throw new Error("#app mount point missing");
mount(el);
+156
View File
@@ -0,0 +1,156 @@
// Versioned localStorage save envelope (SPEC §11). Strict trust-boundary validation.
import type { GameState, LineageId, Mode, PressureId, RotationAction, RingId } from "../domain/types.ts";
import { canonical } from "../domain/core.ts";
import { getScenario } from "../domain/scenarios.ts";
import { replay } from "../domain/solver.ts";
const SAVE_KEY = "adaptive-loop-save-v1";
const CAMPAIGN_SAVE_KEY = "adaptive-loop-campaign-v1";
const SCHEMA = 1;
const SCENARIOS = new Set(["s1-heat", "s2-hunger", "s3-toxin", "s4-immunity", "s5-convergence"]);
const PRESSURES: PressureId[] = ["heat", "hunger", "toxin", "immunity"];
const LINEAGES: LineageId[] = ["producer", "grazer"];
const RINGS: RingId[] = ["inner", "middle", "outer"];
export type CampaignProgress = {
unlocked: string[];
inherited: Record<LineageId, PressureId[]>;
entrySnapshot: Record<LineageId, PressureId[]>;
victory: boolean;
};
export type SaveEnvelope = {
schemaVersion: 1;
mode: Mode;
scenarioId: string;
state: GameState;
progress: CampaignProgress;
actionLog: RotationAction[];
outcome: GameState["outcome"];
savedAt: string;
};
export function saveGame(env: Omit<SaveEnvelope, "savedAt">): void {
const serialized = JSON.stringify({ ...env, savedAt: new Date().toISOString() });
localStorage.setItem(SAVE_KEY, serialized);
if (env.mode === "campaign") localStorage.setItem(CAMPAIGN_SAVE_KEY, serialized);
}
function loadAt(key: string): { ok: true; env: SaveEnvelope } | { ok: false; reason: string } {
const raw = localStorage.getItem(key);
if (!raw) return { ok: false, reason: "No saved game found." };
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
return { ok: false, reason: "Saved game is corrupt (invalid JSON)." };
}
if (!record(parsed)) return { ok: false, reason: "Saved game is empty." };
if (parsed.schemaVersion !== SCHEMA) return { ok: false, reason: `Unsupported save version ${String(parsed.schemaVersion)}.` };
if (!validateEnvelope(parsed)) return { ok: false, reason: "Saved game state is invalid. Start a new campaign to recover." };
return { ok: true, env: parsed };
}
export function loadGame(): ReturnType<typeof loadAt> {
return loadAt(SAVE_KEY);
}
export function loadCampaignGame(): ReturnType<typeof loadAt> {
return loadAt(CAMPAIGN_SAVE_KEY);
}
export function clearSave(): void {
localStorage.removeItem(SAVE_KEY);
localStorage.removeItem(CAMPAIGN_SAVE_KEY);
}
export function hasSave(): boolean {
return !!localStorage.getItem(SAVE_KEY);
}
export function hasCampaignSave(): boolean {
return !!localStorage.getItem(CAMPAIGN_SAVE_KEY);
}
function record(value: unknown): value is Record<string, any> {
return !!value && typeof value === "object" && !Array.isArray(value);
}
function integer(value: unknown, min: number, max: number): value is number {
return typeof value === "number" && Number.isInteger(value) && value >= min && value <= max;
}
function validAction(value: unknown): value is RotationAction {
return record(value) && RINGS.includes(value.ring) && (value.dir === "cw" || value.dir === "ccw");
}
function validTraits(value: unknown): value is Record<LineageId, PressureId[]> {
if (!record(value)) return false;
return LINEAGES.every((lineage) =>
Array.isArray(value[lineage]) &&
value[lineage].every((pressure: unknown) => PRESSURES.includes(pressure as PressureId)) &&
new Set(value[lineage]).size === value[lineage].length,
);
}
function validateProgress(value: unknown): value is CampaignProgress {
if (!record(value) || !Array.isArray(value.unlocked) || typeof value.victory !== "boolean") return false;
if (!value.unlocked.length || value.unlocked.some((id: unknown) => typeof id !== "string" || !SCENARIOS.has(id))) return false;
if (new Set(value.unlocked).size !== value.unlocked.length) return false;
return validTraits(value.inherited) && validTraits(value.entrySnapshot);
}
function validateEnvelope(value: Record<string, any>): value is SaveEnvelope {
if ((value.mode !== "campaign" && value.mode !== "standalone") || !SCENARIOS.has(value.scenarioId)) return false;
if (!validateState(value.state) || !validateProgress(value.progress)) return false;
if (!Array.isArray(value.actionLog) || !value.actionLog.every(validAction)) return false;
if (value.mode !== value.state.mode || value.scenarioId !== value.state.scenarioId || value.outcome !== value.state.outcome) return false;
if (JSON.stringify(value.actionLog) !== JSON.stringify(value.state.actionLog)) return false;
if (typeof value.savedAt !== "string" || Number.isNaN(Date.parse(value.savedAt))) return false;
if (!value.progress.unlocked.includes(value.scenarioId)) return false;
if (canonical(value.progress.entrySnapshot) !== canonical(value.state.inheritedAtStart)) return false;
if (value.mode === "campaign" && canonical(value.progress.inherited) !== canonical(value.progress.entrySnapshot)) return false;
const expectedUnlocked = [...SCENARIOS.keys()].slice(0, value.progress.unlocked.length);
if (canonical(value.progress.unlocked) !== canonical(expectedUnlocked)) return false;
if (value.progress.victory && (value.scenarioId !== expectedUnlocked[expectedUnlocked.length - 1] || value.state.outcome !== "won" || expectedUnlocked.length !== SCENARIOS.size)) return false;
const scenarioIndex = [...SCENARIOS.keys()].indexOf(value.scenarioId) + 1;
const inheritedCount = value.progress.inherited.producer.length + value.progress.inherited.grazer.length;
if (inheritedCount > expectedUnlocked.length - 1) return false;
if (value.mode === "campaign") {
const allowedUnlockCount = value.state.outcome === "won" ? Math.min(scenarioIndex + 1, SCENARIOS.size) : scenarioIndex;
if (expectedUnlocked.length !== scenarioIndex && expectedUnlocked.length !== allowedUnlockCount) return false;
if (inheritedCount > scenarioIndex - 1) return false;
}
const reproduced = replay(getScenario(value.scenarioId), value.state.inheritedAtStart, value.actionLog, value.mode);
return canonical(reproduced) === canonical(value.state);
}
/** Structural and range validation of canonical domain state. */
export function validateState(value: unknown): value is GameState {
if (!record(value) || value.schemaVersion !== 1) return false;
if ((value.mode !== "campaign" && value.mode !== "standalone") || !SCENARIOS.has(value.scenarioId)) return false;
if (!integer(value.turn, 0, 100) || !integer(value.consecutiveObjectiveTurns, 0, value.turn)) return false;
if (!["playing", "won", "collapsed", "expired"].includes(value.outcome)) return false;
if (!Array.isArray(value.actionLog) || value.actionLog.length !== value.turn || !value.actionLog.every(validAction)) return false;
if (!validTraits(value.inheritedAtStart) || !record(value.environmentActive)) return false;
if (!PRESSURES.every((pressure) => typeof value.environmentActive[pressure] === "boolean")) return false;
if (!record(value.rings)) return false;
const sizes: Record<RingId, number> = { inner: 6, middle: 12, outer: 18 };
for (const ring of RINGS) {
const data = value.rings[ring];
if (!record(data) || (data.direction !== "cw" && data.direction !== "ccw") || !Array.isArray(data.tiles) || data.tiles.length !== sizes[ring]) return false;
for (const tile of data.tiles) {
if (!record(tile)) return false;
if (!["nutrient", "heat", "toxin", "producer", "grazer", "phage"].every((field) => integer(tile[field], 0, 6))) return false;
}
}
if (!record(value.lineage)) return false;
for (const lineage of LINEAGES) {
const data = value.lineage[lineage];
if (!record(data) || !record(data.pressure) || !record(data.unlocked)) return false;
if (!PRESSURES.every((pressure) => integer(data.pressure[pressure], 0, 3) && typeof data.unlocked[pressure] === "boolean")) return false;
}
return true;
}
+153
View File
@@ -0,0 +1,153 @@
// Generates canonical solver fixtures (win + loss routes per scenario) and verifies them.
// Run: node --experimental-strip-types src/solver/gen-fixtures.ts
import { readFileSync, writeFileSync } from "fs";
import { SCENARIOS, buildInitialState } from "../domain/scenarios.ts";
import { solveWin, solveLoss, replay, reachableInheritanceAt, inheritanceKey, lastWinTimedOut } from "../domain/solver.ts";
import { nextState, resolve } from "../domain/transition.ts";
import type { GameState, RotationAction, PressureId, Scenario } from "../domain/types.ts";
type Fixture = {
scenarioId: string;
win: RotationAction[];
winOutcome: string;
loss: RotationAction[];
lossOutcome: string;
exploitsAdaptation: boolean;
avoidsAdaptation: boolean;
};
type Effects = { evolved: boolean; benefit: boolean; cost: boolean; spillover: boolean; all: boolean };
function adaptationEffects(sc: Scenario, inherited: GameState["inheritedAtStart"], actions: RotationAction[]): Effects {
let state = buildInitialState(sc, "campaign", inherited);
const effects: Effects = { evolved: false, benefit: false, cost: false, spillover: false, all: false };
for (const action of actions) {
const result = resolve(state, action, true);
state = result.state;
for (const event of result.events) {
if (event.phase === "evolution") effects.evolved = true;
if (event.phase === "adaptation" && event.effect === "cost") effects.cost = true;
if (event.phase === "adaptation" && event.effect === "spillover") effects.spillover = true;
if (event.phase === "consequence" && event.kind === "prevented") effects.benefit = true;
if ((event.phase === "consequence" && (event.kind === "payNutrient" || event.kind === "payPop")) ||
(event.phase === "growth" && event.suppressed) ||
(event.phase === "feed" && (event.suppressed || event.preyRemoved === 2))) effects.cost = true;
if (event.phase === "spillover" || (event.phase === "immuneSelect" && event.retarget)) effects.spillover = true;
}
}
effects.all = effects.evolved && effects.benefit && effects.cost && effects.spillover;
return effects;
}
const themePressure: Partial<Record<string, PressureId>> = {
"s1-heat": "heat", "s2-hunger": "hunger", "s3-toxin": "toxin", "s4-immunity": "immunity",
};
function trimRoute(sc: Scenario, inherited: GameState["inheritedAtStart"], actions: RotationAction[]): RotationAction[] {
let state = buildInitialState(sc, "campaign", inherited);
const route: RotationAction[] = [];
for (const action of actions) {
if (state.outcome !== "playing") break;
route.push(action);
state = nextState(state, action);
}
return route;
}
const preferredWins: Partial<Record<string, RotationAction[]>> = {
// Starts outside the objective, aligns two rings, and wins on the third resolved turn.
"s5-convergence": [
{ ring: "middle", dir: "ccw" },
{ ring: "inner", dir: "cw" },
{ ring: "middle", dir: "cw" },
],
};
let previousRoutes: Record<string, RotationAction[]> = {};
try {
previousRoutes = JSON.parse(readFileSync("test/solver-fixtures.json", "utf8")).campaignRoutes ?? {};
} catch {
// First generation has no candidates; the bounded solver supplies them.
}
const fixtures: Record<string, Fixture> = {};
for (const sc of SCENARIOS) {
const candidate = preferredWins[sc.id];
const preferred = candidate ? trimRoute(sc, { producer: [], grazer: [] }, candidate) : undefined;
const win = preferred && replay(sc, { producer: [], grazer: [] }, preferred).outcome === "won"
? preferred
: solveWin(sc, { producer: [], grazer: [] }, { nodeBudget: 4_000_000, timeMs: 60_000 });
if (!win) throw new Error(`No win found for ${sc.id} (timedOut=${lastWinTimedOut})`);
const winEnd = replay(sc, { producer: [], grazer: [] }, win);
if (winEnd.outcome !== "won") throw new Error(`Win replay mismatch for ${sc.id}: ${winEnd.outcome}`);
const effects = adaptationEffects(sc, { producer: [], grazer: [] }, win);
const theme = themePressure[sc.id];
const avoids = theme ? !winEnd.lineage.producer.unlocked[theme] && !winEnd.lineage.grazer.unlocked[theme] : false;
const loss = solveLoss(sc, { producer: [], grazer: [] }) ?? [];
const lossEnd = replay(sc, { producer: [], grazer: [] }, loss);
if (lossEnd.outcome !== "collapsed" && lossEnd.outcome !== "expired") {
// fallback: play to turn limit with a fixed sequence to force expiry
let s = buildInitialState(sc, "campaign");
let seq: RotationAction[] = [];
while (s.outcome === "playing") {
const a = { ring: "outer" as const, dir: "cw" as const };
s = nextState(s, a);
seq = [...seq, a];
}
fixtures[sc.id] = { scenarioId: sc.id, win, winOutcome: winEnd.outcome, loss: seq, lossOutcome: s.outcome, exploitsAdaptation: effects.all, avoidsAdaptation: avoids };
continue;
}
fixtures[sc.id] = {
scenarioId: sc.id,
win,
winOutcome: winEnd.outcome,
loss,
lossOutcome: lossEnd.outcome,
exploitsAdaptation: effects.all,
avoidsAdaptation: avoids,
};
console.log(`${sc.id}: win=${win.length} (${winEnd.outcome}) loss=${loss.length} (${lossEnd.outcome}) exploits=${effects.all} avoids=${avoids}`);
}
// Prove a conservative superset of all reachable campaign inheritance sets. For N prior
// scenarios this checks every subset of up to N of the eight lineage/pressure slots.
let reachOk = true;
const reachReport: string[] = [];
const campaignRoutes: Record<string, RotationAction[]> = {};
let adaptationEvidence: ({ scenarioId: string; inheritanceKey: string; route: RotationAction[] } & Effects) | null = null;
for (let idx = 2; idx <= 5; idx++) {
const sc = SCENARIOS[idx - 1];
const baseline = fixtures[sc.id].win;
for (const inherited of reachableInheritanceAt(idx)) {
const key = `${sc.id}|${inheritanceKey(inherited)}`;
const inheritedBaseline = trimRoute(sc, inherited, baseline);
const baselineEnd = replay(sc, inherited, inheritedBaseline);
const previousCandidate = previousRoutes[key];
const previous = previousCandidate ? trimRoute(sc, inherited, previousCandidate) : undefined;
const win = baselineEnd.outcome === "won"
? inheritedBaseline
: previous && replay(sc, inherited, previous).outcome === "won"
? previous
: solveWin(sc, inherited, { nodeBudget: 4_000_000, timeMs: 60_000 });
if (!win) {
reachOk = false;
reachReport.push(`FAIL ${key} (timedOut=${lastWinTimedOut})`);
} else {
campaignRoutes[key] = win;
reachReport.push(`ok ${key} win=${win.length}`);
const routeEffects = adaptationEffects(sc, inherited, win);
if (!adaptationEvidence && routeEffects.all) adaptationEvidence = { scenarioId: sc.id, inheritanceKey: inheritanceKey(inherited), route: win, ...routeEffects };
}
}
}
if (!adaptationEvidence) {
reachOk = false;
reachReport.push("FAIL no winning route demonstrated adaptation benefit, cost, and spillover");
}
writeFileSync("test/solver-fixtures.json", JSON.stringify({ fixtures, campaignRoutes, adaptationEvidence, reachOk, reachReport }, null, 2));
console.log("\nReachability:", reachOk ? "OK" : "FAILURES");
console.log("Wrote test/solver-fixtures.json");
if (!reachOk) process.exit(1);
+119
View File
@@ -0,0 +1,119 @@
/* Adaptive Loop — dark laboratory glass. Procedural SVG/CSS only. */
:root {
--bg: #070d18;
--panel: #0e1830;
--panel-2: #131f3b;
--ink: #e6edf7;
--muted: #8aa0c4;
--line: #25344f;
--accent: #5fd0ff;
--accent-2: #7fffd6;
--warn: #ffb347;
--good: #7fff8a;
--bad: #ff6b6b;
--ring-inner: #5fd0ff;
--ring-middle: #9d7bff;
--ring-outer: #7fffd6;
--radius: 8px;
}
* { box-sizing: border-box; }
html, body { margin: 0; padding: 0; background: var(--bg); color: var(--ink); font: 15px/1.45 -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif; }
#app { min-height: 100vh; }
.app { max-width: 1200px; margin: 0 auto; padding: 12px; }
h1, h2, h3 { color: #fff; margin: 0 0 6px; font-weight: 600; }
h1 { font-size: 22px; }
h2 { font-size: 16px; }
p { margin: 4px 0; }
.muted { color: var(--muted); }
/* Topbar */
.topbar { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 6px 4px; border-bottom: 1px solid var(--line); margin-bottom: 8px; flex-wrap: wrap; }
.topnav { display: flex; gap: 6px; flex-wrap: wrap; }
/* Buttons */
.btn { font: inherit; color: var(--ink); background: var(--panel-2); border: 1px solid var(--line); border-radius: var(--radius); padding: 8px 12px; cursor: pointer; min-height: 40px; }
.btn:hover:not(:disabled) { border-color: var(--accent); }
.btn:focus-visible { outline: 3px solid var(--accent); outline-offset: 1px; }
.btn:disabled { opacity: 0.4; cursor: not-allowed; }
.btn.primary { background: linear-gradient(180deg, #1b3a6b, #142a52); border-color: var(--accent); color: #fff; }
.btn.ghost { background: transparent; }
.btn.selected { background: linear-gradient(180deg, #2a5b3a, #1c3f2a); border-color: var(--good); color: #d8ffd8; }
/* Title */
.title { min-height: 90vh; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; gap: 10px; }
.title h1 { font-size: 40px; letter-spacing: 1px; background: linear-gradient(90deg, var(--ring-inner), var(--ring-middle), var(--ring-outer)); -webkit-background-clip: text; background-clip: text; color: transparent; }
.subtitle { color: var(--muted); font-size: 18px; }
.lede { max-width: 640px; color: var(--ink); }
.actions { display: flex; gap: 10px; flex-wrap: wrap; justify-content: center; }
.hint { color: var(--muted); font-size: 13px; }
/* Play layout */
.play { display: grid; grid-template-columns: minmax(360px, 1fr) 340px; gap: 12px; align-items: start; }
@media (max-width: 900px) { .play { grid-template-columns: 1fr; } .rail { order: 2; } .board-wrap { order: 1; } }
.board-wrap { background: radial-gradient(circle at center, #0c1830 0%, #060b16 70%); border: 1px solid var(--line); border-radius: var(--radius); padding: 8px; }
.board-svg { width: 100%; height: auto; display: block; }
.tile-ledger { display: none; }
@media (max-width: 700px) {
.tile-ledger { display: block; margin-top: 8px; color: var(--ink); font-size: 13px; }
.tile-ledger summary { cursor: pointer; font-weight: 600; }
.tile-ledger div { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 4px 8px; margin-top: 6px; }
.tile-ledger span { overflow-wrap: anywhere; }
}
.rail { display: flex; flex-direction: column; gap: 10px; }
.panel { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 10px 12px; }
.obj .obj-text { color: var(--ink); }
.turn { color: var(--accent); font-weight: 600; }
.envflag { display: inline-block; background: #3a2a10; border: 1px solid var(--warn); color: var(--warn); border-radius: 12px; padding: 1px 8px; font-size: 12px; margin-right: 4px; }
.inh { color: var(--muted); font-size: 12px; }
/* Rotation controls */
.rot-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
.rot { display: flex; align-items: center; gap: 6px; justify-content: center; }
.key { display: inline-block; min-width: 16px; padding: 0 4px; background: #0a1426; border: 1px solid var(--line); border-radius: 4px; font-size: 11px; color: var(--muted); }
.commit-row { display: flex; gap: 6px; margin-top: 8px; flex-wrap: wrap; }
.sel-status { color: var(--muted); font-size: 12px; margin-top: 6px; }
/* Traits */
.lineage { display: flex; align-items: center; gap: 8px; margin: 4px 0; flex-wrap: wrap; }
.lin-name { min-width: 78px; color: var(--ink); }
.ptrack { display: inline-grid; grid-template-columns: 18px auto; align-items: center; gap: 0 4px; font-size: 10px; color: var(--muted); }
.ptrack svg { width: 18px; height: 18px; grid-row: span 2; }
.ptrack b { font: 10px ui-monospace, monospace; letter-spacing: 1px; font-weight: 500; }
.ptrack.adapted { color: var(--good); }
.legend-mini { color: var(--muted); font-size: 11px; }
/* Events */
.event-list { margin: 4px 0 0; padding-left: 18px; max-height: 200px; overflow-y: auto; font-size: 13px; }
.event-list li { margin: 2px 0; }
.event-list b { color: var(--accent-2); }
.prediction { color: var(--accent-2); font-size: 12px; }
.relocation { color: var(--muted); font-size: 11px; margin: 6px 0; }
.relocation summary { color: var(--ink); cursor: pointer; }
.relocation p, .delta-list p { margin: 3px 0; overflow-wrap: anywhere; }
.delta-list { color: var(--muted); font-size: 11px; max-height: 90px; overflow-y: auto; border-block: 1px solid var(--line); padding: 5px 0; }
/* Menu / scenarios */
.scn-list { list-style: none; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 10px; }
.scn-list li.locked .scenario-btn { opacity: 0.35; }
.scenario-btn { width: 100%; text-align: left; display: flex; flex-direction: column; gap: 2px; }
.scn-no { color: var(--accent); font-weight: 700; }
.scn-sub { color: var(--muted); font-size: 12px; }
/* Choice */
.choice { max-width: 760px; margin: 0 auto; text-align: center; }
.choice-grid { display: grid; grid-template-columns: 1fr; gap: 8px; margin: 14px 0; }
.choice .ch-lin { color: var(--accent); font-weight: 700; }
.choice .ch-trait { color: var(--good); font-weight: 700; }
.choice .ch-meta { color: var(--muted); font-size: 12px; }
/* Announce + help */
.announce { color: var(--muted); font-size: 13px; min-height: 18px; }
.help-panel { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 14px; margin-top: 12px; }
.help-panel.hidden { display: none; }
kbd { background: #0a1426; border: 1px solid var(--line); border-radius: 4px; padding: 1px 5px; font-family: ui-monospace, monospace; font-size: 12px; }
.victory { text-align: center; padding: 40px; }
/* Reduced motion: we render final states already; ensure no transitions. */
@media (prefers-reduced-motion: reduce) {
* { transition: none !important; animation: none !important; }
}
+568
View File
@@ -0,0 +1,568 @@
// Application: views, controls, preview/commit, campaign flow, persistence, accessibility.
import type { GameState, LineageId, Mode, PressureId, RotationAction, RingId, Scenario } from "../domain/types.ts";
import { SCENARIOS, buildInitialState, getScenario } from "../domain/scenarios.ts";
import { resolve } from "../domain/transition.ts";
import type { GameEvent } from "../domain/transition.ts";
import { renderBoard, renderTraits } from "./board.ts";
import { saveGame, loadGame, loadCampaignGame, clearSave, hasSave, hasCampaignSave } from "../persistence/save.ts";
import type { CampaignProgress, SaveEnvelope } from "../persistence/save.ts";
import { TRAIT_NAME, PRESSURE_META } from "../domain/types.ts";
type View = "title" | "menu" | "play" | "choice" | "victory";
type App = {
view: View;
mode: Mode;
scenario: Scenario;
state: GameState;
progress: CampaignProgress;
selected: RotationAction | null;
preview: { state: GameState; events: GameEvent[] } | null;
lastEvents: GameEvent[];
announce: string;
pendingNewTraits: { lin: LineageId; p: PressureId }[];
};
const ROTATIONS: { ring: RingId; dir: "cw" | "ccw"; label: string; key: string }[] = [
{ ring: "inner", dir: "cw", label: "Inner ⟳", key: "1" },
{ ring: "inner", dir: "ccw", label: "Inner ⟲", key: "2" },
{ ring: "middle", dir: "cw", label: "Middle ⟳", key: "3" },
{ ring: "middle", dir: "ccw", label: "Middle ⟲", key: "4" },
{ ring: "outer", dir: "cw", label: "Outer ⟳", key: "5" },
{ ring: "outer", dir: "ccw", label: "Outer ⟲", key: "6" },
];
let app: App;
let root: HTMLElement;
let suppressFocusPreview = false;
function focusWithoutPreview(element: HTMLElement | null): void {
suppressFocusPreview = true;
element?.focus();
suppressFocusPreview = false;
}
export function mount(el: HTMLElement): void {
root = el;
app = {
view: "title",
mode: "campaign",
scenario: SCENARIOS[0],
state: buildInitialState(SCENARIOS[0], "campaign"),
progress: freshProgress(),
selected: null,
preview: null,
lastEvents: [],
announce: "",
pendingNewTraits: [],
};
render();
}
function freshProgress(): CampaignProgress {
return {
unlocked: [SCENARIOS[0].id],
inherited: { producer: [], grazer: [] },
entrySnapshot: { producer: [], grazer: [] },
victory: false,
};
}
// ---------- rendering ----------
function render(): void {
root.innerHTML = viewHTML();
wireEvents();
const live = root.querySelector<HTMLElement>("#announce");
queueMicrotask(() => { if (live) live.textContent = app.announce; });
}
function viewHTML(): string {
if (app.view === "title") return titleHTML();
if (app.view === "menu") return menuHTML();
if (app.view === "victory") return victoryHTML();
if (app.view === "choice") return choiceHTML();
return playHTML();
}
function shell(inner: string, h1: string): string {
return `<main class="app">
<header class="topbar"><h1>${h1}</h1>
<nav class="topnav">
<button id="btnMenu" class="btn ghost" aria-label="Return to menu">Menu</button>
<button id="btnSaveQuit" class="btn ghost" aria-label="Save and quit to title">Save &amp; Quit</button>
<button id="btnHelp" class="btn ghost" aria-label="Open help and legend" aria-controls="helpPanel" aria-expanded="false">Help</button>
</nav>
</header>
<div id="announce" class="announce" role="status" aria-live="polite" aria-atomic="true"></div>
${inner}
<section id="helpPanel" class="help-panel hidden" aria-hidden="true">${legendHTML()}</section>
</main>`;
}
function titleHTML(): string {
return `<main class="app title">
<div id="announce" class="announce" role="status" aria-live="polite" aria-atomic="true"></div>
<h1>Adaptive Loop</h1>
<p class="subtitle">A calm deterministic microfluidic strategy puzzle.</p>
<p class="lede">Rotate the three concentric glass rings to align the six radial gates, route nutrient inward, and provoke — then exploit — the ecosystem's counter-adaptations.</p>
<div class="actions">
<button id="btnStart" class="btn primary">New Campaign</button>
<button id="btnContinue" class="btn">Continue</button>
<button id="btnResumeCampaign" class="btn" ${hasCampaignSave() ? "" : "disabled"}>Resume Campaign</button>
<button id="btnReplay" class="btn">Replay Standalone</button>
</div>
<p class="hint">${hasSave() ? "A saved run is available." : "Continue starts the next campaign scenario."}</p>
</main>`;
}
function menuHTML(): string {
const standalone = app.mode === "standalone";
const items = SCENARIOS.map((scenario) => {
const unlocked = app.progress.unlocked.includes(scenario.id);
const selectable = standalone ? unlocked : scenario.id === app.scenario.id && app.state.outcome === "playing";
const action = standalone ? "Replay" : "Resume";
return `<li class="${selectable ? "" : "locked"}">
<button class="btn scenario-btn" data-scid="${scenario.id}" ${selectable ? "" : "disabled"} aria-label="${action} ${scenario.name}">
<span class="scn-no">${scenario.index}</span>
<span class="scn-name">${scenario.name}</span>
<span class="scn-sub">${scenario.subtitle}</span>
</button>
</li>`;
}).join("");
const heading = standalone ? "Standalone Replay" : "Current Campaign";
return shell(`<section class="menu"><h2>${heading}</h2><ul class="scn-list">${items}</ul></section>`, "Adaptive Loop — Menu");
}
function playHTML(): string {
const sc = app.scenario;
const st = app.state;
const terminal = st.outcome !== "playing";
const flowEvents = (app.preview?.events ?? []).filter((e) => e.phase === "flow").map((e) => ({ ring: (e as any).ring, index: (e as any).index, field: (e as any).field, tangential: (e as any).tangential, radial: (e as any).radial })) as { ring: RingId; index: number; field: "nutrient" | "toxin"; tangential: number; radial: number }[];
const board = renderBoard(st, sc, { previewState: app.preview?.state ?? null, selectedRing: app.selected?.ring ?? null, flowEvents });
const objective = objectiveText(sc, st);
const turnInfo = `Turn ${st.turn}/${sc.turnLimit}${st.outcome !== "playing" ? ` — ${outcomeLabel(st.outcome)}` : ""}`;
const rotBtns = ROTATIONS.map((r) => {
const sel = app.selected && app.selected.ring === r.ring && app.selected.dir === r.dir;
const pred = sel && app.preview ? ` → ${predictLabel(app.preview.events)}` : "";
return `<button class="btn rot ${sel ? "selected" : ""}" data-ring="${r.ring}" data-dir="${r.dir}" aria-label="Rotate ${r.ring} ${r.dir === "cw" ? "clockwise" : "counter-clockwise"}${pred}"${terminal ? " disabled" : ""}><span class="key">${r.key}</span> ${r.label}</button>`;
}).join("");
const commitDisabled = terminal || !app.selected;
const commitBtn = `<button id="btnCommit" class="btn primary" ${commitDisabled ? "disabled" : ""} aria-label="Commit selected rotation">Commit</button>`;
const cancelBtn = `<button id="btnCancel" class="btn ghost" ${!app.selected ? "disabled" : ""} aria-label="Cancel preview">Cancel (Esc)</button>`;
const retryBtn = st.outcome === "collapsed" || st.outcome === "expired" ? `<button id="btnRetry" class="btn">Retry</button>` : "";
const eventText = eventsToText(app.preview?.events ?? app.lastEvents);
const previewDetails = app.preview && app.selected ? previewDetailsHTML(sc, st, app.preview.state, app.selected) : "";
const traits = renderTraits(st);
const envFlags = (["heat", "hunger", "toxin", "immunity"] as PressureId[]).filter((p) => st.environmentActive[p]).map((p) => `<span class="envflag">${PRESSURE_META[p].label} Response</span>`).join("");
const inherited = [...app.progress.inherited.producer.map((p) => `Lumiflora:${TRAIT_NAME[p]}`), ...app.progress.inherited.grazer.map((p) => `Vellea:${TRAIT_NAME[p]}`)].join(", ") || "none";
return shell(`<section class="play">
<div class="board-wrap">${board}</div>
<aside class="rail">
<div class="panel obj">
<h2>${sc.index}. ${sc.name} <span class="scn-sub">(${sc.subtitle})</span></h2>
<p class="obj-text">${objective}</p>
<p class="turn">${turnInfo}</p>
${envFlags ? `<p class="env">${envFlags}</p>` : ""}
<p class="inh">Inherited: ${inherited}</p>
</div>
<div class="panel controls">
<h2>Rotate a ring</h2>
<div class="rot-grid">${rotBtns}</div>
<div class="commit-row">${commitBtn} ${cancelBtn} ${retryBtn}</div>
<p class="sel-status">${app.selected ? `Selected: ${app.selected.ring} ${app.selected.dir}. Commit enabled.` : "Select a rotation to preview."}</p>
</div>
<div class="panel traits"><h2>Pressure tracks</h2>${traits}<p class="legend-mini">▰ = track step · ✓ = adapted (benefit+cost active)</p></div>
<div class="panel events"><h2>${app.preview ? "Exact one-turn preview" : "Last tick"}</h2>${previewDetails}<ol class="event-list">${eventText}</ol></div>
</aside>
</section>`, `Adaptive Loop — ${sc.name}`);
}
function choiceHTML(): string {
const opts = app.pendingNewTraits.map((t, i) => {
const lin = t.lin === "producer" ? "Lumiflora" : "Vellea";
const meta = PRESSURE_META[t.p];
return `<button class="btn trait-choice" data-i="${i}"><span class="ch-lin">${lin}</span> · <span class="ch-trait">${TRAIT_NAME[t.p]}</span><br><span class="ch-meta">Benefit: prevents ${t.p} loss. Cost: ${costText(t.p)}. ${meta.response}.</span></button>`;
}).join("");
return shell(`<section class="choice">
<h2>Scenario won — preserve a lineage trait?</h2>
<p>The ecosystem unlocked new adaptations. Preserve one to carry its gift (and cost) forward, or decline.</p>
<div class="choice-grid">${opts}</div>
<button id="btnDecline" class="btn ghost">Decline</button>
</section>`, "Lineage choice");
}
function victoryHTML(): string {
return shell(`<section class="victory"><h2>Campaign Victory</h2><p>You stabilized the Adaptive Loop across all five scenarios.</p><button id="btnVictoryMenu" class="btn primary">Return to Menu</button></section>`, "Victory");
}
function legendHTML(): string {
const species = `<li><b>Lumiflora</b> (producer, green diatom) — consumes nutrient, grows.</li>
<li><b>Vellea</b> (grazer, amber crescent) — consumes producers, grows.</li>
<li><b>Phage</b> (pink lander) — consumes grazers; starves without prey.</li>`;
const pressures = (["heat", "hunger", "toxin", "immunity"] as PressureId[]).map((p) => `<li><b>${PRESSURE_META[p].label}</b> → trait <b>${TRAIT_NAME[p]}</b>. Response: ${PRESSURE_META[p].response}.</li>`).join("");
return `<h2>Help &amp; Legend</h2><p>Rotate a ring (buttons or keys 1–6). A rotation moves that ring's payloads and re-aligns the gates; the tick then resolves flow, growth, feeding, migration, adaptation, and pressure. Select to preview exact deltas; Commit applies it.</p>
<h3>Species</h3><ul>${species}</ul>
<h3>Pressures &amp; adaptations</h3><ul>${pressures}</ul>
<p>Gate tiles glow in their ring color; nutrient fills the tile base blue, toxin green, heat warms the rim. <kbd>1</kbd>–<kbd>6</kbd> rotate, <kbd>Enter</kbd>/<kbd>Space</kbd> commits, <kbd>Esc</kbd> cancels.</p>`;
}
// ---------- event wiring ----------
function wireEvents(): void {
const on = (id: string, ev: string, fn: () => void) => root.querySelector<HTMLElement>(id)?.addEventListener(ev, fn);
on("#btnStart", "click", startCampaign);
on("#btnContinue", "click", continueRun);
on("#btnResumeCampaign", "click", resumeCampaign);
on("#btnReplay", "click", openStandalone);
on("#btnMenu", "click", () => { app.view = "menu"; render(); });
on("#btnVictoryMenu", "click", () => { app.view = "menu"; render(); });
on("#btnSaveQuit", "click", saveAndQuit);
on("#btnHelp", "click", toggleHelp);
on("#btnDecline", "click", () => advanceAfterWin(null));
root.querySelectorAll<HTMLElement>(".rot").forEach((b) => {
const ring = b.dataset.ring as RingId;
const dir = b.dataset.dir as "cw" | "ccw";
b.addEventListener("click", () => selectAction({ ring, dir }));
b.addEventListener("focus", () => {
if (!suppressFocusPreview && (!app.selected || app.selected.ring !== ring || app.selected.dir !== dir)) selectAction({ ring, dir });
});
b.addEventListener("mouseenter", () => { if (!app.selected) selectAction({ ring, dir }); });
});
root.querySelectorAll<HTMLElement>(".scenario-btn").forEach((button) => {
button.addEventListener("click", () => {
if (app.mode === "campaign") {
app.view = "play";
app.announce = `Resumed ${app.scenario.name}.`;
render();
} else {
startScenario(button.dataset.scid!, "standalone");
}
});
});
root.querySelectorAll<HTMLElement>(".trait-choice").forEach((b) => {
b.addEventListener("click", () => { const i = +b.dataset.i!; advanceAfterWin(app.pendingNewTraits[i] ?? null); });
});
on("#btnCommit", "click", commit);
on("#btnCancel", "click", cancelPreview);
on("#btnRetry", "click", retry);
document.onkeydown = handleKey;
}
function handleKey(e: KeyboardEvent): void {
if (e.key === "Escape") { cancelPreview(); return; }
if (app.view !== "play" || app.state.outcome !== "playing") return;
const idx = "123456".indexOf(e.key);
if (idx >= 0) { selectAction(ROTATIONS[idx]); return; }
if ((e.key === "Enter" || e.key === " ") && app.selected && document.activeElement?.classList.contains("rot")) { e.preventDefault(); commit(); }
}
// ---------- actions ----------
function startCampaign(): void {
if (hasSave() && !window.confirm("Start a new campaign and clear the current campaign save?")) return;
clearSave();
app.mode = "campaign";
app.progress = freshProgress();
app.view = "play";
startScenario(SCENARIOS[0].id, "campaign");
}
function openStandalone(): void {
const saved = loadGame();
app.progress = saved.ok ? saved.env.progress : freshProgress();
app.mode = "standalone";
app.view = "menu";
app.announce = "Choose an unlocked scenario. Standalone runs never change campaign progress.";
render();
}
function continueRun(): void {
const r = loadGame();
if (!r.ok) {
if (!hasSave()) {
startScenario(app.progress.unlocked[app.progress.unlocked.length - 1] ?? SCENARIOS[0].id, "campaign");
return;
}
app.announce = r.reason;
render();
return;
}
restoreRun(r.env, "Resumed saved run.");
}
function resumeCampaign(): void {
const result = loadCampaignGame();
if (!result.ok) { app.announce = result.reason; render(); return; }
restoreRun(result.env, "Resumed campaign run.");
}
function restoreRun(env: SaveEnvelope, announcement: string): void {
app.mode = env.mode;
app.progress = env.progress;
app.scenario = getScenario(env.scenarioId);
app.state = env.state;
app.selected = null;
app.preview = null;
app.lastEvents = [];
app.view = "play";
app.announce = announcement;
if (app.mode === "campaign" && app.state.outcome === "won") onWin();
else render();
}
function startScenario(id: string, mode: Mode): void {
const sc = getScenario(id);
app.scenario = sc;
app.mode = mode;
const inh = mode === "standalone" ? { producer: [], grazer: [] } : app.progress.inherited;
app.state = buildInitialState(sc, mode, inh);
app.progress.entrySnapshot = { producer: [...inh.producer], grazer: [...inh.grazer] };
app.selected = null;
app.preview = null;
app.lastEvents = [];
app.view = "play";
app.announce = `${sc.name}: ${sc.teaches}`;
saveCurrent();
render();
}
function selectAction(a: RotationAction): void {
if (app.state.outcome !== "playing") return;
app.selected = a;
const { state, events } = resolve(app.state, a, true);
app.preview = { state, events };
app.announce = `Previewing ${a.ring} ${a.dir}: ${predictLabel(events)}`;
render();
// keep focus on the selected control for keyboard flow
const sel = root.querySelector<HTMLElement>(`.rot[data-ring="${a.ring}"][data-dir="${a.dir}"]`);
sel?.focus();
}
function cancelPreview(): void {
if (!app.selected) return;
const action = app.selected;
app.selected = null;
app.preview = null;
app.announce = "Preview cancelled.";
render();
focusWithoutPreview(root.querySelector<HTMLElement>(`.rot[data-ring="${action.ring}"][data-dir="${action.dir}"]`));
}
function commit(): void {
if (!app.selected || app.state.outcome !== "playing") return;
const a = app.selected;
const { state, events } = resolve(app.state, a, true);
app.state = state;
app.lastEvents = events;
app.selected = null;
app.preview = null;
app.announce = `Turn ${state.turn}: ${outcomeLabel(state.outcome)}.`;
saveCurrent();
if (state.outcome === "won") {
onWin();
} else {
render();
const selector = state.outcome === "playing" ? `.rot[data-ring="${a.ring}"][data-dir="${a.dir}"]` : "#btnRetry";
focusWithoutPreview(root.querySelector<HTMLElement>(selector));
}
}
function onWin(): void {
if (app.mode === "standalone") {
app.announce = "Standalone scenario complete.";
render();
root.querySelector<HTMLElement>("#btnMenu")?.focus();
return;
}
// newly unlocked traits during this scenario (not already inherited)
const start = app.state.inheritedAtStart;
const newly: { lin: LineageId; p: PressureId }[] = [];
for (const lin of ["producer", "grazer"] as LineageId[]) {
for (const p of ["heat", "hunger", "toxin", "immunity"] as PressureId[]) {
if (app.state.lineage[lin].unlocked[p] && !start[lin].includes(p) && !app.progress.inherited[lin].includes(p)) {
newly.push({ lin, p });
}
}
}
const nextIdx = app.scenario.index; // 0-based next
const next = SCENARIOS[nextIdx];
// unlock next scenario and persist the won state before the choice screen.
if (next && !app.progress.unlocked.includes(next.id)) app.progress.unlocked.push(next.id);
if (!next) {
app.progress.victory = true;
saveCurrent();
app.view = "victory";
render();
root.querySelector<HTMLElement>("#btnMenu")?.focus();
return;
}
saveCurrent();
if (newly.length === 0) { advanceAfterWin(null); return; }
app.pendingNewTraits = newly;
app.view = "choice";
render();
root.querySelector<HTMLElement>(".trait-choice, #btnDecline")?.focus();
}
function advanceAfterWin(choice: { lin: LineageId; p: PressureId } | null): void {
if (choice) {
app.progress.inherited[choice.lin] = [...app.progress.inherited[choice.lin], choice.p];
}
const nextIdx = app.scenario.index; // 0-based
const next = SCENARIOS[nextIdx];
if (!next) { app.progress.victory = true; saveCurrent(); app.view = "victory"; render(); return; }
startScenario(next.id, "campaign");
}
function retry(): void {
// restore scenario-entry inheritance snapshot
if (app.mode === "campaign") app.progress.inherited = { producer: [...app.progress.entrySnapshot.producer], grazer: [...app.progress.entrySnapshot.grazer] };
startScenario(app.scenario.id, app.mode);
}
function saveAndQuit(): void {
saveCurrent();
app.view = "title";
app.announce = "Saved. Quit to title.";
render();
}
function saveCurrent(): void {
if (app.view !== "play" && app.view !== "choice") return;
saveGame({
schemaVersion: 1,
mode: app.mode,
scenarioId: app.scenario.id,
state: app.state,
progress: app.progress,
actionLog: app.state.actionLog,
outcome: app.state.outcome,
});
}
function toggleHelp(): void {
const p = root.querySelector<HTMLElement>("#helpPanel");
if (!p) return;
p.classList.toggle("hidden");
p.setAttribute("aria-hidden", p.classList.contains("hidden") ? "true" : "false");
root.querySelector<HTMLElement>("#btnHelp")?.setAttribute("aria-expanded", p.classList.contains("hidden") ? "false" : "true");
}
// ---------- helpers ----------
function objectiveText(sc: Scenario, st: GameState): string {
if (sc.id === "s1-heat") return `Grow producers: producer at I0 ≥ 4 and total producer ≥ 12.`;
if (sc.id === "s2-hunger") return `Endure to turn 10: total producer ≥ 8, grazer ≥ 4, across ≥3 producer tiles and ≥2 grazer tiles.`;
if (sc.id === "s3-toxin") return `Contain: by turn 6–9 reach total toxin ≤ 8 and producer+grazer ≥ 8. (Tuned)`;
if (sc.id === "s4-immunity") return `Escort: grazer at I0 (sanctuary) ≥ 4 and total producer ≥ 6. (Tuned)`;
if (sc.id === "s5-convergence") return `Hold equilibrium: assay spoke + balanced ecosystem sustained for 2 consecutive turns. (Tuned)`;
return sc.teaches;
}
function previewDetailsHTML(sc: Scenario, current: GameState, preview: GameState, action: RotationAction): string {
const prefix = action.ring === "inner" ? "I" : action.ring === "middle" ? "M" : "O";
const size = preview.rings[action.ring].tiles.length;
const destinations = Array.from({ length: size }, (_, index) => {
const destination = action.dir === "cw" ? (index + 1) % size : (index + size - 1) % size;
return `${prefix}${index}→${prefix}${destination}`;
}).join(" · ");
const fields = [["N", "nutrient"], ["H", "heat"], ["T", "toxin"], ["P", "producer"], ["V", "grazer"], ["F", "phage"]] as const;
const changes: string[] = [];
for (const ring of ["outer", "middle", "inner"] as RingId[]) {
for (let index = 0; index < current.rings[ring].tiles.length; index++) {
const before = current.rings[ring].tiles[index];
const after = preview.rings[ring].tiles[index];
const deltas = fields.flatMap(([label, field]) => {
const delta = after[field] - before[field];
return delta ? [`${label}${delta > 0 ? "+" : ""}${delta}`] : [];
});
if (deltas.length) changes.push(`${lbl(ring, index)} ${deltas.join(" ")}`);
}
}
return `<p class="prediction"><b>Predicted turn ${preview.turn}:</b> ${objectiveProgress(sc, preview)}</p>
<details class="relocation"><summary>Payload destinations · ${action.ring} ${action.dir} · gates g0–g5 stay fixed</summary><p>${destinations}</p></details>
<div class="delta-list" aria-label="Exact tile deltas"><b>Exact deltas</b><p>${changes.join(" · ") || "No value changes"}</p></div>`;
}
function objectiveProgress(sc: Scenario, state: GameState): string {
const tiles = ["inner", "middle", "outer"].flatMap((ring) => state.rings[ring as RingId].tiles);
const total = (field: "producer" | "grazer" | "phage" | "toxin") => tiles.reduce((sum, tile) => sum + tile[field], 0);
const occupied = (field: "producer" | "grazer") => tiles.filter((tile) => tile[field] > 0).length;
if (state.outcome !== "playing") return outcomeLabel(state.outcome);
if (sc.id === "s1-heat") return `I0 P ${state.rings.inner.tiles[0].producer}/4 · total P ${total("producer")}/12`;
if (sc.id === "s2-hunger") return `P ${total("producer")}/8 on ${occupied("producer")}/3 tiles · V ${total("grazer")}/4 on ${occupied("grazer")}/2 tiles`;
if (sc.id === "s3-toxin") return `toxin ${total("toxin")}/8 max · P+V ${total("producer") + total("grazer")}/8`;
if (sc.id === "s4-immunity") return `I0 V ${state.rings.inner.tiles[0].grazer}/4 · total P ${total("producer")}/6`;
const assay = [state.rings.inner.tiles[0], state.rings.middle.tiles[0], state.rings.outer.tiles[0]].filter((tile) => tile.producer + tile.grazer > 0).length;
return `assay ${assay}/3 · P ${total("producer")} · V ${total("grazer")} · F ${total("phage")} · toxin ${total("toxin")} · sustained ${state.consecutiveObjectiveTurns}/2`;
}
function adaptationSummary(pressure: PressureId): string {
if (pressure === "heat") return "Benefit: prevents heat loss. Cost: no population gain while hot. Spillover: cools the shared tile.";
if (pressure === "hunger") return "Benefit: prevents hunger loss. Cost: dormant carriers cannot migrate. Spillover: dormant prey becomes inedible.";
if (pressure === "toxin") return "Benefit: prevents toxin loss. Cost: pays 1 nutrient. Spillover: detoxifies the shared tile.";
return "Benefit: avoids immune selection. Cost: predators remove 2 cloaked prey. Spillover: immune nodes retarget the other lineage.";
}
function outcomeLabel(o: GameState["outcome"]): string {
return o === "won" ? "Objective achieved" : o === "collapsed" ? "Ecosystem collapsed" : o === "expired" ? "Turn limit expired" : "resolved";
}
function predictLabel(events: GameEvent[]): string {
const parts: string[] = [];
for (const e of events) {
if (e.phase === "evolution") parts.push(`unlocks ${TRAIT_NAME[e.pressure]}`);
if (e.phase === "env") parts.push(`${PRESSURE_META[e.pressure].label} response`);
if (e.phase === "outcome" && e.outcome !== "playing") parts.push(`→ ${e.outcome}`);
}
return parts.slice(0, 3).join(", ") || "tick resolves";
}
function costText(p: PressureId): string {
if (p === "heat") return "no growth/feeding while hot";
if (p === "hunger") return "dormant when starving (inedible, can't migrate)";
if (p === "toxin") return "pays 1 nutrient under toxin";
return "predator removes 2 cloaked prey at immune nodes";
}
function eventsToText(events: GameEvent[]): string {
if (events.length === 0) return `<li class="muted">Select a rotation to preview the tick.</li>`;
const out: string[] = [];
for (const e of events) {
const t = eventLine(e);
if (t) out.push(`<li>${t}</li>`);
}
return (out.length ? out : [`<li class="muted">No notable changes.</li>`]).join("");
}
function eventLine(e: GameEvent): string | null {
switch (e.phase) {
case "rotate": return `<b>Rotate</b> ${e.ring} ${e.dir}.`;
case "flow": return `Flow ${e.field} at ${lbl(e.ring, e.index)} (${e.delta >= 0 ? "+" : ""}${e.delta}).`;
case "overflow": return `Overflow discarded: ${e.amount} ${e.field} at ${lbl(e.ring, e.index)}.`;
case "growth": return e.suppressed ? `Heat Shield cost: growth suppressed at ${lbl(e.ring, e.index)}.` : `Producer +${e.gained} at ${lbl(e.ring, e.index)}.`;
case "feed": return e.predator === "grazer" ? `Grazer ate ${e.preyRemoved}${e.preyRemoved === 2 ? " cloaked (Cloak cost)" : ""} producer at ${lbl(e.ring, e.index)}${e.suppressed ? "; Heat Shield cost suppressed grazer gain" : ""}.` : e.phageStarve ? `Phage starved at ${lbl(e.ring, e.index)}.` : `Phage ate ${e.preyRemoved}${e.preyRemoved === 2 ? " cloaked (Cloak cost)" : ""} grazer at ${lbl(e.ring, e.index)}.`;
case "migrate": return `${e.species} migrated ${e.from}→${e.to}.`;
case "evolution": return `<b>${e.lineage === "producer" ? "Lumiflora" : "Vellea"} unlocked ${TRAIT_NAME[e.pressure]}.</b> ${adaptationSummary(e.pressure)}`;
case "env": return `<b>${PRESSURE_META[e.pressure].label} response active</b>: ${PRESSURE_META[e.pressure].response}.`;
case "fixture": return `${e.kind} at ${lbl(e.ring, e.index)}: ${e.field} ${e.delta >= 0 ? "+" : ""}${e.delta}.`;
case "fixtureGlobal": return null;
case "immuneSelect": return `Immune node at ${lbl(e.ring, e.index)} targets ${e.lineage}${e.retarget ? " (retarget spillover)" : ""}.`;
case "pressureInc": return `${e.lineage} ${e.pressure} track → ${e.to}/3.`;
case "consequence":
if (e.kind === "prevented") return `Benefit active: ${e.lineage} ${e.pressure} loss prevented at ${lbl(e.ring, e.index)}.`;
if (e.kind === "payNutrient") return `${e.lineage} pays 1 nutrient (Efflux) at ${lbl(e.ring, e.index)}.`;
if (e.kind === "payPop") return `${e.lineage} loses ${e.amount} (Efflux, no nutrient) at ${lbl(e.ring, e.index)}.`;
return `${e.lineage} loses ${e.amount} to ${e.pressure} at ${lbl(e.ring, e.index)}.`;
case "spillover": return `Spillover: ${e.field} −${e.reduced} at ${lbl(e.ring, e.index)} (${e.pressure} adaptation).`;
case "adaptation": return e.effect === "cost"
? `Cost active: dormant ${e.lineage} could not migrate at ${lbl(e.ring, e.index)}.`
: `Spillover active: dormant ${e.lineage} was inedible at ${lbl(e.ring, e.index)}.`;
case "outcome": return e.outcome === "playing" ? null : `<b>${outcomeLabel(e.outcome)}.</b>`;
}
}
function lbl(ring: RingId, index: number): string {
const c = ring === "inner" ? "I" : ring === "middle" ? "M" : "O";
return `${c}${index}`;
}
+203
View File
@@ -0,0 +1,203 @@
// Renders the full SVG board from state + scenario fixtures (+ optional preview overlay).
import type { GameState, RingId, Scenario, RotationAction, FixtureKind } from "../domain/types.ts";
import { PRESSURE_META } from "../domain/types.ts";
import { fixturesByTile } from "../domain/scenarios.ts";
import { gateIndex, isOnGate } from "../domain/core.ts";
import { CX, CY, RING_R, TILE_R, RING_COLOR, hexPoints, tileCenter, tileLabel, VIEW } from "./geom.ts";
import { glyphFixture, glyphPressure, glyphSpecies } from "./svg.ts";
export type RenderOpts = {
previewState?: GameState | null;
previewAction?: RotationAction | null;
flowEvents?: { ring: RingId; index: number; field: "nutrient" | "toxin"; tangential: number; radial: number }[];
selectedRing?: RingId | null;
};
export function renderBoard(state: GameState, scenario: Scenario, opts: RenderOpts = {}): string {
const fx = fixturesByTile(scenario);
const fixturesAt = (ring: RingId, index: number): { kind: FixtureKind; label?: string }[] =>
(fx.get(`${ring}:${index}`) ?? []).map((f) => ({ kind: f.kind as FixtureKind, label: f.label }));
const preview = opts.previewState;
// ---- gate connectors (drawn first, behind tiles) ----
const gates: string[] = [];
for (let g = 0; g < 6; g++) {
const ip = tileCenter("inner", gateIndex("inner", g));
const mp = tileCenter("middle", gateIndex("middle", g));
const op = tileCenter("outer", gateIndex("outer", g));
const active = opts.selectedRing ? true : false;
gates.push(
`<line x1="${op[0].toFixed(1)}" y1="${op[1].toFixed(1)}" x2="${ip[0].toFixed(1)}" y2="${ip[1].toFixed(1)}" stroke="url(#gateGlow)" stroke-width="${active ? 5 : 3}" stroke-linecap="round" opacity="0.55"/>`,
);
void mp;
}
// ---- ring guide polygons ----
const guides: string[] = [];
for (const ring of ["inner", "middle", "outer"] as RingId[]) {
const pts: string[] = [];
for (let k = 0; k < 6; k++) {
const ang = (90 - 60 * k) * Math.PI / 180;
const R = RING_R[ring] + TILE_R[ring] * 0.9;
pts.push(`${(CX + R * Math.cos(ang)).toFixed(1)},${(CY - R * Math.sin(ang)).toFixed(1)}`);
}
guides.push(`<polygon points="${pts.join(" ")}" fill="none" stroke="${RING_COLOR[ring]}" stroke-width="1" stroke-dasharray="3 5" opacity="0.25"/>`);
}
// ---- tiles ----
const tiles: string[] = [];
for (const ring of ["outer", "middle", "inner"] as RingId[]) {
const tr = TILE_R[ring];
for (let i = 0; i < state.rings[ring].tiles.length; i++) {
const [x, y] = tileCenter(ring, i);
const current = state.rings[ring].tiles[i];
const c = preview?.rings[ring].tiles[i] ?? current;
const onGate = isOnGate(ring, i);
const label = tileLabel(ring, i);
// heat rim glow
const heatGlow = c.heat > 0 ? `filter="url(#heatGlow)" ` : "";
const fillCol = ring === "inner" ? "#10243a" : ring === "middle" ? "#152039" : "#0f1c33";
// nutrient liquid level at base (blue), toxin level (green)
const baseY = y + tr * 0.55;
const lvlH = tr * 1.1;
const nutH = (c.nutrient / 6) * lvlH;
const toxH = (c.toxin / 6) * lvlH;
const clipId = `clip-${ring}-${i}`;
const shownState = preview ?? state;
const adapted = (c.producer > 0 && Object.values(shownState.lineage.producer.unlocked).some(Boolean)) ||
(c.grazer > 0 && Object.values(shownState.lineage.grazer.unlocked).some(Boolean));
const resources = ([['N', c.nutrient], ['H', c.heat], ['T', c.toxin]] as [string, number][]).filter(([, value]) => value > 0).map(([name, value]) => `${name}${value}`).join(" ");
const resourceText = resources ? `<text x="${x.toFixed(1)}" y="${(y + tr * 0.62).toFixed(1)}" text-anchor="middle" font-size="${ring === "inner" ? 10 : 8}" fill="#e6edf7" font-weight="600">${resources}</text>` : "";
const adaptedMark = adapted ? `<text class="adapted-tag" x="${(x + tr * 0.55).toFixed(1)}" y="${(y - tr * 0.55).toFixed(1)}" font-size="${ring === "inner" ? 12 : 10}" fill="#fff" font-weight="800">✓</text>` : "";
// preview delta highlight
let deltaMark = "";
if (preview) {
const fields = [["N", "nutrient"], ["H", "heat"], ["T", "toxin"], ["P", "producer"], ["V", "grazer"], ["F", "phage"]] as const;
const changes = fields.flatMap(([label, field]) => {
const delta = c[field] - current[field];
return delta ? [`${label}${delta > 0 ? "+" : ""}${delta}`] : [];
});
if (changes.length) {
deltaMark = `<text class="tile-delta" x="${x.toFixed(1)}" y="${(y - tr - 4).toFixed(1)}" text-anchor="middle" font-size="${ring === "inner" ? 9 : 7}" fill="#ffe08a" font-weight="700">${changes.join(" ")}</text>`;
}
}
// species glyphs + counts
let entities = "";
const gs = tr * 0.5;
if (c.producer > 0) entities += glyphSpecies("producer", x - tr * 0.32, y - tr * 0.18, gs);
if (c.grazer > 0) entities += glyphSpecies("grazer", x + tr * 0.30, y - tr * 0.18, gs * 0.95);
if (c.phage > 0) entities += glyphSpecies("phage", x, y + tr * 0.22, gs * 0.85);
const counts: string[] = [];
if (c.producer > 0) counts.push(`<tspan fill="#7fff8a">P${c.producer}</tspan>`);
if (c.grazer > 0) counts.push(`<tspan fill="#ffc46a">V${c.grazer}</tspan>`);
if (c.phage > 0) counts.push(`<tspan fill="#ff9ec7">F${c.phage}</tspan>`);
const countText = counts.length ? `<text x="${x.toFixed(1)}" y="${(y + tr * 0.95).toFixed(1)}" text-anchor="middle" font-size="${ring === "inner" ? 12 : 10}" font-weight="700">${counts.join(" ")}</text>` : "";
// fixtures
let fixG = "";
const tileFixtures = fixturesAt(ring, i);
const fixtureDescription = tileFixtures.length ? `, fixtures: ${tileFixtures.map((fixture) => fixture.label ?? fixture.kind).join(", ")}` : "";
for (const f of tileFixtures) {
if (f.kind === "objective") continue; // drawn separately subtle
fixG += glyphFixture(f.kind, x, y - tr * 0.0, tr * 0.7);
}
// objective marker as a faint reticle behind
const objF = tileFixtures.find((f) => f.kind === "objective");
const objMark = objF ? glyphFixture("objective", x, y, tr * 1.15) : "";
tiles.push(`
<g class="tile${adapted ? " adapted" : ""}" role="img" aria-label="${label}: nutrient ${c.nutrient}, heat ${c.heat}, toxin ${c.toxin}, producer ${c.producer}, grazer ${c.grazer}, phage ${c.phage}${fixtureDescription}${adapted ? ", adapted" : ""}" data-ring="${ring}" data-index="${i}" data-values="${c.nutrient},${c.heat},${c.toxin},${c.producer},${c.grazer},${c.phage}">
${objMark}
<polygon points="${hexPoints(x, y, tr)}" ${heatGlow}fill="${fillCol}" stroke="${adapted ? "#ffffff" : onGate ? RING_COLOR[ring] : "#2a3b55"}" stroke-width="${adapted ? 3 : onGate ? 2.2 : 1.2}"/>
<defs><clipPath id="${clipId}"><polygon points="${hexPoints(x, y, tr * 0.96)}"/></clipPath></defs>
${nutH > 0 ? `<rect x="${(x - tr*0.96).toFixed(1)}" y="${(baseY - nutH).toFixed(1)}" width="${(tr*1.92).toFixed(1)}" height="${nutH.toFixed(1)}" fill="#1f6fd6" opacity="0.32" clip-path="url(#${clipId})"/>` : ""}
${toxH > 0 ? `<rect x="${(x - tr*0.96).toFixed(1)}" y="${(baseY - toxH).toFixed(1)}" width="${(tr*1.92).toFixed(1)}" height="${toxH.toFixed(1)}" fill="#5fbf4a" opacity="0.40" clip-path="url(#${clipId})"/>` : ""}
${c.heat > 0 ? `<polygon points="${hexPoints(x, y, tr)}" fill="none" stroke="#ff8a4c" stroke-width="${1 + c.heat * 0.4}" opacity="${0.3 + c.heat * 0.1}"/>` : ""}
${fixG}
${entities}
${countText}
${resourceText}
${adaptedMark}
<text x="${(x - tr*0.78).toFixed(1)}" y="${(y - tr*0.82).toFixed(1)}" font-size="${ring === "inner" ? 9 : 8}" fill="#6f86a8">${label}</text>
${deltaMark}
</g>`);
}
}
// center hub
const hub = `<circle cx="${CX}" cy="${CY}" r="34" fill="#0a1426" stroke="#2a3b55"/><text x="${CX}" y="${(CY+4).toFixed(1)}" text-anchor="middle" font-size="11" fill="#7d97bf">ADAPTIVE</text><text x="${CX}" y="${(CY+16).toFixed(1)}" text-anchor="middle" font-size="11" fill="#7d97bf">LOOP</text>`;
// ---- preview flow arrows (SPEC §12): tangential chevrons + inward radial arrows ----
const flowArrows: string[] = [];
if (opts.flowEvents && opts.flowEvents.length) {
const dirOf = (ring: RingId) => w_ringDir(ring);
for (const fe of opts.flowEvents) {
const [x, y] = tileCenter(fe.ring, fe.index);
const tr = TILE_R[fe.ring];
const col = fe.field === "nutrient" ? "#5fb0ff" : "#9fe06a";
if (fe.tangential > 0) {
// chevron along the ring direction (cw = clockwise arc)
const cw = dirOf(fe.ring) === "cw";
const dx = cw ? tr * 0.5 : -tr * 0.5;
flowArrows.push(`<path d="M ${(x - dx).toFixed(1)} ${(y - tr*0.95).toFixed(1)} l ${dx.toFixed(1)} ${(tr*0.5).toFixed(1)} l ${dx.toFixed(1)} ${(-tr*0.5).toFixed(1)}" fill="none" stroke="${col}" stroke-width="2.2" stroke-linecap="round" opacity="0.95"><title>${fe.field} tangential flow at ${tileLabel(fe.ring, fe.index)}</title></path>`);
}
if (fe.radial > 0) {
// inward arrow toward center
const ia = Math.atan2(CY - y, CX - x);
const ax = x + Math.cos(ia) * tr * 0.4, ay = y + Math.sin(ia) * tr * 0.4;
const bx = x + Math.cos(ia) * tr * 0.95, by = y + Math.sin(ia) * tr * 0.95;
flowArrows.push(`<line x1="${bx.toFixed(1)}" y1="${by.toFixed(1)}" x2="${ax.toFixed(1)}" y2="${ay.toFixed(1)}" stroke="${col}" stroke-width="2.4" stroke-linecap="round" opacity="0.95" marker-end="url(#flowHead)"><title>${fe.field} radial-inward flow at ${tileLabel(fe.ring, fe.index)}</title></line>`);
}
}
}
function w_ringDir(ring: RingId): string { return (preview ?? state).rings[ring].direction; }
const ledgerState = preview ?? state;
const ledger = (["inner", "middle", "outer"] as RingId[]).flatMap((ring) => ledgerState.rings[ring].tiles.flatMap((chamber, index) => {
const fixtureNames = fixturesAt(ring, index).map((fixture) => fixture.label ?? fixture.kind);
const occupied = Object.values(chamber).some((value) => value > 0);
if (!occupied && fixtureNames.length === 0) return [];
return [`<span><b>${tileLabel(ring, index)}</b> N${chamber.nutrient} H${chamber.heat} T${chamber.toxin} P${chamber.producer} V${chamber.grazer} F${chamber.phage}${fixtureNames.length ? ` · ${fixtureNames.join(", ")}` : ""}</span>`];
})).join("");
const ledgerHTML = `<details class="tile-ledger" open><summary>Readable tile state</summary><div>${ledger}</div></details>`;
return `<svg viewBox="0 0 ${VIEW} ${VIEW}" role="group" aria-label="Culture board: three concentric hexagonal rings linked by six radial gates${opts.flowEvents?.length ? "; preview shows flow arrows" : ""}" class="board-svg">
<defs>
<linearGradient id="gateGlow" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#7fffd6"/><stop offset="50%" stop-color="#9d7bff"/><stop offset="100%" stop-color="#5fd0ff"/>
</linearGradient>
<filter id="heatGlow" x="-50%" y="-50%" width="200%" height="200%">
<feGaussianBlur stdDeviation="2.2" result="b"/><feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
</filter>
<marker id="flowHead" markerWidth="7" markerHeight="7" refX="3.5" refY="3.5" orient="auto"><path d="M0,0 L7,3.5 L0,7 z" fill="#9fe06a"/></marker>
</defs>
<rect x="0" y="0" width="${VIEW}" height="${VIEW}" fill="#070d18"/>
${guides.join("")}
${gates.join("")}
${tiles.join("")}
${flowArrows.join("")}
${hub}
</svg>${ledgerHTML}`;
}
/** Compact textual status of pressure tracks + lineage traits for the rail. */
export function renderTraits(state: GameState): string {
const rows: string[] = [];
for (const lin of ["producer", "grazer"] as const) {
const L = state.lineage[lin];
const name = lin === "producer" ? "Lumiflora" : "Vellea";
const cells = (["heat", "hunger", "toxin", "immunity"] as const).map((p) => {
const v = L.pressure[p];
const u = L.unlocked[p];
const bar = "▰".repeat(v) + "▱".repeat(3 - v);
return `<span class="ptrack ${u ? "adapted" : ""}" aria-label="${name} ${PRESSURE_META[p].label} ${v} of 3${u ? ", adapted" : ""}"><svg viewBox="0 0 24 24" aria-hidden="true">${glyphPressure(p, 12, 12, 18)}</svg><span>${PRESSURE_META[p].label}</span><b>${bar}${u ? "✓" : ""}</b></span>`;
});
rows.push(`<div class="lineage"><span class="lin-name">${name}</span>${cells.join("")}</div>`);
}
return rows.join("");
}
+54
View File
@@ -0,0 +1,54 @@
// Board geometry: three concentric hexagonal rings + six radial gates (SPEC §4, docs/board-layout.md).
import type { RingId } from "../domain/types.ts";
export const VIEW = 640;
export const CX = VIEW / 2;
export const CY = VIEW / 2;
// Vertex radius (center to vertex) per ring.
export const RING_R: Record<RingId, number> = { inner: 96, middle: 168, outer: 246 };
// Pointy-top hex tile "radius" (circumscribed) per ring.
export const TILE_R: Record<RingId, number> = { inner: 30, middle: 23, outer: 17.5 };
const DEG = Math.PI / 180;
/** Vertex k (0..5, clockwise from top) of a hexagonal perimeter at radius R. */
function vertex(R: number, k: number): [number, number] {
const ang = (90 - 60 * k) * DEG;
return [CX + R * Math.cos(ang), CY - R * Math.sin(ang)];
}
/** Center position [x,y] of tile `index` in `ring`. */
export function tileCenter(ring: RingId, index: number): [number, number] {
const r = ring === "inner" ? 1 : ring === "middle" ? 2 : 3;
const R = RING_R[ring];
const group = Math.floor(index / r);
const frac = (index % r) / r;
const a = vertex(R, group % 6);
const b = vertex(R, (group + 1) % 6);
return [a[0] + (b[0] - a[0]) * frac, a[1] + (b[1] - a[1]) * frac];
}
/** Pointy-top hexagon polygon points string centered at (x,y) with circumradius s. */
export function hexPoints(x: number, y: number, s: number): string {
const pts: string[] = [];
for (let k = 0; k < 6; k++) {
const ang = (90 - 60 * k) * DEG;
pts.push(`${(x + s * Math.cos(ang)).toFixed(2)},${(y - s * Math.sin(ang)).toFixed(2)}`);
}
return pts.join(" ");
}
/** Label for a tile, e.g. "I0", "M2", "O3". */
export function tileLabel(ring: RingId, index: number): string {
const c = ring === "inner" ? "I" : ring === "middle" ? "M" : "O";
return `${c}${index}`;
}
/** Ring color family. */
export const RING_COLOR: Record<RingId, string> = {
inner: "#5fd0ff",
middle: "#9d7bff",
outer: "#7fffd6",
};
+100
View File
@@ -0,0 +1,100 @@
// Procedural SVG glyphs for species, fixtures, and pressure icons (SPEC §13).
// Each returns inner SVG markup (shapes) centered at (x,y) at the given scale.
import type { FixtureKind, PressureId } from "../domain/types.ts";
// ---------- Species ----------
/** Producer "Lumiflora": 6-petal diatom/flower around a chloroplast center. Green. */
export function glyphProducer(x: number, y: number, s: number): string {
const petals = [];
for (let i = 0; i < 6; i++) {
const a = (i * 60) * Math.PI / 180;
const px = x + Math.cos(a) * s * 0.5;
const py = y - Math.sin(a) * s * 0.5;
petals.push(
`<ellipse cx="${px.toFixed(1)}" cy="${py.toFixed(1)}" rx="${(s*0.30).toFixed(1)}" ry="${(s*0.16).toFixed(1)}" transform="rotate(${-i*60} ${px.toFixed(1)} ${py.toFixed(1)})" fill="#5fd97a" fill-opacity="0.85"/>`,
);
}
return `<g>${petals.join("")}<circle cx="${x}" cy="${y}" r="${(s*0.22).toFixed(1)}" fill="#bdf56a"/><circle cx="${x}" cy="${y}" r="${(s*0.11).toFixed(1)}" fill="#2e8b3d"/></g>`;
}
/** Grazer "Vellea": segmented crescent with cilia legs + mouth notch. Amber. */
export function glyphGrazer(x: number, y: number, s: number): string {
const cilia: string[] = [];
for (let i = 0; i < 3; i++) {
const t = (i + 1) / 4;
const lx = x - s * 0.45 + t * s * 0.9;
cilia.push(`<line x1="${lx.toFixed(1)}" y1="${y}" x2="${(lx+s*0.06).toFixed(1)}" y2="${(y+s*0.42).toFixed(1)}" stroke="#e6a23c" stroke-width="${(s*0.05).toFixed(1)}"/>`);
cilia.push(`<line x1="${lx.toFixed(1)}" y1="${y}" x2="${(lx-s*0.06).toFixed(1)}" y2="${(y+s*0.42).toFixed(1)}" stroke="#e6a23c" stroke-width="${(s*0.05).toFixed(1)}"/>`);
}
return `<g>
<path d="M ${(x-s*0.5).toFixed(1)} ${y} a ${ (s*0.5).toFixed(1)} ${(s*0.32).toFixed(1)} 0 0 0 ${(s).toFixed(1)} 0 a ${(s*0.34).toFixed(1)} ${(s*0.22).toFixed(1)} 0 0 0 ${(-s).toFixed(1)} 0 z" fill="#f3b34a" stroke="#c97f1e" stroke-width="${(s*0.05).toFixed(1)}"/>
<path d="M ${(x+s*0.42).toFixed(1)} ${(y-s*0.04).toFixed(1)} l ${(s*0.14).toFixed(1)} ${(s*0.10).toFixed(1)} l ${(-s*0.14).toFixed(1)} ${(s*0.10).toFixed(1)} z" fill="#7a4a08"/>
${cilia.join("")}
</g>`;
}
/** Phage: lunar-lander virus (hex capsid head + 6 leg spikes). Pink. */
export function glyphPhage(x: number, y: number, s: number): string {
const legs: string[] = [];
for (let i = 0; i < 6; i++) {
const a = (i * 60 + 30) * Math.PI / 180;
const x1 = x + Math.cos(a) * s * 0.5;
const y1 = y + Math.sin(a) * s * 0.5;
const x2 = x + Math.cos(a) * s * 0.78;
const y2 = y + Math.sin(a) * s * 0.78;
legs.push(`<line x1="${x1.toFixed(1)}" y1="${y1.toFixed(1)}" x2="${x2.toFixed(1)}" y2="${y2.toFixed(1)}" stroke="#ff6fae" stroke-width="${(s*0.07).toFixed(1)}"/><circle cx="${x2.toFixed(1)}" cy="${y2.toFixed(1)}" r="${(s*0.05).toFixed(1)}" fill="#ff6fae"/>`);
}
const hp = [];
for (let i = 0; i < 6; i++) {
const a = (90 - 60 * i) * Math.PI / 180;
hp.push(`${(x + Math.cos(a) * s * 0.45).toFixed(1)},${(y - Math.sin(a) * s * 0.45).toFixed(1)}`);
}
return `<g>${legs.join("")}<polygon points="${hp.join(" ")}" fill="#ff9ec7" stroke="#d63d86" stroke-width="${(s*0.05).toFixed(1)}"/><polygon points="${hp.slice(0,3).join(" ")}" fill="#ffd0e4" fill-opacity="0.7"/></g>`;
}
export function glyphSpecies(id: "producer" | "grazer" | "phage", x: number, y: number, s: number): string {
if (id === "producer") return glyphProducer(x, y, s);
if (id === "grazer") return glyphGrazer(x, y, s);
return glyphPhage(x, y, s);
}
// ---------- Fixtures ----------
export function glyphFixture(kind: FixtureKind, x: number, y: number, s: number): string {
switch (kind) {
case "nutrientInlet": // pipette/valve dropping a bead (blue)
return `<g>
<rect x="${(x-s*0.14).toFixed(1)}" y="${(y-s*0.5).toFixed(1)}" width="${(s*0.28).toFixed(1)}" height="${(s*0.5).toFixed(1)}" rx="${(s*0.05).toFixed(1)}" fill="#3a6ea5" stroke="#8fb8e6"/>
<polygon points="${(x-s*0.14).toFixed(1)},${y} ${(x+s*0.14).toFixed(1)},${y} ${x.toFixed(1)},${(y+s*0.22).toFixed(1)}" fill="#6fa8dc"/>
<circle cx="${x}" cy="${(y+s*0.36).toFixed(1)}" r="${(s*0.12).toFixed(1)}" fill="#9fd0ff"/>
</g>`;
case "heatSource": // coiled filament radiating warm rays (orange)
{ const rays: string[] = []; for (let i=0;i<8;i++){const a=(i*45)*Math.PI/180;rays.push(`<line x1="${(x+Math.cos(a)*s*0.55).toFixed(1)}" y1="${(y-Math.sin(a)*s*0.55).toFixed(1)}" x2="${(x+Math.cos(a)*s*0.8).toFixed(1)}" y2="${(y-Math.sin(a)*s*0.8).toFixed(1)}" stroke="#ff7a3c" stroke-width="${(s*0.05).toFixed(1)}"/>`);}
return `<g>${rays.join("")}<path d="M ${(x-s*0.3).toFixed(1)} ${y} q ${(s*0.3).toFixed(1)} ${(-s*0.3).toFixed(1)} ${(s*0.6).toFixed(1)} 0 q ${(s*0.3).toFixed(1)} ${(s*0.3).toFixed(1)} ${(s*0.6).toFixed(1)} 0" fill="none" stroke="#ff9a5c" stroke-width="${(s*0.09).toFixed(1)}"/><circle cx="${x}" cy="${y}" r="${(s*0.13).toFixed(1)}" fill="#ffb347"/></g>`; }
case "toxinInlet": // dropper of greenish droplet
return `<g><polygon points="${(x-s*0.22).toFixed(1)},${(y-s*0.4).toFixed(1)} ${(x+s*0.22).toFixed(1)},${(y-s*0.4).toFixed(1)} ${x.toFixed(1)},${(y-s*0.1).toFixed(1)}" fill="#6b8f3a" stroke="#a7d977"/><path d="M ${(x-s*0.12).toFixed(1)} ${(y-s*0.42).toFixed(1)} l ${(s*0.24).toFixed(1)} 0 l 0 ${(-s*0.18).toFixed(1)} l ${(-s*0.24).toFixed(1)} 0 z" fill="#8a6fbf"/><circle cx="${x}" cy="${(y+s*0.18).toFixed(1)}" r="${(s*0.15).toFixed(1)}" fill="#9fe06a" stroke="#5e8a2e" stroke-width="${(s*0.04).toFixed(1)}"/></g>`;
case "drain": // funnel siphon
return `<g><polygon points="${(x-s*0.34).toFixed(1)},${(y-s*0.34).toFixed(1)} ${(x+s*0.34).toFixed(1)},${(y-s*0.34).toFixed(1)} ${x.toFixed(1)},${(y+s*0.05).toFixed(1)}" fill="#445" stroke="#7d8aa0"/><rect x="${(x-s*0.07).toFixed(1)}" y="${(y+s*0.05).toFixed(1)}" width="${(s*0.14).toFixed(1)}" height="${(s*0.3).toFixed(1)}" fill="#6a7588"/><path d="M ${(x-s*0.26).toFixed(1)} ${(y-s*0.32).toFixed(1)} q ${(s*0.26).toFixed(1)} ${(s*0.16).toFixed(1)} ${(s*0.52).toFixed(1)} 0" fill="none" stroke="#9fe06a" stroke-width="${(s*0.06).toFixed(1)}"/></g>`;
case "immuneNode": // sentinel eye/lens (cyan)
return `<g><ellipse cx="${x}" cy="${y}" rx="${(s*0.4).toFixed(1)}" ry="${(s*0.24).toFixed(1)}" fill="#10303a" stroke="#5fd0ff" stroke-width="${(s*0.05).toFixed(1)}"/><circle cx="${x}" cy="${y}" r="${(s*0.16).toFixed(1)}" fill="#5fd0ff"/><circle cx="${(x-s*0.05).toFixed(1)}" cy="${(y-s*0.05).toFixed(1)}" r="${(s*0.06).toFixed(1)}" fill="#eafdff"/></g>`;
case "objective": // targeting reticle (gold)
return `<g><circle cx="${x}" cy="${y}" r="${(s*0.42).toFixed(1)}" fill="none" stroke="#ffd24a" stroke-width="${(s*0.05).toFixed(1)}" stroke-dasharray="${(s*0.14).toFixed(1)} ${(s*0.1).toFixed(1)}"/><circle cx="${x}" cy="${y}" r="${(s*0.10).toFixed(1)}" fill="#ffd24a"/><line x1="${(x-s*0.55).toFixed(1)}" y1="${y}" x2="${(x-s*0.2).toFixed(1)}" y2="${y}" stroke="#ffd24a" stroke-width="${(s*0.04).toFixed(1)}"/><line x1="${(x+s*0.2).toFixed(1)}" y1="${y}" x2="${(x+s*0.55).toFixed(1)}" y2="${y}" stroke="#ffd24a" stroke-width="${(s*0.04).toFixed(1)}"/><line x1="${x}" y1="${(y-s*0.55).toFixed(1)}" x2="${x}" y2="${(y-s*0.2).toFixed(1)}" stroke="#ffd24a" stroke-width="${(s*0.04).toFixed(1)}"/><line x1="${x}" y1="${(y+s*0.2).toFixed(1)}" x2="${x}" y2="${(y+s*0.55).toFixed(1)}" stroke="#ffd24a" stroke-width="${(s*0.04).toFixed(1)}"/></g>`;
}
}
// ---------- Pressure icons ----------
export function glyphPressure(p: PressureId, x: number, y: number, s: number): string {
switch (p) {
case "heat": { // radiating sun rays (warm)
const r: string[] = []; for (let i=0;i<8;i++){const a=(i*45)*Math.PI/180;r.push(`<line x1="${x}" y1="${y}" x2="${(x+Math.cos(a)*s*0.5).toFixed(1)}" y2="${(y-Math.sin(a)*s*0.5).toFixed(1)}" stroke="#ff8a4c" stroke-width="${(s*0.06).toFixed(1)}"/>`);}
return `<g>${r.join("")}<circle cx="${x}" cy="${y}" r="${(s*0.2).toFixed(1)}" fill="#ff8a4c"/></g>`; }
case "hunger": // waning crescent (violet)
return `<g><path d="M ${(x+s*0.28).toFixed(1)} ${y} a ${(s*0.4).toFixed(1)} ${(s*0.4).toFixed(1)} 0 1 0 0 ${(s*0.001).toFixed(1)} z" fill="#b388ff"/><path d="M ${(x+s*0.28).toFixed(1)} ${y} a ${(s*0.28).toFixed(1)} ${(s*0.28).toFixed(1)} 0 1 1 0 ${(s*0.001).toFixed(1)} z" fill="#0d1117"/></g>`;
case "toxin": // skull-and-drop (green)
return `<g><path d="M ${(x-s*0.18).toFixed(1)} ${(y+s*0.34).toFixed(1)} q ${(s*0.18).toFixed(1)} ${(-s*0.1).toFixed(1)} ${(s*0.36).toFixed(1)} 0 q ${(-s*0.05).toFixed(1)} ${(s*0.18).toFixed(1)} ${(-s*0.36).toFixed(1)} 0 z" fill="#7fd66b"/><circle cx="${(x-s*0.07).toFixed(1)}" cy="${(y-s*0.08).toFixed(1)}" r="${(s*0.10).toFixed(1)}" fill="#0d1117"/><circle cx="${(x+s*0.07).toFixed(1)}" cy="${(y-s*0.08).toFixed(1)}" r="${(s*0.10).toFixed(1)}" fill="#0d1117"/></g>`;
case "immunity": // shield (cyan)
return `<g><path d="M ${x} ${(y-s*0.4).toFixed(1)} l ${(s*0.34).toFixed(1)} ${(s*0.12).toFixed(1)} l 0 ${(s*0.26).toFixed(1)} q 0 ${(s*0.22).toFixed(1)} ${(-s*0.34).toFixed(1)} ${(s*0.14).toFixed(1)} q ${(-s*0.34).toFixed(1)} ${(-s*0.22).toFixed(1)} 0 ${(-s*0.14).toFixed(1)} z" fill="#5fd0ff" fill-opacity="0.5" stroke="#5fd0ff" stroke-width="${(s*0.05).toFixed(1)}"/><path d="M ${(x-s*0.12).toFixed(1)} ${y} l ${(s*0.10).toFixed(1)} ${(s*0.12).toFixed(1)} l ${(s*0.18).toFixed(1)} ${(-s*0.2).toFixed(1)}" fill="none" stroke="#0d1117" stroke-width="${(s*0.06).toFixed(1)}"/></g>`;
}
}
+286
View File
@@ -0,0 +1,286 @@
import { describe, it, expect } from "vitest";
import { buildTestState } from "../src/domain/scenarios.ts";
import { nextState, resolve } from "../src/domain/transition.ts";
import { canonical, canonicalEqual, cloneState } from "../src/domain/core.ts";
// Helper: trigger a tick that does NOT rotate the inner/middle/outer ring under test
// by rotating a different ring. Direction of the rotated ring is set; others keep initial cw.
const tickOuter = (s: Parameters<typeof nextState>[0]) => nextState(s, { ring: "outer", dir: "cw" });
const tickMiddle = (s: Parameters<typeof nextState>[0]) => nextState(s, { ring: "middle", dir: "cw" });
describe("rotation", () => {
it("cw moves payload i -> i+1 (heat marker; global cooldown -1)", () => {
const s = buildTestState({ tiles: [{ ring: "inner", index: 0, chamber: { heat: 5 } }] });
const n = nextState(s, { ring: "inner", dir: "cw" });
expect(n.rings.inner.direction).toBe("cw");
expect(n.rings.inner.tiles[1].heat).toBe(4); // 5 moved 0->1, then cooldown -1
expect(n.rings.inner.tiles[0].heat).toBe(0);
});
it("ccw moves payload i -> i-1", () => {
const s = buildTestState({ tiles: [{ ring: "inner", index: 0, chamber: { heat: 5 } }] });
const n = nextState(s, { ring: "inner", dir: "ccw" });
expect(n.rings.inner.direction).toBe("ccw");
expect(n.rings.inner.tiles[5].heat).toBe(4); // 0 -> 5 (ccw), cooldown -1
});
it("middle and outer rotate and update direction", () => {
for (const ring of ["middle", "outer"] as const) {
const s = buildTestState({ tiles: [{ ring, index: 0, chamber: { heat: 5 } }] });
const n = nextState(s, { ring, dir: "ccw" });
expect(n.rings[ring].direction).toBe("ccw");
const last = ring === "middle" ? 11 : 17;
expect(n.rings[ring].tiles[last].heat).toBe(4);
}
});
});
describe("gate alignment after rotation", () => {
it("rotating outer moves an on-gate payload off the gate", () => {
// O3 is on gate 1 (3*1). Put a marker; rotate outer cw -> payload moves to O4 (off gate).
const s = buildTestState({ tiles: [{ ring: "outer", index: 3, chamber: { heat: 5 } }] });
const n = nextState(s, { ring: "outer", dir: "cw" });
expect(n.rings.outer.tiles[4].heat).toBe(4); // marker now at O4 (off-gate, 4%3=1!=0)
expect(n.rings.outer.tiles[3].heat).toBe(0);
});
});
describe("channel flow", () => {
it("tangential: nutrient flows cw to next tile", () => {
const s = buildTestState({ tiles: [{ ring: "inner", index: 0, chamber: { nutrient: 6 } }] });
const n = tickOuter(s); // inner doesn't rotate; inner dir cw
expect(n.rings.inner.tiles[0].nutrient).toBe(5); // sent 1 tangential
expect(n.rings.inner.tiles[1].nutrient).toBe(1); // received
});
it("radial inward: outer on-gate sends nutrient to middle on-gate", () => {
const s = buildTestState({ tiles: [{ ring: "outer", index: 0, chamber: { nutrient: 6 } }] });
const n = tickMiddle(s); // middle rotates (empty); outer gate0 has nutrient
// outer0 sent 1 tangential (->O1) + 1 radial (->M0): 6-2=4
expect(n.rings.outer.tiles[0].nutrient).toBe(4);
expect(n.rings.middle.tiles[0].nutrient).toBe(1); // received radial at M0 (gate0)
});
it("caps at 6 (overflow discarded)", () => {
// producer at cap with high nutrient consumes nutrient, gains 0 (clamped)
const s = buildTestState({ tiles: [{ ring: "inner", index: 0, chamber: { producer: 6, nutrient: 6 } }] });
const n = tickOuter(s);
expect(n.rings.inner.tiles[0].producer).toBe(6);
expect(n.rings.inner.tiles[0].nutrient).toBe(4); // 6 -1 flow -1 growth = 4
});
});
describe("growth and biological interactions", () => {
it("producer grows consuming nutrient (high nutrient isolates from migration)", () => {
const s = buildTestState({ tiles: [{ ring: "inner", index: 0, chamber: { producer: 1, nutrient: 6 } }] });
const n = tickOuter(s);
expect(n.rings.inner.tiles[0].producer).toBe(2); // 1 -> 2
expect(n.rings.inner.tiles[0].nutrient).toBe(4); // 6 -1 flow -1 growth
});
it("grazer consumes one producer and gains one grazer", () => {
const s = buildTestState({ tiles: [{ ring: "inner", index: 0, chamber: { producer: 2, grazer: 1, nutrient: 6 } }] });
const n = tickOuter(s);
// growth: producer 2->3 (nutrient 6->4 after flow); grazer eats 1 -> producer 2, grazer 2
expect(n.rings.inner.tiles[0].producer).toBe(2);
expect(n.rings.inner.tiles[0].grazer).toBe(2);
});
it("phage consumes a grazer and gains; otherwise starves", () => {
const fed = buildTestState({ tiles: [{ ring: "inner", index: 0, chamber: { producer: 2, grazer: 2, phage: 1, nutrient: 6 } }] });
const nf = tickOuter(fed);
// growth prod2->3; grazer eats prod 3->2 grazer2->3; phage eats grazer 3->2 phage1->2
expect(nf.rings.inner.tiles[0].phage).toBe(2);
const starve = buildTestState({ tiles: [{ ring: "inner", index: 0, chamber: { phage: 2 } }] });
const ns = tickOuter(starve);
expect(ns.rings.inner.tiles[0].phage).toBe(1); // starved -1
});
});
describe("migration", () => {
it("producer migrates one step toward strictly-greater food (nutrient)", () => {
// I0 producer3 + nutrient6 (survives, stays put mostly); I1 nutrient6 attracts migration
const s = buildTestState({
tiles: [
{ ring: "inner", index: 0, chamber: { producer: 3, nutrient: 6 } },
{ ring: "inner", index: 1, chamber: { nutrient: 6 } },
],
});
const n = tickOuter(s);
// I0 grows 3->4 (nutrient 6->4 after flow); food at I0=4, I1 nutrient=6 >4 -> migrate 1 to I1
expect(n.rings.inner.tiles[0].producer).toBe(3); // 4 -1 migrated
expect(n.rings.inner.tiles[1].producer).toBe(1); // migrated in
});
it("radial migration through a gate toward greater food", () => {
// I0 producer2 + low nutrient; M0 (gate0) high nutrient attracts radial migration outward
const s = buildTestState({
tiles: [
{ ring: "inner", index: 0, chamber: { producer: 2, nutrient: 2 } },
{ ring: "middle", index: 0, chamber: { nutrient: 6 } },
],
});
const n = tickOuter(s);
// I0 nutrient stays low; M0 nutrient > I0 -> producer migrates radially to M0
expect(n.rings.middle.tiles[0].producer).toBe(1); // producer reached M0 via gate
expect(n.rings.inner.tiles[0].producer).toBe(2); // grew 2->3 then -1 migrated
});
});
describe("adaptations: benefit, cost, spillover", () => {
it("heat shield: prevents loss (benefit), suppresses growth (cost), cools tile (spillover)", () => {
// nutrient present (no hunger); heat-adapted suppresses growth (cost) and prevents heat loss (benefit)
const s = buildTestState({
tiles: [{ ring: "inner", index: 0, chamber: { producer: 2, nutrient: 6, heat: 3 } }],
unlocked: { producer: ["heat"], grazer: [] },
});
const n = tickOuter(s);
expect(n.rings.inner.tiles[0].producer).toBe(2); // no growth (cost), no loss (benefit)
expect(n.rings.inner.tiles[0].nutrient).toBe(4); // flow -1; producer still consumes 1, only gain is suppressed
});
it("heat-adapted grazer consumes prey but gains no population", () => {
const s = buildTestState({
tiles: [{ ring: "inner", index: 0, chamber: { producer: 3, grazer: 1, nutrient: 6, heat: 3 } }],
unlocked: { producer: [], grazer: ["heat"] },
});
const result = resolve(s, { ring: "outer", dir: "cw" });
expect(result.state.rings.inner.tiles[0].producer).toBe(1); // grew, was eaten, then lost 2 to heat
expect(result.state.rings.inner.tiles[0].grazer).toBe(1);
expect(result.events.some((event) => event.phase === "feed" && event.suppressed)).toBe(true);
});
it("unadapted heat loses 2 population", () => {
const s = buildTestState({
tiles: [{ ring: "inner", index: 0, chamber: { producer: 2, nutrient: 6, heat: 3 } }],
});
const n = tickOuter(s);
// growth 2->3 (nutrient 6->4); heat loss -2 -> producer 1
expect(n.rings.inner.tiles[0].producer).toBe(1);
});
it("dormancy: prevents hunger loss (benefit)", () => {
const s = buildTestState({
tiles: [{ ring: "inner", index: 0, chamber: { producer: 2, nutrient: 0 } }],
unlocked: { producer: ["hunger"], grazer: [] },
});
const n = tickOuter(s);
expect(n.rings.inner.tiles[0].producer).toBe(2); // no loss
});
it("unadapted hunger loses 1 population", () => {
const s = buildTestState({ tiles: [{ ring: "inner", index: 0, chamber: { producer: 2, nutrient: 0 } }] });
const n = tickOuter(s);
expect(n.rings.inner.tiles[0].producer).toBe(1);
});
it("efflux: prevents toxin pop loss, pays nutrient (cost), reduces toxin (spillover)", () => {
const s = buildTestState({
tiles: [{ ring: "inner", index: 0, chamber: { producer: 2, nutrient: 6, toxin: 4 } }],
unlocked: { producer: ["toxin"], grazer: [] },
});
const n = tickOuter(s);
// growth 2->3 (nutrient 6->4 after flow); toxin 4->3 after flow; efflux pays 1 nutrient; spillover -1 toxin
expect(n.rings.inner.tiles[0].producer).toBe(3); // no toxin pop loss (benefit)
expect(n.rings.inner.tiles[0].nutrient).toBe(3); // 4 -1 efflux pay
expect(n.rings.inner.tiles[0].toxin).toBe(2); // 3 -1 spillover
});
it("unadapted toxin loses 1 population", () => {
const s = buildTestState({ tiles: [{ ring: "inner", index: 0, chamber: { producer: 2, nutrient: 6, toxin: 4 } }] });
const n = tickOuter(s);
expect(n.rings.inner.tiles[0].producer).toBe(2); // grew 2->3 then toxin loss -1 -> 2
});
it("immune node damages the selected lineage by 2", () => {
const s = buildTestState({
tiles: [{ ring: "inner", index: 1, chamber: { producer: 3, nutrient: 6 } }],
fixtures: [{ kind: "immuneNode", ring: "inner", index: 1 }],
});
const n = tickOuter(s);
// growth 3->4; immune damage -2 -> producer 2
expect(n.rings.inner.tiles[1].producer).toBe(2);
});
it("cloak: cloaked lineage is protected from immune selection (spillover retarget)", () => {
const cloaked = buildTestState({
tiles: [{ ring: "inner", index: 1, chamber: { producer: 2, grazer: 3 } }],
unlocked: { producer: [], grazer: ["immunity"] },
fixtures: [{ kind: "immuneNode", ring: "inner", index: 1 }],
});
const nc = tickOuter(cloaked);
// grazer feeds (producer 2->1, grazer 3->4); immune selects producer (grazer cloaked) -> producer 1->0
expect(nc.rings.inner.tiles[1].grazer).toBe(4); // protected by cloak, survived + fed
const exposed = buildTestState({
tiles: [{ ring: "inner", index: 1, chamber: { producer: 2, grazer: 3 } }],
fixtures: [{ kind: "immuneNode", ring: "inner", index: 1 }],
});
const ne = tickOuter(exposed);
// grazer feeds (3->4); immune selects largest (grazer 4) -> grazer 4-2=2
expect(ne.rings.inner.tiles[1].grazer).toBe(2); // damaged without cloak
});
});
describe("environmental response", () => {
it("heat response active: heat source adds 3 (vs 2 when inactive)", () => {
const active = buildTestState({
tiles: [{ ring: "outer", index: 3, chamber: {} }],
fixtures: [{ kind: "heatSource", ring: "outer", index: 3 }],
environmentActive: ["heat"],
});
const na = tickOuter(active);
expect(na.rings.outer.tiles[3].heat).toBe(2); // +3 then -1 cooldown
const inactive = buildTestState({
tiles: [{ ring: "outer", index: 3, chamber: {} }],
fixtures: [{ kind: "heatSource", ring: "outer", index: 3 }],
});
const ni = tickOuter(inactive);
expect(ni.rings.outer.tiles[3].heat).toBe(1); // +2 then -1 cooldown
});
});
describe("immutability, determinism, terminal", () => {
it("input is not mutated", () => {
const s = buildTestState({ tiles: [{ ring: "inner", index: 0, chamber: { producer: 1, nutrient: 1 } }] });
const before = cloneState(s);
nextState(s, { ring: "inner", dir: "cw" });
expect(canonicalEqual(before, s)).toBe(true);
});
it("canonical determinism: same input+action -> same canonical", () => {
const s = buildTestState({ tiles: [{ ring: "inner", index: 0, chamber: { producer: 1, nutrient: 3 } }] });
const a = nextState(s, { ring: "inner", dir: "cw" });
const b = nextState(s, { ring: "inner", dir: "cw" });
expect(canonical(a)).toBe(canonical(b));
});
it("collapse when total producer+grazer = 0", () => {
const s = buildTestState({ tiles: [{ ring: "inner", index: 0, chamber: { producer: 1, heat: 6 } }] });
const n = tickOuter(s);
expect(n.outcome).toBe("collapsed");
});
it("expiry when turn limit reached without win/collapse", () => {
const s = buildTestState({
tiles: [{ ring: "inner", index: 0, chamber: { producer: 2, nutrient: 6 } }],
scenarioId: "expire1",
turnLimit: 1,
});
const n = tickOuter(s);
expect(n.outcome).toBe("expired");
});
it("terminal precedence: collapse beats win", () => {
// win would be true, but population hits 0 -> collapsed
const s = buildTestState({
tiles: [{ ring: "inner", index: 0, chamber: { producer: 1, heat: 6 } }],
scenarioId: "winbutdie",
turnLimit: 5,
win: () => true,
});
const n = tickOuter(s);
expect(n.outcome).toBe("collapsed");
});
it("rejects actions in terminal states without changing canonical state", () => {
const s = buildTestState({ tiles: [{ ring: "inner", index: 0, chamber: { producer: 1, heat: 6 } }] });
const terminal = tickOuter(s);
const after = nextState(terminal, { ring: "inner", dir: "cw" });
expect(canonical(after)).toBe(canonical(terminal));
});
});
describe("preview/commit equality + replay", () => {
it("resolve preview state equals committed nextState", () => {
const s = buildTestState({ tiles: [{ ring: "inner", index: 0, chamber: { producer: 2, nutrient: 4, grazer: 1 } }] });
const { state: preview } = resolve(s, { ring: "inner", dir: "cw" });
const committed = nextState(s, { ring: "inner", dir: "cw" });
expect(canonicalEqual(preview, committed)).toBe(true);
});
it("event list is deterministic from prior state + action", () => {
const s = buildTestState({ tiles: [{ ring: "inner", index: 0, chamber: { producer: 2, nutrient: 4 } }] });
const e1 = resolve(s, { ring: "inner", dir: "cw" }).events;
const e2 = resolve(s, { ring: "inner", dir: "cw" }).events;
expect(JSON.stringify(e1)).toBe(JSON.stringify(e2));
});
});
+76
View File
@@ -0,0 +1,76 @@
import { describe, it, expect } from "vitest";
import { readFileSync } from "fs";
import { SCENARIOS, buildInitialState, getScenario } from "../src/domain/scenarios.ts";
import { replay } from "../src/domain/solver.ts";
import type { GameState, LineageId, PressureId, RotationAction } from "../src/domain/types.ts";
type Fix = { fixtures: Record<string, { win: RotationAction[] }> };
const data = JSON.parse(readFileSync("test/solver-fixtures.json", "utf8")) as Fix;
/** Simulate campaign progression: win each scenario with the verified route, optionally
* preserving the first newly-unlocked trait, carrying inheritance forward. */
function runCampaign(preserveFirst: boolean): { victory: boolean; inherited: Record<LineageId, PressureId[]>; perScenario: GameState[] } {
let inherited: Record<LineageId, PressureId[]> = { producer: [], grazer: [] };
const perScenario: GameState[] = [];
for (const sc of SCENARIOS) {
const start = buildInitialState(sc, "campaign", inherited);
const end = replay(sc, inherited, data.fixtures[sc.id].win);
expect(end.outcome, `${sc.id} should be won in campaign`).toBe("won");
perScenario.push(end);
if (sc.id === SCENARIOS[SCENARIOS.length - 1].id) break; // no next after last
if (preserveFirst) {
// preserve first newly-unlocked trait not already inherited
for (const lin of ["producer", "grazer"] as LineageId[]) {
for (const p of ["heat", "hunger", "toxin", "immunity"] as PressureId[]) {
if (end.lineage[lin].unlocked[p] && !inherited[lin].includes(p)) {
inherited = { producer: [...inherited.producer], grazer: [...inherited.grazer] };
inherited[lin] = [...inherited[lin], p];
lin; p;
break;
}
}
break;
}
}
}
return { victory: true, inherited, perScenario };
}
describe("Gate 5 — campaign progression", () => {
it("wins all five scenarios in order with baseline lineages (campaign victory reachable)", () => {
const r = runCampaign(false);
expect(r.perScenario).toHaveLength(5);
expect(r.perScenario.every((s) => s.outcome === "won")).toBe(true);
});
it("a preserved lineage trait (gift+cost) still lets the next scenario be won", async () => {
// carry producer Heat Shield (from s1) into s2 and re-solve: campaign can proceed with the burden
const { solveWin } = await import("../src/domain/solver.ts");
const win = solveWin(getScenario("s2-hunger"), { producer: ["heat"], grazer: [] }, { nodeBudget: 3_000_000, timeMs: 60000 });
expect(win, "s2 must remain solvable when carrying inherited Heat Shield").not.toBeNull();
}, 90000);
it("pressure counters and env flags reset between scenarios even when traits inherited", () => {
const inh: Record<LineageId, PressureId[]> = { producer: ["heat"], grazer: [] };
const start = buildInitialState(getScenario("s2-hunger"), "campaign", inh);
expect(start.lineage.producer.pressure.heat).toBe(0); // counter reset
expect(start.environmentActive.heat).toBe(false); // env flag reset
expect(start.lineage.producer.unlocked.heat).toBe(true); // trait preserved
});
it("retry restores the scenario-entry inheritance snapshot", () => {
// entering s3 with a preserved trait, then retry must restore exactly that entry set
const entry: Record<LineageId, PressureId[]> = { producer: ["heat"], grazer: [] };
const s3 = buildInitialState(getScenario("s3-toxin"), "campaign", entry);
expect(s3.lineage.producer.unlocked.heat).toBe(true);
// a retry rebuilds from the same entry snapshot
const retried = buildInitialState(getScenario("s3-toxin"), "campaign", entry);
expect(JSON.stringify(retried)).toBe(JSON.stringify(s3));
});
it("standalone uses clean baseline (no carried traits)", () => {
const standalone = buildInitialState(getScenario("s4-immunity"), "standalone", { producer: [], grazer: [] });
expect(standalone.lineage.producer.unlocked.heat).toBe(false);
expect(standalone.mode).toBe("standalone");
});
});
+64
View File
@@ -0,0 +1,64 @@
import { beforeEach, describe, expect, it } from "vitest";
import { canonical } from "../src/domain/core.ts";
import { buildInitialState, getScenario } from "../src/domain/scenarios.ts";
import { nextState } from "../src/domain/transition.ts";
import { loadGame, saveGame } from "../src/persistence/save.ts";
const values = new Map<string, string>();
Object.defineProperty(globalThis, "localStorage", {
value: {
getItem: (key: string) => values.get(key) ?? null,
setItem: (key: string, value: string) => values.set(key, value),
removeItem: (key: string) => values.delete(key),
},
configurable: true,
});
beforeEach(() => values.clear());
describe("exact persistence", () => {
it("restores canonical state and its exact next transition", () => {
const scenario = getScenario("s1-heat");
const state = nextState(buildInitialState(scenario, "campaign"), { ring: "inner", dir: "cw" });
const progress = { unlocked: [scenario.id], inherited: { producer: [], grazer: [] }, entrySnapshot: { producer: [], grazer: [] }, victory: false };
saveGame({ schemaVersion: 1, mode: "campaign", scenarioId: scenario.id, state, progress, actionLog: state.actionLog, outcome: state.outcome });
const loaded = loadGame();
expect(loaded.ok).toBe(true);
if (!loaded.ok) return;
expect(canonical(loaded.env.state)).toBe(canonical(state));
const action = { ring: "middle", dir: "ccw" } as const;
expect(canonical(nextState(loaded.env.state, action))).toBe(canonical(nextState(state, action)));
});
it("rejects a structurally valid save whose state cannot be reproduced from its action log", () => {
const scenario = getScenario("s1-heat");
const state = nextState(buildInitialState(scenario, "campaign"), { ring: "inner", dir: "cw" });
const progress = { unlocked: [scenario.id], inherited: { producer: [], grazer: [] }, entrySnapshot: { producer: [], grazer: [] }, victory: false };
saveGame({ schemaVersion: 1, mode: "campaign", scenarioId: scenario.id, state, progress, actionLog: state.actionLog, outcome: state.outcome });
const tampered = JSON.parse(values.get("adaptive-loop-save-v1")!);
tampered.state.rings.inner.tiles[0].nutrient++;
values.set("adaptive-loop-save-v1", JSON.stringify(tampered));
expect(loadGame().ok).toBe(false);
});
it("rejects impossible campaign unlock and victory progress", () => {
const scenario = getScenario("s1-heat");
const state = buildInitialState(scenario, "campaign");
const progress = { unlocked: [scenario.id], inherited: { producer: [], grazer: [] }, entrySnapshot: { producer: [], grazer: [] }, victory: false };
saveGame({ schemaVersion: 1, mode: "campaign", scenarioId: scenario.id, state, progress, actionLog: [], outcome: state.outcome });
const tampered = JSON.parse(values.get("adaptive-loop-save-v1")!);
tampered.progress.unlocked.push("s5-convergence");
tampered.progress.victory = true;
values.set("adaptive-loop-save-v1", JSON.stringify(tampered));
expect(loadGame().ok).toBe(false);
});
it("canonicalizes nested object keys recursively", () => {
expect(canonical({ z: { b: 2, a: 1 }, a: [{ d: 4, c: 3 }] })).toBe(canonical({ a: [{ c: 3, d: 4 }], z: { a: 1, b: 2 } }));
});
it("rejects malformed JSON safely", () => {
values.set("adaptive-loop-save-v1", "{bad");
expect(loadGame()).toEqual({ ok: false, reason: "Saved game is corrupt (invalid JSON)." });
});
});
+34
View File
@@ -0,0 +1,34 @@
import { describe, expect, it } from "vitest";
import { canonical } from "../src/domain/core.ts";
import { buildInitialState, getScenario } from "../src/domain/scenarios.ts";
import { replay } from "../src/domain/solver.ts";
import type { RotationAction } from "../src/domain/types.ts";
const scenario = getScenario("s1-heat");
const win: RotationAction[] = [
{ ring: "inner", dir: "cw" }, { ring: "inner", dir: "ccw" },
{ ring: "middle", dir: "ccw" }, { ring: "middle", dir: "ccw" },
{ ring: "middle", dir: "ccw" }, { ring: "middle", dir: "ccw" },
{ ring: "middle", dir: "cw" }, { ring: "outer", dir: "cw" },
];
const collapse: RotationAction[] = [
{ ring: "inner", dir: "cw" }, { ring: "middle", dir: "ccw" },
{ ring: "outer", dir: "cw" }, { ring: "outer", dir: "cw" },
{ ring: "inner", dir: "cw" },
];
const expire: RotationAction[] = Array.from({ length: 8 }, () => ({ ring: "inner", dir: "cw" as const }));
describe("Gate 2 — complete Scenario 1", () => {
it("has playable win, collapse, and expiration routes", () => {
expect(replay(scenario, { producer: [], grazer: [] }, win).outcome).toBe("won");
expect(replay(scenario, { producer: [], grazer: [] }, collapse).outcome).toBe("collapsed");
expect(replay(scenario, { producer: [], grazer: [] }, expire).outcome).toBe("expired");
});
it("retry restores the exact scenario baseline", () => {
const baseline = buildInitialState(scenario, "campaign");
const afterLoss = replay(scenario, { producer: [], grazer: [] }, collapse);
expect(afterLoss.outcome).toBe("collapsed");
expect(canonical(buildInitialState(scenario, "campaign"))).toBe(canonical(baseline));
});
});
+44
View File
@@ -0,0 +1,44 @@
import { describe, it, expect } from "vitest";
import { buildInitialState, getScenario } from "../src/domain/scenarios.ts";
import { nextState, resolve } from "../src/domain/transition.ts";
import { canonical, cloneState, canonicalEqual, gateIndex } from "../src/domain/core.ts";
describe("smoke", () => {
it("builds and runs scenario 1 initial rotation without throwing", () => {
const s = buildInitialState(getScenario("s1-heat"), "campaign");
const before = cloneState(s);
const next = nextState(s, { ring: "outer", dir: "cw" });
// input immutability
expect(canonicalEqual(before, s)).toBe(true);
// turn advanced
expect(next.turn).toBe(1);
// outer ring direction updated
expect(next.rings.outer.direction).toBe("cw");
// action logged
expect(next.actionLog).toHaveLength(1);
});
it("cw rotation moves payload at i to i+1", () => {
const s = buildInitialState(getScenario("s1-heat"), "campaign");
// O0 has producer 2, nutrient 3; rotate outer cw -> payload moves to O1, then grows to 3
const next = nextState(s, { ring: "outer", dir: "cw" });
expect(next.rings.outer.tiles[1].producer).toBe(3); // 2 from rotation + 1 growth
expect(next.rings.outer.tiles[0].producer).toBe(0);
});
it("resolve returns deterministic events", () => {
const s = buildInitialState(getScenario("s1-heat"), "campaign");
const a = nextState(s, { ring: "inner", dir: "cw" });
const b = nextState(s, { ring: "inner", dir: "cw" });
expect(canonical(a)).toBe(canonical(b));
const { events } = resolve(s, { ring: "inner", dir: "cw" });
expect(events.some((e) => e.phase === "rotate")).toBe(true);
expect(events.some((e) => e.phase === "outcome")).toBe(true);
});
it("gate index derivation", () => {
expect(gateIndex("inner", 0)).toBe(0);
expect(gateIndex("middle", 1)).toBe(2);
expect(gateIndex("outer", 2)).toBe(6);
});
});
File diff suppressed because it is too large. Load diff
+109
View File
@@ -0,0 +1,109 @@
import { describe, it, expect } from "vitest";
import { readFileSync } from "fs";
import { SCENARIOS, getScenario, buildInitialState } from "../src/domain/scenarios.ts";
import { inheritanceKey, reachableInheritanceAt, replay } from "../src/domain/solver.ts";
import { nextState, resolve } from "../src/domain/transition.ts";
import type { RotationAction } from "../src/domain/types.ts";
type Fixtures = {
fixtures: Record<string, { win: RotationAction[]; winOutcome: string; loss: RotationAction[]; lossOutcome: string; exploitsAdaptation: boolean; avoidsAdaptation: boolean }>;
campaignRoutes: Record<string, RotationAction[]>;
adaptationEvidence: { scenarioId: string; inheritanceKey: string; route: RotationAction[]; evolved: boolean; benefit: boolean; cost: boolean; spillover: boolean; all: boolean };
reachOk: boolean;
reachReport: string[];
};
const data = JSON.parse(readFileSync("test/solver-fixtures.json", "utf8")) as Fixtures;
describe("Gate 4 — scenario solver routes (baseline)", () => {
for (const [id, f] of Object.entries(data.fixtures)) {
it(`${id}: win route replays to 'won'`, () => {
const sc = getScenario(id);
const end = replay(sc, { producer: [], grazer: [] }, f.win);
expect(end.outcome).toBe("won");
});
it(`${id}: loss route replays to a loss (collapsed or expired)`, () => {
const sc = getScenario(id);
const end = replay(sc, { producer: [], grazer: [] }, f.loss);
expect(end.outcome === "collapsed" || end.outcome === "expired").toBe(true);
});
}
it("a baseline winning route provokes and exercises adaptation benefit, cost, and spillover", () => {
const evidence = data.adaptationEvidence;
const scenario = getScenario(evidence.scenarioId);
const inherited = reachableInheritanceAt(scenario.index).find((candidate) => inheritanceKey(candidate) === evidence.inheritanceKey)!;
let state = buildInitialState(scenario, "campaign", inherited);
const effects = { evolved: false, benefit: false, cost: false, spillover: false };
for (const action of evidence.route) {
const result = resolve(state, action, true);
state = result.state;
for (const event of result.events) {
if (event.phase === "evolution") effects.evolved = true;
if (event.phase === "adaptation" && event.effect === "cost") effects.cost = true;
if (event.phase === "adaptation" && event.effect === "spillover") effects.spillover = true;
if (event.phase === "consequence" && event.kind === "prevented") effects.benefit = true;
if ((event.phase === "consequence" && (event.kind === "payNutrient" || event.kind === "payPop")) ||
(event.phase === "growth" && event.suppressed) ||
(event.phase === "feed" && (event.suppressed || event.preyRemoved === 2))) effects.cost = true;
if (event.phase === "spillover" || (event.phase === "immuneSelect" && event.retarget)) effects.spillover = true;
}
}
expect(evidence.inheritanceKey).toBe("P:|G:");
expect(state.outcome).toBe("won");
expect(effects).toEqual({ evolved: true, benefit: true, cost: true, spillover: true });
});
it("at least one baseline route avoids its scenario's matching adaptation", () => {
const anyAvoids = Object.values(data.fixtures).some((f) => f.avoidsAdaptation);
expect(anyAvoids).toBe(true);
});
it("a verified route changes gate alignment and produces radial flow", () => {
const scenario = getScenario("s1-heat");
let state = buildInitialState(scenario, "campaign");
let proved = false;
for (const action of data.fixtures[scenario.id].win) {
const result = resolve(state, action);
if (action.ring !== "inner" && result.events.some((event) => event.phase === "flow" && event.radial > 0)) proved = true;
state = result.state;
}
expect(proved).toBe(true);
});
it("Scenario 5 starts outside its objective and its winning route aligns multiple rings", () => {
const scenario = getScenario("s5-convergence");
const initial = buildInitialState(scenario, "campaign");
expect(scenario.sustained(initial, {} as never)).toBe(false);
expect(new Set(data.fixtures[scenario.id].win.map((action) => action.ring)).size).toBeGreaterThan(1);
expect(data.fixtures[scenario.id].win.length).toBeGreaterThan(2);
});
});
describe("Gate 4 — campaign inheritance reachability", () => {
it("replays a win for every conservative-superset inheritance set", () => {
expect(data.reachOk, data.reachReport.filter((r) => r.startsWith("FAIL")).join("\n")).toBe(true);
let checked = 0;
for (let scenarioIndex = 2; scenarioIndex <= 5; scenarioIndex++) {
const scenario = SCENARIOS[scenarioIndex - 1];
for (const inherited of reachableInheritanceAt(scenarioIndex)) {
const route = data.campaignRoutes[`${scenario.id}|${inheritanceKey(inherited)}`];
expect(route, `${scenario.id} ${inheritanceKey(inherited)}`).toBeDefined();
expect(replay(scenario, inherited, route).outcome).toBe("won");
checked++;
}
}
expect(checked).toBe(302);
});
});
describe("Gate 4 — replay reproduction (action log from baseline)", () => {
it("replaying a win's action log from baseline reproduces the exact final state", () => {
const sc = getScenario("s1-heat");
const viaReplay = replay(sc, { producer: [], grazer: [] }, data.fixtures["s1-heat"].win);
let viaLog = buildInitialState(sc, "campaign");
for (const a of data.fixtures["s1-heat"].win) viaLog = nextState(viaLog, a);
expect(JSON.stringify(viaReplay)).toBe(JSON.stringify(viaLog));
});
});
+14
View File
@@ -0,0 +1,14 @@
import { describe, expect, it } from "vitest";
import { buildInitialState, getScenario } from "../src/domain/scenarios.ts";
import { hashState, reachableInheritanceAt } from "../src/domain/solver.ts";
describe("solver support", () => {
it("hashes identical canonical states identically", () => {
const scenario = getScenario("s1-heat");
expect(hashState(buildInitialState(scenario, "campaign"))).toBe(hashState(buildInitialState(scenario, "campaign")));
});
it("enumerates the complete conservative inheritance superset", () => {
expect([2, 3, 4, 5].map((index) => reachableInheritanceAt(index).length)).toEqual([9, 37, 93, 163]);
});
});
+150
View File
@@ -0,0 +1,150 @@
import { describe, expect, it } from "vitest";
import { buildTestState } from "../src/domain/scenarios.ts";
import { nextState, resolve } from "../src/domain/transition.ts";
const tickOuter = (state: ReturnType<typeof buildTestState>) => resolve(state, { ring: "outer", dir: "cw" });
describe("Gate 3 — literal simulation truth", () => {
it("rotates every ring in both directions", () => {
for (const ring of ["inner", "middle", "outer"] as const) {
const size = ring === "inner" ? 6 : ring === "middle" ? 12 : 18;
for (const dir of ["cw", "ccw"] as const) {
const state = buildTestState({ tiles: [{ ring, index: 0, chamber: { heat: 5 } }] });
const next = nextState(state, { ring, dir });
const destination = dir === "cw" ? 1 : size - 1;
expect(next.rings[ring].tiles[destination].heat, `${ring} ${dir}`).toBe(4);
}
}
});
it("re-aligns gate payloads for inner, middle, and outer rotations", () => {
const cases = [
{ ring: "inner", from: 0, to: 1 },
{ ring: "middle", from: 2, to: 3 },
{ ring: "outer", from: 3, to: 4 },
] as const;
for (const { ring, from, to } of cases) {
const state = buildTestState({ tiles: [{ ring, index: from, chamber: { heat: 5 } }] });
const next = nextState(state, { ring, dir: "cw" });
expect(next.rings[ring].tiles[to].heat).toBe(4);
expect(next.rings[ring].tiles[from].heat).toBe(0);
}
});
it("commits simultaneous tangential + radial contention and attributes overflow", () => {
const state = buildTestState({ tiles: [
{ ring: "inner", index: 0, chamber: { nutrient: 6 } },
{ ring: "inner", index: 5, chamber: { nutrient: 1 } },
{ ring: "middle", index: 0, chamber: { nutrient: 1 } },
] });
const result = tickOuter(state);
expect(result.state.rings.inner.tiles[0].nutrient).toBe(6);
expect(result.events).toContainEqual({ phase: "overflow", ring: "inner", index: 0, field: "nutrient", amount: 1 });
expect(result.events.some((event) => event.phase === "flow" && event.ring === "middle" && event.index === 0 && event.radial === 1)).toBe(true);
});
it("attributes population overflow at the integer cap", () => {
const state = buildTestState({ tiles: [{ ring: "inner", index: 0, chamber: { producer: 6, nutrient: 6 } }] });
const result = tickOuter(state);
expect(result.state.rings.inner.tiles[0].producer).toBe(6);
expect(result.events).toContainEqual({ phase: "overflow", ring: "inner", index: 0, field: "producer", amount: 1 });
});
it("unlocks a threshold trait on the following evolution phase and activates its response", () => {
const state = buildTestState({ tiles: [{ ring: "inner", index: 0, chamber: { producer: 2, nutrient: 6 } }] });
state.lineage.producer.pressure.heat = 3;
const result = tickOuter(state);
expect(result.state.lineage.producer.unlocked.heat).toBe(true);
expect(result.state.environmentActive.heat).toBe(true);
expect(result.events).toContainEqual({ phase: "evolution", lineage: "producer", pressure: "heat", unlocked: true });
expect(result.events).toContainEqual({ phase: "env", pressure: "heat", active: true });
});
it("dormancy prevents loss and migration and makes prey inedible", () => {
const state = buildTestState({
tiles: [
{ ring: "inner", index: 0, chamber: { producer: 2, grazer: 1 } },
{ ring: "inner", index: 1, chamber: { nutrient: 6 } },
],
unlocked: { producer: ["hunger"], grazer: [] },
});
const result = tickOuter(state);
expect(result.state.rings.inner.tiles[0].producer).toBe(2);
expect(result.state.rings.inner.tiles[1].producer).toBe(0);
expect(result.state.rings.inner.tiles[0].grazer).toBe(1);
expect(result.events.some((event) => event.phase === "consequence" && event.pressure === "hunger" && event.kind === "prevented")).toBe(true);
expect(result.events).toContainEqual({ phase: "adaptation", ring: "inner", index: 0, lineage: "producer", pressure: "hunger", effect: "cost" });
expect(result.events).toContainEqual({ phase: "adaptation", ring: "inner", index: 0, lineage: "producer", pressure: "hunger", effect: "spillover" });
});
it("does not attribute a Dormancy migration cost when no better destination exists", () => {
const state = buildTestState({
tiles: [{ ring: "inner", index: 0, chamber: { producer: 2 } }],
unlocked: { producer: ["hunger"], grazer: [] },
});
const result = tickOuter(state);
expect(result.events.some((event) => event.phase === "adaptation" && event.effect === "cost")).toBe(false);
});
it("Cloak protects and retargets while predators remove one extra cloaked prey", () => {
const state = buildTestState({
tiles: [{ ring: "inner", index: 1, chamber: { producer: 6, grazer: 1 } }],
unlocked: { producer: ["immunity"], grazer: [] },
fixtures: [{ kind: "immuneNode", ring: "inner", index: 1 }],
});
const result = tickOuter(state);
expect(result.events.some((event) => event.phase === "feed" && event.predator === "grazer" && event.preyRemoved === 2)).toBe(true);
expect(result.events.some((event) => event.phase === "immuneSelect" && event.lineage === "grazer" && event.retarget)).toBe(true);
});
it("reports the actual Cloak prey removal when fewer than two prey exist", () => {
const state = buildTestState({
tiles: [{ ring: "inner", index: 1, chamber: { producer: 1, grazer: 1 } }],
unlocked: { producer: ["immunity"], grazer: [] },
fixtures: [{ kind: "immuneNode", ring: "inner", index: 1 }],
});
const result = tickOuter(state);
expect(result.events.some((event) => event.phase === "feed" && event.predator === "grazer" && event.preyRemoved === 1)).toBe(true);
});
it("fixture phase applies inlet, source, drain, and immune node rules", () => {
const state = buildTestState({
tiles: [
{ ring: "outer", index: 1, chamber: { producer: 2 } },
{ ring: "outer", index: 2, chamber: { producer: 2 } },
{ ring: "outer", index: 3, chamber: { producer: 2 } },
{ ring: "inner", index: 1, chamber: { producer: 3, toxin: 3 } },
],
fixtures: [
{ kind: "nutrientInlet", ring: "outer", index: 1 },
{ kind: "heatSource", ring: "outer", index: 2 },
{ kind: "toxinInlet", ring: "outer", index: 3 },
{ kind: "drain", ring: "inner", index: 1 },
{ kind: "immuneNode", ring: "inner", index: 1 },
],
});
const result = tickOuter(state);
const kinds = new Set(result.events.filter((event) => event.phase === "fixture").map((event) => event.kind));
expect(kinds).toEqual(new Set(["nutrientInlet", "heatSource", "toxinInlet", "drain"]));
expect(result.events.some((event) => event.phase === "immuneSelect")).toBe(true);
});
it("migration attribution names the actual source and destination", () => {
const state = buildTestState({ tiles: [
{ ring: "inner", index: 0, chamber: { producer: 3, nutrient: 6 } },
{ ring: "inner", index: 1, chamber: { nutrient: 6 } },
] });
const result = tickOuter(state);
expect(result.events).toContainEqual({ phase: "migrate", from: "inner:0", to: "inner:1", species: "producer" });
});
it("win takes precedence over turn-limit expiration", () => {
const state = buildTestState({
tiles: [{ ring: "inner", index: 0, chamber: { producer: 2, nutrient: 6 } }],
scenarioId: "win-on-limit",
turnLimit: 1,
win: () => true,
});
expect(nextState(state, { ring: "outer", dir: "cw" }).outcome).toBe("won");
});
});
+337
View File
@@ -0,0 +1,337 @@
import { test, expect, type Page } from "@playwright/test";
import { readFileSync } from "fs";
type Fix = { fixtures: Record<string, { win: { ring: string; dir: string }[]; loss: { ring: string; dir: string }[] }> };
const data = JSON.parse(readFileSync("test/solver-fixtures.json", "utf8")) as Fix;
const s1win = data.fixtures["s1-heat"].win;
const s1loss = data.fixtures["s1-heat"].loss;
const s1collapse = [
{ ring: "inner", dir: "cw" }, { ring: "middle", dir: "ccw" },
{ ring: "outer", dir: "cw" }, { ring: "outer", dir: "cw" },
{ ring: "inner", dir: "cw" },
];
const BASE = "http://localhost:4173";
async function playRoute(page: Page, route: { ring: string; dir: string }[]): Promise<void> {
for (const action of route) {
await page.getByRole("button", { name: new RegExp(`Rotate ${action.ring} ${action.dir === "cw" ? "clockwise" : "counter-clockwise"}`) }).click();
await page.locator("#btnCommit").click();
}
}
test("loads, renders title, no console errors", async ({ page }) => {
const errors: string[] = [];
page.on("pageerror", (e) => errors.push(String(e)));
page.on("console", (m) => { if (m.type() === "error") errors.push(m.text()); });
await page.goto(BASE);
await expect(page.locator("h1")).toContainText("Adaptive Loop");
await expect(page.getByRole("button", { name: "New Campaign" })).toBeVisible();
expect(errors).toEqual([]);
});
test("Continue without a save enters the next campaign scenario", async ({ page }) => {
await page.goto(BASE);
await page.getByRole("button", { name: "Continue" }).click();
await expect(page.locator(".obj h2")).toContainText("Cultivation Quota");
await expect(page.locator(".turn")).toContainText("Turn 0");
});
test("start campaign, board renders, controls present", async ({ page }) => {
await page.goto(BASE);
await page.getByRole("button", { name: "New Campaign" }).click();
await expect(page.locator(".board-svg")).toBeVisible();
await expect(page.getByRole("button", { name: /Rotate inner clockwise/ })).toBeVisible();
await expect(page.locator(".tile").first()).toBeVisible();
// 36 tiles total
await expect(page.locator(".tile")).toHaveCount(36);
await expect(page.locator(".tile").first()).toHaveAttribute("aria-label", /nutrient \d, heat \d, toxin \d/);
});
test("exact preview shows relocation, flow, deltas, and equals commit", async ({ page }) => {
await page.goto(BASE);
await page.getByRole("button", { name: "New Campaign" }).click();
await page.getByRole("button", { name: /Rotate outer clockwise/ }).click();
await expect(page.locator("#btnCommit")).toBeEnabled();
await expect(page.locator(".relocation")).toContainText("O0→O1");
await expect(page.locator(".delta-list")).toContainText(/[NHTPVF][+-]\d/);
await expect(page.locator(".tile-delta").first()).toBeVisible();
await expect(page.locator(".board-svg title").filter({ hasText: "radial-inward flow" }).first()).toBeAttached();
const previewValues = await page.locator(".tile").evaluateAll((tiles) => tiles.map((tile) => tile.getAttribute("data-values")));
await page.locator("#btnCancel").focus();
await expect(page.locator("#btnCommit")).toBeEnabled();
await page.locator("#btnCommit").click();
await expect(page.locator(".turn")).toContainText("Turn 1");
const committedValues = await page.locator(".tile").evaluateAll((tiles) => tiles.map((tile) => tile.getAttribute("data-values")));
expect(committedValues).toEqual(previewValues);
});
test("keyboard operation (1 selects, Enter commits, Esc cancels)", async ({ page }) => {
await page.goto(BASE);
await page.getByRole("button", { name: "New Campaign" }).click();
await page.keyboard.press("3"); // middle cw
await expect(page.locator(".rot.selected")).toHaveCount(1);
await page.keyboard.press("Enter");
await expect(page.locator(".turn")).toContainText("Turn 1");
await page.keyboard.press("1"); // inner cw
await page.keyboard.press("Escape");
await expect(page.locator(".rot.selected")).toHaveCount(0);
});
test("cancel and commit restore keyboard focus; Help exposes disclosure state", async ({ page }) => {
await page.goto(BASE);
await page.getByRole("button", { name: "New Campaign" }).click();
const focusPreview = page.getByRole("button", { name: /Rotate outer clockwise/ });
await focusPreview.focus();
await expect(page.locator("#btnCommit")).toBeEnabled();
await page.keyboard.press("Escape");
await expect(focusPreview).toBeFocused();
const rotation = page.getByRole("button", { name: /Rotate inner clockwise/ });
await rotation.click();
await page.locator("#btnCancel").click();
await expect(rotation).toBeFocused();
await rotation.click();
await page.locator("#btnCommit").click();
await expect(rotation).toBeFocused();
const help = page.locator("#btnHelp");
await expect(help).toHaveAttribute("aria-controls", "helpPanel");
await expect(help).toHaveAttribute("aria-expanded", "false");
await help.click();
await expect(help).toHaveAttribute("aria-expanded", "true");
await expect(page.locator("#helpPanel")).toHaveAttribute("aria-hidden", "false");
await rotation.click();
await help.focus();
await page.keyboard.press("Enter");
await expect(page.locator(".turn")).toContainText("Turn 1");
});
test("full scenario 1 win via verified route -> outcome + lineage choice (adaptation)", async ({ page }) => {
await page.goto(BASE);
await page.getByRole("button", { name: "New Campaign" }).click();
await playRoute(page, s1win);
// won -> lineage choice or next scenario
await expect(page.locator("h1, h2").first()).toContainText(/Lineage choice|Endurance|Adaptive Loop/i, { timeout: 10000 });
});
test("adaptation benefit, cost, spillover, and strengthened response are visible", async ({ page }) => {
await page.goto(BASE);
await page.getByRole("button", { name: "New Campaign" }).click();
for (const action of s1win.slice(0, 4)) await playRoute(page, [action]);
const events = page.locator(".event-list");
await expect(events).toContainText("unlocked Dormancy");
await expect(events).toContainText("Benefit:");
await expect(events).toContainText("Cost:");
await expect(events).toContainText("Spillover:");
await expect(events).toContainText("Hunger response active");
await expect(events).toContainText("nutrient +1");
await expect(events).toContainText("Benefit active");
});
test("a provoked adaptation visibly triggers its benefit, cost, and spillover", async ({ page }) => {
await page.goto(BASE);
await page.getByRole("button", { name: "New Campaign" }).click();
await playRoute(page, s1win);
await page.getByRole("button", { name: "Decline" }).click();
await playRoute(page, data.fixtures["s2-hunger"].win.slice(0, 5));
const events = page.locator(".event-list");
await expect(events).toContainText("Benefit active");
await expect(events).toContainText("Cost active");
await expect(events).toContainText("Spillover active");
await expect(page.locator(".tile.adapted").first()).toBeVisible();
await expect(page.locator(".adapted-tag").first()).toContainText("✓");
});
test("collapse, retry, then win through public controls", async ({ page }) => {
await page.goto(BASE);
await page.getByRole("button", { name: "New Campaign" }).click();
await playRoute(page, s1collapse);
await expect(page.locator(".turn")).toContainText("Ecosystem collapsed");
await page.getByRole("button", { name: "Retry" }).click();
await expect(page.locator(".turn")).toContainText("Turn 0");
await playRoute(page, s1win);
await expect(page.getByRole("heading", { name: "Lineage choice" })).toBeVisible();
});
test("lose then retry via verified loss route", async ({ page }) => {
await page.goto(BASE);
await page.getByRole("button", { name: "New Campaign" }).click();
await playRoute(page, s1loss);
await expect(page.locator(".turn").first()).toContainText(/collapsed|expired|Turn limit|Ecosystem|Turn 8/i);
await expect(page.getByRole("button", { name: "Retry" })).toBeVisible();
await page.getByRole("button", { name: "Retry" }).click();
await expect(page.locator(".turn")).toContainText("Turn 0");
});
test("Save & Quit, close/reopen, Continue restores exact public state", async ({ page }) => {
await page.goto(BASE);
await page.getByRole("button", { name: "New Campaign" }).click();
await page.getByRole("button", { name: /Rotate inner clockwise/ }).click();
await page.locator("#btnCommit").click();
const expectedValues = await page.locator(".tile").evaluateAll((tiles) => tiles.map((tile) => tile.getAttribute("data-values")));
const expectedTurn = await page.locator(".turn").textContent();
await page.locator("#btnSaveQuit").click();
const context = page.context();
await page.close();
const reopened = await context.newPage();
await reopened.goto(BASE);
await reopened.locator("#btnContinue").click();
expect(await reopened.locator(".turn").textContent()).toBe(expectedTurn);
const restoredValues = await reopened.locator(".tile").evaluateAll((tiles) => tiles.map((tile) => tile.getAttribute("data-values")));
expect(restoredValues).toEqual(expectedValues);
});
test("narrow viewport (390px) has no horizontal scroll and controls reachable", async ({ page }) => {
await page.setViewportSize({ width: 390, height: 800 });
await page.goto(BASE);
await page.getByRole("button", { name: "New Campaign" }).click();
await expect(page.locator(".board-svg")).toBeVisible();
const ledger = page.locator(".tile-ledger");
await expect(ledger).toBeVisible();
await expect(ledger).toContainText(/I\d.*N\d.*H\d.*T\d/);
expect(await ledger.evaluate((element) => parseFloat(getComputedStyle(element).fontSize))).toBeGreaterThanOrEqual(13);
const scrollWidth = await page.evaluate(() => document.documentElement.scrollWidth);
const clientWidth = await page.evaluate(() => document.documentElement.clientWidth);
expect(scrollWidth).toBeLessThanOrEqual(clientWidth);
await expect(page.locator("#btnCommit")).toBeVisible();
});
test("200% browser zoom keeps every control reachable and operable", async ({ page }) => {
await page.goto(BASE);
await page.getByRole("button", { name: "New Campaign" }).click();
const cdp = await page.context().newCDPSession(page);
await cdp.send("Emulation.setDeviceMetricsOverride", { width: 640, height: 450, deviceScaleFactor: 2, mobile: false });
await expect(page.locator(".board-svg")).toBeVisible();
await expect(page.locator(".rot")).toHaveCount(6);
const controls = page.locator("button:visible");
expect(await controls.count()).toBeGreaterThanOrEqual(10);
for (const control of await controls.all()) {
await control.scrollIntoViewIfNeeded();
await expect(control).toBeVisible();
}
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(await page.evaluate(() => document.documentElement.clientWidth));
const rotation = page.getByRole("button", { name: /Rotate inner clockwise/ });
await rotation.focus();
await expect(rotation).toBeFocused();
await page.keyboard.press("Enter");
await expect(page.locator(".turn")).toContainText("Turn 1");
});
test("touch input previews and commits on a mobile context", async ({ browser }) => {
const context = await browser.newContext({ hasTouch: true, isMobile: true, viewport: { width: 390, height: 844 } });
const page = await context.newPage();
await page.goto(BASE);
await page.getByRole("button", { name: "New Campaign" }).tap();
await page.getByRole("button", { name: /Rotate inner clockwise/ }).tap();
await expect(page.locator("#btnCommit")).toBeEnabled();
await page.locator("#btnCommit").tap();
await expect(page.locator(".turn")).toContainText("Turn 1");
await context.close();
});
test("reduced-motion preference renders without error", async ({ browser }) => {
const ctx = await browser.newContext({ reducedMotion: "reduce", viewport: { width: 1280, height: 900 } });
const page = await ctx.newPage();
const errors: string[] = [];
page.on("pageerror", (e) => errors.push(String(e)));
await page.goto(BASE);
await page.getByRole("button", { name: "New Campaign" }).click();
await expect(page.locator(".board-svg")).toBeVisible();
const motion = await page.locator(".tile").first().evaluate((element) => ({ animation: getComputedStyle(element).animationName, transition: getComputedStyle(element).transitionDuration }));
expect(motion).toEqual({ animation: "none", transition: "0s" });
expect(errors).toEqual([]);
await ctx.close();
});
test("primary text contrast meets WCAG AA", async ({ page }) => {
await page.goto(BASE);
await page.getByRole("button", { name: "New Campaign" }).click();
const ratios = await page.evaluate(() => {
const rgb = (value: string) => value.match(/[\d.]+/g)!.slice(0, 3).map(Number);
const luminance = (value: string) => {
const channels = rgb(value).map((channel) => channel / 255).map((channel) => channel <= 0.03928 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4);
return 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2];
};
const ratio = (foreground: string, background: string) => {
const [lighter, darker] = [luminance(foreground), luminance(background)].sort((a, b) => b - a);
return (lighter + 0.05) / (darker + 0.05);
};
const body = getComputedStyle(document.body);
const button = getComputedStyle(document.querySelector(".btn")!);
return [ratio(body.color, body.backgroundColor), ratio(button.color, button.backgroundColor)];
});
expect(Math.min(...ratios)).toBeGreaterThanOrEqual(4.5);
});
test("five scenarios unlock in order and campaign victory is playable", async ({ page }) => {
await page.goto(BASE);
await page.getByRole("button", { name: "New Campaign" }).click();
const names = ["Cultivation Quota", "Endurance", "Cleansing", "Escort", "Stable Equilibrium"];
for (let index = 0; index < names.length; index++) {
await expect(page.locator(".obj h2")).toContainText(names[index]);
await playRoute(page, data.fixtures[["s1-heat", "s2-hunger", "s3-toxin", "s4-immunity", "s5-convergence"][index]].win);
if (index < names.length - 1) {
await expect(page.getByRole("heading", { name: "Lineage choice" })).toBeVisible();
await page.getByRole("button", { name: "Decline" }).click();
}
}
await expect(page.getByRole("heading", { name: "Campaign Victory" })).toBeVisible();
await page.locator("#btnVictoryMenu").click();
await expect(page.getByRole("heading", { name: "Current Campaign" })).toBeVisible();
});
test("lineage choice carries its visible gift and cost", async ({ page }) => {
await page.goto(BASE);
await page.getByRole("button", { name: "New Campaign" }).click();
await playRoute(page, s1win);
const choice = page.locator(".choice-grid .trait-choice").first();
await expect(choice).toContainText(/Benefit:/);
await expect(choice).toContainText(/Cost:/);
const label = (await choice.locator(".ch-trait").textContent()) ?? "";
await choice.click();
await expect(page.locator(".inh")).toContainText(label);
});
test("standalone save and retry preserve the retained campaign", async ({ page }) => {
await page.goto(BASE);
await page.getByRole("button", { name: "New Campaign" }).click();
await playRoute(page, s1win);
const choice = page.locator(".choice-grid .trait-choice").first();
const inheritedLabel = (await choice.locator(".ch-trait").textContent()) ?? "";
await choice.click();
await expect(page.locator(".obj h2")).toContainText("Endurance");
await page.locator("#btnSaveQuit").click();
await page.getByRole("button", { name: "Replay Standalone" }).click();
await expect(page.getByRole("button", { name: "Replay Cultivation Quota" })).toBeEnabled();
await expect(page.getByRole("button", { name: "Replay Endurance" })).toBeEnabled();
await expect(page.getByRole("button", { name: "Replay Cleansing" })).toBeDisabled();
await page.getByRole("button", { name: "Replay Cultivation Quota" }).click();
await page.getByRole("button", { name: /Rotate inner clockwise/ }).click();
await page.locator("#btnCommit").click();
await page.locator("#btnSaveQuit").click();
await page.locator("#btnContinue").click();
await expect(page.locator(".obj h2")).toContainText("Cultivation Quota");
await expect(page.locator(".turn")).toContainText("Turn 1");
await playRoute(page, s1loss.slice(1));
await page.getByRole("button", { name: "Retry" }).click();
await expect(page.locator(".turn")).toContainText("Turn 0");
await page.locator("#btnSaveQuit").click();
await page.locator("#btnResumeCampaign").click();
await expect(page.locator(".obj h2")).toContainText("Endurance");
await expect(page.locator(".inh")).toContainText(inheritedLabel);
});
test("campaign menu resumes only the active run", async ({ page }) => {
await page.goto(BASE);
await page.getByRole("button", { name: "New Campaign" }).click();
await page.getByRole("button", { name: /Rotate inner clockwise/ }).click();
await page.locator("#btnCommit").click();
await page.locator("#btnMenu").click();
await expect(page.getByRole("heading", { name: "Current Campaign" })).toBeVisible();
await expect(page.getByRole("button", { name: "Resume Cultivation Quota" })).toBeEnabled();
await expect(page.getByRole("button", { name: "Resume Endurance" })).toBeDisabled();
await page.getByRole("button", { name: "Resume Cultivation Quota" }).click();
await expect(page.locator(".turn")).toContainText("Turn 1");
});
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "ES2021",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ES2021", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"strict": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src", "test", "tests"]
}
+14
View File
@@ -0,0 +1,14 @@
import { defineConfig } from "vite";
export default defineConfig({
base: "./",
build: {
target: "es2020",
outDir: "dist",
sourcemap: false,
},
test: {
environment: "node",
include: ["test/**/*.test.ts"],
},
});