(Adaptive Loop) Prepare for Pass 2

This commit is contained in:
AlexKucera committed 2026-08-12 22:29:35 +02:00
1 parent bd7203fc9e
commit f262da55e5
32 files changed
+93 -7113

No files matched your search

-21
View File
@@ -1,21 +0,0 @@
# Dependencies
node_modules/
# Build output
dist/
dist-ssr/
# Test artifacts
playwright-report/
test-results/
.playwright/
coverage/
# Local env / editor
.env
.env.local
.DS_Store
*.log
# Pi agent infrastructure (run artifacts, not game code)
.pi/
-22
View File
@@ -1,22 +0,0 @@
# Assets
All Adaptive Loop visuals are **procedural SVG/CSS** generated at runtime by the
code in `src/presentation/geometry.ts` and `src/main.ts` (board rings, chamber
nodes, fixture glyphs, flow arrows) and `src/styles.css` (dark laboratory-glass
palette, layout, responsive rules). No downloaded, ripped, or commercial art,
fonts, music, icons, or other binary assets are used.
The only raster images in the repository are:
- `.pi/…` agent-infrastructure artifacts (run transcripts) — not part of the game.
- Playwright trace/error-context artifacts under `test-results/` (gitignored,
generated by test runs) — not part of the game.
No image asset was generated for the game during the run (the `image_generate`
tool was not used). If a generated asset is ever added, it will be listed here
with its source prompt and license.
Species and pressure encodings are deliberately **non-color-only**: each uses a
distinct glyph plus short text (Veridan/Cilia/Phage; 🔥/☾/⚗/◊ for heat/hunger/
toxin/immunity; P/G/H/N/T counts) so the board remains legible without color and
to screen readers.
-154
View File
@@ -1,154 +0,0 @@
# Context Manifest — Adaptive Loop
This manifest closes the disclosure boundary for the Agentic Labs one-prompt run.
It records the one prompt, all staged local context, the effective harness
(model, extensions, steering), provenance verification of the session log, and
the precondition status at kickoff. Generated in-session; not edited after freeze.
## 1. Prompt source
- **Authoritative private prompt path:** `/Users/alex/Projects/scripting/agentic-labs-challenge/adaptive-loop/PROMPT.md`
- **sha256 (raw, with leading `/goal `):** `52e8fa98a54858fcc55e1db0216be85677b688d76a2e1f646a5b13b97786e070`
- **sha256 (goal-state text, `/goal ` prefix stripped):** `9ea54d7d51b2a0d67e01de5ff62e9b3eb12218e84d84750a5a0ae8aa6626021b`
- The prompt is preserved privately at its path and is not duplicated into the
public game repo by default (operator DMs it per competition rules).
## 2. Effective model / provider
- **Provider:** `zai` (Zhipu AI)
- **Effective model:** `glm-5.2` (first entry of `~/.pi/fallback-chains.json`
`default` chain; matches the session log `model_change` entry).
- **Reasoning:** GLM-5.2 thinking mode (set via `thinking_level_change` in the
session log).
- **Multimodal note:** GLM-5.2 is **not multimodal** in this harness; the parent
cannot read images/screenshots. Browser verification is therefore performed
via DOM-based semantic UI tooling and, for the one visual QA pass, by a
delegated vision subagent. No judging-affecting visual fact is asserted
without a DOM-level check.
## 3. Pi harness
- **Pi core:** `@earendil-works/pi-coding-agent` `0.84.1` (node `v26.5.1`).
- **Expected isolated config (per PROMPT):** context/skills/prompts/themes/
ambient extensions disabled; only the four extensions in §4 loaded.
- **Effective config (observed):** the isolated config was **not** applied.
Ambient project context (`AGENTS.md`), global skills, and additional
extensions (e.g. `pi-hermes-memory`, `ponytail`, `gitnexus`, `pi-design-deck`,
`glimpse`, MCP adapters) are active; `~/.pi/disabled-skills.json` is `[]`
(no skills disabled). These are **agent-side steering only** — they inject no
game domain state and no `localStorage`. The build honors the SPEC's
hard scope and forbidden list regardless. This deviation is disclosed here
rather than hidden.
## 4. Loaded extensions / packages (versions)
Expected four (all present at expected versions):
| Package | Expected | Effective |
|---|---|---|
| `@narumitw/pi-goal` | 0.51.0 | 0.51.0 |
| `@juicesharp/rpiv-todo` | 2.4.0 | 2.4.0 |
| `pi-subagents` | 0.47.1 | 0.47.1 |
| `@injaneity/pi-computer-use` | 0.5.0 | 0.5.0 |
Build toolchain (dev dependencies, `package.json`): `vite@6.4.3`,
`typescript@5.9.3`, `vitest@2.1.9`, `@playwright/test@1.62.1`,
`@types/node@22`. Playwright Chromium browser is pre-cached locally
(`~/Library/Caches/ms-playwright`), so black-box tests run offline.
## 5. Staged local context (human-authored)
| Path | sha256 | Role |
|---|---|---|
| `SPEC.md` | `50d3c46a0d42b9308eb015f788331cb5d0ede96071828fc266d5c13978029f21` | Authoritative implementation spec |
| `PROMPT.md` | `52e8fa98…77e070` | The one prompt (private) |
| `.agents/skills/pi-game-factory/SKILL.md` | `b44005242a71ee2a8c087c6f13ca51f8675f31c99e8d55dc5a9db1f5245969a6` | Steering: orchestration |
| `.agents/skills/deterministic-game-core/SKILL.md` | `e63356c9ccb28a9d62d8266b788019df2bc266a378b7a8d771998e179bce824b` | Steering: simulation rules |
| `.agents/skills/game-ui-proof/SKILL.md` | `665b66af96efd40abe38c512bcf7259e1d34243122d51c7e40dafeca0814049c` | Steering: UI proof |
| `docs/brainstorming-summary.md` | `46a2ed3d76ea9436077319891b54049ff4b359429fb32fa8f08710a7cc40585d` | Pre-staged design summary (consistent with SPEC) |
## 6. Session log provenance (inspection, not copied live)
- **`PI_SESSION_FILE` (env var unset; canonical path resolved from session id):**
`/Users/alex/.pi/agent/sessions/--Users-alex-Projects-scripting-agentic-labs-challenge-adaptive-loop--/2026-08-12T15-16-35-418Z_019ff68b-f5da-72ad-a434-20f6da130066.jsonl`
- **Session id:** `019ff68b-f5da-72ad-a434-20f6da130066`.
- **First user-role entry:** message index `3` — the sole `role:user` entry in
the log; carries a `pi-goal-prompt` marker (Goal kickoff).
- **Later user-role entries:** none. Subsequent goal turns are recorded as
embedded `pi-goal-continuation` markers (6 observed), i.e. Goal-owned
continuations for the same objective/goal id — no human follow-ups.
- **Structural `parentSession`:** absent from the session-metadata line
(`type:session` keys are `cwd,id,timestamp,type,version`). The substring
`parentSession` appears only inside message bodies (system/AGENTS text and
this manifest's own discussion), not as a structural parent link. This is a
root session, not a subagent child.
- The verbatim prompt body is not inlined as a single string in the log (pi-goal
stores a reference). Exact byte-reconstruction of `goal-state.text` vs
`PROMPT.md` is the **operator-owned post-exit submission step**, explicitly
excluded from the in-session game-code freeze (SPEC §15 Gate 0).
## 7. Precondition status at kickoff (deviations disclosed)
PROMPT/SPEC Gate 0 expects: *a fresh standalone directory containing only
`SPEC.md` and the three `.agents/skills/*/SKILL.md` files, no Git history*.
**Observed (not matching):**
- Git history **exists** — this `adaptive-loop/` directory is part of a shared
repo that also contains sibling challenges (Body Snatcher, Underdepths).
Head: `6c2eef0 (Adaptive Loop) Initial Plan`. Nuking sibling history is out of
scope and forbidden; the run instead commits new game work onto this branch.
- Extra staged files present: `PROMPT.md` (the prompt itself) and
`docs/brainstorming-summary.md` (a pre-staged design summary, consistent with
SPEC). A `docs/brainstorming-session-…md` was staged by the initial-plan
commit but is not present in the working tree.
- `.pi/` contains prior subagent artifacts/missions from earlier runs; these are
agent infrastructure (gitignored), not game code.
The three steering SKILL files and SPEC.md are **preserved at their original
paths, unmodified** (hashes in §5). No game-code edits occur before Gate 1.
## 8. Post-exit operator procedure (not performed in-session)
```bash
# Copy the authoritative session log out, then parse/validate provenance + hash.
SESS="/Users/alex/.pi/agent/sessions/--Users-alex-Projects-scripting-agentic-labs-challenge-adaptive-loop--/2026-08-12T15-16-35-418Z_019ff68b-f5da-72ad-a434-20f6da130066.jsonl"
cp "$SESS" ./adaptive-loop.session.jsonl
shasum -a 256 ./adaptive-loop.session.jsonl # record hash
# Validate: exactly one role:user entry (pi-goal-prompt kickoff); every later
# user-role entry (if any) carries a pi-goal-continuation marker for the same
# goal id; the session-metadata line has no structural parentSession field;
# reconstruct goal-state.text and confirm it byte-equals PROMPT.md without the
# leading "/goal " prefix.
```
Per SPEC, this copy/parse is operator-owned and excluded from the in-session
freeze; the parent does not copy the live log during the run.
## 9. Residual risks & known deviations
- **Scenario tuning (documented):** Scenarios 3 and 4 were provably unwinnable as
originally specified and minimally retuned per SPEC §9. Full proofs and exact
changes are in `docs/scenario-tuning.md`. All invariants preserved.
- **Heat carrier cost scope:** SPEC §8 Heat row carrier cost says "while hot,
growth/feeding cannot add population." The implementation applies this at the
producer **growth** phase (SPEC §7 phase 3, which explicitly mentions trait-cost
suppression of reproduction). It is **not** additionally applied to grazer/phage
**feeding** gains in phase 4 (SPEC §7 phase 4 is silent on heat suppression).
This is latent: no verified campaign route unlocks a heat-adapted grazer/phage
feeding in a hot chamber, so no verified play is affected. It is documented
here rather than applied to avoid destabilizing the exhaustively-proven
scenario solvability.
- **Counterfactual (Scenario 5):** s5's frozen-ownership state space exceeds
8,000,000 reachable states, so the exhaustive proof is `complete === false`.
Two independent bounded searches (greedy beam to width 20,000; exhaustive DFS to
8M states) found no frozen win while the normal game is trivially winnable —
concordant bounded-search evidence that shared-slot ownership materially
affects s5 solvability.
- **Solver `fastHash`** uses raw (insertion-order) JSON rather than sorted-key
canonical form for dedup; this is correct because all states are constructed
by the same code path (stable key order) but is weaker than the canonical
hash used for domain equality. It affects only offline solver node counts,
never game correctness.
- **GLM-5.2 is non-multimodal** in this harness; the one visual QA pass was
performed via DOM-level Playwright checks rather than pixel inspection.
-95
View File
@@ -1,95 +0,0 @@
# Adaptive Loop
A calm, deterministic microfluidic strategy puzzle. Rotate three overlapping
loops to move chamber payloads and re-route nutrient/toxin flow, provoking and
exploiting the ecosystem's counter-adaptations. Built for the Agentic Labs
one-prompt challenge.
- **Stack:** Vite + TypeScript + Vitest + Playwright. No framework, no engine,
no downloaded assets. SVG/CSS only.
- **Determinism:** one pure transition `nextState(state, action)` owns every
committed turn; previews call the same function on a clone, so preview always
equals commit. No runtime randomness anywhere.
## Install
```bash
npm install
```
Node 20+ recommended (developed on Node 26). Playwright's Chromium browser is
fetched on first e2e run via `npx playwright install chromium` (already cached on
the build machine).
## Run (development)
```bash
npm run dev # Vite dev server with HMR
```
Open the printed local URL.
## Play (production build)
```bash
npm run build # type-check-free bunde into dist/
npm run preview # serve the production build at http://localhost:4173
```
### How to play
- **New Campaign** starts Scenario 1. **Continue** resumes a saved run.
**Replay Standalone** replays any unlocked scenario with clean baseline traits.
- Each turn, focus or hover one of the six rotation buttons (Loop A/B/C × CW/CCW)
to see an exact one-turn **preview** (chamber deltas, flow arrows, predicted
outcome). Press **Commit rotation** (or Enter on a focused rotation) to play it.
**Escape** cancels a preview.
- A rotation moves that loop's six chambers, sets its flow direction, and claims
its shared slots — changing where nutrient/toxin flow next.
- Pressures build toward 3, at which point a lineage **adapts** (benefit + cost +
spillover). Win by meeting the scenario objective before the turn limit or
ecosystem collapse. After a campaign win you may preserve one adapted trait
(gift and burden) into the next scenario.
- **Save & Quit** persists to `localStorage`; closing and reopening the page then
**Continue** restores the exact state. **Retry** resets the current scenario to
its campaign-entry inheritance snapshot.
### Controls & accessibility
Real buttons for every action, visible focus, semantic headings/landmarks,
screen-reader live region announcing each turn, non-color encodings (glyphs +
text for species/pressures), keyboard operation, `prefers-reduced-motion` support,
responsive down to 390 CSS px, and readable at 200% zoom.
## Test
```bash
npm run typecheck # tsc --noEmit (strict)
npm run test # Vitest unit/behavior/solver/persistence (fast, in Node)
npm run e2e # Playwright black-box browser tests against the build
npm run verify # typecheck + unit + build + e2e
```
## Project layout
```
src/
domain/ types, constants, serialize, scenario (state/win), pipeline (nextState), solver
content/ scenarios.ts — immutable declarative scenarios + win specs
persistence/ save.ts — versioned localStorage envelope, validation, replay
presentation/ geometry.ts — interlocking-ring board coordinates
session.ts campaign/session controller (pure)
main.ts presentation controller + SVG rendering
tests/ pipeline.test.ts (truth), solver.test.ts (routes), persistence.test.ts
tests/fixtures/ solver-results.json — verified win/lose routes + counterfactual evidence
e2e/ smoke.spec.ts — black-box browser proof
docs/ scenario-tuning.md, brainstorming-summary.md
SPEC.md authoritative spec (unchanged)
CONTEXT-MANIFEST.md disclosure boundary for the one-prompt run
```
## Scenario tuning
Two baseline scenarios were provably unwinnable as originally specified and were
minimally retuned (SPEC §9). See `docs/scenario-tuning.md` for proofs and exact
changes. All invariants (topology, turn order, caps, trait semantics) preserved.
-53
View File
@@ -1,53 +0,0 @@
# Recording Route
This route is generated from **verified** solver/browser actions
(`tests/fixtures/solver-results.json`, replayed by `tests/solver.test.ts` and
exercised through the public UI in `e2e/smoke.spec.ts`), not invented prose. It
is short and deterministic — record it as one uncut take from the production
build (`npm run preview` → http://localhost:4173).
## One-continuous-take route
1. **Title / campaign start.** Click **New Campaign** → Scenario 1 (Heat:
Cultivation Quota) board appears.
2. **Exact preview of a rotation.** Focus the **Loop C CW** rotation button; the
Preview panel shows the exact one-turn outcome (turn 0→1, producer+grazer
total, predicted result) and the board shows flow arrows + chamber deltas.
3. **Rotation causes movement + flow.** Commit it (Enter / Commit). Chambers
along loop C shift and nutrient flows along the reclaimed outlets (flow arrows
re-route).
4. **Pressure causes an adaptation (Scenario 2).** From the title, **Replay
Standalone → Scenario 2 (Endurance)**. Play the verified winning route:
`A-ccw → C-ccw → B-ccw → C-cw → C-cw → C-ccw → A-ccw → A-ccw → C-cw → A-cw`.
The **Pressures & Traits** panel shows the producer/grazer hunger track
climbing to 3 and **Dormancy** unlocking (✓); event log attributes the unlock.
5. **Adaptation benefit / cost / spillover.** During Scenario 2, once Dormancy is
active, the event log attributes *prevented hunger loss* (benefit) and *dormant
prey is inedible, denying predator food* (spillover); dormant population cannot
migrate (cost).
6. **Global pressure response.** In a heat-heavy line (Scenario 1 over several
turns, or Scenario 5), heat sources add **+3 instead of +2** once the global
Heat Response activates — visible in the event log ("Global heat response
active") and the strengthened fixture effect.
7. **Ecosystem collapse and retry.** Repeat a single loop rotation in a campaign
scenario to drive collapse/expiry; the live region announces it. Click
**Retry** to restore the scenario-entry snapshot (turn resets to 0).
8. **Scenario win + preserved lineage choice.** Finish the Scenario 1 verified
route `C-cw → B-cw → A-ccw → C-ccw → A-cw` (5 turns) → **Scenario 1 complete**;
choose to preserve nothing (or a newly adapted trait).
9. **Save & Quit.** Mid-scenario, click **Save & Quit** → returns to title;
**Continue** now appears.
10. **Close/reopen + Continue.** Reload the page; click **Continue** → exact state
restored (same turn, same chambers).
11. **Visible access to multiple scenarios.** **Replay Standalone** lists all five
scenarios.
## Notes
- Automated tests validate all five scenarios and campaign victory
(`tests/solver.test.ts`); the recording need not play all five — the route above
is concise and covers the required beats.
- The S1 winning route `C-cw → B-cw → A-ccw → C-ccw → A-cw` is verified to reach
`outcome === "won"` (producer at slot 11 ≥ 5 and total producer ≥ 12).
- The S2 route unlocks Dormancy (exploit evidence); the S1 route wins while Heat
Shield stays locked (avoid evidence). Both are asserted in `tests/solver.test.ts`.
+93
View File
@@ -0,0 +1,93 @@
# Board Layout — three interlocking hexagonal rings
This document is the rendering reference for the Adaptive Loop board (SPEC §4
"Board layout (rendering)"). The topology (12 slots, 3 loops, 6 shared slots) is
authoritative and unchanged; this file prescribes **how to draw it as three
interlocking hexagonal rings**, not as a network of connected spheres or a
numbered wiring diagram.
## Why the obvious drawings fail
The three loops pairwise share *edges* (A∩B = slots {2,3}; A∩C = {4,5};
B∩C = {8,9}). In a flat hexagonal *tiling*, three mutually edge-adjacent hexagons
meet at a single triple vertex and yield only 4 shared vertices — not the 6 this
topology requires. So the board **cannot** be drawn as three regular hexagons
that geometrically share edges in the plane. It must be drawn as three
**interlocking rings** (like chain links): hexagonal outlines that overlap, with
the six shared chambers sitting at the six overlap/crossing points.
## Requirements (binding)
1. Each loop is a **regular six-sided hexagon** (pointy-top), drawn as a stroked
`<polygon>` with a distinct per-loop color (A, B, C).
2. The three rings are arranged in a **symmetric trefoil** (centers at the
corners of an equilateral triangle) so each pair overlaps and the rings read
as interlocked.
3. At each of the six ring crossings use a consistent **over/under weave**
(break one ring's stroke where the other passes over it) so no ring outline is
visually broken and the "interlocking" reads clearly.
4. Chambers are circular nodes placed **on the rings at the hexagon vertices**,
in each loop's clockwise cyclic order:
- Loop A: `0 → 1 → 2 → 3 → 4 → 5 → 0`
- Loop B: `2 → 3 → 6 → 7 → 8 → 9 → 2`
- Loop C: `4 → 5 → 10 → 11 → 8 → 9 → 4`
5. A shared chamber belongs to two rings; render it **once** and route **both**
ring outlines through that single node (it is the visible overlap point).
6. Label each chamber with its slot index; mark shared chambers with the loops
that own them (e.g. `2 ⓪ⓑ`). Rotation moves payloads along the chosen loop's
cyclic order above; channel-flow arrows are drawn along the owner loop's edges
in its current direction.
## Construction (recommended)
Define the 12 chamber coordinates, then draw each loop as the polygon through its
6 chambers in cyclic order. Because a shared chamber is one coordinate used by two
loops' polygons, shared vertices **coincide by construction** and each loop is a
genuine 6-gon. Place the chambers so the three resulting 6-gons form a clean
trefoil (tune spacing/rotation until each ring reads as a distinct hexagon and
the six shared nodes sit at clear crossings).
A pointy-top hexagon of radius `R` centered at `C` has vertex offsets (clockwise
from top): `(0,-R)`, `(R·√3/2,-R/2)`, `(R·√3/2,R/2)`, `(0,R)`, `(-R·√3/2,R/2)`,
`(-R·√3/2,-R/2)`.
### Reference starting coordinates (viewBox 440×400, tune for legibility)
Three pointy-top hexagons, `R = 68`, trefoil centers `A=(220,114)`,
`B=(145,243)`, `C=(295,243)`. Generate each loop's six vertex positions from its
center, assign chambers in the cyclic order above, then for the six **shared**
chambers use a single coordinate at the overlap of the two loops that own them
(the midpoint of the two loops' nearest vertices is a fine starting point; nudge
so it lands on a clean crossing). Unique chambers keep their own vertex
coordinates. The implementer **must** visually/DOM-verify the result is three
distinct interlocking hexagons and adjust spacing if any ring collapses into a
tangle.
## ASCII schematic (topology only — not to scale)
`` Loop A
0─────1
/ \
5 2 ──┐ shared A∩B
│ C │ │
4─────────3 │ Loop B
\ │ / │
11 10 6────7
\ │ / │
\ │ / │
9─8 ──────┘ shared B∩C
↑ ↑
shared A∩C (4,5) and B∩C (8,9) and A∩B (2,3)
```
Each loop is a hexagon; shared slots (2,3 / 4,5 / 8,9) are the chambers where two
rings cross. Draw rings as stroked hexagons with an over/under weave at these six
crossings.
## Interaction note (see SPEC §13)
Selecting a rotation (focus/hover/tap) shows the preview and **enables Commit**;
the selection **persists** until the player commits, picks a different rotation,
or cancels (Escape). Do **not** clear the selection — and therefore do not grey
out Commit — when the pointer leaves the rotation control or focus moves to the
Commit button.
-99
View File
@@ -1,99 +0,0 @@
# Scenario Tuning Log (SPEC §9)
SPEC §9 permits the autonomous agent to adjust **starting populations/resources,
fixture locations, or numeric objective thresholds by at most 1 per tuning pass**
when a scenario is impossible or trivial, provided it documents every adjustment,
preserves all invariants (topology, turn order, caps, trait semantics, objective
type), and reruns all solver tests.
Two baseline scenarios were proven **unwinnable as originally specified** by an
exhaustive state-space search (`src/domain/solver.ts → exhaust`, iterative DFS
over canonical states). Each was minimally retuned and re-proven solvable. No
other scenarios were changed. Board topology, the 8-phase turn pipeline, caps,
trait semantics, and objective *types* are unchanged.
## Method
`exhaust(scenarioId, inheritance, opts)` visits every reachable canonical state
once (memory-light: stores only state hashes). `complete === true` with `win ===
null` is a proof of unwinnability within the turn limit. All proofs below ran to
`complete === true`.
## Scenario 3 — Toxin: Cleansing
**Original:** toxin inlets at slots 3 and 9 (+2 each/turn = +4), drains at 5 and
11 (−2 each/turn = −4), start toxin 2@3 and 2@9, win = total toxin ≤ 2 with
total producer+grazer ≥ 8 during turns 6–9.
**Proof of unwinnability:** exhaust explored **1,932,332** reachable states,
`complete === true`, no winning state. Root cause: the inlet/drain balance is
exactly net-zero (+4/−4), and toxin is otherwise conserved (flow only moves it;
overflow cannot bring the total below the steady floor). The reachable toxin
floor is **5**, never ≤ 2. The Efflux-spillover detox path cannot overcome the
+4/turn inlet pressure because adapted producers exhaust nutrient to the carrier
cost and cannot sustain enough spillover.
**Tuning (1 fixture change):** removed the toxin inlet at slot 9. With one inlet
(+2) against two drains (−4), toxin becomes purgable. Starting toxin kept at the
original 2@3 and 2@9.
**Re-proof:** exhaust (510,156 states, `complete === true`) finds an 8-turn win;
`tests/fixtures/solver-results.json` records a verified winning route (replayed
to `outcome === "won"` in `tests/solver.test.ts`).
## Scenario 4 — Immunity: Escort
**Original:** immune nodes at 2, 4, 6 (2 damage/turn each to the largest eligible
lineage), win = grazer ≥ 3 **and** phage ≥ 1 at the sanctuary slot 11, with total
producer ≥ 6.
**Proof of unwinnability:** exhaust explored **307,008** states, `complete ===
true`, no winning state. Root cause (confirmed by frontier probes): grazers can
reach slot 11 (up to 6 stack there) and producers can survive (total 6), but
**phage can never co-locate with ≥ 2 grazers at slot 11** — a phage arriving
consumes the grazers it must cohabit with, and the rotations that bring a phage
to slot 11 disperse the grazers. `max phage@11 === 1` and `max grazer@11 === 6`
are individually reachable but never simultaneously with grazer@11 ≥ 2. Every
variant win condition involving phage@11 ≥ 1 (with grazer@11 ≥ 2, ≥ 3, or any
producer floor) is infeasible.
**Tuning (1 objective-threshold change):** dropped the phage@11 requirement
(`phageMin: 1 → 0`). The win is now grazer ≥ 3 at slot 11 with total producer ≥ 6
(the original producer floor, which is achievable). This preserves the scenario's
teaching — immune targeting, escort through immune nodes to the sanctuary, and
predator vulnerability (phages still exist and prey on grazers during play) —
while removing a mechanically impossible co-location constraint.
**Re-proof:** exhaust (6,108 states, `complete === true`) finds an 8-turn win;
verified route in the fixtures.
## Counterfactual — shared-slot ownership (SPEC §4)
SPEC §4 requires at least one scenario solver-proven unwinnable when
`sharedOwner` is frozen at the scenario baseline (payload permutation and loop
direction still update). Scenarios 1–4 remain winnable under frozen ownership
(proven `complete === true`). **Scenario 5 (Convergence)** is winnable normally
(beam search finds a 9-turn win) but **no winning route exists under frozen
ownership** within bounded search: greedy beam search to width 20,000 and
exhaustive DFS to 8,000,000 states both find no win (the frozen state space
exceeds 8 M states, so the exhaustive pass is `complete === false`; the
concordance of two independent bounded searches is the recorded evidence). This
establishes that shared-slot ownership materially changes Scenario 5's
solvability.
## Adaptation evidence (SPEC §8)
- **Exploit:** Scenario 2 (Hunger) winning route unlocks Dormancy
(`producer:hunger`, `grazer:hunger`).
- **Avoid:** Scenario 1 (Heat) winning route wins while Heat Shield stays locked
(`producer:hunger` unlocks, but `heat` never reaches an evolution phase at 3).
Both recorded in `tests/fixtures/solver-results.json → adaptationEvidence` and
asserted in `tests/solver.test.ts`.
## Invariants preserved
Board topology (loops A/B/C, shared slots), the fixed 8-phase turn order, the
0–6 caps, the 0–3 pressure tracks, trait benefit/cost/spillover semantics, and
each scenario's objective *type* (producerAt / endurance / cleanse / escort /
sustained) are all unchanged. Only the two adjustments above were made.
-162
View File
@@ -1,162 +0,0 @@
// Adaptive Loop — black-box browser proof (SPEC §15 Gate 6).
// Exercises the production build through PUBLIC controls only (no state/localStorage injection).
import { test, expect, type ConsoleMessage } from "@playwright/test";
import { readFileSync } from "node:fs";
const fixtures = JSON.parse(readFileSync("tests/fixtures/solver-results.json", "utf8")) as {
scenarios: Record<string, { win: { loop: "A" | "B" | "C"; direction: "cw" | "ccw" }[] }>;
};
import type { Page } from "@playwright/test";
// Public-control preview-then-commit: select a rotation, then commit via the Commit button.
async function play(page: Page, loop: string, dir: string) {
await page.locator('[data-action="rotate"][data-loop="' + loop + '"][data-dir="' + dir + '"]').click();
await page.getByRole("button", { name: "Commit rotation" }).click();
}
test("no severe console errors on load", async ({ page }) => {
const errors: string[] = [];
page.on("console", (m: ConsoleMessage) => {
if (m.type() === "error") errors.push(m.text());
});
await page.goto("/");
await expect(page.locator("h1")).toHaveText("Adaptive Loop");
expect(errors.filter((e) => !e.includes("favicon"))).toEqual([]);
});
test("campaign start, preview, commit, movement + flow, win via public controls", async ({ page }) => {
await page.goto("/");
await page.getByRole("button", { name: "New Campaign" }).click();
// game screen
await expect(page.locator("svg.board")).toBeVisible();
await expect(page.locator('[data-action="rotate"]')).toHaveCount(6);
// focus a rotation -> preview appears
await page.locator('[data-action="rotate"]').first().focus();
await expect(page.locator("#preview-box")).toContainText(/Preview/);
// commit via Enter on the focused rotation
await page.keyboard.press("Enter");
await expect(page.locator(".stat-row").filter({ hasText: "Turn" })).toContainText("1 / 8");
await expect(page.locator("#event-box .event-list li").first()).toBeVisible();
// Fresh campaign, then drive the verified S1 winning route from turn 0.
await page.getByRole("button", { name: "Menu" }).click();
await page.getByRole("button", { name: "New Campaign" }).click();
const route = fixtures.scenarios["s1-heat"]!.win;
for (const a of route) {
await play(page, a.loop, a.direction);
}
await expect(page.locator("h2")).toContainText(/complete|Victory/i);
});
test("Save & Quit then close/reopen Continue restores exact state", async ({ page }) => {
await page.goto("/");
await page.getByRole("button", { name: "New Campaign" }).click();
// play two rotations (select then commit)
await play(page, "A", "ccw");
const turnAfter1 = await page.locator(".stat-row").filter({ hasText: "Turn" }).textContent();
await play(page, "A", "cw");
const turnAfter2 = await page.locator(".stat-row").filter({ hasText: "Turn" }).textContent();
expect(turnAfter2).not.toEqual(turnAfter1);
// Save & Quit
await page.getByRole("button", { name: "Save & Quit" }).click();
await expect(page.getByRole("button", { name: "Continue" })).toBeVisible();
// reload (close/reopen) and Continue
await page.reload();
await page.getByRole("button", { name: "Continue" }).click();
const restored = await page.locator(".stat-row").filter({ hasText: "Turn" }).textContent();
expect(restored).toEqual(turnAfter2);
});
test("lose by collapse/expiry then retry is reachable", async ({ page }) => {
await page.goto("/");
await page.getByRole("button", { name: "Replay Standalone" }).click();
await page.getByRole("button", { name: /Scenario 1:/ }).click();
// repeatedly rotate to push toward turn limit; keep going until terminal or many turns
for (let i = 0; i < 10; i++) {
const turn = (await page.locator(".stat-row").filter({ hasText: "Turn" }).textContent()) ?? "";
if (/expired|collapsed|won/i.test(turn)) break;
await play(page, "A", "ccw");
const live = await page.locator('[data-region="live"]').textContent();
if (live && /expired|collapsed|won/i.test(live)) break;
}
// Retry button present in campaign; in standalone we just confirm board still operational
await expect(page.locator("svg.board")).toBeVisible();
});
test("keyboard: Tab to a rotation, Enter commits; Escape cancels preview", async ({ page }) => {
await page.goto("/");
await page.getByRole("button", { name: "New Campaign" }).click();
await page.keyboard.press("Tab"); // into controls
await page.locator('[data-action="rotate"]').first().focus();
await expect(page.locator("#preview-box")).toContainText(/Preview/);
await page.keyboard.press("Escape");
await expect(page.locator("#preview-box")).toContainText(/Focus or hover/);
});
test("narrow viewport (390px) keeps board + controls reachable", async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
await page.goto("/");
await page.getByRole("button", { name: "New Campaign" }).click();
await expect(page.locator("svg.board")).toBeVisible();
await expect(page.locator('[data-action="rotate"]')).toHaveCount(6);
// no horizontal scroll (body scrollWidth within viewport)
const sw = await page.evaluate(() => document.documentElement.scrollWidth);
expect(sw).toBeLessThanOrEqual(410);
});
test("200% zoom and reduced motion render without errors", async ({ page }) => {
await page.addInitScript(() => {
// emulate reduced motion preference
Object.defineProperty(window, "matchMedia", {
writable: true,
value: (q: string) => ({ matches: q.includes("reduced-motion"), media: q, addEventListener() {}, removeEventListener() {} }),
});
});
await page.goto("/");
await page.evaluate(() => (document.body.style.zoom = "2"));
await page.getByRole("button", { name: "New Campaign" }).click();
await expect(page.locator('[data-action="rotate"]')).toHaveCount(6);
await page.locator('[data-action="rotate"]').first().focus();
await page.keyboard.press("Enter");
await expect(page.locator("#event-box .event-list li").first()).toBeVisible();
});
test("visible access to multiple scenarios via standalone replay", async ({ page }) => {
await page.goto("/");
await page.getByRole("button", { name: "Replay Standalone" }).click();
for (let i = 1; i <= 5; i++) {
await expect(page.getByRole("button", { name: new RegExp(`Scenario ${i}:`) })).toBeVisible();
}
});
test("adaptation is visible: driving the S2 route shows an adapted (unlocked) trait in the panel", async ({ page }) => {
await page.goto("/");
await page.getByRole("button", { name: "Replay Standalone" }).click();
await page.getByRole("button", { name: /Scenario 2:/ }).click();
let sawAdaptationEvent = false;
for (const a of fixtures.scenarios["s2-hunger"]!.win) {
await play(page, a.loop, a.direction);
const logText = (await page.locator("#event-box").textContent()) ?? "";
if (/unlock|Dormancy|hunger/i.test(logText)) sawAdaptationEvent = true;
}
// Either an adaptation event was attributed mid-play, or the final panel shows an unlocked trait.
const adaptedCount = await page.locator(".pressure-cell.unlocked").count();
expect(sawAdaptationEvent || adaptedCount > 0).toBeTruthy();
});
test("lose then retry then continue playing (S1)", async ({ page }) => {
await page.goto("/");
await page.getByRole("button", { name: "New Campaign" }).click();
// push to expiry by repeatedly rotating one loop
for (let i = 0; i < 9; i++) {
const live = (await page.locator('[data-region="live"]').textContent()) ?? "";
if (/expired|collapsed|won/i.test(live)) break;
await play(page, "A", "ccw");
}
const live = (await page.locator('[data-region="live"]').textContent()) ?? "";
// reached a terminal state (expired or collapsed)
expect(/expired|collapsed|won/i.test(live)).toBeTruthy();
// Retry restores entry snapshot (turn 0)
await page.getByRole("button", { name: "Retry" }).click();
await expect(page.locator(".stat-row").filter({ hasText: "Turn" })).toContainText("0 / 8");
});
-18
View File
@@ -1,18 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="color-scheme" content="dark" />
<meta name="description" content="Adaptive Loop — a deterministic microfluidic strategy puzzle." />
<title>Adaptive Loop</title>
<link rel="stylesheet" href="./src/styles.css" />
</head>
<body>
<a class="skip-link" href="#main">Skip to game</a>
<div id="app" aria-label="Adaptive Loop game">
<!-- App shell rendered procedurally by main.ts -->
</div>
<script type="module" src="./src/main.ts"></script>
</body>
</html>
-2706
View File
File diff suppressed because it is too large. Load diff
-24
View File
@@ -1,24 +0,0 @@
{
"name": "adaptive-loop",
"private": true,
"version": "1.0.0",
"type": "module",
"description": "Adaptive Loop — a deterministic microfluidic strategy puzzle (Agentic Labs one-prompt build).",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview --port 4173",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest",
"e2e": "playwright test",
"verify": "npm run typecheck && npm run test && npm run build && npm run e2e"
},
"devDependencies": {
"@playwright/test": "^1.58.2",
"@types/node": "^22.10.0",
"typescript": "^5.7.2",
"vite": "^6.0.0",
"vitest": "^2.1.0"
}
}
-28
View File
@@ -1,28 +0,0 @@
import { defineConfig, devices } from "@playwright/test";
// Black-box browser proof against the production build via public controls only.
export default defineConfig({
testDir: "./e2e",
timeout: 60_000,
expect: { timeout: 10_000 },
fullyParallel: false,
retries: 0,
workers: 1,
reporter: [["list"], ["html", { open: "never", outputFolder: "playwright-report" }]],
use: {
baseURL: "http://localhost:4173",
headless: true,
actionTimeout: 10_000,
viewport: { width: 1280, height: 900 },
trace: "retain-on-failure",
},
projects: [
{ name: "chromium", use: { ...devices["Desktop Chrome"] } },
],
webServer: {
command: "npm run preview",
url: "http://localhost:4173",
reuseExistingServer: !process.env.CI,
timeout: 60_000,
},
});
-211
View File
@@ -1,211 +0,0 @@
// Adaptive Loop — immutable declarative scenarios. SPEC §9.
// Sparse start notation order: nutrient / producer / grazer / phage / heat / toxin.
import type { LineageId, PressureId } from "../domain/types";
export type FixtureKind =
| "nutrientInlet"
| "heatSource"
| "toxinInlet"
| "drain"
| "immuneNode"
| "objectiveMarker";
export interface FixtureDef {
slot: number;
kind: FixtureKind;
/** For objectiveMarker: a label like "sanctuary" / "assay". */
marker?: string;
}
/** Start tuple in notation order: [nutrient, producer, grazer, phage, heat, toxin]. */
export type StartTuple = [number, number, number, number, number, number];
export interface SustainedSpec {
assaySlots: number[];
assayPopMin: number;
producerRange: [number, number];
grazerRange: [number, number];
phageMax: number;
toxinMax: number;
}
export type WinSpec =
| { kind: "producerAt"; slot: number; producerMin: number; totalProducerMin: number }
| {
kind: "endurance";
atTurn: number;
totalProducerMin: number;
totalGrazerMin: number;
producerChambersMin: number;
grazerChambersMin: number;
}
| { kind: "cleanse"; totalToxinMax: number; totalPopMin: number; fromTurn: number; toTurn: number }
| { kind: "escort"; slot: number; grazerMin: number; phageMin: number; totalProducerMin: number }
| { kind: "sustained"; required: number; sustained: SustainedSpec };
export interface ScenarioDef {
id: string;
index: number;
title: string;
pressure: PressureId;
subtitle: string;
teaches: string;
turnLimit: number;
fixtures: FixtureDef[];
start: Record<number, StartTuple>;
win: WinSpec;
winDescription: string;
}
export const SCENARIOS: ScenarioDef[] = [
{
id: "s1-heat",
index: 0,
title: "Cultivation Quota",
pressure: "heat",
subtitle: "Heat",
teaches: "rotation, ownership, flow, growth, preview, first visible pressure",
turnLimit: 8,
fixtures: [
{ slot: 1, kind: "nutrientInlet" },
{ slot: 7, kind: "nutrientInlet" },
{ slot: 3, kind: "heatSource" },
{ slot: 9, kind: "heatSource" },
],
start: {
0: [3, 2, 0, 0, 0, 0],
6: [3, 2, 0, 0, 0, 0],
10: [2, 1, 0, 0, 0, 0],
4: [1, 0, 0, 0, 0, 0],
},
win: { kind: "producerAt", slot: 11, producerMin: 5, totalProducerMin: 12 },
winDescription: "producer at slot 11 ≥ 5 and total producer ≥ 12",
},
{
id: "s2-hunger",
index: 1,
title: "Endurance",
pressure: "hunger",
subtitle: "Hunger",
teaches: "competition, migration, dormancy, deliberate denial of predator food",
turnLimit: 10,
fixtures: [{ slot: 0, kind: "nutrientInlet" }],
start: {
1: [2, 3, 0, 0, 0, 0],
5: [1, 2, 1, 0, 0, 0],
7: [2, 3, 1, 0, 0, 0],
10: [0, 2, 2, 0, 0, 0],
},
win: {
kind: "endurance",
atTurn: 10,
totalProducerMin: 8,
totalGrazerMin: 4,
producerChambersMin: 3,
grazerChambersMin: 2,
},
winDescription:
"at turn 10: total producer ≥ 8, total grazer ≥ 4, producer in ≥ 3 chambers, grazer in ≥ 2 chambers",
},
{
id: "s3-toxin",
index: 2,
title: "Cleansing",
pressure: "toxin",
subtitle: "Toxin",
teaches: "routing contaminants, resistance payment, shared detoxification spillover",
turnLimit: 9,
fixtures: [
{ slot: 1, kind: "nutrientInlet" },
{ slot: 3, kind: "toxinInlet" },
{ slot: 5, kind: "drain" },
{ slot: 11, kind: "drain" },
],
start: {
0: [3, 3, 0, 0, 0, 0],
3: [0, 0, 0, 0, 0, 2],
6: [2, 3, 0, 0, 0, 0],
9: [0, 0, 0, 0, 0, 2],
10: [2, 2, 1, 0, 0, 0],
},
win: { kind: "cleanse", totalToxinMax: 2, totalPopMin: 8, fromTurn: 6, toTurn: 9 },
winDescription: "turn 6–9: total toxin ≤ 2 and total producer + grazer ≥ 8",
},
{
id: "s4-immunity",
index: 3,
title: "Escort",
pressure: "immunity",
subtitle: "Immunity",
teaches: "immune targeting, cloak, retargeting spillover, predator vulnerability",
turnLimit: 8,
fixtures: [
{ slot: 0, kind: "nutrientInlet" },
{ slot: 8, kind: "nutrientInlet" },
{ slot: 2, kind: "immuneNode" },
{ slot: 4, kind: "immuneNode" },
{ slot: 6, kind: "immuneNode" },
{ slot: 11, kind: "objectiveMarker", marker: "sanctuary" },
],
start: {
1: [2, 3, 0, 0, 0, 0],
5: [2, 3, 2, 0, 0, 0],
7: [0, 0, 0, 1, 0, 0],
9: [1, 0, 2, 1, 0, 0],
},
win: { kind: "escort", slot: 11, grazerMin: 3, phageMin: 0, totalProducerMin: 6 },
winDescription: "grazer at slot 11 ≥ 3 and total producer ≥ 6",
},
{
id: "s5-convergence",
index: 4,
title: "Stable Equilibrium",
pressure: "immunity",
subtitle: "Convergence",
teaches: "all systems plus inherited gift-and-burden consequences",
turnLimit: 12,
fixtures: [
{ slot: 0, kind: "nutrientInlet" },
{ slot: 6, kind: "nutrientInlet" },
{ slot: 2, kind: "heatSource" },
{ slot: 8, kind: "heatSource" },
{ slot: 3, kind: "toxinInlet" },
{ slot: 9, kind: "drain" },
{ slot: 4, kind: "immuneNode" },
{ slot: 10, kind: "immuneNode" },
{ slot: 1, kind: "objectiveMarker", marker: "assay" },
{ slot: 7, kind: "objectiveMarker", marker: "assay" },
{ slot: 11, kind: "objectiveMarker", marker: "assay" },
],
start: {
0: [3, 3, 0, 0, 0, 0],
3: [0, 0, 0, 0, 0, 2],
5: [2, 2, 1, 0, 0, 0],
6: [3, 2, 0, 0, 0, 0],
8: [0, 0, 0, 0, 2, 0],
9: [0, 0, 0, 0, 0, 1],
10: [2, 2, 2, 1, 0, 0],
},
win: {
kind: "sustained",
required: 2,
sustained: {
assaySlots: [1, 7, 11],
assayPopMin: 2,
producerRange: [8, 14],
grazerRange: [3, 7],
phageMax: 3,
toxinMax: 6,
},
},
winDescription: "hold the equilibrium for 2 consecutive turns",
},
];
export const SCENARIO_BY_ID: Record<string, ScenarioDef> = Object.fromEntries(
SCENARIOS.map((s) => [s.id, s]),
);
export type InheritanceSet = Partial<Record<LineageId, PressureId[]>>;
export const STORAGE_KEY = "adaptive-loop-save-v1";
-103
View File
@@ -1,103 +0,0 @@
// Adaptive Loop — immutable topology + species/trait tables. SPEC §4, §6, §8.
import type { Direction, LineageId, LoopId, PressureId } from "./types";
/** Slots of each loop in clockwise visual order. SPEC §4. */
export const LOOPS: Record<LoopId, number[]> = {
A: [0, 1, 2, 3, 4, 5],
B: [2, 3, 6, 7, 8, 9],
C: [4, 5, 10, 11, 8, 9],
};
/** Which loops contain each shared slot. */
export const SHARED_LOOPS: Record<string, LoopId[]> = {
"2": ["A", "B"],
"3": ["A", "B"],
"4": ["A", "C"],
"5": ["A", "C"],
"8": ["B", "C"],
"9": ["B", "C"],
};
export const SHARED_SLOT_KEYS = ["2", "3", "4", "5", "8", "9"];
/** Shared slots claimed by a loop when it is rotated. SPEC §4 step 4. */
export const LOOP_SHARED_SLOTS: Record<LoopId, number[]> = {
A: [2, 3, 4, 5],
B: [2, 3, 8, 9],
C: [4, 5, 8, 9],
};
/** All 12 slots. Non-shared slots own themselves via their only loop. */
export const ALL_SLOTS = Array.from({ length: 12 }, (_, i) => i);
/** The single loop that owns a non-shared slot. */
export function loopOfNonShared(slot: number): LoopId | null {
if ([0, 1].includes(slot)) return "A";
if ([6, 7].includes(slot)) return "B";
if ([10, 11].includes(slot)) return "C";
return null;
}
/** Step used for "next"/outlet and rotation: +1 cw, +5 ccw. SPEC §4. */
export function dirStep(dir: Direction): number {
return dir === "cw" ? 1 : 5;
}
/** Default (alphabetical) owner of a shared slot at scenario start. */
export function defaultOwner(slotKey: string): LoopId {
const loops = SHARED_LOOPS[slotKey] ?? [];
return loops.slice().sort()[0] as LoopId;
}
// --- Species / pressure flavor (SPEC §6) ------------------------------------
export interface SpeciesInfo {
id: "producer" | "grazer" | "phage";
name: string;
food: "nutrient" | "producer" | "grazer";
persistent: boolean;
}
export const SPECIES: Record<string, SpeciesInfo> = {
producer: { id: "producer", name: "Veridan", food: "nutrient", persistent: true },
grazer: { id: "grazer", name: "Cilia", food: "producer", persistent: true },
phage: { id: "phage", name: "Phage", food: "grazer", persistent: false },
};
/** Food quantity a species chases, read from a chamber. */
export function foodOf(chamber: { nutrient: number; producer: number; grazer: number }, sp: "producer" | "grazer" | "phage"): number {
if (sp === "producer") return chamber.nutrient;
if (sp === "grazer") return chamber.producer;
return chamber.grazer;
}
export interface PressureInfo {
id: PressureId;
traitName: string;
/** Hot-key symbol for non-color encoding. */
glyph: string;
}
export const PRESSURES: Record<PressureId, PressureInfo> = {
heat: { id: "heat", traitName: "Heat Shield", glyph: "🔥" },
hunger: { id: "hunger", traitName: "Dormancy", glyph: "☾" },
toxin: { id: "toxin", traitName: "Efflux", glyph: "⚗" },
immunity: { id: "immunity", traitName: "Cloak", glyph: "◊" },
};
/** Trait unlock order within a lineage for content/reference. */
export const TRAIT_BY_PRESSURE: Record<PressureId, string> = {
heat: "Heat Shield",
hunger: "Dormancy",
toxin: "Efflux",
immunity: "Cloak",
};
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 const PRESSURE_LINEAGE_ORDER: LineageId[] = ["producer", "grazer"];
-520
View File
@@ -1,520 +0,0 @@
// Adaptive Loop — the one pure transition. nextState(state, action) runs the
// fixed 8-phase tick (SPEC §7) and derives deterministic events (SPEC §8, §12).
// Never mutates its input. Preview calls this on a clone; commit calls it for real.
import type {
GameState,
RotationAction,
GameEvent,
TurnResult,
LineageId,
PressureId,
Chamber,
} from "./types";
import { LINEAGE_IDS, PRESSURE_IDS } from "./types";
import { LOOPS, LOOP_SHARED_SLOTS, dirStep, CAP, clamp } from "./constants";
import { cloneState } from "./serialize";
import { outletOf, totalPersistent, sustainedHolds, evaluateWin } from "./scenario";
import { SCENARIO_BY_ID } from "../content/scenarios";
import type { FixtureDef } from "../content/scenarios";
const ALL_ACTIONS: RotationAction[] = [
{ loop: "A", direction: "cw" },
{ loop: "A", direction: "ccw" },
{ loop: "B", direction: "cw" },
{ loop: "B", direction: "ccw" },
{ loop: "C", direction: "cw" },
{ loop: "C", direction: "ccw" },
];
export function allActions(): RotationAction[] {
return ALL_ACTIONS.map((a) => ({ ...a }));
}
function fixturesOf(state: GameState): FixtureDef[] {
return SCENARIO_BY_ID[state.scenarioId]?.fixtures ?? [];
}
function isImmuneNode(state: GameState, slot: number): boolean {
return fixturesOf(state).some((f) => f.slot === slot && f.kind === "immuneNode");
}
function popOf(c: Chamber, lid: LineageId): number {
return lid === "producer" ? c.producer : c.grazer;
}
function addPop(c: Chamber, lid: LineageId, delta: number) {
if (lid === "producer") c.producer = clamp(c.producer + delta, 0, CAP);
else c.grazer = clamp(c.grazer + delta, 0, CAP);
}
function lineageFood(c: Chamber, lid: LineageId): number {
return lid === "producer" ? c.nutrient : c.producer;
}
function speciesFood(c: Chamber, sp: "producer" | "grazer" | "phage"): number {
if (sp === "producer") return c.nutrient;
if (sp === "grazer") return c.producer;
return c.grazer;
}
// Locally-active trait predicates (SPEC §8 "global unlock ≠ always active").
function heatActive(state: GameState, lid: LineageId, c: Chamber): boolean {
return state.lineage[lid].unlocked.heat && c.heat >= 2;
}
function hungerActive(state: GameState, lid: LineageId, c: Chamber): boolean {
return state.lineage[lid].unlocked.hunger && lineageFood(c, lid) === 0;
}
function cloakActive(state: GameState, lid: LineageId, slot: number): boolean {
return state.lineage[lid].unlocked.immunity && isImmuneNode(state, slot);
}
function ev(e: GameEvent): GameEvent {
return e;
}
export function nextState(
input: GameState,
action: RotationAction,
opts?: { freezeOwnership?: boolean },
): TurnResult {
// Terminal/illegal: reject without changing domain state.
if (input.outcome !== "playing") {
return {
state: input,
events: [ev({ phase: "outcome", kind: "rejected", text: `Terminal state (${input.outcome}); action rejected.` })],
};
}
const state = cloneState(input);
const events: GameEvent[] = [];
const L = action.loop;
const step = dirStep(action.direction);
const loopSlots = LOOPS[L];
// ---- Phase 1: rotate & reconnect ---------------------------------------
const rotSnap = loopSlots.map((s) => state.chambers[s]);
for (let i = 0; i < 6; i++) {
const dest = loopSlots[(i + step) % 6]!;
state.chambers[dest] = rotSnap[i]!;
}
state.loops[L].direction = action.direction;
if (!opts?.freezeOwnership) {
for (const slot of LOOP_SHARED_SLOTS[L]) state.sharedOwner[String(slot)] = L;
}
events.push(
ev({
phase: "rotate",
kind: "rotate",
text: `Loop ${L} rotated ${action.direction.toUpperCase()}: chambers shift, ownership reclaimed.`,
}),
);
// ---- Phase 2: channel flow (nutrient & toxin along outlets) ------------
{
const snapN = state.chambers.map((c) => c.nutrient);
const snapT = state.chambers.map((c) => c.toxin);
const sendN = new Array(12).fill(0);
const sendT = new Array(12).fill(0);
const recvN = new Array(12).fill(0);
const recvT = new Array(12).fill(0);
for (let i = 0; i < 12; i++) {
const out = outletOf(state, i);
if (snapN[i]! > 0) {
sendN[i] = 1;
recvN[out]! += 1;
}
if (snapT[i]! > 0) {
sendT[i] = 1;
recvT[out]! += 1;
}
}
for (let i = 0; i < 12; i++) {
const nn = clamp(snapN[i]! - sendN[i]! + recvN[i]!, 0, CAP);
const nt = clamp(snapT[i]! - sendT[i]! + recvT[i]!, 0, CAP);
const overN = snapN[i]! - sendN[i]! + recvN[i]! - nn;
const overT = snapT[i]! - sendT[i]! + recvT[i]! - nt;
state.chambers[i]!.nutrient = nn;
state.chambers[i]!.toxin = nt;
if (recvN[i]! > 0)
events.push(ev({ phase: "flow", kind: "nutrient", slot: i, text: `+${recvN[i]} nutrient arrived; ${overN > 0 ? `${overN} overflow discarded` : "no overflow"}.` }));
if (recvT[i]! > 0)
events.push(ev({ phase: "flow", kind: "toxin", slot: i, text: `+${recvT[i]} toxin arrived; ${overT > 0 ? `${overT} overflow discarded` : "no overflow"}.` }));
}
}
// ---- Phase 3: producer growth ------------------------------------------
{
const snap = state.chambers.map((c) => ({ ...c }));
for (let i = 0; i < 12; i++) {
const cur = state.chambers[i]!;
const s = snap[i]!;
if (s.producer > 0 && s.nutrient > 0) {
cur.nutrient -= 1; // consumed unconditionally (SPEC §7 phase 3)
const suppressed = heatActive(state, "producer", s);
const gain = suppressed ? 0 : 1;
const before = cur.producer;
cur.producer = clamp(cur.producer + gain, 0, CAP);
const wasted = before + gain - cur.producer;
events.push(
ev({
phase: "growth",
kind: suppressed ? "growth-suppressed" : "growth",
slot: i,
lineage: "producer",
text: suppressed
? "Heat-adapted: feeding consumes nutrient but adds no population."
: `Producer +${cur.producer - before}${wasted > 0 ? ` (${wasted} overflow)` : ""}.`,
}),
);
}
}
}
// ---- Phase 4: biological interactions (grazer then phage) --------------
runGrazerSubphase(state, events);
runPhageSubphase(state, events);
// ---- Phase 5: migration (producer, grazer, phage) ---------------------
migrateSpecies(state, "producer", events);
migrateSpecies(state, "grazer", events);
migrateSpecies(state, "phage", events);
// ---- Phase 6: evolution & environmental response activation -----------
for (const lid of LINEAGE_IDS) {
const lin = state.lineage[lid];
for (const p of PRESSURE_IDS) {
if (lin.pressure[p] >= 3 && !lin.unlocked[p]) {
lin.unlocked[p] = true;
events.push(ev({ phase: "evolve", kind: "unlock", lineage: lid, pressure: p, text: `${lid} unlocked ${p} trait.` }));
}
}
}
for (const p of PRESSURE_IDS) {
const anyAt3 = LINEAGE_IDS.some((lid) => state.lineage[lid].pressure[p] >= 3);
if (anyAt3 && !state.environmentActive[p]) {
state.environmentActive[p] = true;
events.push(ev({ phase: "evolve", kind: "env-response", pressure: p, text: `Global ${p} response active.` }));
}
}
// ---- Phase 7: fixtures, exposure, pressure consequences ---------------
runFixturesAndPressures(state, events);
// ---- Phase 8: outcome & turn finalization ------------------------------
const resolvedTurn = input.turn + 1;
const consecutive = sustainedHolds(state) ? input.consecutiveObjectiveTurns + 1 : 0;
const collapsed = totalPersistent(state) === 0;
let outcome: GameState["outcome"] = "playing";
if (collapsed) {
outcome = "collapsed";
events.push(ev({ phase: "outcome", kind: "collapse", text: "Ecosystem collapse: no producer or grazer remains." }));
} else if (evaluateWin(state, resolvedTurn, consecutive)) {
outcome = "won";
events.push(ev({ phase: "outcome", kind: "win", text: "Objective achieved." }));
} else if (resolvedTurn >= (SCENARIO_BY_ID[state.scenarioId]?.turnLimit ?? Infinity)) {
outcome = "expired";
events.push(ev({ phase: "outcome", kind: "expire", text: "Turn limit reached." }));
}
state.turn = resolvedTurn;
state.consecutiveObjectiveTurns = consecutive;
state.outcome = outcome;
state.actionLog = [...input.actionLog, { loop: action.loop, direction: action.direction }];
return { state, events };
}
// --- phase 4 helpers --------------------------------------------------------
function runGrazerSubphase(state: GameState, events: GameEvent[]) {
const snap = state.chambers.map((c) => ({ ...c }));
for (let i = 0; i < 12; i++) {
const cur = state.chambers[i]!;
const s = snap[i]!;
if (s.grazer <= 0) continue;
const dormantPrey = hungerActive(state, "producer", s);
const edible = s.producer > 0 && !dormantPrey;
if (!edible) continue;
const cloak = cloakActive(state, "producer", i);
const remove = cloak ? Math.min(2, s.producer) : 1;
cur.producer = clamp(cur.producer - remove, 0, CAP);
const before = cur.grazer;
cur.grazer = clamp(cur.grazer + 1, 0, CAP);
events.push(
ev({
phase: "interact",
kind: cloak ? "graze-cloak" : "graze",
slot: i,
lineage: "grazer",
text: cloak
? `Grazer eats cloaked producer: removes ${remove} prey (cloak cost), grazer +${cur.grazer - before}.`
: `Grazer consumes producer, grazer +${cur.grazer - before}.`,
}),
);
}
}
function runPhageSubphase(state: GameState, events: GameEvent[]) {
const snap = state.chambers.map((c) => ({ ...c }));
for (let i = 0; i < 12; i++) {
const cur = state.chambers[i]!;
const s = snap[i]!;
if (s.phage <= 0) continue;
const dormantPrey = hungerActive(state, "grazer", s);
const edible = s.grazer > 0 && !dormantPrey;
if (edible) {
const cloak = cloakActive(state, "grazer", i);
const remove = cloak ? Math.min(2, s.grazer) : 1;
cur.grazer = clamp(cur.grazer - remove, 0, CAP);
const before = cur.phage;
cur.phage = clamp(cur.phage + 1, 0, CAP);
events.push(
ev({
phase: "interact",
kind: cloak ? "phage-cloak" : "phage",
slot: i,
text: cloak
? `Phage eats cloaked grazer: removes ${remove} prey (cloak cost), phage +${cur.phage - before}.`
: `Phage consumes grazer, phage +${cur.phage - before}.`,
}),
);
} else {
const before = cur.phage;
cur.phage = clamp(cur.phage - 1, 0, CAP);
events.push(ev({ phase: "interact", kind: "phage-starve", slot: i, text: `Phage cannot feed, phage ${before}→${cur.phage}.` }));
}
}
}
// --- phase 5 helper ----------------------------------------------------------
function migrateSpecies(state: GameState, sp: "producer" | "grazer" | "phage", events: GameEvent[]) {
const snap = state.chambers.map((c) => ({ ...c }));
const send = new Array(12).fill(0);
const recv = new Array(12).fill(0);
for (let i = 0; i < 12; i++) {
const s = snap[i]!;
if (s[sp] < 2) continue;
// Dormancy prevents migration for lineages (phage has no traits).
if (sp !== "phage") {
const lid = sp as LineageId;
if (hungerActive(state, lid, s)) continue;
}
const dest = outletOf(state, i);
if (speciesFood(snap[dest]!, sp) > speciesFood(s, sp)) {
send[i] = 1;
recv[dest]! += 1;
}
}
for (let i = 0; i < 12; i++) {
if (send[i] === 0 && recv[i] === 0) continue;
const before = state.chambers[i]![sp];
const next = clamp(before - send[i]! + recv[i]!, 0, CAP);
state.chambers[i]![sp] = next;
if (send[i] || recv[i]) {
events.push(
ev({
phase: "migrate",
kind: "migrate",
slot: i,
text: `${sp}: ${send[i] ? "−1 out" : "stays"}${recv[i] ? `, +${recv[i]} in` : ""} (${before}→${next}).`,
}),
);
}
}
}
// --- phase 7: fixtures + exposure + consequences ----------------------------
function runFixturesAndPressures(state: GameState, events: GameEvent[]) {
const fx = fixturesOf(state);
const nutrientInlets = fx.filter((f) => f.kind === "nutrientInlet").map((f) => f.slot);
const heatSources = fx.filter((f) => f.kind === "heatSource").map((f) => f.slot);
const toxinInlets = fx.filter((f) => f.kind === "toxinInlet").map((f) => f.slot);
const drains = fx.filter((f) => f.kind === "drain").map((f) => f.slot);
const immuneNodes = fx.filter((f) => f.kind === "immuneNode").map((f) => f.slot).sort((a, b) => a - b);
// (1) nutrient inlets
for (const slot of nutrientInlets) {
const add = state.environmentActive.hunger ? 1 : 2;
state.chambers[slot]!.nutrient = clamp(state.chambers[slot]!.nutrient + add, 0, CAP);
}
// (2) heat sources, then global heat -1
for (const slot of heatSources) {
const add = state.environmentActive.heat ? 3 : 2;
state.chambers[slot]!.heat = clamp(state.chambers[slot]!.heat + add, 0, CAP);
}
for (let i = 0; i < 12; i++) state.chambers[i]!.heat = clamp(state.chambers[i]!.heat - 1, 0, CAP);
// (3) toxin inlets
for (const slot of toxinInlets) {
const add = state.environmentActive.toxin ? 3 : 2;
state.chambers[slot]!.toxin = clamp(state.chambers[slot]!.toxin + add, 0, CAP);
}
// (4) drains
for (const slot of drains) {
state.chambers[slot]!.toxin = clamp(state.chambers[slot]!.toxin - 2, 0, CAP);
}
events.push(ev({ phase: "fixtures", kind: "fixtures", text: "Fixtures applied: inlets, sources, drains." }));
// (5) immunity target selection
const immuneDamage = state.environmentActive.immunity ? 3 : 2;
const selections: { slot: number; lineage: LineageId }[] = [];
for (const slot of immuneNodes) {
const c = state.chambers[slot]!;
const eligible: LineageId[] = LINEAGE_IDS.filter((lid) => popOf(c, lid) > 0 && !state.lineage[lid].unlocked.immunity);
if (eligible.length === 0) continue;
let chosen: LineageId = eligible[0]!;
for (const lid of eligible) {
if (popOf(c, lid) > popOf(c, chosen)) chosen = lid;
}
// tie -> producer (producer comes first in LINEAGE_IDS, and we only replace on strictly greater)
selections.push({ slot, lineage: chosen });
const cloakedPresent = LINEAGE_IDS.some((lid) => popOf(c, lid) > 0 && state.lineage[lid].unlocked.immunity);
events.push(
ev({
phase: "fixtures",
kind: "immune-select",
slot,
lineage: chosen,
text: `Immune node selects ${chosen} (damage ${immuneDamage})${cloakedPresent ? "; cloaked lineage forced retarget (spillover)" : ""}.`,
}),
);
}
// (6) exposure snapshot: qualification + occupied, per (slot, lineage, pressure)
type Qual = { heat: boolean; hunger: boolean; toxin: boolean };
const qual: Record<string, Qual> = {}; // key `${slot}:${lineage}`
for (let i = 0; i < 12; i++) {
const c = state.chambers[i]!;
for (const lid of LINEAGE_IDS) {
if (popOf(c, lid) <= 0) continue;
qual[`${i}:${lid}`] = {
heat: c.heat >= 2,
hunger: lineageFood(c, lid) === 0,
toxin: c.toxin >= 2,
};
}
}
// immunity qualification from selections
const immuneQualified = new Set(selections.map((s) => `${s.slot}:${s.lineage}`));
// (7) increment pressure tracks (+1 if lineage occupied >=1 qualifying chamber)
for (const lid of LINEAGE_IDS) {
const lin = state.lineage[lid];
for (const p of PRESSURE_IDS) {
let any = false;
if (p === "immunity") any = selections.some((s) => s.lineage === lid);
else
for (let i = 0; i < 12; i++) {
const q = qual[`${i}:${lid}`];
if (q && (q as Record<PressureId, boolean>)[p]) {
any = true;
break;
}
}
if (any) {
const before = lin.pressure[p];
lin.pressure[p] = clamp(lin.pressure[p] + 1, 0, 3);
if (lin.pressure[p] !== before)
events.push(ev({ phase: "pressure", kind: "pressure-up", lineage: lid, pressure: p, text: `${lid} ${p} pressure ${before}→${lin.pressure[p]}.` }));
}
}
}
// (8) consequences: heat, hunger, toxin, immunity (in order); spillover after heat/toxin
applyPressureConsequences(state, "heat", qual, immuneQualified, selections, immuneDamage, events);
applyPressureConsequences(state, "hunger", qual, immuneQualified, selections, immuneDamage, events);
applyPressureConsequences(state, "toxin", qual, immuneQualified, selections, immuneDamage, events);
applyPressureConsequences(state, "immunity", qual, immuneQualified, selections, immuneDamage, events);
}
function applyPressureConsequences(
state: GameState,
pressure: PressureId,
qual: Record<string, { heat: boolean; hunger: boolean; toxin: boolean }>,
_immuneQualified: Set<string>,
selections: { slot: number; lineage: LineageId }[],
immuneDamage: number,
events: GameEvent[],
) {
if (pressure === "immunity") {
for (const sel of selections) {
const c = state.chambers[sel.slot]!;
if (popOf(c, sel.lineage) <= 0) continue; // skip if already zero
const before = popOf(c, sel.lineage);
addPop(c, sel.lineage, -immuneDamage);
events.push(ev({ phase: "pressure", kind: "immune-damage", slot: sel.slot, lineage: sel.lineage, text: `Immune damage ${sel.lineage} ${before}→${popOf(c, sel.lineage)}.` }));
}
return;
}
for (let i = 0; i < 12; i++) {
for (const lid of LINEAGE_IDS) {
const c = state.chambers[i]!;
if (popOf(c, lid) <= 0) continue; // skip current-zero even if qualified
const q = qual[`${i}:${lid}`];
if (!q || !(q as Record<PressureId, boolean>)[pressure]) continue;
const adapted = state.lineage[lid].unlocked[pressure];
if (pressure === "heat") {
if (adapted) {
events.push(ev({ phase: "pressure", kind: "heat-shield", slot: i, lineage: lid, text: `${lid} Heat Shield prevents heat loss.` }));
} else {
const before = popOf(c, lid);
addPop(c, lid, -2);
events.push(ev({ phase: "pressure", kind: "heat-loss", slot: i, lineage: lid, text: `${lid} heat loss ${before}→${popOf(c, lid)}.` }));
}
} else if (pressure === "hunger") {
if (adapted) {
events.push(ev({ phase: "pressure", kind: "dormancy", slot: i, lineage: lid, text: `${lid} Dormancy prevents hunger loss.` }));
} else {
const before = popOf(c, lid);
addPop(c, lid, -1);
events.push(ev({ phase: "pressure", kind: "hunger-loss", slot: i, lineage: lid, text: `${lid} hunger loss ${before}→${popOf(c, lid)}.` }));
}
} else if (pressure === "toxin") {
if (adapted) {
// Efflux: pay 1 nutrient; if none, lose 1 pop. Producer pays before grazer (loop order).
if (c.nutrient > 0) {
c.nutrient = clamp(c.nutrient - 1, 0, CAP);
events.push(ev({ phase: "pressure", kind: "efflux-pay", slot: i, lineage: lid, text: `${lid} Efflux pays 1 nutrient to resist toxin.` }));
} else {
const before = popOf(c, lid);
addPop(c, lid, -1);
events.push(ev({ phase: "pressure", kind: "efflux-cost", slot: i, lineage: lid, text: `${lid} Efflux: no nutrient, loses ${before - popOf(c, lid)} population.` }));
}
} else {
const before = popOf(c, lid);
addPop(c, lid, -1);
events.push(ev({ phase: "pressure", kind: "toxin-loss", slot: i, lineage: lid, text: `${lid} toxin loss ${before}→${popOf(c, lid)}.` }));
}
}
}
}
// spillover: heat & toxin detox after both lineages resolved
if (pressure === "heat" || pressure === "toxin") {
for (let i = 0; i < 12; i++) {
const c = state.chambers[i]!;
let reducers = 0;
for (const lid of LINEAGE_IDS) {
if (state.lineage[lid].unlocked[pressure] && popOf(c, lid) > 0) reducers++;
}
if (reducers > 0) {
const reduce = Math.min(2, reducers);
const field = pressure === "heat" ? "heat" : "toxin";
const before = c[field];
c[field] = clamp(c[field] - reduce, 0, CAP);
if (c[field] !== before)
events.push(ev({ phase: "pressure", kind: "spillover", slot: i, pressure, text: `${field} −${before - c[field]} (adapted spillover).` }));
}
}
}
}
// Replay an action log from a baseline+inheritance; must reproduce canonical state.
export function replayLog(
baseline: GameState,
actions: RotationAction[],
opts?: { freezeOwnership?: boolean },
): GameState {
let s = baseline;
for (const a of actions) {
const r = nextState(s, a, opts);
s = r.state;
if (s.outcome !== "playing") break; // terminal stops further resolution
}
return s;
}
-168
View File
@@ -1,168 +0,0 @@
// Adaptive Loop — scenario state construction, ownership/outlet, aggregations,
// win & sustained predicates. SPEC §4, §8, §9.
import type { GameState, LoopId, Mode, LineageId, PressureId, Chamber } from "./types";
import { LINEAGE_IDS, PRESSURE_IDS } from "./types";
import {
LOOPS,
SHARED_SLOT_KEYS,
defaultOwner,
dirStep,
loopOfNonShared,
} from "./constants";
import { emptyChamber } from "./serialize";
import { SCENARIO_BY_ID } from "../content/scenarios";
import type { InheritanceSet } from "../content/scenarios";
/** Owning loop of any slot (shared uses state.sharedOwner; else its only loop). */
export function ownerOf(state: GameState, slot: number): LoopId {
const key = String(slot);
if (SHARED_SLOT_KEYS.includes(key)) {
return state.sharedOwner[key]!;
}
const only = loopOfNonShared(slot);
if (!only) throw new Error(`slot ${slot} has no owner`);
return only;
}
/** Outlet slot = next slot along the owning loop in its current direction. */
export function outletOf(state: GameState, slot: number): number {
const owner = ownerOf(state, slot);
const arr = LOOPS[owner];
const idx = arr.indexOf(slot);
if (idx < 0) throw new Error(`slot ${slot} not in owner loop ${owner}`);
const step = dirStep(state.loops[owner].direction);
return arr[(idx + step) % arr.length] as number;
}
export function makeLineage(inherited: PressureId[] = []) {
const unlocked: Record<PressureId, boolean> = { heat: false, hunger: false, toxin: false, immunity: false };
for (const p of inherited) unlocked[p] = true;
return {
pressure: { heat: 0, hunger: 0, toxin: 0, immunity: 0 } as Record<PressureId, number>,
unlocked,
};
}
export function createScenarioState(
scenarioId: string,
mode: Mode,
inheritance: InheritanceSet = {},
): GameState {
const scenario = SCENARIO_BY_ID[scenarioId];
if (!scenario) throw new Error(`unknown scenario ${scenarioId}`);
const chambers: Chamber[] = Array.from({ length: 12 }, () => emptyChamber());
for (const slotStr of Object.keys(scenario.start)) {
const slot = Number(slotStr);
const [nutrient, producer, grazer, phage, heat, toxin] = scenario.start[slot]!;
const c = chambers[slot]!;
c.nutrient = nutrient;
c.producer = producer;
c.grazer = grazer;
c.phage = phage;
c.heat = heat;
c.toxin = toxin;
}
const sharedOwner: Record<string, LoopId> = {};
for (const k of SHARED_SLOT_KEYS) sharedOwner[k] = defaultOwner(k);
const lineage = {
producer: makeLineage(inheritance.producer),
grazer: makeLineage(inheritance.grazer),
} as Record<LineageId, ReturnType<typeof makeLineage>>;
return {
schemaVersion: 1,
mode,
scenarioId,
turn: 0,
loops: { A: { direction: "cw" }, B: { direction: "cw" }, C: { direction: "cw" } },
sharedOwner,
chambers,
lineage,
inheritedAtStart: {
producer: [...(inheritance.producer ?? [])],
grazer: [...(inheritance.grazer ?? [])],
},
consecutiveObjectiveTurns: 0,
environmentActive: { heat: false, hunger: false, toxin: false, immunity: false },
outcome: "playing",
actionLog: [],
};
}
// --- aggregations ----------------------------------------------------------
export type SpeciesField = "producer" | "grazer" | "phage";
export function totalOf(state: GameState, field: "producer" | "grazer" | "phage" | "toxin" | "nutrient" | "heat"): number {
let sum = 0;
for (const c of state.chambers) sum += c[field];
return sum;
}
export function chambersOccupied(state: GameState, field: SpeciesField): number {
let n = 0;
for (const c of state.chambers) if (c[field] > 0) n++;
return n;
}
/** producer + grazer across all chambers (the collapse metric). */
export function totalPersistent(state: GameState): number {
return totalOf(state, "producer") + totalOf(state, "grazer");
}
// --- win & sustained -------------------------------------------------------
export function sustainedHolds(state: GameState): boolean {
const sc = SCENARIO_BY_ID[state.scenarioId];
if (!sc || sc.win.kind !== "sustained") return false;
const s = sc.win.sustained;
for (const slot of s.assaySlots) {
const c = state.chambers[slot]!;
if (c.producer + c.grazer < s.assayPopMin) return false;
}
const tp = totalOf(state, "producer");
const tg = totalOf(state, "grazer");
const tpha = totalOf(state, "phage");
const tt = totalOf(state, "toxin");
if (tp < s.producerRange[0] || tp > s.producerRange[1]) return false;
if (tg < s.grazerRange[0] || tg > s.grazerRange[1]) return false;
if (tpha > s.phageMax) return false;
if (tt > s.toxinMax) return false;
return true;
}
export function evaluateWin(state: GameState, resolvedTurn: number, consecutive: number): boolean {
const sc = SCENARIO_BY_ID[state.scenarioId];
if (!sc) return false;
const w = sc.win;
switch (w.kind) {
case "producerAt":
return (
state.chambers[w.slot]!.producer >= w.producerMin &&
totalOf(state, "producer") >= w.totalProducerMin
);
case "endurance":
if (resolvedTurn !== w.atTurn) return false;
return (
totalOf(state, "producer") >= w.totalProducerMin &&
totalOf(state, "grazer") >= w.totalGrazerMin &&
chambersOccupied(state, "producer") >= w.producerChambersMin &&
chambersOccupied(state, "grazer") >= w.grazerChambersMin
);
case "cleanse":
if (resolvedTurn < w.fromTurn || resolvedTurn > w.toTurn) return false;
return totalOf(state, "toxin") <= w.totalToxinMax && totalPersistent(state) >= w.totalPopMin;
case "escort":
return (
state.chambers[w.slot]!.grazer >= w.grazerMin &&
state.chambers[w.slot]!.phage >= w.phageMin &&
totalOf(state, "producer") >= w.totalProducerMin
);
case "sustained":
return consecutive >= w.required;
}
}
export const ALL_PRESSURES: PressureId[] = PRESSURE_IDS;
export const ALL_LINEAGES: LineageId[] = LINEAGE_IDS;
-47
View File
@@ -1,47 +0,0 @@
// Adaptive Loop — canonical serialization & deep clone. SPEC §5 (canonical equality).
import type { GameState, Chamber } from "./types";
/** Stable-key JSON: object keys sorted recursively. Excludes nothing here —
* callers must keep transient UI data out of GameState (it is). */
export function canonicalStringify(value: unknown): string {
return JSON.stringify(sortKeys(value));
}
function sortKeys(value: unknown): unknown {
if (Array.isArray(value)) return value.map(sortKeys);
if (value && typeof value === "object") {
const out: Record<string, unknown> = {};
for (const k of Object.keys(value as Record<string, unknown>).sort()) {
out[k] = sortKeys((value as Record<string, unknown>)[k]);
}
return out;
}
return value;
}
export function canonicalHash(state: GameState): string {
// FNV-1a 32-bit of canonical string — good enough for dedup keys (non-crypto).
let h = 0x811c9dc5;
const s = canonicalStringify(state);
for (let i = 0; i < s.length; i++) {
h ^= s.charCodeAt(i);
h = Math.imul(h, 0x01000193);
}
return (h >>> 0).toString(16).padStart(8, "0");
}
export function canonicalEqual(a: GameState, b: GameState): boolean {
return canonicalStringify(a) === canonicalStringify(b);
}
export function cloneState(state: GameState): GameState {
return JSON.parse(JSON.stringify(state)) as GameState;
}
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 };
}
-402
View File
@@ -1,402 +0,0 @@
// Adaptive Loop — bounded deterministic solver (SPEC §9, §15 Gate 4).
// Proves one winning and one losing route per scenario via canonical-state BFS,
// the shared-ownership counterfactual, and reachable campaign inheritance sets.
import { nextState, allActions } from "./pipeline";
import { createScenarioState } from "./scenario";
import { SCENARIOS } from "../content/scenarios";
import type { InheritanceSet } from "../content/scenarios";
import type { GameState, RotationAction, LineageId, PressureId, Outcome } from "./types";
import { LINEAGE_IDS, PRESSURE_IDS } from "./types";
export interface SolveResult {
win: RotationAction[] | null;
lose: RotationAction[] | null;
explored: number;
winOutcome: Outcome | null;
loseOutcome: Outcome | null;
capped: boolean;
}
const ACTIONS = allActions();
function fastHash(s: GameState): string {
// FNV-1a of raw JSON (key order is stable for cloned states built the same way).
const str = JSON.stringify(s);
let h = 0x811c9dc5;
for (let i = 0; i < str.length; i++) {
h ^= str.charCodeAt(i);
h = Math.imul(h, 0x01000193);
}
return (h >>> 0).toString(36);
}
type SolveOpts = { freezeOwnership?: boolean; maxNodes?: number; timeMs?: number; seed?: number };
function mkRng(seed: number) {
let s = seed >>> 0;
return () => {
s = (Math.imul(s, 1664525) + 1013904223) >>> 0;
return s / 0x100000000;
};
}
function shuffled<T>(arr: T[], rng: () => number): T[] {
const a = arr.slice();
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(rng() * (i + 1));
const tmp = a[i]!; a[i] = a[j]!; a[j] = tmp;
}
return a;
}
// --- heuristic scoring for guided search (health + objective proximity) ---
function totalPersistentOf(s: GameState): number {
let n = 0;
for (const c of s.chambers) n += c.producer + c.grazer;
return n;
}
function scoreState(s: GameState): number {
if (s.outcome === "won") return 1e9;
if (s.outcome !== "playing") return -1e8; // collapsed/expired
const sc = SCENARIOS.find((x) => x.id === s.scenarioId);
let occP = 0, occG = 0, totNut = 0, totTox = 0, totHeat = 0;
for (const c of s.chambers) {
if (c.producer > 0) occP++;
if (c.grazer > 0) occG++;
totNut += c.nutrient;
totTox += c.toxin;
totHeat += c.heat;
}
let score = totalPersistentOf(s) * 100 + (occP + occG) * 12 + totNut * 3 - totTox * 6 - totHeat * 2;
const w = sc?.win;
if (w) {
switch (w.kind) {
case "producerAt":
score += (s.chambers[w.slot]?.producer ?? 0) * 60;
break;
case "endurance":
score += Math.min(occP, w.producerChambersMin) * 8 + Math.min(occG, w.grazerChambersMin) * 8;
break;
case "cleanse":
score -= totTox * 25;
break;
case "escort":
score += (s.chambers[w.slot]?.grazer ?? 0) * 60 + (s.chambers[w.slot]?.phage ?? 0) * 40;
break;
case "sustained": {
const ok = s.chambers[1]!.producer + s.chambers[1]!.grazer >= 2 && s.chambers[7]!.producer + s.chambers[7]!.grazer >= 2 && s.chambers[11]!.producer + s.chambers[11]!.grazer >= 2;
score += ok ? 400 : 0;
score += s.consecutiveObjectiveTurns * 300;
break;
}
}
}
return score;
}
/** Beam search guided by scoreState. Reliably finds wins for routing/survival puzzles. */
export function beamSearch(
scenarioId: string,
inheritance: InheritanceSet,
opts: SolveOpts & { beamWidth?: number } = {},
): { route: RotationAction[] | null; explored: number; capped: boolean } {
const beamWidth = opts.beamWidth ?? 400;
const start = createScenarioState(scenarioId, "standalone", inheritance);
const limit = SCENARIOS.find((x) => x.id === scenarioId)?.turnLimit ?? 12;
type N = { s: GameState; path: RotationAction[]; score: number };
let beam: N[] = [{ s: start, path: [], score: scoreState(start) }];
let explored = 0;
const seen = new Map<string, number>();
seen.set(fastHash(start), 0);
for (let depth = 0; depth < limit; depth++) {
const cand: N[] = [];
for (const node of beam) {
for (const a of ACTIONS) {
explored++;
const ns = nextState(node.s, a, opts).state;
const path = node.path.length ? [...node.path, a] : [a];
if (ns.outcome === "won") return { route: path, explored, capped: false };
if (ns.outcome !== "playing") continue;
const h = fastHash(ns);
const prev = seen.get(h);
const minLen = path.length;
if (prev !== undefined && prev <= minLen) continue;
seen.set(h, minLen);
cand.push({ s: ns, path, score: scoreState(ns) });
}
}
if (cand.length === 0) break;
cand.sort((x, y) => y.score - x.score);
beam = cand.slice(0, beamWidth);
}
return { route: null, explored, capped: false };
}
/** Memory-light randomized DFS that finds ONE route reaching `target` outcome. */
export function findRoute(
scenarioId: string,
inheritance: InheritanceSet,
target: "won" | "lose",
opts: SolveOpts = {},
): { route: RotationAction[] | null; explored: number; capped: boolean } {
const maxNodes = opts.maxNodes ?? 1_500_000;
const timeMs = opts.timeMs ?? 90_000;
const rng = mkRng(opts.seed ?? 0xC0FFEE);
const start = createScenarioState(scenarioId, "standalone", inheritance);
const t0 = Date.now();
let explored = 0;
let capped = false;
// capped memo: dedup while small, drop once full to bound memory
const memo = new Set<string>();
const memoCap = 250_000;
let memoOn = true;
function rec(s: GameState): RotationAction[] | null {
if (s.outcome !== "playing") return null;
if (Date.now() - t0 > timeMs || explored > maxNodes) {
capped = true;
return null;
}
for (const a of shuffled(ACTIONS, rng)) {
explored++;
const ns = nextState(s, a, opts).state;
const hit = target === "won" ? ns.outcome === "won" : ns.outcome === "collapsed" || ns.outcome === "expired";
if (hit) return [a];
if (ns.outcome === "playing") {
let proceed = true;
if (memoOn) {
const h = fastHash(ns);
if (memo.has(h)) proceed = false;
else {
memo.add(h);
if (memo.size > memoCap) memoOn = false;
}
}
if (proceed) {
const sub = rec(ns);
if (sub) return [a, ...sub];
if (capped) return null;
}
}
}
return null;
}
const route = rec(start);
return { route, explored, capped };
}
/** Bounded BFS over canonical states. Returns first win route and first lose route. */
export function solve(
scenarioId: string,
inheritance: InheritanceSet = {},
opts: SolveOpts = {},
): SolveResult {
const maxNodes = opts.maxNodes ?? 500_000;
const timeMs = opts.timeMs ?? 60_000;
const start = createScenarioState(scenarioId, "standalone", inheritance);
const seen = new Set<string>([fastHash(start)]);
type Node = { s: GameState; path: RotationAction[] };
const queue: Node[] = [{ s: start, path: [] }];
let head = 0;
let explored = 0;
let win: RotationAction[] | null = null;
let lose: RotationAction[] | null = null;
let winOutcome: Outcome | null = null;
let loseOutcome: Outcome | null = null;
let capped = false;
const t0 = Date.now();
while (head < queue.length) {
const { s, path } = queue[head++]!;
explored++;
if (explored > maxNodes || Date.now() - t0 > timeMs) {
capped = true;
break;
}
for (const a of ACTIONS) {
const ns = nextState(s, a, opts).state;
const npath = path.length ? [...path, a] : [a];
if (ns.outcome === "won" && !win) {
win = npath;
winOutcome = "won";
} else if ((ns.outcome === "collapsed" || ns.outcome === "expired") && !lose) {
lose = npath;
loseOutcome = ns.outcome;
}
if (win && lose) {
return { win, lose, explored, winOutcome, loseOutcome, capped: false };
}
if (ns.outcome === "playing") {
const h = fastHash(ns);
if (!seen.has(h)) {
seen.add(h);
queue.push({ s: ns, path: npath });
}
}
}
}
queue.length = 0;
return { win, lose, explored, winOutcome, loseOutcome, capped };
}
/**
* Memory-light EXHAUSTIVE DFS (stores only state hashes). Visits every reachable
* state once. Returns win route if any reachable, plus statesSeen and whether the
* full reachable space was exhausted (proves unwinnable when win=null & complete=true).
*/
export function exhaust(
scenarioId: string,
inheritance: InheritanceSet = {},
opts: { freezeOwnership?: boolean; maxStates?: number } = {},
): { win: RotationAction[] | null; statesSeen: number; complete: boolean } {
const maxStates = opts.maxStates ?? 4_000_000;
const start = createScenarioState(scenarioId, "standalone", inheritance);
const seen = new Set<string>();
let win: RotationAction[] | null = null;
let complete = true;
// iterative DFS (bounded stack; safe for very large state spaces)
type Frame = { s: GameState; path: RotationAction[]; ai: number };
const stack: Frame[] = [];
function consider(s: GameState, path: RotationAction[]): boolean {
if (s.outcome === "won") {
win = path;
return true;
}
if (s.outcome !== "playing") return false;
const h = fastHash(s);
if (seen.has(h)) return false;
if (seen.size >= maxStates) {
complete = false;
return true; // signal stop
}
seen.add(h);
stack.push({ s, path, ai: 0 });
return false;
}
if (consider(start, [])) {
return { win, statesSeen: seen.size, complete };
}
while (stack.length && !win && complete) {
const top = stack[stack.length - 1]!;
if (top.ai >= ACTIONS.length) {
stack.pop();
continue;
}
const a = ACTIONS[top.ai++]!;
const ns = nextState(top.s, a, opts).state;
const npath = top.path.length ? [...top.path, a] : [a];
if (consider(ns, npath)) {
if (win || !complete) break;
}
}
return { win, statesSeen: seen.size, complete };
}
/** Which traits unlocked along a route (beyond inherited). */
export function unlockedAlong(
scenarioId: string,
inheritance: InheritanceSet,
route: RotationAction[],
): { lineage: LineageId; pressure: PressureId }[] {
let s = createScenarioState(scenarioId, "standalone", inheritance);
const inherited = new Set<string>();
for (const lid of LINEAGE_IDS)
for (const p of inheritance[lid] ?? []) inherited.add(`${lid}:${p}`);
const became = new Set<string>();
const apply = (lid: LineageId, p: PressureId) => {
if (s.lineage[lid].unlocked[p] && !inherited.has(`${lid}:${p}`)) became.add(`${lid}:${p}`);
};
for (const lid of LINEAGE_IDS) for (const p of PRESSURE_IDS) apply(lid, p);
for (const a of route) {
s = nextState(s, a).state;
for (const lid of LINEAGE_IDS) for (const p of PRESSURE_IDS) apply(lid, p);
if (s.outcome !== "playing") break;
}
return [...became].map((k) => {
const [lineage, pressure] = k.split(":") as [LineageId, PressureId];
return { lineage, pressure };
});
}
export interface ReachableSet {
set: InheritanceSet;
key: string;
}
function inheritanceKey(is: InheritanceSet): string {
return LINEAGE_IDS.map((lid) => `${lid}=(${(is[lid] ?? []).join(",")})`).join("|");
}
/**
* Enumerate reachable campaign inheritance sets by solving each scenario with
* each reachable set, then branching on 0 or 1 newly-unlocked trait from the
* found winning route. Returns the tree of sets and solvability per (scenario,set).
*/
export interface ReachabilityReport {
perScenario: {
scenarioId: string;
sets: { key: string; set: InheritanceSet; solvable: boolean; win?: RotationAction[] | null; capped?: boolean }[];
}[];
}
export function verifyReachability(opts?: { maxNodes?: number }): ReachabilityReport {
const report: ReachabilityReport = { perScenario: [] };
let frontier: ReachableSet[] = [{ set: {}, key: inheritanceKey({}) }];
for (const sc of SCENARIOS) {
const entries: ReachabilityReport["perScenario"][number]["sets"] = [];
const next: ReachableSet[] = [];
const seenKeys = new Set<string>();
for (let i = 0; i < frontier.length; i++) {
const item = frontier[i]!;
// Light win-finder (memory-bounded); fall back to exhaustive BFS if it caps.
const fr = findRoute(sc.id, item.set, "won", { ...(opts as SolveOpts), seed: 0x1234 + i });
let win: RotationAction[] | null = fr.route;
let capped = fr.capped;
if (!win && !capped) {
// confirm with exhaustive search on smaller spaces
const res = solve(sc.id, item.set, opts);
win = res.win;
capped = res.capped;
}
entries.push({ key: item.key, set: item.set, solvable: win !== null, win, capped });
if (win) {
const unlocked = unlockedAlong(sc.id, item.set, win);
// branch: keep nothing, or keep one unlocked trait
const candidates: ReachableSet[] = [{ set: item.set, key: item.key }];
for (const u of unlocked) {
const ns: InheritanceSet = {
producer: [...(item.set.producer ?? [])],
grazer: [...(item.set.grazer ?? [])],
};
ns[u.lineage] = [...new Set([...(ns[u.lineage] ?? []), u.pressure])].sort() as PressureId[];
const k = inheritanceKey(ns);
candidates.push({ set: ns, key: k });
}
for (const c of candidates) {
if (!seenKeys.has(c.key)) {
seenKeys.add(c.key);
next.push(c);
}
}
}
}
report.perScenario.push({ scenarioId: sc.id, sets: entries });
frontier = next;
if (frontier.length === 0) break; // unsolvable predecessor; stop
}
return report;
}
/** Counterfactual: freeze sharedOwner at baseline. At least one scenario must be unwinnable. */
export function counterfactualUnwinnable(
scenarioId: string,
opts?: { maxNodes?: number },
): { solvableNormal: boolean; solvableFrozen: boolean; normal: SolveResult; frozen: SolveResult } {
const normal = solve(scenarioId, {}, opts);
const frozen = solve(scenarioId, {}, { ...opts, freezeOwnership: true });
return {
solvableNormal: normal.win !== null,
solvableFrozen: frozen.win !== null,
normal,
frozen,
};
}
-76
View File
@@ -1,76 +0,0 @@
// Adaptive Loop — domain types. Pure serializable data; no rendering, no time.
// Mirrors SPEC §5 exactly. Fixtures/objective markers are NOT in GameState: they
// are immutable scenario data looked up by scenarioId (see content/scenarios.ts).
export type LoopId = "A" | "B" | "C";
export type Direction = "cw" | "ccw";
export type LineageId = "producer" | "grazer";
export type PressureId = "heat" | "hunger" | "toxin" | "immunity";
export type Mode = "campaign" | "standalone";
export type Outcome = "playing" | "won" | "collapsed" | "expired";
export const LOOP_IDS: LoopId[] = ["A", "B", "C"];
export const LINEAGE_IDS: LineageId[] = ["producer", "grazer"];
export const PRESSURE_IDS: PressureId[] = ["heat", "hunger", "toxin", "immunity"];
/** Movable chamber payload. All quantities are capped integers 0..6. */
export interface 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 interface Lineage {
pressure: Record<PressureId, number>; // 0..3
unlocked: Record<PressureId, boolean>;
}
export interface RotationAction {
loop: LoopId;
direction: Direction;
}
export interface GameState {
schemaVersion: 1;
mode: Mode;
scenarioId: string;
turn: number;
loops: Record<LoopId, { direction: Direction }>;
/** Keyed by slot index as string. Only shared slots {2,3,4,5,8,9} are stored. */
sharedOwner: Record<string, LoopId>;
chambers: Chamber[]; // length 12
lineage: Record<LineageId, Lineage>;
inheritedAtStart: Record<LineageId, PressureId[]>;
consecutiveObjectiveTurns: number;
environmentActive: Record<PressureId, boolean>;
outcome: Outcome;
actionLog: RotationAction[];
}
/** Discrete tick event for the event panel (deterministic from state + action). */
export interface GameEvent {
phase:
| "rotate"
| "flow"
| "growth"
| "interact"
| "migrate"
| "evolve"
| "fixtures"
| "pressure"
| "outcome";
kind: string;
slot?: number;
lineage?: LineageId;
pressure?: PressureId;
text: string;
delta?: Partial<Record<"producer" | "grazer" | "phage" | "nutrient" | "heat" | "toxin", number>>;
}
export interface TurnResult {
state: GameState;
events: GameEvent[];
}
-706
View File
@@ -1,706 +0,0 @@
// Adaptive Loop — presentation controller + SVG rendering (SPEC §12, §13).
// Vanilla TS, no framework. Renders state, drives preview/commit through the
// pure nextState, persists after every turn, and is keyboard/screen-reader usable.
import type { GameState, RotationAction, LineageId, PressureId, GameEvent } from "./domain/types";
import { nextState } from "./domain/pipeline";
import { cloneState, canonicalStringify } from "./domain/serialize";
import { outletOf, totalPersistent } from "./domain/scenario";
import { SCENARIOS, SCENARIO_BY_ID } from "./content/scenarios";
import { PRESSURES, SPECIES } from "./domain/constants";
import { SLOT_POS, LOOP_POLYGONS, VIEWBOX, loopCenter } from "./presentation/geometry";
import {
startCampaign,
retry as retrySession,
enterScenario,
eligibleTraits,
preserveTrait,
unlockNext,
nextScenarioId,
type Session,
} from "./session";
import {
browserStorage,
saveEnvelope,
loadEnvelope,
clearSave,
emptyCampaign,
type CampaignProgress,
} from "./persistence/save";
type Screen = "title" | "game" | "trait-choice" | "standalone-pick";
type PendingWin = { session: Session; choices: { lineage: LineageId; pressure: PressureId }[] } | null;
interface App {
screen: Screen;
session: Session | null;
preview: RotationAction | null;
pendingWin: PendingWin;
lastEvents: GameEvent[];
}
const app: App = { screen: "title", session: null, preview: null, pendingWin: null, lastEvents: [] };
const root = document.getElementById("app")!;
const store = browserStorage();
let liveTimer: number | undefined;
// ---------- helpers ----------
function el<K extends keyof HTMLElementTagNameMap>(tag: K, cls?: string, text?: string): HTMLElementTagNameMap[K] {
const e = document.createElement(tag);
if (cls) e.className = cls;
if (text != null) e.textContent = text;
return e;
}
function announce(msg: string) {
const live = root.querySelector<HTMLElement>('[data-region="live"]');
if (live) {
live.textContent = "";
window.clearTimeout(liveTimer);
liveTimer = window.setTimeout(() => (live.textContent = msg), 30);
}
}
function saveCurrent(session: Session) {
saveEnvelope({ schemaVersion: 1, state: session.state, campaign: session.campaign, savedAt: Date.now() }, store);
}
// ---------- title screen ----------
function renderTitle() {
const hasSave = loadEnvelope(store).env != null;
root.innerHTML = "";
const main = el("main", "screen title-screen");
main.id = "main";
main.tabIndex = -1;
const h1 = el("h1", "title", "Adaptive Loop");
const tag = el("p", "muted tagline", "A deterministic microfluidic strategy puzzle.");
const panel = el("div", "menu");
const newBtn = mkBtn("new-campaign", "New Campaign", () => startNewCampaign());
panel.append(newBtn);
if (hasSave) {
panel.append(mkBtn("continue", "Continue", () => continueGame()));
}
const standalone = mkBtn("standalone", "Replay Standalone", () => {
app.screen = "standalone-pick";
renderStandalonePick();
});
panel.append(standalone);
const help = el("details", "help");
help.innerHTML = `<summary>How to play & legend</summary>
<div class="help-body">
<p>Rotate the three loops (A, B, C) clockwise or counter-clockwise. Each rotation moves the
chamber payloads, sets that loop's flow direction, and claims its shared slots — changing where
nutrient and toxin flow.</p>
<ul>
<li><b>Veridan</b> (producer) eats nutrient and grows.</li>
<li><b>Cilia</b> (grazer) eats producers.</li>
<li><b>Phage</b> eats grazers; starves without them.</li>
<li>Pressures: 🔥 heat, ☾ hunger, ⚗ toxin, ◊ immunity. At pressure 3 a lineage adapts
(benefit + cost + spillover).</li>
</ul>
<p>Focus or hover a rotation to preview; press the Commit button (or Enter on a rotation) to play it.
Escape cancels a preview.</p>
</div>`;
main.append(h1, tag, panel, help);
const live = el("div", "sr-only");
live.setAttribute("data-region", "live");
live.setAttribute("aria-live", "polite");
live.setAttribute("aria-atomic", "true");
root.append(main, live);
newBtn.focus();
}
function mkBtn(action: string, label: string, onClick: () => void, opts: { keys?: string; primary?: boolean } = {}): HTMLButtonElement {
const b = el("button", opts.primary ? "btn primary" : "btn", label);
b.dataset.action = action;
if (opts.keys) b.dataset.key = opts.keys;
b.addEventListener("click", onClick);
return b;
}
const LEGEND_HTML = `<p><b>● Veridan</b> (producer, cyan) eats nutrient and grows. <b>▲ Cilia</b> (grazer, gold)
eats producers. <b>◆ Phage</b> (purple) eats grazers; starves without them.</p>
<p>Fixtures: <span class=\"fixture-nutrientInlet\">▽N</span> nutrient inlet,
<span class=\"fixture-toxinInlet\">▽T</span> toxin inlet, <span class=\"fixture-heatSource\">🔥s</span> heat source,
<span class=\"fixture-drain\">▼</span> drain, <span class=\"fixture-immuneNode\">◊</span> immune node,
<span class=\"fixture-objectiveMarker\">◎</span> objective marker.</p>
<p>Pressures build to 3 → a lineage adapts (benefit + cost + spillover):
🔥 heat→Heat Shield, ☾ hunger→Dormancy, ⚗ toxin→Efflux, ◊ immunity→Cloak.</p>
<p><b>Select a loop direction to preview</b> (focus/hover/tap); press <b>Commit</b> or <b>Enter</b> to play it. <b>Escape</b> cancels.</p>`;
function legendPanel(open: boolean): HTMLElement {
const d = el("details", "help in-game-help");
if (open) d.setAttribute("open", "");
d.id = "in-game-help";
d.innerHTML = `<summary>Legend & controls</summary><div class="help-body">${LEGEND_HTML}</div>`;
return d;
}
function toggleHelp() {
const d = root.querySelector<HTMLElement>("#in-game-help");
if (d) { if (d.hasAttribute("open")) d.removeAttribute("open"); else d.setAttribute("open", ""); }
}
// ---------- standalone pick ----------
function renderStandalonePick() {
root.innerHTML = "";
const main = el("main", "screen");
main.id = "main";
main.tabIndex = -1;
main.append(el("h2", "", "Replay Standalone"), el("p", "muted", "Clean baseline lineages. No traits carry in or out."));
const list = el("div", "scenario-list");
for (const sc of SCENARIOS) {
const b = mkBtn("play-standalone", `Scenario ${sc.index + 1}: ${sc.title}`, () => {
const campaign = emptyCampaign(); // standalone: all unlocked for replay, clean
const state = enterScenario(campaign, sc.id, "standalone");
app.session = { state, campaign };
app.screen = "game";
renderGameWithControls();
announce(`Standalone replay: ${sc.title}.`);
});
const desc = el("div", "muted small", `${sc.subtitle} — ${sc.teaches}`);
const wrap = el("div", "scenario-item");
wrap.append(b, desc);
list.append(wrap);
}
list.append(mkBtn("menu", "Back", () => { app.screen = "title"; renderTitle(); }));
main.append(list);
const live = el("div", "sr-only");
live.setAttribute("data-region", "live");
live.setAttribute("aria-live", "polite");
root.append(main, live);
}
// ---------- game screen ----------
function renderGame() {
const session = app.session!;
const sc = SCENARIO_BY_ID[session.state.scenarioId]!;
root.innerHTML = "";
const main = el("main", "screen game-screen");
main.id = "main";
main.tabIndex = -1;
main.append(el("h1", "sr-only", "Adaptive Loop"));
const topbar = el("header", "topbar");
topbar.append(
el("h2", "scenario-title", `Scenario ${sc.index + 1}: ${sc.title}`),
el("span", "badge", `${sc.subtitle}`),
);
const controls = el("div", "controls");
controls.append(
mkBtn("menu", "Menu", () => { app.screen = "title"; renderTitle(); }),
mkBtn("save-quit", "Save & Quit", () => { if (app.session) saveCurrent(app.session); app.screen = "title"; renderTitle(); announce("Saved. Returning to title."); }),
session.state.mode === "campaign" ? mkBtn("retry", "Retry", () => doRetry()) : mkBtn("menu", "Back to menu", () => { app.screen = "title"; renderTitle(); }),
mkBtn("help", "Legend", () => toggleHelp()),
);
topbar.append(controls);
main.append(topbar);
main.append(legendPanel(false));
topbar.append(controls);
main.append(topbar);
const layout = el("div", "layout");
const leftRail = el("aside", "rail rail-left");
leftRail.setAttribute("aria-label", "Scenario status");
leftRail.append(
statRow("Objective", sc.winDescription),
statRow("Turn", `${session.state.turn} / ${sc.turnLimit}`),
statRow("Producer + Grazer", `${totalPersistent(session.state)}`),
statRow("Mode", session.state.mode),
);
if (session.state.mode === "campaign") {
leftRail.append(statRow("Campaign", `${session.campaign.unlocked.length}/${SCENARIOS.length} unlocked`));
const traits = inheritedTraitsText(session.campaign);
if (traits) leftRail.append(statRow("Inherited traits", traits));
}
const boardWrap = el("div", "board-wrap");
boardWrap.append(renderBoard(session.state));
const commitBar = el("div", "commit-bar");
const commitBtn = mkBtn("commit", "Commit rotation", () => doCommit(), { primary: true, keys: "Enter" });
commitBtn.disabled = !app.preview;
commitBar.append(commitBtn, mkBtn("cancel-preview", "Cancel preview (Esc)", () => clearPreview()));
boardWrap.append(commitBar);
const rightRail = el("aside", "rail rail-right");
rightRail.setAttribute("aria-label", "Pressures, traits, events");
rightRail.append(renderPressuresAndTraits(session.state));
const previewBox = el("div", "preview-box");
previewBox.id = "preview-box";
rightRail.append(previewBox);
const eventBox = el("div", "event-box");
eventBox.id = "event-box";
eventBox.setAttribute("role", "log");
eventBox.setAttribute("aria-label", "Last turn events");
renderEventsInto(eventBox);
rightRail.append(eventBox);
layout.append(leftRail, boardWrap, rightRail);
main.append(layout);
const live = el("div", "sr-only");
live.setAttribute("data-region", "live");
live.setAttribute("aria-live", "polite");
live.setAttribute("aria-atomic", "true");
root.append(main, live);
// focus first rotation control
const firstRot = main.querySelector<HTMLButtonElement>('[data-action="rotate"]');
firstRot?.focus();
updatePreviewBox();
}
function statRow(label: string, value: string): HTMLElement {
const row = el("div", "stat-row");
row.append(el("span", "stat-label", label), el("span", "stat-value", value));
return row;
}
function inheritedTraitsText(c: CampaignProgress): string {
const parts: string[] = [];
(["producer", "grazer"] as LineageId[]).forEach((lid) => {
for (const p of c.inherited[lid] ?? []) parts.push(`${lid}:${PRESSURES[p].traitName}`);
});
return parts.join(", ");
}
// ---------- SVG board ----------
function renderBoard(state: GameState): SVGElement {
const svgNS = "http://www.w3.org/2000/svg";
const svg = document.createElementNS(svgNS, "svg");
svg.setAttribute("viewBox", `0 0 ${VIEWBOX.w} ${VIEWBOX.h}`);
svg.setAttribute("class", "board");
svg.setAttribute("role", "img");
svg.setAttribute("aria-label", "Culture board: three interlocking loops of chambers.");
// loop ring outlines
(["A", "B", "C"] as const).forEach((L) => {
const pts = LOOP_POLYGONS[L].map((p) => `${p.x},${p.y}`).join(" ");
const poly = document.createElementNS(svgNS, "polygon");
poly.setAttribute("points", pts);
poly.setAttribute("class", `loop-ring loop-${L.toLowerCase()}`);
poly.setAttribute("data-loop", L);
poly.setAttribute("aria-hidden", "true");
svg.append(poly);
// loop label at center
const c = loopCenter(L);
const lbl = document.createElementNS(svgNS, "text");
lbl.setAttribute("x", String(c.x));
lbl.setAttribute("y", String(c.y));
lbl.setAttribute("class", "loop-label");
lbl.setAttribute("text-anchor", "middle");
lbl.textContent = L;
lbl.setAttribute("aria-hidden", "true");
svg.append(lbl);
});
const sc = SCENARIO_BY_ID[state.scenarioId]!;
const fixturesBySlot = new Map<number, typeof sc.fixtures>();
for (const f of sc.fixtures) fixturesBySlot.set(f.slot, [...(fixturesBySlot.get(f.slot) ?? []), f]);
// preview deltas
const preview = app.preview ? nextState(cloneState(state), app.preview).state : null;
const previewEvents = app.preview ? nextState(cloneState(state), app.preview).events : null;
// flow arrows (nutrient/toxin) for current or preview
drawFlowArrows(svg, preview ?? state);
for (let i = 0; i < 12; i++) {
const p = SLOT_POS[i]!;
const g = document.createElementNS(svgNS, "g");
g.setAttribute("transform", `translate(${p.x},${p.y})`);
g.setAttribute("class", "chamber-group");
g.dataset.slot = String(i);
const c = state.chambers[i]!;
const circle = document.createElementNS(svgNS, "circle");
circle.setAttribute("r", "30");
circle.setAttribute("class", "chamber");
g.append(circle);
// fixture glyphs
const fx = fixturesBySlot.get(i) ?? [];
for (const f of fx) {
const mark = document.createElementNS(svgNS, "text");
mark.setAttribute("class", `fixture fixture-${f.kind}`);
mark.setAttribute("text-anchor", "middle");
mark.setAttribute("y", "-34");
mark.textContent = fixtureGlyph(f.kind);
mark.setAttribute("aria-hidden", "true");
g.append(mark);
}
// species counts (shape glyph + short label + color, SPEC §13)
type Sp = { glyph: string; n: number; cls: string };
const sps: Sp[] = [];
if (c.producer) sps.push({ glyph: "●", n: c.producer, cls: "sp-producer" });
if (c.grazer) sps.push({ glyph: "▲", n: c.grazer, cls: "sp-grazer" });
if (c.phage) sps.push({ glyph: "◆", n: c.phage, cls: "sp-phage" });
const popTxt = document.createElementNS(svgNS, "text");
popTxt.setAttribute("class", "chamber-pop");
popTxt.setAttribute("text-anchor", "middle");
popTxt.setAttribute("y", "2");
if (sps.length === 0) {
popTxt.textContent = "·";
} else {
sps.forEach((s, i) => {
const t = document.createElementNS(svgNS, "tspan");
t.setAttribute("class", s.cls);
if (i > 0) t.setAttribute("dx", "4");
t.textContent = `${s.glyph}${s.n}`;
popTxt.append(t);
});
}
g.append(popTxt);
// resource line
const res: string[] = [];
if (c.nutrient) res.push(`N${c.nutrient}`);
if (c.heat) res.push(`🔥${c.heat}`);
if (c.toxin) res.push(`⚗${c.toxin}`);
if (res.length) {
const rt = document.createElementNS(svgNS, "text");
rt.setAttribute("class", "chamber-res");
rt.setAttribute("text-anchor", "middle");
rt.setAttribute("y", "16");
rt.textContent = res.join(" ");
g.append(rt);
}
// preview delta annotation
if (preview && previewEvents) {
const d = chamberDelta(state.chambers[i]!, preview.chambers[i]!);
if (d) {
const dt = document.createElementNS(svgNS, "text");
dt.setAttribute("class", "chamber-delta");
dt.setAttribute("text-anchor", "middle");
dt.setAttribute("y", "44");
dt.textContent = d;
g.append(dt);
}
}
svg.append(g);
}
return svg;
}
function fixtureGlyph(kind: string): string {
switch (kind) {
case "nutrientInlet": return "▽N";
case "heatSource": return "🔥s";
case "toxinInlet": return "▽T";
case "drain": return "▼";
case "immuneNode": return "◊";
case "objectiveMarker": return "◎";
default: return "";
}
}
function chamberDelta(a: GameState["chambers"][number], b: GameState["chambers"][number]): string {
const parts: string[] = [];
const fields: [keyof typeof a, string][] = [
["producer", "P"], ["grazer", "G"], ["phage", "H"], ["nutrient", "N"], ["toxin", "T"], ["heat", "🔥"],
];
for (const [f, lbl] of fields) {
const d = (b[f] as number) - (a[f] as number);
if (d !== 0) parts.push(`${lbl}${d > 0 ? "+" : ""}${d}`);
}
return parts.join(" ");
}
function drawFlowArrows(svg: SVGElement, state: GameState) {
const svgNS = "http://www.w3.org/2000/svg";
for (let i = 0; i < 12; i++) {
const c = state.chambers[i]!;
if (c.nutrient <= 0 && c.toxin <= 0) continue;
const out = outletOf(state, i);
const a = SLOT_POS[i]!;
const b = SLOT_POS[out]!;
const ln = document.createElementNS(svgNS, "line");
ln.setAttribute("x1", String(a.x));
ln.setAttribute("y1", String(a.y));
ln.setAttribute("x2", String(b.x));
ln.setAttribute("y2", String(b.y));
ln.setAttribute("class", `flow-arrow ${c.toxin > 0 ? "flow-toxin" : "flow-nutrient"}`);
ln.setAttribute("marker-end", "url(#arrowhead)");
ln.setAttribute("aria-hidden", "true");
svg.append(ln);
}
// arrowhead def
const defs = document.createElementNS(svgNS, "defs");
defs.innerHTML = `<marker id="arrowhead" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto">
<path d="M0,0 L6,3 L0,6 Z" fill="currentColor"/></marker>`;
svg.prepend(defs);
}
// ---------- pressures & traits panel ----------
function renderPressuresAndTraits(state: GameState): HTMLElement {
const box = el("div", "panel");
box.append(el("h3", "panel-h", "Pressures & Traits"));
(["producer", "grazer"] as LineageId[]).forEach((lid) => {
const lin = state.lineage[lid];
const row = el("div", "lineage-row");
row.append(el("div", "lineage-name", `${SPECIES[lid]!.name} (${lid})`));
(["heat", "hunger", "toxin", "immunity"] as PressureId[]).forEach((p) => {
const cell = el("div", "pressure-cell");
const unlocked = lin.unlocked[p];
cell.classList.toggle("unlocked", unlocked);
cell.setAttribute("title", `${PRESSURES[p].traitName}: ${lin.pressure[p]}/3${unlocked ? " (adapted)" : ""}`);
cell.append(el("span", "pressure-glyph", PRESSURES[p].glyph), el("span", "pressure-val", `${lin.pressure[p]}`));
if (unlocked) cell.append(el("span", "adapted-tag", "✓"));
row.append(cell);
});
box.append(row);
});
// environment responses
const envActive = (["heat", "hunger", "toxin", "immunity"] as PressureId[]).filter((p) => state.environmentActive[p]);
if (envActive.length) {
box.append(el("div", "env-row", "Active responses: " + envActive.map((p) => PRESSURES[p].glyph + p).join(", ")));
}
if (state.consecutiveObjectiveTurns > 0) {
box.append(el("div", "env-row", `Equilibrium held: ${state.consecutiveObjectiveTurns} turn(s).`));
}
return box;
}
// ---------- rotation controls (rendered under the board via commit bar; also a control grid) ----------
// We render the 6 rotation controls inside the board wrap.
function renderRotationControls(state: GameState): HTMLElement {
const grid = el("div", "rotation-grid");
grid.setAttribute("role", "group");
grid.setAttribute("aria-label", "Loop rotations");
(["A", "B", "C"] as const).forEach((L) => {
(["ccw", "cw"] as const).forEach((d) => {
const action: RotationAction = { loop: L, direction: d };
const b = el("button", "btn rot-btn", `Loop ${L} ${d.toUpperCase()}`);
b.dataset.action = "rotate";
b.dataset.loop = L;
b.dataset.dir = d;
const pred = predictLabel(state, action);
b.setAttribute("aria-label", `Select loop ${L} ${d === "cw" ? "clockwise" : "counter-clockwise"} (preview). Press Enter to commit. ${pred}`);
b.addEventListener("focus", () => setPreview(action));
b.addEventListener("mouseenter", () => setPreview(action));
// (no blur-clear: would clear the preview when focus moves to Commit)
b.addEventListener("mouseleave", () => { if (app.preview && sameAction(app.preview, action)) maybeClearPreview(); });
// pointer/touch: SELECT to preview (preview-then-commit, SPEC §13)
b.addEventListener("click", () => setPreview(action));
// keyboard: Enter / Space commits the focused (previewed) rotation
b.addEventListener("keydown", (e) => {
if (e.key === "Enter" || e.key === " ") { e.preventDefault(); doCommit(action); }
});
grid.append(b);
});
});
return grid;
}
function sameAction(a: RotationAction, b: RotationAction) { return a.loop === b.loop && a.direction === b.direction; }
function predictLabel(state: GameState, action: RotationAction): string {
const r = nextState(cloneState(state), action);
if (r.state.outcome === "won") return "Predicted: WIN";
if (r.state.outcome === "collapsed") return "Predicted: collapse";
if (r.state.outcome === "expired") return "Predicted: turn limit reached";
return `Preview: turn ${r.state.turn}`;
}
// We need rotation controls visible — append into board wrap after render.
const _origRenderGame = renderGame;
function renderGameWithControls() {
_origRenderGame();
const boardWrap = root.querySelector(".board-wrap");
if (boardWrap && app.session) boardWrap.append(renderRotationControls(app.session.state));
}
// ---------- preview ----------
function setPreview(action: RotationAction) {
app.preview = action;
// re-render board + preview box without full screen rebuild
const boardWrap = root.querySelector(".board-wrap");
if (boardWrap && app.session) {
const oldSvg = boardWrap.querySelector("svg");
const newSvg = renderBoard(app.session.state);
if (oldSvg) oldSvg.replaceWith(newSvg);
const commitBtn = root.querySelector<HTMLButtonElement>('[data-action="commit"]');
if (commitBtn) commitBtn.disabled = false;
}
updatePreviewBox();
}
function maybeClearPreview() {
// only clear if no rotation control is focused
const focused = document.activeElement as HTMLElement | null;
if (focused && focused.dataset?.action === "rotate") return;
clearPreview();
}
function clearPreview() {
app.preview = null;
const boardWrap = root.querySelector(".board-wrap");
if (boardWrap && app.session) {
const oldSvg = boardWrap.querySelector("svg");
const newSvg = renderBoard(app.session.state);
if (oldSvg) oldSvg.replaceWith(newSvg);
const commitBtn = root.querySelector<HTMLButtonElement>('[data-action="commit"]');
if (commitBtn) commitBtn.disabled = true;
}
updatePreviewBox();
}
function updatePreviewBox() {
const box = root.querySelector("#preview-box");
if (!box || !app.session) return;
if (!app.preview) {
box.innerHTML = `<h3 class="panel-h">Preview</h3><p class="muted">Focus or hover a rotation to see the exact one-turn outcome.</p>`;
return;
}
const r = nextState(cloneState(app.session.state), app.preview);
const lines: string[] = [];
lines.push(`<h3 class="panel-h">Preview: Loop ${app.preview.loop} ${app.preview.direction.toUpperCase()}</h3>`);
if (r.state.outcome !== "playing") lines.push(`<p class="outcome outcome-${r.state.outcome}">Result: ${r.state.outcome.toUpperCase()}</p>`);
lines.push(`<p class="small">Turn ${app.session.state.turn} → ${r.state.turn}. Producer+Grazer ${totalPersistent(app.session.state)} → ${totalPersistent(r.state)}.</p>`);
// highlight key events
const keyEvents = r.events.filter((e) => ["pressure-up", "unlock", "env-response", "heat-shield", "heat-loss", "dormancy", "hunger-loss", "efflux-pay", "efflux-cost", "toxin-loss", "spillover", "immune-select", "immune-damage", "collapse", "win", "expire"].includes(e.kind));
if (keyEvents.length) {
lines.push(`<ul class="preview-events">${keyEvents.slice(0, 8).map((e) => `<li>${e.text}</li>`).join("")}</ul>`);
}
box.innerHTML = lines.join("");
}
// ---------- commit / flow ----------
function doCommit(forceAction?: RotationAction) {
if (!app.session) return;
const action = forceAction ?? app.preview;
if (!action) { announce("Select a rotation first."); return; }
if (app.session.state.outcome !== "playing") return;
const before = canonicalStringify(app.session.state);
const res = nextState(app.session.state, action);
const after = res.state;
if (canonicalStringify(after) === before) return; // rejected (shouldn't happen for playing)
const newSession: Session = { state: after, campaign: app.session.campaign };
app.session = newSession;
app.preview = null;
saveCurrent(newSession);
app.lastEvents = res.events;
showEvents(res.events);
announce(`Turn ${after.turn}: ${res.events.filter((e) => e.phase === "outcome").map((e) => e.text).join(" ") || "rotation resolved."}`);
if (after.outcome === "won") {
handleWin(newSession);
} else if (after.outcome === "collapsed" || after.outcome === "expired") {
renderGameWithControls();
announce(`Scenario ${after.outcome}. Press Retry to try again.`);
} else {
renderGameWithControls();
}
}
function renderEventsInto(box: HTMLElement) {
box.innerHTML = "";
box.append(el("h3", "panel-h", "Last turn (phase order)"));
const ul = el("ul", "event-list");
for (const e of app.lastEvents) {
const li = el("li", `event event-${e.phase}`, e.text);
ul.append(li);
}
if (app.lastEvents.length === 0) ul.append(el("li", "muted", "No turns committed yet."));
box.append(ul);
}
function showEvents(events: GameEvent[]) {
app.lastEvents = events;
const box = root.querySelector("#event-box");
if (box) renderEventsInto(box as HTMLElement);
}
function handleWin(session: Session) {
const sc = SCENARIO_BY_ID[session.state.scenarioId]!;
if (session.state.mode === "standalone") {
// standalone completion doesn't change campaign; show a win banner + back.
renderGameWithControls();
announce(`Standalone scenario complete: ${sc.title}.`);
return;
}
// campaign: offer trait preservation (0 or 1 newly unlocked, not already inherited)
const choices = eligibleTraits(session);
app.pendingWin = { session, choices };
app.screen = "trait-choice";
renderTraitChoice();
}
function renderTraitChoice() {
const pw = app.pendingWin!;
const sc = SCENARIO_BY_ID[pw.session.state.scenarioId]!;
root.innerHTML = "";
const main = el("main", "screen trait-screen");
main.id = "main";
main.tabIndex = -1;
const isLast = sc.index === SCENARIOS.length - 1;
main.append(el("h2", "", isLast ? "Campaign Victory!" : `Scenario ${sc.index + 1} complete`));
main.append(el("p", "muted", isLast ? "You stabilized the final equilibrium. The campaign is won." : `You may preserve zero or one trait that adapted this scenario.`));
const panel = el("div", "menu");
panel.append(mkBtn("skip-trait", "Preserve nothing", () => advanceCampaign(null)));
for (const ch of pw.choices) {
const label = `Keep ${SPECIES[ch.lineage]!.name} ${PRESSURES[ch.pressure].traitName} (${ch.lineage})`;
panel.append(mkBtn("keep-trait", label, () => advanceCampaign(ch), { primary: true }));
}
main.append(panel);
const live = el("div", "sr-only");
live.setAttribute("data-region", "live");
live.setAttribute("aria-live", "polite");
root.append(main, live);
panel.querySelector<HTMLButtonElement>('[data-action="skip-trait"]')?.focus();
announce(isLast ? "Campaign victory!" : "Choose a trait to preserve, or nothing.");
}
function advanceCampaign(trait: { lineage: LineageId; pressure: PressureId } | null) {
const pw = app.pendingWin!;
let campaign = unlockNext(pw.session.campaign, pw.session.state.scenarioId);
campaign = preserveTrait(campaign, trait);
clearSave(store);
const sc = SCENARIO_BY_ID[pw.session.state.scenarioId]!;
if (sc.index === SCENARIOS.length - 1) {
// campaign victory
app.pendingWin = null;
app.session = null;
app.screen = "title";
renderTitle();
announce("Campaign complete. Returning to title.");
return;
}
const nextId = nextScenarioId(campaign);
const state = enterScenario(campaign, nextId, "campaign");
app.session = { state, campaign };
app.pendingWin = null;
app.screen = "game";
renderGameWithControls();
announce(`Entering ${SCENARIO_BY_ID[nextId]!.title}.`);
}
// ---------- retry ----------
function doRetry() {
if (!app.session) return;
app.session = retrySession(app.session);
app.preview = null;
renderGameWithControls();
announce("Scenario reset to entry snapshot.");
}
// ---------- title actions ----------
function startNewCampaign() {
clearSave(store);
app.session = startCampaign();
app.screen = "game";
renderGameWithControls();
announce(`New campaign: ${SCENARIO_BY_ID[app.session.state.scenarioId]!.title}.`);
}
function continueGame() {
const loaded = loadEnvelope(store);
if (!loaded.env) { renderTitle(); return; }
app.session = { state: loaded.env.state, campaign: loaded.env.campaign };
app.screen = "game";
renderGameWithControls();
announce("Continued saved game.");
}
// ---------- keyboard (Escape cancels preview) ----------
document.addEventListener("keydown", (e) => {
if (e.key === "Escape" && app.preview) {
clearPreview();
e.preventDefault();
}
});
// ---------- bootstrap ----------
function boot() {
renderTitle();
renderTitle();
}
boot();
// re-export for potential tooling
export { renderGameWithControls };
-130
View File
@@ -1,130 +0,0 @@
// Adaptive Loop — versioned persistence (SPEC §11). localStorage envelope with
// schema/value validation and safe failure. savedAt is outside canonical compare.
import type { GameState, Outcome, RotationAction, LineageId, PressureId } from "../domain/types";
import { SCENARIOS, SCENARIO_BY_ID } from "../content/scenarios";
import type { InheritanceSet } from "../content/scenarios";
import { STORAGE_KEY } from "../content/scenarios";
import { createScenarioState } from "../domain/scenario";
import { nextState } from "../domain/pipeline";
import { canonicalStringify } from "../domain/serialize";
export interface CampaignProgress {
unlocked: string[]; // scenario ids unlocked (s1 always unlocked)
inherited: InheritanceSet; // cumulative preserved traits across the campaign
entrySnapshot: Record<string, InheritanceSet>; // inheritance at first entry per scenario
}
export interface SaveEnvelope {
schemaVersion: 1;
state: GameState; // canonical current game state
campaign: CampaignProgress;
savedAt: number; // outside canonical comparison
}
export interface StorageAdapter {
loadRaw(): string | null;
saveRaw(s: string): void;
removeRaw(): void;
}
export const SCHEMA_VERSION = 1;
/** Browser localStorage adapter (guarded for non-browser / disabled storage). */
export function browserStorage(): StorageAdapter {
return {
loadRaw() {
try {
return typeof localStorage !== "undefined" ? localStorage.getItem(STORAGE_KEY) : null;
} catch {
return null;
}
},
saveRaw(s: string) {
try {
if (typeof localStorage !== "undefined") localStorage.setItem(STORAGE_KEY, s);
} catch {
/* quota / disabled — ignore; game continues in-memory */
}
},
removeRaw() {
try {
if (typeof localStorage !== "undefined") localStorage.removeItem(STORAGE_KEY);
} catch {
/* ignore */
}
},
};
}
/** Validate envelope shape and value ranges; return null if malformed. */
export function validateEnvelope(data: unknown): SaveEnvelope | null {
if (!data || typeof data !== "object") return null;
const e = data as Partial<SaveEnvelope>;
if (e.schemaVersion !== SCHEMA_VERSION) return null;
if (!e.state || typeof e.state !== "object") return null;
const s = e.state as Partial<GameState>;
if (s.schemaVersion !== 1) return null;
if (!s.mode || !s.scenarioId || !SCENARIO_BY_ID[s.scenarioId]) return null;
if (!Array.isArray(s.chambers) || s.chambers.length !== 12) return null;
for (const c of s.chambers) {
if (!c || typeof c !== "object") return null;
for (const f of ["nutrient", "heat", "toxin", "producer", "grazer", "phage"] as const) {
if (typeof c[f] !== "number" || c[f] < 0 || c[f] > 6 || !Number.isInteger(c[f])) return null;
}
}
if (typeof s.turn !== "number" || s.turn < 0) return null;
if (!s.loops || !s.sharedOwner || !s.lineage || !s.environmentActive) return null;
if (!Array.isArray(s.actionLog)) return null;
for (const a of s.actionLog as RotationAction[]) {
if (!a || !["A", "B", "C"].includes(a.loop) || !["cw", "ccw"].includes(a.direction)) return null;
}
if (!["playing", "won", "collapsed", "expired"].includes(s.outcome as Outcome)) return null;
if (!e.campaign || !Array.isArray(e.campaign.unlocked) || typeof e.campaign.inherited !== "object") return null;
return e as SaveEnvelope;
}
export function saveEnvelope(env: SaveEnvelope, store: StorageAdapter): void {
store.saveRaw(canonicalStringify({ ...env, savedAt: Date.now() }));
}
export function loadEnvelope(store: StorageAdapter): { env: SaveEnvelope } | { env: null } {
const raw = store.loadRaw();
if (!raw) return { env: null };
try {
const parsed: unknown = JSON.parse(raw);
const env = validateEnvelope(parsed);
return { env };
} catch {
return { env: null }; // malformed -> safe recovery (caller offers New Campaign / Retry)
}
}
export function clearSave(store: StorageAdapter): void {
store.removeRaw();
}
/** Replay a state's action log from its baseline + entry inheritance; must reproduce canonical state. */
export function replayFromBaseline(state: GameState): GameState {
const inheritance: InheritanceSet = {
producer: [...state.inheritedAtStart.producer] as PressureId[],
grazer: [...state.inheritedAtStart.grazer] as PressureId[],
};
let s = createScenarioState(state.scenarioId, state.mode, inheritance);
for (const a of state.actionLog) {
s = nextState(s, a).state;
if (s.outcome !== "playing") break;
}
return s;
}
export function emptyCampaign(): CampaignProgress {
return {
unlocked: [SCENARIOS[0]!.id],
inherited: {},
entrySnapshot: {},
};
}
export function lineageIds(): LineageId[] {
return ["producer", "grazer"];
}
@@ -1,77 +0,0 @@
// Adaptive Loop — board geometry. Three interlocking hexagonal rings (SPEC §4, §13).
// Slots are placed at the vertices of three mutually-adjacent flat-top hexagons;
// shared slots coincide at the ring overlaps. Pure data, no DOM.
import type { LoopId } from "../domain/types";
import { LOOPS } from "../domain/constants";
export interface Pt { x: number; y: number; }
// Three flat-top hexagon centers (mutually adjacent cluster), vertex radius R.
const R = 78;
const SQRT3 = Math.sqrt(3);
// centers: A central-left, B right, C top — chosen so the three rings overlap
// pairwise and read as interlocking from a single viewpoint.
const CENTERS: Record<LoopId, Pt> = {
A: { x: 150, y: 250 },
B: { x: 150 + 1.5 * R, y: 250 - (R * SQRT3) / 2 },
C: { x: 150, y: 250 - R * SQRT3 },
};
function hexVertices(c: Pt, r: number): Pt[] {
// flat-top: vertices at 0,60,...,300 degrees
const v: Pt[] = [];
for (let k = 0; k < 6; k++) {
const a = (k * 60 * Math.PI) / 180;
v.push({ x: c.x + r * Math.cos(a), y: c.y + r * Math.sin(a) });
}
return v;
}
// Build a coordinate per slot by assigning each loop's vertex order, then dedup
// shared slots to a single point (averaged) so overlaps coincide visually.
function buildSlots(): { slots: Pt[]; polygons: Record<LoopId, Pt[]> } {
const rawPerLoop: Record<LoopId, { slot: number; pt: Pt }[]> = { A: [], B: [], C: [] };
(Object.keys(LOOPS) as LoopId[]).forEach((L) => {
const verts = hexVertices(CENTERS[L], R);
LOOPS[L].forEach((slot, i) => {
rawPerLoop[L].push({ slot, pt: verts[i]! });
});
});
// collect each slot's candidate points (a shared slot gets >1), average them
const acc: Record<number, Pt[]> = {};
(Object.keys(rawPerLoop) as LoopId[]).forEach((L) => {
for (const e of rawPerLoop[L]) {
(acc[e.slot] ??= []).push(e.pt);
}
});
const slots: Pt[] = [];
for (let i = 0; i < 12; i++) {
const pts = acc[i] ?? [{ x: 0, y: 0 }];
const ax = pts.reduce((s, p) => s + p.x, 0) / pts.length;
const ay = pts.reduce((s, p) => s + p.y, 0) / pts.length;
slots[i] = { x: ax, y: ay };
}
const polygons = {} as Record<LoopId, Pt[]>;
(Object.keys(LOOPS) as LoopId[]).forEach((L) => {
polygons[L] = LOOPS[L].map((slot) => slots[slot]!);
});
return { slots, polygons };
}
const built = buildSlots();
export const SLOT_POS: Pt[] = built.slots;
export const LOOP_POLYGONS: Record<LoopId, Pt[]> = built.polygons;
export const VIEWBOX = { w: 460, h: 420 };
export function loopCenter(L: LoopId): Pt {
return CENTERS[L];
}
/** Outlet direction unit vector at a slot (for flow arrow rendering). */
export function outletVector(from: Pt, to: Pt): Pt {
const dx = to.x - from.x;
const dy = to.y - from.y;
const len = Math.hypot(dx, dy) || 1;
return { x: dx / len, y: dy / len };
}
-111
View File
@@ -1,111 +0,0 @@
// Adaptive Loop — campaign/session controller (SPEC §10). Pure orchestration
// over (GameState, CampaignProgress); the UI holds a Session and calls these.
import type { GameState, LineageId, Mode, PressureId, RotationAction } from "./domain/types";
import { LINEAGE_IDS, PRESSURE_IDS } from "./domain/types";
import { createScenarioState } from "./domain/scenario";
import { nextState } from "./domain/pipeline";
import { SCENARIOS, SCENARIO_BY_ID } from "./content/scenarios";
import type { InheritanceSet } from "./content/scenarios";
import { emptyCampaign, type CampaignProgress } from "./persistence/save";
export interface Session {
state: GameState;
campaign: CampaignProgress;
}
export function startCampaign(): Session {
const campaign = emptyCampaign();
const state = enterScenario(campaign, SCENARIOS[0]!.id, "campaign");
return { state, campaign };
}
/** Build a fresh game state for a scenario. Campaign mode uses cumulative
* inherited traits (and records the entry snapshot); standalone uses a clean baseline. */
export function enterScenario(campaign: CampaignProgress, scenarioId: string, mode: Mode): GameState {
const inheritance: InheritanceSet =
mode === "campaign"
? { producer: [...(campaign.inherited.producer ?? [])], grazer: [...(campaign.inherited.grazer ?? [])] }
: {};
const state = createScenarioState(scenarioId, mode, inheritance);
if (mode === "campaign" && !campaign.entrySnapshot[scenarioId]) {
campaign.entrySnapshot[scenarioId] = {
producer: [...(campaign.inherited.producer ?? [])] as PressureId[],
grazer: [...(campaign.inherited.grazer ?? [])] as PressureId[],
};
}
return state;
}
export interface CommitResult {
session: Session;
result: { state: GameState; events: import("./domain/types").GameEvent[] };
}
export function commit(session: Session, action: RotationAction): CommitResult {
const res = nextState(session.state, action);
const next: Session = { state: res.state, campaign: session.campaign };
return { session: next, result: res };
}
/** Retry: restore the scenario-entry inheritance snapshot (clean baseline of this scenario). */
export function retry(session: Session): Session {
const snapshot = session.campaign.entrySnapshot[session.state.scenarioId] ?? {};
const state = createScenarioState(session.state.scenarioId, session.state.mode, snapshot);
return { state, campaign: session.campaign };
}
/** Traits unlocked during this run that are not already inherited — eligible to preserve. */
export function eligibleTraits(session: Session): { lineage: LineageId; pressure: PressureId }[] {
const out: { lineage: LineageId; pressure: PressureId }[] = [];
for (const lid of LINEAGE_IDS) {
const inherited = new Set(session.campaign.inherited[lid] ?? []);
for (const p of PRESSURE_IDS) {
if (session.state.lineage[lid].unlocked[p] && !inherited.has(p)) {
out.push({ lineage: lid, pressure: p });
}
}
}
return out;
}
/** Preserve zero or one eligible trait into the cumulative campaign inheritance. */
export function preserveTrait(campaign: CampaignProgress, trait: { lineage: LineageId; pressure: PressureId } | null): CampaignProgress {
if (!trait) return campaign;
const next: CampaignProgress = {
unlocked: [...campaign.unlocked],
inherited: {
producer: [...(campaign.inherited.producer ?? [])] as PressureId[],
grazer: [...(campaign.inherited.grazer ?? [])] as PressureId[],
},
entrySnapshot: { ...campaign.entrySnapshot },
};
next.inherited[trait.lineage] = [...new Set([...(next.inherited[trait.lineage] ?? []), trait.pressure])].sort() as PressureId[];
return next;
}
/** On a scenario win, unlock the next scenario (if any). */
export function unlockNext(campaign: CampaignProgress, scenarioId: string): CampaignProgress {
const idx = SCENARIO_BY_ID[scenarioId]?.index ?? 0;
const nextSc = SCENARIOS.find((s) => s.index === idx + 1);
if (!nextSc) return campaign;
const unlocked = campaign.unlocked.includes(nextSc.id) ? campaign.unlocked : [...campaign.unlocked, nextSc.id];
return { ...campaign, unlocked };
}
/** The scenario the campaign should enter next (most recent unlocked progress). */
export function nextScenarioId(campaign: CampaignProgress): string {
const last = SCENARIOS.filter((s) => campaign.unlocked.includes(s.id)).slice(-1)[0];
return last ? last.id : SCENARIOS[0]!.id;
}
export function isCampaignVictory(session: Session): boolean {
const last = SCENARIOS[SCENARIOS.length - 1]!;
return session.state.scenarioId === last.id && session.state.outcome === "won";
}
// Fix the startCampaign return shape (kept simple + correct below).
export function newCampaignSession(): Session {
const campaign = emptyCampaign();
const state = enterScenario(campaign, SCENARIOS[0]!.id, "campaign");
return { state, campaign };
}
-181
View File
@@ -1,181 +0,0 @@
:root {
color-scheme: dark;
/* Dark laboratory-glass palette (SPEC §13). */
--bg: #070b0f;
--bg-2: #0c131b;
--panel: #0f1a24;
--panel-2: #0b141d;
--glass: #0a141e;
--ink: #eaf1f8;
--muted: #93a4b6;
--line: #21303f;
--line-2: #2c3f4f;
--accent: #5fd3f0; /* producer / loops accent — AA on dark */
--grazer: #f2c14e; /* grazer */
--phage: #c77dff; /* phage */
--nutrient: #7ee787; /* nutrient */
--heat: #ff7b72; /* heat */
--toxin: #d2a8ff; /* toxin */
--immunity: #79c0ff; /* immunity */
--good: #8fd17a;
--bad: #ff6b6b;
--warn: #e6c07b;
--ring-a: #5fd3f0;
--ring-b: #f2c14e;
--ring-c: #c77dff;
}
* { box-sizing: border-box; }
html, body { height: 100%; }
body {
margin: 0;
background:
radial-gradient(1200px 700px at 50% -10%, #0e1a26 0%, var(--bg) 60%) fixed,
var(--bg);
color: var(--ink);
font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
line-height: 1.45;
-webkit-font-smoothing: antialiased;
}
h1, h2, h3 { margin: 0 0 0.3em; line-height: 1.15; }
h1.title { font-size: clamp(1.8rem, 5vw, 2.8rem); letter-spacing: 0.02em; }
.muted { color: var(--muted); }
.small { font-size: 0.85rem; }
.tagline { margin: 0 0 1.2rem; }
.sr-only {
position: absolute !important; width: 1px; height: 1px; padding: 0; margin: -1px;
overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0;
}
.skip-link {
position: absolute; left: -9999px; top: 0; z-index: 100;
background: var(--accent); color: #04121a; padding: 0.5rem 0.9rem; border-radius: 6px; font-weight: 600;
}
.skip-link:focus { left: 8px; top: 8px; }
:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; border-radius: 4px; }
#app { max-width: 1180px; margin: 0 auto; padding: 1rem; }
.screen { padding: 0.5rem 0; }
/* ---------- title ---------- */
.title-screen { text-align: center; padding-top: 2.5rem; }
.menu { display: flex; flex-direction: column; gap: 0.6rem; align-items: stretch; max-width: 24rem; margin: 1rem auto; }
.help { max-width: 42rem; margin: 1.5rem auto 0; text-align: left; background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 0.8rem 1rem; }
.help summary { cursor: pointer; font-weight: 600; }
.help-body ul { margin: 0.5rem 0; padding-left: 1.2rem; }
.help-body li { margin: 0.2rem 0; }
/* ---------- buttons ---------- */
.btn {
font: inherit; font-weight: 600;
color: var(--ink); background: var(--panel);
border: 1px solid var(--line); border-radius: 8px;
padding: 0.6rem 0.9rem; cursor: pointer;
transition: background 0.12s ease, border-color 0.12s ease, transform 0.05s ease;
}
.btn:hover { background: #15233200; background-color: #14222f; }
.btn:active { transform: translateY(1px); }
.btn.primary { background: var(--accent); color: #04121a; border-color: var(--accent); }
.btn.primary:hover { background: #7cdef6; }
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
/* ---------- game layout ---------- */
.topbar { display: flex; align-items: center; gap: 0.8rem; flex-wrap: wrap; margin-bottom: 0.6rem; }
.topbar h2 { margin: 0; font-size: 1.15rem; }
.badge { color: var(--muted); border: 1px solid var(--line); padding: 0.1rem 0.5rem; border-radius: 999px; font-size: 0.8rem; }
.controls { margin-left: auto; display: flex; gap: 0.4rem; flex-wrap: wrap; }
.layout {
display: grid;
grid-template-columns: 16rem minmax(0, 1fr) 19rem;
gap: 1rem;
align-items: start;
}
.rail { background: var(--panel-2); border: 1px solid var(--line); border-radius: 10px; padding: 0.8rem; }
.stat-row { display: flex; justify-content: space-between; gap: 0.5rem; padding: 0.25rem 0; border-bottom: 1px dashed var(--line); font-size: 0.9rem; }
.stat-row:last-child { border-bottom: 0; }
.stat-label { color: var(--muted); }
.stat-value { font-weight: 600; text-align: right; }
/* ---------- board ---------- */
.board-wrap { background: var(--glass); border: 1px solid var(--line); border-radius: 12px; padding: 0.5rem; }
.board { width: 100%; height: auto; display: block; }
.loop-ring { fill: none; stroke-width: 4; opacity: 0.5; }
.loop-a { stroke: var(--ring-a); }
.loop-b { stroke: var(--ring-b); }
.loop-c { stroke: var(--ring-c); }
.loop-label { font-size: 26px; font-weight: 800; fill: var(--muted); opacity: 0.3; pointer-events: none; }
.chamber { fill: #0d1924; stroke: var(--line); stroke-width: 2; }
.chamber-group .chamber-pop { font-size: 13px; font-weight: 700; fill: var(--ink); }
.sp-producer { fill: var(--accent); }
.sp-grazer { fill: var(--grazer); }
.sp-phage { fill: var(--phage); }
.chamber-res { font-size: 10px; fill: var(--muted); }
.chamber-delta { font-size: 10px; font-weight: 700; fill: var(--accent); }
.fixture { font-size: 11px; font-weight: 700; }
.fixture-nutrientInlet { fill: var(--nutrient); }
.fixture-toxinInlet { fill: var(--toxin); }
.fixture-heatSource { fill: var(--heat); }
.fixture-drain { fill: var(--immunity); }
.fixture-immuneNode { fill: var(--immunity); }
.fixture-objectiveMarker { fill: var(--warn); }
.flow-arrow { stroke-width: 3; opacity: 0.55; pointer-events: none; }
.flow-nutrient { stroke: var(--nutrient); color: var(--nutrient); }
.flow-toxin { stroke: var(--toxin); color: var(--toxin); stroke-dasharray: 4 3; }
.commit-bar { display: flex; gap: 0.5rem; margin-top: 0.6rem; flex-wrap: wrap; }
.rotation-grid {
display: grid; grid-template-columns: repeat(3, 1fr); gap: 0.4rem; margin-top: 0.6rem;
}
.rot-btn { font-size: 0.85rem; padding: 0.5rem 0.3rem; }
/* ---------- right rail panels ---------- */
.panel { background: var(--panel-2); border: 1px solid var(--line); border-radius: 10px; padding: 0.7rem 0.8rem; margin-bottom: 0.6rem; }
.panel-h { font-size: 0.8rem; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); margin-bottom: 0.4rem; }
.lineage-row { display: grid; grid-template-columns: 5.5rem repeat(4, 1fr); gap: 0.3rem; align-items: center; margin-bottom: 0.4rem; }
.lineage-name { font-size: 0.78rem; color: var(--muted); }
.pressure-cell {
display: flex; flex-direction: column; align-items: center; gap: 1px;
border: 1px solid var(--line); border-radius: 6px; padding: 0.2rem 0; font-size: 0.75rem;
background: #0a141d;
}
.pressure-cell.unlocked { border-color: var(--good); background: #0f2018; }
.pressure-glyph { font-size: 0.95rem; }
.pressure-val { font-weight: 700; }
.adapted-tag { color: var(--good); font-size: 0.7rem; }
.in-game-help { margin: 0 0 0.6rem; }
.env-row { font-size: 0.78rem; color: var(--warn); margin-top: 0.3rem; }
.preview-box .outcome { font-weight: 700; }
.outcome-won { color: var(--good); }
.outcome-collapsed, .outcome-expired { color: var(--bad); }
.preview-events { margin: 0.3rem 0 0; padding-left: 1.1rem; font-size: 0.78rem; }
.event-box { max-height: 16rem; overflow: auto; }
.event-list { margin: 0; padding-left: 1.1rem; font-size: 0.78rem; }
.event-list li { margin: 0.15rem 0; }
.event-outcome { font-weight: 700; color: var(--accent); }
/* ---------- scenario pick / trait ---------- */
.scenario-list { display: flex; flex-direction: column; gap: 0.5rem; max-width: 30rem; margin: 1rem auto; }
.scenario-item { border: 1px solid var(--line); border-radius: 8px; padding: 0.4rem 0.6rem; }
.trait-screen { text-align: center; padding-top: 2rem; }
/* ---------- responsive ---------- */
@media (max-width: 920px) {
.layout { grid-template-columns: 1fr; }
.rail-left, .rail-right { order: 2; }
.board-wrap { order: 1; }
}
@media (max-width: 390px) {
#app { padding: 0.4rem; }
h1.title { font-size: 1.5rem; }
.rot-btn { font-size: 0.78rem; padding: 0.45rem 0.1rem; }
.lineage-row { grid-template-columns: 4.6rem repeat(4, 1fr); }
}
/* 200% zoom: ensure controls stay reachable and labels readable */
@media (min-resolution: 1.9dppx) {
.controls { width: 100%; }
.btn { font-size: 1rem; }
}
/* ---------- reduced motion ---------- */
@media (prefers-reduced-motion: reduce) {
* { transition: none !important; animation: none !important; }
.btn:active { transform: none; }
}
-1
View File
@@ -1 +0,0 @@
/// <reference types="vite/client" />
-463
View File
@@ -1,463 +0,0 @@
{
"generatedAt": "2026-08-12T18:41:58.706Z",
"scenarios": {
"s1-heat": {
"win": [
{
"loop": "C",
"direction": "cw"
},
{
"loop": "B",
"direction": "cw"
},
{
"loop": "A",
"direction": "ccw"
},
{
"loop": "C",
"direction": "ccw"
},
{
"loop": "A",
"direction": "cw"
}
],
"lose": [
{
"loop": "C",
"direction": "ccw"
},
{
"loop": "B",
"direction": "cw"
},
{
"loop": "A",
"direction": "cw"
},
{
"loop": "A",
"direction": "cw"
},
{
"loop": "B",
"direction": "ccw"
},
{
"loop": "A",
"direction": "ccw"
},
{
"loop": "B",
"direction": "ccw"
},
{
"loop": "B",
"direction": "cw"
}
],
"winTurns": 5,
"loseTurns": 8,
"loseOutcome": "expired",
"winVerified": true,
"loseVerified": true,
"pressure": "heat",
"ownPressureUnlocked": false,
"unlockedTraits": [
"producer:hunger"
],
"usesMultipleLoops": true
},
"s2-hunger": {
"win": [
{
"loop": "A",
"direction": "ccw"
},
{
"loop": "C",
"direction": "ccw"
},
{
"loop": "B",
"direction": "ccw"
},
{
"loop": "C",
"direction": "cw"
},
{
"loop": "C",
"direction": "cw"
},
{
"loop": "C",
"direction": "ccw"
},
{
"loop": "A",
"direction": "ccw"
},
{
"loop": "A",
"direction": "ccw"
},
{
"loop": "C",
"direction": "cw"
},
{
"loop": "A",
"direction": "cw"
}
],
"lose": [
{
"loop": "C",
"direction": "ccw"
},
{
"loop": "B",
"direction": "cw"
},
{
"loop": "A",
"direction": "cw"
},
{
"loop": "A",
"direction": "cw"
},
{
"loop": "B",
"direction": "ccw"
},
{
"loop": "A",
"direction": "ccw"
},
{
"loop": "B",
"direction": "ccw"
},
{
"loop": "B",
"direction": "cw"
},
{
"loop": "C",
"direction": "cw"
},
{
"loop": "C",
"direction": "ccw"
}
],
"winTurns": 10,
"loseTurns": 10,
"loseOutcome": "expired",
"winVerified": true,
"loseVerified": true,
"pressure": "hunger",
"ownPressureUnlocked": true,
"unlockedTraits": [
"producer:hunger",
"grazer:hunger"
],
"usesMultipleLoops": true
},
"s3-toxin": {
"win": [
{
"loop": "A",
"direction": "ccw"
},
{
"loop": "B",
"direction": "ccw"
},
{
"loop": "A",
"direction": "ccw"
},
{
"loop": "C",
"direction": "cw"
},
{
"loop": "A",
"direction": "cw"
},
{
"loop": "A",
"direction": "cw"
},
{
"loop": "A",
"direction": "cw"
},
{
"loop": "A",
"direction": "ccw"
}
],
"lose": [
{
"loop": "C",
"direction": "ccw"
},
{
"loop": "B",
"direction": "cw"
},
{
"loop": "A",
"direction": "cw"
},
{
"loop": "A",
"direction": "cw"
},
{
"loop": "B",
"direction": "ccw"
},
{
"loop": "A",
"direction": "ccw"
},
{
"loop": "B",
"direction": "ccw"
},
{
"loop": "B",
"direction": "cw"
},
{
"loop": "C",
"direction": "cw"
}
],
"winTurns": 8,
"loseTurns": 9,
"loseOutcome": "expired",
"winVerified": true,
"loseVerified": true,
"pressure": "toxin",
"ownPressureUnlocked": true,
"unlockedTraits": [
"producer:hunger",
"producer:toxin"
],
"usesMultipleLoops": true
},
"s4-immunity": {
"win": [
{
"loop": "A",
"direction": "cw"
},
{
"loop": "A",
"direction": "ccw"
},
{
"loop": "C",
"direction": "cw"
},
{
"loop": "C",
"direction": "cw"
},
{
"loop": "A",
"direction": "cw"
}
],
"lose": [
{
"loop": "C",
"direction": "ccw"
},
{
"loop": "B",
"direction": "cw"
},
{
"loop": "A",
"direction": "cw"
},
{
"loop": "A",
"direction": "cw"
},
{
"loop": "B",
"direction": "ccw"
},
{
"loop": "A",
"direction": "ccw"
},
{
"loop": "B",
"direction": "ccw"
},
{
"loop": "B",
"direction": "cw"
}
],
"winTurns": 5,
"loseTurns": 8,
"loseOutcome": "expired",
"winVerified": true,
"loseVerified": true,
"pressure": "immunity",
"ownPressureUnlocked": false,
"unlockedTraits": [
"producer:hunger"
],
"usesMultipleLoops": true
},
"s5-convergence": {
"win": [
{
"loop": "A",
"direction": "cw"
},
{
"loop": "B",
"direction": "ccw"
},
{
"loop": "B",
"direction": "cw"
},
{
"loop": "B",
"direction": "cw"
},
{
"loop": "B",
"direction": "ccw"
},
{
"loop": "B",
"direction": "ccw"
},
{
"loop": "B",
"direction": "ccw"
},
{
"loop": "C",
"direction": "ccw"
},
{
"loop": "A",
"direction": "cw"
},
{
"loop": "A",
"direction": "ccw"
}
],
"lose": [
{
"loop": "C",
"direction": "ccw"
},
{
"loop": "B",
"direction": "cw"
},
{
"loop": "A",
"direction": "cw"
},
{
"loop": "A",
"direction": "cw"
},
{
"loop": "B",
"direction": "ccw"
},
{
"loop": "A",
"direction": "ccw"
},
{
"loop": "B",
"direction": "ccw"
},
{
"loop": "B",
"direction": "cw"
},
{
"loop": "C",
"direction": "cw"
},
{
"loop": "C",
"direction": "ccw"
},
{
"loop": "C",
"direction": "cw"
},
{
"loop": "B",
"direction": "ccw"
}
],
"winTurns": 10,
"loseTurns": 12,
"loseOutcome": "expired",
"winVerified": true,
"loseVerified": true,
"pressure": "immunity",
"ownPressureUnlocked": false,
"unlockedTraits": [
"producer:hunger",
"producer:toxin"
],
"usesMultipleLoops": true
}
},
"counterfactual": {
"scenario": "s5-convergence",
"solvableNormal": true,
"normalWinTurns": 9,
"frozenBeamSearchWidths": [
800,
3000,
8000,
20000
],
"frozenBeamFoundWin": false,
"frozenExhaustiveStatesChecked": 8000000,
"frozenExhaustiveComplete": false,
"frozenExhaustiveFoundWin": false,
"conclusion": "s5 winnable normally; no winning route under frozen ownership via greedy beam (width<=20000) or exhaustive DFS (8M states). Shared-slot ownership materially affects solvability."
},
"adaptationEvidence": {
"exploit": {
"scenario": "s2-hunger",
"pressure": "hunger",
"traits": [
"producer:hunger",
"grazer:hunger"
]
},
"avoid": {
"scenario": "s1-heat",
"pressure": "heat"
}
}
}
-134
View File
@@ -1,134 +0,0 @@
// Adaptive Loop — persistence & campaign flow tests (SPEC §11, §15 Gate 5).
import { describe, it, expect } from "vitest";
import {
type SaveEnvelope,
type StorageAdapter,
validateEnvelope,
saveEnvelope,
loadEnvelope,
replayFromBaseline,
emptyCampaign,
SCHEMA_VERSION,
} from "../src/persistence/save";
import { startCampaign, commit, retry, enterScenario, preserveTrait, unlockNext, eligibleTraits, isCampaignVictory, nextScenarioId } from "../src/session";
import { nextState } from "../src/domain/pipeline";
import { canonicalEqual, cloneState } from "../src/domain/serialize";
import type { RotationAction } from "../src/domain/types";
import { SCENARIOS } from "../src/content/scenarios";
function memStore(): StorageAdapter {
let v: string | null = null;
return {
loadRaw: () => v,
saveRaw: (s) => {
v = s;
},
removeRaw: () => {
v = null;
},
};
}
describe("persistence", () => {
it("round-trips a valid envelope and restores exact canonical state", () => {
const store = memStore();
const session = startCampaign();
const env: SaveEnvelope = { schemaVersion: SCHEMA_VERSION, state: session.state, campaign: session.campaign, savedAt: 1 };
saveEnvelope(env, store);
const loaded = loadEnvelope(store);
expect(loaded.env).not.toBeNull();
expect(canonicalEqual(loaded.env!.state, session.state)).toBe(true);
});
it("malformed save fails safely to null (no crash)", () => {
const store = memStore();
store.saveRaw("{not valid json");
expect(loadEnvelope(store).env).toBeNull();
store.saveRaw(JSON.stringify({ schemaVersion: 999, state: {} }));
expect(loadEnvelope(store).env).toBeNull();
});
it("rejects out-of-range chamber values", () => {
const s = startCampaign().state;
s.chambers[0]!.producer = 99;
const env: SaveEnvelope = { schemaVersion: SCHEMA_VERSION, state: s, campaign: emptyCampaign(), savedAt: 1 };
expect(validateEnvelope(env)).toBeNull();
});
it("replay-from-baseline reproduces canonical current state after a sequence", () => {
let s = startCampaign().state;
const seq: RotationAction[] = [
{ loop: "A", direction: "cw" },
{ loop: "B", direction: "ccw" },
{ loop: "C", direction: "cw" },
];
for (const a of seq) s = nextState(s, a).state;
const replayed = replayFromBaseline(s);
expect(canonicalEqual(replayed, s)).toBe(true);
});
it("save preserves the exact next transition (continue restores mid-game)", () => {
const store = memStore();
let session = startCampaign();
session = commit(session, { loop: "A", direction: "cw" }).session;
saveEnvelope({ schemaVersion: SCHEMA_VERSION, state: session.state, campaign: session.campaign, savedAt: 2 }, store);
const restored = loadEnvelope(store).env!;
// continuing: applying the same next action yields identical results
const a: RotationAction = { loop: "B", direction: "cw" };
const fromLive = nextState(session.state, a).state;
const fromRestored = nextState(restored.state, a).state;
expect(canonicalEqual(fromLive, fromRestored)).toBe(true);
});
});
describe("campaign flow", () => {
it("retry restores the scenario-entry inheritance snapshot", () => {
let session = startCampaign();
// play a couple turns
session = commit(session, { loop: "A", direction: "cw" }).session;
session = commit(session, { loop: "B", direction: "cw" }).session;
const before = cloneState(session.state);
const retried = retry(session);
// retried is a fresh baseline (turn 0) of the same scenario
expect(retried.state.turn).toBe(0);
expect(retried.state.scenarioId).toBe(before.scenarioId);
});
it("preserveTrait carries a gift into the cumulative inheritance", () => {
let campaign = emptyCampaign();
campaign = preserveTrait(campaign, { lineage: "producer", pressure: "heat" });
expect(campaign.inherited.producer).toContain("heat");
const s = enterScenario(campaign, SCENARIOS[1]!.id, "campaign");
expect(s.lineage.producer.unlocked.heat).toBe(true); // gift carried
expect(s.lineage.producer.unlocked.toxin).toBe(false); // others not
});
it("unlockNext advances the unlocked set by one scenario", () => {
let c = emptyCampaign();
c = unlockNext(c, SCENARIOS[0]!.id);
expect(c.unlocked).toContain(SCENARIOS[1]!.id);
expect(c.unlocked.length).toBe(2);
});
it("eligibleTraits lists traits unlocked this run, excluding already-inherited", () => {
const session = startCampaign();
session.state.lineage.producer.unlocked.heat = true; // simulate an unlock during play
const elig = eligibleTraits(session);
expect(elig.some((t) => t.lineage === "producer" && t.pressure === "heat")).toBe(true);
});
it("campaign victory only after winning the last scenario", () => {
const session = startCampaign();
expect(isCampaignVictory(session)).toBe(false);
session.state.scenarioId = SCENARIOS[4]!.id;
session.state.outcome = "won";
expect(isCampaignVictory(session)).toBe(true);
});
it("nextScenarioId returns the most recently unlocked scenario", () => {
const c = emptyCampaign();
expect(nextScenarioId(c)).toBe(SCENARIOS[0]!.id);
const c2 = unlockNext(c, SCENARIOS[0]!.id);
expect(nextScenarioId(c2)).toBe(SCENARIOS[1]!.id);
});
});
-232
View File
@@ -1,232 +0,0 @@
// Adaptive Loop — simulation truth tests (SPEC §15 Gate 3). Literal worked
// outcomes plus event-based proofs of each adaptation mechanic, and invariant
// fuzzing. Events are deterministic outputs of the pipeline (SPEC §7, §8).
import { describe, it, expect, beforeAll } from "vitest";
import { nextState, allActions } from "../src/domain/pipeline";
import { createScenarioState, ownerOf, outletOf } from "../src/domain/scenario";
import { canonicalEqual, canonicalStringify, cloneState, emptyChamber } from "../src/domain/serialize";
import { SCENARIO_BY_ID, SCENARIOS } from "../src/content/scenarios";
import type { Chamber, GameState, RotationAction, GameEvent } from "../src/domain/types";
import { LOOPS } from "../src/domain/constants";
beforeAll(() => {
SCENARIO_BY_ID["_test"] = {
id: "_test", index: 99, title: "Test", pressure: "heat", subtitle: "Test",
teaches: "test", turnLimit: 999, fixtures: [], start: {},
win: { kind: "producerAt", slot: 11, producerMin: 999, totalProducerMin: 999 },
winDescription: "test",
};
});
function ch(p: Partial<Chamber> = {}): Chamber {
return { ...emptyChamber(), ...p };
}
function build(arr: (Partial<Chamber> | null)[], scenarioId = "_test"): GameState {
const s = createScenarioState(scenarioId, "standalone", {});
s.chambers = Array.from({ length: 12 }, (_, i) => (arr[i] ? ch(arr[i]!) : ch()));
return s;
}
const A = (d: "cw" | "ccw"): RotationAction => ({ loop: "A", direction: d });
const B = (d: "cw" | "ccw"): RotationAction => ({ loop: "B", direction: d });
const C = (d: "cw" | "ccw"): RotationAction => ({ loop: "C", direction: d });
const hasEvent = (evs: GameEvent[], kind: string) => evs.some((e) => e.kind === kind);
describe("rotation + ownership + flow + caps", () => {
it("CW A advances payloads one slot then flow follows the outlet", () => {
const r = nextState(build([ch({ nutrient: 3 })]), A("cw"));
expect(r.state.chambers[1]!.nutrient).toBe(2); // moved 0->1, sent 1 to outlet 2
expect(r.state.chambers[2]!.nutrient).toBe(1);
expect(r.state.chambers[0]!.nutrient).toBe(0);
expect(r.state.loops.A.direction).toBe("cw");
});
it("CCW A moves payloads the other way", () => {
const r = nextState(build([ch({ nutrient: 3 })]), A("ccw"));
expect(r.state.chambers[5]!.nutrient).toBe(2);
expect(r.state.chambers[4]!.nutrient).toBe(1);
});
it("rotating B reassigns ownership of {2,3,8,9}; A/C shared untouched", () => {
const r = nextState(build([ch({ producer: 1, nutrient: 5 })]), B("cw"));
expect(r.state.sharedOwner["2"]).toBe("B");
expect(r.state.sharedOwner["3"]).toBe("B");
expect(r.state.sharedOwner["8"]).toBe("B");
expect(r.state.sharedOwner["9"]).toBe("B");
expect(r.state.sharedOwner["4"]).toBe("A");
expect(r.state.sharedOwner["5"]).toBe("A");
});
it("outlet follows owner + direction directly (ownership changes flow target)", () => {
const s = build([ch({ producer: 1, nutrient: 5 })]);
expect(outletOf(s, 4)).toBe(5); // A cw default
s.sharedOwner["4"] = "C"; // simulate C claiming slot 4
s.loops.C.direction = "cw";
expect(ownerOf(s, 4)).toBe("C");
expect(outletOf(s, 4)).toBe(5); // C cw: 4 -> 5
s.loops.C.direction = "ccw";
expect(outletOf(s, 4)).toBe(9); // C ccw: 4 -> 9
});
it("flow sums receivers and discards overflow at cap 6", () => {
const r = nextState(build([ch({ nutrient: 6 }), ch({ nutrient: 6 })]), C("cw"));
expect(r.state.chambers[1]!.nutrient).toBe(6); // 6 -1 +1 = 6 (1 discarded)
expect(r.state.chambers[0]!.nutrient).toBe(5);
expect(r.state.chambers[2]!.nutrient).toBe(1);
});
});
describe("growth", () => {
it("producer consumes 1 nutrient and gains 1 producer", () => {
const r = nextState(build([ch({ producer: 1, nutrient: 3 })]), C("cw"));
expect(r.state.chambers[0]!.producer).toBe(2);
expect(r.state.chambers[0]!.nutrient).toBe(1);
});
});
describe("adaptations (event-proven, SPEC §8)", () => {
it("heat: unadapted loses 2 (heat-loss event)", () => {
const r = nextState(build([ch({ producer: 1, nutrient: 5, heat: 3 })]), C("cw"));
expect(hasEvent(r.events, "heat-loss")).toBe(true);
expect(r.state.chambers[0]!.producer).toBe(0); // 1 - 2 floored
});
it("heat: Heat Shield prevents loss (heat-shield event, growth suppressed, spillover)", () => {
const s = build([ch({ producer: 1, nutrient: 5, heat: 3 })]);
s.lineage.producer.unlocked.heat = true;
const r = nextState(s, C("cw"));
expect(hasEvent(r.events, "growth-suppressed")).toBe(true);
expect(hasEvent(r.events, "heat-shield")).toBe(true);
expect(hasEvent(r.events, "heat-loss")).toBe(false);
expect(r.state.chambers[0]!.producer).toBe(1); // survived
expect(r.state.chambers[0]!.heat).toBe(1); // spillover -1
});
it("toxin: unadapted loses 1 (toxin-loss)", () => {
const r = nextState(build([ch({ producer: 1, nutrient: 5, toxin: 3 })]), C("cw"));
expect(hasEvent(r.events, "toxin-loss")).toBe(true);
expect(r.state.chambers[0]!.toxin).toBe(2); // no spillover (unadapted)
});
it("toxin: Efflux pays nutrient (efflux-pay) + spillover detox vs unadapted", () => {
const base = build([ch({ producer: 1, nutrient: 5, toxin: 3 })]);
const adapted = cloneState(base);
adapted.lineage.producer.unlocked.toxin = true;
const ra = nextState(adapted, C("cw"));
const ru = nextState(base, C("cw"));
expect(hasEvent(ra.events, "efflux-pay")).toBe(true);
expect(hasEvent(ru.events, "efflux-pay")).toBe(false);
// adapted spillover removes 1 extra toxin vs unadapted
expect(ra.state.chambers[0]!.toxin).toBe(ru.state.chambers[0]!.toxin - 1);
expect(ra.state.chambers[0]!.producer).toBeGreaterThan(ru.state.chambers[0]!.producer);
});
it("hunger: unadapted loses 1 at food 0 (hunger-loss)", () => {
const r = nextState(build([ch({ producer: 2 })]), C("cw"));
expect(hasEvent(r.events, "hunger-loss")).toBe(true);
expect(r.state.chambers[0]!.producer).toBe(1);
});
it("hunger: Dormancy prevents loss AND makes dormant prey inedible", () => {
const s = build([ch({ producer: 2, grazer: 1 })]); // nutrient 0 -> producer dormant
s.lineage.producer.unlocked.hunger = true;
const r = nextState(s, C("cw"));
expect(hasEvent(r.events, "dormancy")).toBe(true);
expect(hasEvent(r.events, "hunger-loss")).toBe(false);
expect(hasEvent(r.events, "graze")).toBe(false); // grazer could not eat dormant prey
expect(r.state.chambers[0]!.producer).toBe(2);
expect(r.state.chambers[0]!.grazer).toBe(1);
});
it("immunity: node selects largest eligible lineage and applies damage", () => {
const s = createScenarioState("s4-immunity", "standalone", {});
s.chambers = Array.from({ length: 12 }, (_, i) =>
i === 2 ? ch({ producer: 4 }) : ch(),
);
const r = nextState(s, C("cw"));
expect(hasEvent(r.events, "immune-select")).toBe(true);
expect(hasEvent(r.events, "immune-damage")).toBe(true);
expect(r.state.lineage.producer.pressure.immunity).toBeGreaterThan(0);
});
it("immunity: Cloak carrier cost (predator removes 2) + retarget spillover", () => {
const s = createScenarioState("s4-immunity", "standalone", {});
s.lineage.producer.unlocked.immunity = true; // producer cloaked at nodes
s.chambers = Array.from({ length: 12 }, (_, i) =>
i === 2 ? ch({ producer: 3, grazer: 1 }) : ch(),
);
const r = nextState(s, C("cw"));
expect(hasEvent(r.events, "graze-cloak")).toBe(true); // carrier cost fired
expect(hasEvent(r.events, "immune-damage")).toBe(true); // retargeted damage applied
// node 2 could not select cloaked producer -> selected grazer (retarget)
const node2Select = r.events.find((e) => e.kind === "immune-select" && e.slot === 2);
expect(node2Select?.lineage).toBe("grazer");
});
it("evolution: track at 3 unlocks trait + activates env response (one-turn lag)", () => {
const s = build([ch({ producer: 1, nutrient: 5, heat: 3 })]);
const r1 = nextState(s, C("cw"));
expect(r1.state.lineage.producer.pressure.heat).toBe(1); // exposure increments
// drive heat pressure to 3 by repeated exposure (heat rebuilt each turn via heat inlets? _test has none)
// Instead set pressure directly to 2 and expose once more:
const s2 = build([ch({ producer: 3, nutrient: 5, heat: 3 })]); // enough to survive heat-loss to the unlock turn
s2.lineage.producer.pressure.heat = 2;
const r2 = nextState(s2, C("cw"));
expect(r2.state.lineage.producer.pressure.heat).toBe(3);
expect(r2.state.lineage.producer.unlocked.heat).toBe(false); // unlocks next turn (phase 6)
const r3 = nextState(r2.state, C("cw"));
expect(r3.state.lineage.producer.unlocked.heat).toBe(true);
expect(r3.state.environmentActive.heat).toBe(true);
});
});
describe("outcome + determinism + invariants", () => {
it("collapse when total producer+grazer = 0", () => {
const r = nextState(build([ch({ phage: 3 })]), A("cw"));
expect(r.state.outcome).toBe("collapsed");
});
it("terminal actions rejected without changing domain state", () => {
const collapsed = nextState(build([ch({ phage: 3 })]), A("cw")).state;
const before = canonicalStringify(collapsed);
expect(canonicalStringify(nextState(collapsed, A("cw")).state)).toBe(before);
});
it("input is not mutated", () => {
const s = build([ch({ nutrient: 2, producer: 1 })]);
const before = canonicalStringify(s);
nextState(s, A("cw"));
expect(canonicalStringify(s)).toBe(before);
});
it("preview (clone) == commit for every action", () => {
const s = build([ch({ nutrient: 2, producer: 1, grazer: 1, toxin: 1 })]);
for (const a of allActions()) {
expect(canonicalEqual(nextState(cloneState(s), a).state, nextState(s, a).state)).toBe(true);
}
});
it("replaying an action log reproduces committed state", () => {
const s0 = createScenarioState("s1-heat", "campaign", {});
const seq: RotationAction[] = [A("cw"), B("ccw"), C("cw"), A("ccw")];
let cur = s0;
for (const a of seq) cur = nextState(cur, a).state;
let rr = s0;
for (const a of seq) rr = nextState(rr, a).state;
expect(canonicalEqual(cur, rr)).toBe(true);
});
it("loop topology: 3 loops of 6 distinct slots", () => {
for (const k of ["A", "B", "C"] as const) {
expect(LOOPS[k].length).toBe(6);
expect(new Set(LOOPS[k]).size).toBe(6);
}
});
it("invariant fuzz: caps/pressures/outcome always valid across random play", () => {
let seed = 123456789;
const rnd = () => ((seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff);
const actions = allActions();
for (const sc of SCENARIOS) {
for (let trial = 0; trial < 40; trial++) {
let s = createScenarioState(sc.id, "standalone", {});
for (let step = 0; step < sc.turnLimit + 2 && s.outcome === "playing"; step++) {
s = nextState(s, actions[Math.floor(rnd() * 6)]!).state;
for (const c of s.chambers) {
for (const f of ["nutrient", "heat", "toxin", "producer", "grazer", "phage"] as const) {
expect(c[f]).toBeGreaterThanOrEqual(0);
expect(c[f]).toBeLessThanOrEqual(6);
}
}
for (const lid of ["producer", "grazer"] as const) {
for (const p of ["heat", "hunger", "toxin", "immunity"] as const) {
expect(s.lineage[lid].pressure[p]).toBeGreaterThanOrEqual(0);
expect(s.lineage[lid].pressure[p]).toBeLessThanOrEqual(3);
}
}
expect(["playing", "won", "collapsed", "expired"]).toContain(s.outcome);
}
}
}
});
});
-7
View File
@@ -1,7 +0,0 @@
import { describe, it, expect } from "vitest";
describe("toolchain", () => {
it("runs vitest", () => {
expect(1 + 1).toBe(2);
});
});
-115
View File
@@ -1,115 +0,0 @@
// Adaptive Loop — solver/replay proof (SPEC §15 Gate 4). Replays the verified
// win/lose routes stored in tests/fixtures/solver-results.json (generated by the
// bounded solver) and asserts the exploit/avoid/counterfactual evidence.
import { describe, it, expect } from "vitest";
import { nextState } from "../src/domain/pipeline";
import { createScenarioState } from "../src/domain/scenario";
import { SCENARIOS, SCENARIO_BY_ID } from "../src/content/scenarios";
import type { RotationAction, LineageId, PressureId } from "../src/domain/types";
import results from "./fixtures/solver-results.json";
interface RouteEntry {
win: { loop: "A" | "B" | "C"; direction: "cw" | "ccw" }[];
lose: { loop: "A" | "B" | "C"; direction: "cw" | "ccw" }[];
winTurns: number;
loseTurns: number;
loseOutcome: "collapsed" | "expired";
winVerified: boolean;
loseVerified: boolean;
pressure: PressureId;
ownPressureUnlocked: boolean;
usesMultipleLoops: boolean;
}
const R = results as unknown as {
scenarios: Record<string, RouteEntry>;
adaptationEvidence: { exploit: { scenario: string; pressure: PressureId } | null; avoid: { scenario: string; pressure: PressureId } | null };
counterfactual: { scenario: string; solvableNormal: boolean; frozenBeamFoundWin: boolean; frozenExhaustiveFoundWin: boolean; conclusion: string };
};
function replay(scenarioId: string, route: { loop: "A" | "B" | "C"; direction: "cw" | "ccw" }[], inheritance: Partial<Record<LineageId, PressureId[]>> = {}) {
let s = createScenarioState(scenarioId, "standalone", inheritance);
for (const a of route) {
s = nextState(s, a as RotationAction).state;
if (s.outcome !== "playing") break;
}
return s;
}
describe("Gate 4 — solver routes (replayed from fixtures)", () => {
for (const sc of SCENARIOS) {
const entry = R.scenarios[sc.id]!;
describe(sc.id, () => {
it("has a verified winning route", () => {
expect(entry, `fixture for ${sc.id}`).toBeDefined();
expect(entry.win.length).toBeGreaterThan(0);
expect(entry.win.length).toBeLessThanOrEqual(sc.turnLimit);
const final = replay(sc.id, entry.win);
expect(final.outcome).toBe("won");
});
it("has a verified losing route", () => {
expect(entry.lose.length).toBeGreaterThan(0);
const final = replay(sc.id, entry.lose);
expect(["collapsed", "expired"]).toContain(final.outcome);
});
it("uses rotations of multiple loops (ownership-relevant)", () => {
expect(entry.usesMultipleLoops).toBe(true);
});
});
}
it("at least one route exploits an adaptation (unlocks its scenario's pressure trait)", () => {
expect(R.adaptationEvidence.exploit, "exploit route").not.toBeNull();
const ex = R.adaptationEvidence.exploit!;
const entry = R.scenarios[ex.scenario]!;
expect(entry.ownPressureUnlocked).toBe(true);
// replay and confirm the trait actually unlocked during the winning route
let s = createScenarioState(ex.scenario, "standalone", {});
let unlocked = false;
for (const a of entry.win) {
s = nextState(s, a as RotationAction).state;
if (s.lineage.producer.unlocked[ex.pressure] || s.lineage.grazer.unlocked[ex.pressure]) unlocked = true;
if (s.outcome !== "playing") break;
}
expect(unlocked).toBe(true);
});
it("at least one route avoids an adaptation (its scenario's pressure trait stays locked)", () => {
expect(R.adaptationEvidence.avoid, "avoid route").not.toBeNull();
const av = R.adaptationEvidence.avoid!;
const entry = R.scenarios[av.scenario]!;
expect(entry.ownPressureUnlocked).toBe(false);
const final = replay(av.scenario, entry.win);
expect(final.outcome).toBe("won");
expect(final.lineage.producer.unlocked[av.pressure]).toBe(false);
expect(final.lineage.grazer.unlocked[av.pressure]).toBe(false);
});
it("counterfactual: ownership materially changes solvability", () => {
const cf = R.counterfactual;
expect(cf.solvableNormal, "normal game must be winnable").toBe(true);
const normalFinal = replay(cf.scenario, R.scenarios[cf.scenario]!.win);
expect(normalFinal.outcome).toBe("won");
// No winning route exists under frozen ownership (bounded-search evidence recorded).
expect(cf.frozenBeamFoundWin).toBe(false);
expect(cf.frozenExhaustiveFoundWin).toBe(false);
});
});
describe("scenario definitions are well-formed", () => {
it("all five scenarios present and unique", () => {
expect(SCENARIOS.length).toBe(5);
expect(new Set(SCENARIOS.map((s) => s.id)).size).toBe(5);
});
for (const sc of SCENARIOS) {
it(`${sc.id} fixtures reference valid slots`, () => {
for (const f of sc.fixtures) expect(f.slot).toBeGreaterThanOrEqual(0);
for (const slotStr of Object.keys(sc.start)) {
expect(Number(slotStr)).toBeGreaterThanOrEqual(0);
expect(Number(slotStr)).toBeLessThan(12);
}
});
}
it("scenario lookup works for all ids", () => {
for (const sc of SCENARIOS) expect(SCENARIO_BY_ID[sc.id]).toBeDefined();
});
});
-24
View File
@@ -1,24 +0,0 @@
{
"compilerOptions": {
"target": "ES2022",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": false,
"resolveJsonModule": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": false,
"types": ["node", "vite/client"]
},
"include": ["src", "tests", "e2e", "vite.config.ts", "playwright.config.ts"],
"references": []
}
-23
View File
@@ -1,23 +0,0 @@
import { defineConfig } from "vitest/config";
import { fileURLToPath, URL } from "node:url";
// Adaptive Loop: vanilla-TS + SVG, no framework/engine. Static single-page build.
export default defineConfig({
base: "./",
resolve: {
alias: {
"@": fileURLToPath(new URL("./src", import.meta.url)),
},
},
build: {
target: "es2022",
outDir: "dist",
sourcemap: true,
},
test: {
// Vitest: pure domain tests run in node (no DOM needed for the core).
environment: "node",
include: ["tests/**/*.test.ts"],
reporters: ["default"],
},
});