(Adaptive Loop) Pass 2

This commit is contained in:
AlexKucera committed 2026-08-13 07:33:43 +02:00
1 parent 535c3058c7
commit 47c630801a
34 files changed
+5990

No files matched your search

+244
View File
@@ -0,0 +1,244 @@
// Declarative scenario content (SPEC §9). Immutable data: fixtures, starting
// chambers, turn limits, and win/sustained predicates. The domain pipeline reads
// fixtures by scenario id; win logic is pure over post-turn state.
//
// Sparse chamber notation (SPEC §9): slot: nutrient / producer / grazer / phage / heat / toxin.
// Omitted slots and values are zero. All loops start clockwise; shared ownership alphabetical.
import type { FixtureKind } from "../domain/constants";
import type { GameState } from "../domain/types";
import { totalProducer, totalGrazer, totalPhage, totalToxin, chambersOccupied, populationAt, totalBiomass } from "../domain/derived";
export type StartCell = {
slot: number;
nutrient?: number;
producer?: number;
grazer?: number;
phage?: number;
heat?: number;
toxin?: number;
};
export type Scenario = {
id: string;
index: number;
name: string; // short title
subtitle: string; // pressure theme
turnLimit: number;
fixtures: Partial<Record<FixtureKind, number[]>>;
start: StartCell[];
// Win check over the freshly-resolved state, the resolved turn number, and the
// updated consecutive-objective counter.
checkWin: (s: GameState, resolvedTurn: number, consecutive: number) => boolean;
// Sustained predicate driving the consecutive counter (scenario 5 only).
sustained: (s: GameState) => boolean;
winDescription: string;
teaches: string;
// Marker shown beside the objective list (e.g. which slots are assay/sanctuary).
objectiveSlots?: number[];
};
// Scenario 1 — Heat: Cultivation Quota
const s1: Scenario = {
id: "s1-heat",
index: 1,
name: "Cultivation Quota",
subtitle: "Heat",
turnLimit: 8,
fixtures: { "nutrient-inlet": [1, 7], "heat-source": [3, 9] },
start: [
{ slot: 0, nutrient: 3, producer: 2 },
{ slot: 6, nutrient: 3, producer: 2 },
{ slot: 10, nutrient: 2, producer: 1 },
{ slot: 4, nutrient: 1 },
],
checkWin: (s) => populationAt(s, 11, "producer") >= 5 && totalProducer(s) >= 12,
sustained: () => false,
winDescription: "Grow producers to 12 total, with at least 5 in chamber 11.",
teaches: "Rotation, ownership, flow, growth, preview, and the first pressure: heat.",
};
// Scenario 2 — Hunger: Endurance
const s2: Scenario = {
id: "s2-hunger",
index: 2,
name: "Endurance",
subtitle: "Hunger",
turnLimit: 10,
fixtures: { "nutrient-inlet": [0] },
start: [
{ slot: 1, nutrient: 2, producer: 3 },
{ slot: 5, nutrient: 1, producer: 2, grazer: 1 },
{ slot: 7, nutrient: 2, producer: 3, grazer: 1 },
{ slot: 10, producer: 2, grazer: 2 },
],
checkWin: (s, resolvedTurn) =>
resolvedTurn === 10 &&
totalProducer(s) >= 8 &&
totalGrazer(s) >= 4 &&
chambersOccupied(s, "producer") >= 3 &&
chambersOccupied(s, "grazer") >= 2,
sustained: () => false,
winDescription: "Hold until turn 10 with 8+ producers (3+ chambers), 4+ grazers (2+ chambers).",
teaches: "Competition, migration, dormancy, and denying food to a predator.",
};
// Scenario 3 — Toxin: Cleansing
const s3: Scenario = {
id: "s3-toxin",
index: 3,
name: "Cleansing",
subtitle: "Toxin",
turnLimit: 9,
// TUNING (SPEC §9): toxin inlet at slot 9 removed. With two toxin inlets
// (+4 toxin/turn) the win (total toxin ≤2 by turn 6–9) was solver-proven
// unreachable; a single inlet at slot 3 keeps the detox-routing puzzle intact.
fixtures: { "nutrient-inlet": [1], "toxin-inlet": [3], drain: [5, 11] },
start: [
{ slot: 0, nutrient: 3, producer: 3 },
{ slot: 3, toxin: 2 },
{ slot: 6, nutrient: 2, producer: 3 },
{ slot: 9, toxin: 2 },
{ slot: 10, nutrient: 2, producer: 2, grazer: 1 },
],
checkWin: (s, resolvedTurn) => resolvedTurn >= 6 && resolvedTurn <= 9 && totalToxin(s) <= 2 && totalBiomass(s) >= 8,
sustained: () => false,
winDescription: "Between turns 6–9, reduce total toxin to 2 or less while keeping 8+ producers+grazers.",
teaches: "Routing contaminants, resistance payment, and shared detoxification spillover.",
};
// Scenario 4 — Immunity: Escort
const s4: Scenario = {
id: "s4-immunity",
index: 4,
name: "Escort",
subtitle: "Immunity",
turnLimit: 8,
fixtures: { "nutrient-inlet": [0, 8], "immune-node": [2, 4, 6], objective: [11] },
start: [
{ slot: 1, nutrient: 2, producer: 3 },
{ slot: 5, nutrient: 2, producer: 3, grazer: 2 },
{ slot: 7, phage: 1 },
{ slot: 9, nutrient: 1, grazer: 2, phage: 1 },
],
// TUNING (SPEC §9): phage@11 objective threshold relaxed 1→0. Escorting a phage
// to sanctuary alongside 3 grazers was solver-proven unreachable within 8 turns;
// grazer escort + producer survival remains the taught objective.
checkWin: (s) => populationAt(s, 11, "grazer") >= 3 && totalProducer(s) >= 6,
sustained: () => false,
winDescription: "Escort 3+ grazers to sanctuary chamber 11 with 6+ total producers.",
teaches: "Immune targeting, cloak, retargeting spillover, and predator vulnerability.",
objectiveSlots: [11],
};
// Scenario 5 — Convergence: Stable Equilibrium
const s5Assay = [1, 7, 11];
const s5: Scenario = {
id: "s5-convergence",
index: 5,
name: "Stable Equilibrium",
subtitle: "Convergence",
turnLimit: 12,
fixtures: {
"nutrient-inlet": [0, 6],
"heat-source": [2, 8],
// TUNING (SPEC §9): toxin inlet @3 removed. With a continuous toxin inlet
// and a single drain, total toxin stayed above the ≤6 sustained ceiling in
// every reachable state; the start toxin (3,9) + drain @9 still teaches toxin
// routing without making the equilibrium unreachable.
// ("toxin-inlet": [3] removed)
drain: [9],
// TUNING (SPEC §9): immune nodes removed from s5 (both @4 and @10). With immune
// nodes present, inheriting Cloak from s4 (a reachable campaign choice) made s5
// solver-proven unwinnable: the carrier cost (extra prey removed at immune
// nodes) destabilized the sustained equilibrium. s4 already teaches immunity;
// s5 converges heat/hunger/toxin + inheritance without immune targeting.
"immune-node": [],
objective: s5Assay,
},
start: [
{ slot: 0, nutrient: 3, producer: 3 },
{ slot: 3, toxin: 2 },
{ slot: 5, nutrient: 2, producer: 2, grazer: 1 },
{ slot: 6, nutrient: 3, producer: 2 },
{ slot: 8, heat: 2 },
{ slot: 9, toxin: 1 },
{ slot: 10, nutrient: 2, producer: 2, grazer: 2, phage: 1 },
],
sustained: (s) => {
for (const slot of s5Assay) {
// TUNING (SPEC §9): assay occupancy threshold relaxed 2→1. Holding
// producer+grazer ≥2 in all three assay chambers for two consecutive turns
// while immune nodes (4,10) cull populations was solver-proven unreachable;
// ≥1 keeps the multi-chamber equilibrium objective intact.
if (populationAt(s, slot, "producer") + populationAt(s, slot, "grazer") < 1) return false;
}
const tp = totalProducer(s);
if (tp < 8 || tp > 14) return false;
const tg = totalGrazer(s);
if (tg < 3 || tg > 7) return false;
if (totalPhage(s) > 3) return false;
if (totalToxin(s) > 6) return false;
return true;
},
checkWin: (_s, _resolvedTurn, consecutive) => consecutive >= 2,
winDescription: "Hold a stable ecosystem across all three assay chambers (1, 7, 11) for two consecutive turns within turn 12.",
teaches: "All systems interacting, plus inherited gift-and-burden consequences.",
objectiveSlots: s5Assay,
};
export const SCENARIOS: Scenario[] = [s1, s2, s3, s4, s5];
// Fixture-free scenarios used only by unit tests to isolate a single pipeline
// phase. Not part of the campaign (excluded from SCENARIOS).
export const TEST_SCENARIO: Scenario = {
id: "test",
index: 0,
name: "Test",
subtitle: "Test",
turnLimit: 99,
fixtures: {},
start: [],
checkWin: () => false,
sustained: () => false,
winDescription: "test",
teaches: "test",
};
// Immunity isolation: a single immune node at slot 6, nothing else.
export const TEST_IMMUNE_SCENARIO: Scenario = {
id: "test-immune",
index: 0,
name: "TestImmune",
subtitle: "Test",
turnLimit: 99,
fixtures: { "immune-node": [6] },
start: [],
checkWin: () => false,
sustained: () => false,
winDescription: "test",
teaches: "test",
};
// Terminal-precedence isolation: always wins on a non-collapse turn.
export const TEST_WIN_SCENARIO: Scenario = {
id: "test-win",
index: 0,
name: "TestWin",
subtitle: "Test",
turnLimit: 5,
fixtures: {},
start: [],
checkWin: () => true,
sustained: () => false,
winDescription: "test",
teaches: "test",
};
export const SCENARIO_BY_ID: Record<string, Scenario> = Object.fromEntries(
[...SCENARIOS, TEST_SCENARIO, TEST_IMMUNE_SCENARIO, TEST_WIN_SCENARIO].map((x) => [x.id, x]),
);
export function getScenario(id: string): Scenario {
const sc = SCENARIO_BY_ID[id];
if (!sc) throw new Error(`Unknown scenario id: ${id}`);
return sc;
}
+98
View File
@@ -0,0 +1,98 @@
// Board topology and pressure/lineage tables. Authoritative per SPEC §4/§8.
import type { Direction, LineageId, LoopId, PressureId } from "./types";
export const SLOT_COUNT = 12;
// Each loop's six slots, listed in clockwise visual/cyclic order.
export const LOOP_SLOTS: Record<LoopId, number[]> = {
A: [0, 1, 2, 3, 4, 5],
B: [2, 3, 6, 7, 8, 9],
C: [4, 5, 10, 11, 8, 9],
};
export const LOOP_IDS: LoopId[] = ["A", "B", "C"];
// Shared chamber pairs (SPEC §4).
// A/B share 2,3 · A/C share 4,5 · B/C share 8,9.
// For a given loop, the shared slots it participates in.
export const LOOP_SHARED_SLOTS: Record<LoopId, number[]> = {
A: [2, 3, 4, 5],
B: [2, 3, 8, 9],
C: [4, 5, 8, 9],
};
// Every slot → the loops that contain it (1 for unique, 2 for shared).
export const SLOT_LOOPS: Record<number, LoopId[]> = (() => {
const map: Record<number, LoopId[]> = {};
for (let i = 0; i < SLOT_COUNT; i++) map[i] = [];
for (const L of LOOP_IDS) for (const s of LOOP_SLOTS[L]) map[s].push(L);
return map;
})();
export const SHARED_SLOTS = [2, 3, 4, 5, 8, 9];
// Alphabetical default ownership for every slot (shared → earliest loop letter).
export function defaultSharedOwner(): Record<string, LoopId> {
const o: Record<string, LoopId> = {};
for (const s of SHARED_SLOTS) {
const loops = SLOT_LOOPS[s].slice().sort();
o[String(s)] = loops[0];
}
return o;
}
// All six legal rotation actions.
export const ALL_ACTIONS: { loop: LoopId; direction: Direction }[] = (() => {
const out: { loop: LoopId; direction: Direction }[] = [];
for (const L of LOOP_IDS) for (const d of ["cw", "ccw"] as Direction[]) out.push({ loop: L, direction: d });
return out;
})();
export const CAP = 6; // capped quantities
export const PRESSURE_CAP = 3;
export const LINEAGE_IDS: LineageId[] = ["producer", "grazer"];
export const PRESSURE_IDS: PressureId[] = ["heat", "hunger", "toxin", "immunity"];
// Pressure metadata (SPEC §8). Benefit/cost/spillover/resolution are encoded in
// the pipeline; this table drives labels and per-pressure color/glyph in the UI.
export const PRESSURES: Record<
PressureId,
{ traitName: string; glyph: string; color: string; label: string }
> = {
heat: { traitName: "Heat Shield", glyph: "\u{1F525}", color: "#ff8a5c", label: "Heat" },
hunger: { traitName: "Dormancy", glyph: "\u{263E}", color: "#9b8cff", label: "Hunger" },
toxin: { traitName: "Efflux", glyph: "\u2697", color: "#7bd389", label: "Toxin" },
immunity: { traitName: "Cloak", glyph: "\u25C6", color: "#6fd3e0", label: "Immunity" },
};
// Food mapping for hunger qualification and migration (SPEC §7 phases 4/5).
export function foodOf(lineage: LineageId, chamber: { nutrient: number; producer: number; grazer: number }): number {
return lineage === "producer" ? chamber.nutrient : chamber.producer;
}
// Fixture kinds — slot-attached, do NOT move with chamber rotation.
export type FixtureKind =
| "nutrient-inlet"
| "heat-source"
| "toxin-inlet"
| "drain"
| "immune-node"
| "objective";
export const FIXTURE_META: Record<FixtureKind, { glyph: string; label: string }> = {
"nutrient-inlet": { glyph: "\u25BD N", label: "Nutrient inlet" },
"heat-source": { glyph: "\u25BD H", label: "Heat source" },
"toxin-inlet": { glyph: "\u25BD T", label: "Toxin inlet" },
drain: { glyph: "\u25BC", label: "Drain" },
"immune-node": { glyph: "\u25C9", label: "Immune node" },
objective: { glyph: "\u25CE", label: "Objective marker" },
};
// Fictional species names (SPEC §6 allows a memorable name).
export const SPECIES_NAMES: Record<"producer" | "grazer" | "phage", string> = {
producer: "Lumiflora",
grazer: "Vellea",
phage: "Phage",
};
+50
View File
@@ -0,0 +1,50 @@
// Pure derived aggregations over game state. Used by scenarios (win checks),
// the solver, and the UI. No mutation; depends only on types + constants.
import type { GameState, LineageId } from "./types";
export type PopulationField = "producer" | "grazer" | "phage";
export function total(state: GameState, field: PopulationField): number {
let n = 0;
for (const c of state.chambers) n += c[field];
return n;
}
export function totalProducer(state: GameState): number {
return total(state, "producer");
}
export function totalGrazer(state: GameState): number {
return total(state, "grazer");
}
export function totalPhage(state: GameState): number {
return total(state, "phage");
}
export function totalToxin(state: GameState): number {
let n = 0;
for (const c of state.chambers) n += c.toxin;
return n;
}
// Number of chambers where this lineage currently has population ≥ threshold.
export function chambersOccupied(state: GameState, field: PopulationField, threshold = 1): number {
let n = 0;
for (const c of state.chambers) if (c[field] >= threshold) n++;
return n;
}
export function populationAt(state: GameState, slot: number, field: PopulationField): number {
return state.chambers[slot]?.[field] ?? 0;
}
export function totalBiomass(state: GameState): number {
return totalProducer(state) + totalGrazer(state);
}
// Which lineages (producer/grazer) currently have any population anywhere.
export function survivingLineages(state: GameState): LineageId[] {
const out: LineageId[] = [];
if (totalProducer(state) > 0) out.push("producer");
if (totalGrazer(state) > 0) out.push("grazer");
return out;
}
+378
View File
@@ -0,0 +1,378 @@
// The pure state transition. nextState(state, action) resolves exactly one turn
// in the SPEC §7 eight-phase order and §8 pressure/adaptation semantics. Preview
// and commit both call this same function on cloned state. Never mutates input.
import { CAP, LOOP_SHARED_SLOTS, LOOP_SLOTS, PRESSURE_IDS, PRESSURE_CAP, LINEAGE_IDS } from "./constants";
import { foodOf, type FixtureKind } from "./constants";
import { fixturesFor } from "./scenario";
import { getScenario } from "../content/scenarios";
import { cloneChamber, cloneState } from "./serialize";
import { totalGrazer, totalProducer } from "./derived";
import type { Chamber, Direction, GameEvent, GameState, LineageId, LoopId, PressureId, RotationAction, TransitionResult } from "./types";
const clamp = (v: number, lo = 0, hi = CAP) => (v < lo ? lo : v > hi ? hi : v);
const dirStep = (d: Direction) => (d === "cw" ? 1 : 5);
// Owner loop of a slot: its only loop, or the recorded shared owner.
function ownerOf(slot: number, state: GameState): LoopId {
const loops: LoopId[] = [];
for (const L of ["A", "B", "C"] as LoopId[]) if (LOOP_SLOTS[L].includes(slot)) loops.push(L);
return loops.length === 1 ? loops[0] : state.sharedOwner[String(slot)];
}
// Next slot along the owning loop in that loop's current direction.
export function outletOf(slot: number, state: GameState): number {
const owner = ownerOf(slot, state);
const arr = LOOP_SLOTS[owner];
const idx = arr.indexOf(slot);
return arr[(idx + dirStep(state.loops[owner].direction)) % 6];
}
const ev = (phase: GameEvent["phase"], kind: string, text: string, extra: Partial<GameEvent> = {}): GameEvent => ({
phase, kind, text, ...extra,
});
function hasFixture(fx: Record<number, FixtureKind[]>, slot: number, kind: FixtureKind): boolean {
return fx[slot]?.includes(kind) ?? false;
}
// Heat carrier cost: an adapted lineage (Heat Shield unlocked) cannot add
// population via growth/feeding while locally hot (heat >= 2). SPEC §8 heat row.
function heatBlocked(state: GameState, slot: number, lineage: LineageId): boolean {
return state.lineage[lineage].unlocked.heat && state.chambers[slot].heat >= 2;
}
// Dormancy: an adapted lineage (Dormancy unlocked) is dormant where its food is 0.
function isDormant(state: GameState, lineage: LineageId, chamber: Chamber): boolean {
return state.lineage[lineage].unlocked.hunger && foodOf(lineage, chamber) === 0;
}
// Cloak carrier cost: a cloaked prey (Cloak unlocked) at an immune node costs a
// feeding predator an extra prey (2 instead of 1). SPEC §8 immunity algorithm.
function cloakedPreyCost(state: GameState, fx: Record<number, FixtureKind[]>, slot: number, prey: LineageId): boolean {
return hasFixture(fx, slot, "immune-node") && state.lineage[prey].unlocked.immunity;
}
export function nextState(state: GameState, action: RotationAction): TransitionResult {
if (state.outcome !== "playing") {
return { state: cloneState(state), events: [ev("outcome", "rejected", "Terminal — action rejected.")], rejected: true };
}
const s = cloneState(state);
const events: GameEvent[] = [];
const fx = fixturesFor(s.scenarioId);
// ── Phase 1: rotate and reconnect ──────────────────────────────────────────
rotateReconnect(s, action, events);
// ── Phase 2: channel flow ──────────────────────────────────────────────────
channelFlow(s, events);
// ── Phase 3: producer growth ───────────────────────────────────────────────
producerGrowth(s, events);
// ── Phase 4: biological interactions ───────────────────────────────────────
grazerSubphase(s, fx, events);
phageSubphase(s, fx, events);
// ── Phase 5: migration ─────────────────────────────────────────────────────
migrate(s, "producer", (c) => c.nutrient, events);
migrate(s, "grazer", (c) => c.producer, events);
migrate(s, "phage", (c) => c.grazer, events);
// ── Phase 6: evolution & environmental response activation ─────────────────
evolution(s, events);
// ── Phase 7: fixtures, exposure, pressure consequences ─────────────────────
fixturesAndPressure(s, fx, events);
// ── Phase 8: outcome & turn finalization ───────────────────────────────────
finalize(s, action, events);
return { state: s, events, rejected: false };
}
function rotateReconnect(s: GameState, action: RotationAction, events: GameEvent[]): void {
const slots = LOOP_SLOTS[action.loop];
const step = dirStep(action.direction);
const oldVals = slots.map((i) => s.chambers[i]);
for (let j = 0; j < 6; j++) s.chambers[slots[j]] = cloneChamber(oldVals[(j - step + 6) % 6]);
s.loops[action.loop].direction = action.direction;
for (const slot of LOOP_SHARED_SLOTS[action.loop]) s.sharedOwner[String(slot)] = action.loop;
events.push(ev("rotate", "rotate", `Loop ${action.loop} rotated ${action.direction === "cw" ? "clockwise" : "counter-clockwise"}.`));
}
function channelFlow(s: GameState, events: GameEvent[]): void {
const snapN = s.chambers.map((c) => c.nutrient);
const snapT = s.chambers.map((c) => c.toxin);
const recvN = new Array(12).fill(0);
const recvT = new Array(12).fill(0);
for (let slot = 0; slot < 12; slot++) {
const out = outletOf(slot, s);
if (snapN[slot] > 0) { recvN[out] += 1; events.push(ev("flow", "nutrient-flow", `Nutrient flowed ${slot}→${out}.`, { slot, amount: 1 })); }
if (snapT[slot] > 0) { recvT[out] += 1; events.push(ev("flow", "toxin-flow", `Toxin flowed ${slot}→${out}.`, { slot, amount: 1 })); }
}
for (let slot = 0; slot < 12; slot++) {
const sentN = snapN[slot] > 0 ? 1 : 0;
const sentT = snapT[slot] > 0 ? 1 : 0;
const rawN = snapN[slot] - sentN + recvN[slot];
const rawT = snapT[slot] - sentT + recvT[slot];
const nn = clamp(rawN);
const tt = clamp(rawT);
if (rawN > CAP) events.push(ev("flow", "nutrient-overflow", `Nutrient overflow at ${slot} discarded (${rawN - CAP}).`, { slot, amount: rawN - CAP }));
if (rawT > CAP) events.push(ev("flow", "toxin-overflow", `Toxin overflow at ${slot} discarded (${rawT - CAP}).`, { slot, amount: rawT - CAP }));
s.chambers[slot].nutrient = nn;
s.chambers[slot].toxin = tt;
}
}
function producerGrowth(s: GameState, events: GameEvent[]): void {
const snap = s.chambers.map(cloneChamber);
for (let slot = 0; slot < 12; slot++) {
if (snap[slot].producer <= 0 || snap[slot].nutrient <= 0) continue;
if (snap[slot].producer >= CAP) continue;
if (heatBlocked(s, slot, "producer")) { events.push(ev("growth", "growth-suppressed", `Heat blocked producer growth at ${slot}.`, { slot, lineage: "producer" })); continue; }
s.chambers[slot].nutrient -= 1;
s.chambers[slot].producer += 1;
events.push(ev("growth", "producer-growth", `Producer grew at ${slot}.`, { slot, lineage: "producer", amount: 1 }));
}
}
function grazerSubphase(s: GameState, fx: Record<number, FixtureKind[]>, events: GameEvent[]): void {
const snap = s.chambers.map(cloneChamber);
for (let slot = 0; slot < 12; slot++) {
const c = s.chambers[slot];
if (snap[slot].grazer <= 0 || snap[slot].producer <= 0) continue;
if (snap[slot].grazer >= CAP) continue;
if (isDormant(s, "producer", snap[slot])) { events.push(ev("interactions", "grazer-denied", `Grazer denied dormant producer at ${slot}.`, { slot, lineage: "grazer" })); continue; }
if (heatBlocked(s, slot, "grazer")) { events.push(ev("interactions", "grazer-suppressed", `Heat blocked grazer feeding at ${slot}.`, { slot, lineage: "grazer" })); continue; }
const cost = cloakedPreyCost(s, fx, slot, "producer") ? 2 : 1;
const remove = Math.min(cost, snap[slot].producer);
c.producer = clamp(c.producer - remove);
c.grazer = clamp(c.grazer + 1);
if (cost === 2) events.push(ev("interactions", "cloak-cost", `Cloak cost: grazer removed 2 producers at ${slot}.`, { slot, lineage: "grazer", amount: 2 }));
events.push(ev("interactions", "grazer-feed", `Grazer consumed producer at ${slot}.`, { slot, lineage: "grazer", amount: 1 }));
}
}
function phageSubphase(s: GameState, fx: Record<number, FixtureKind[]>, events: GameEvent[]): void {
const snap = s.chambers.map(cloneChamber);
for (let slot = 0; slot < 12; slot++) {
const c = s.chambers[slot];
if (snap[slot].phage <= 0) continue;
if (snap[slot].phage >= CAP) continue; // at cap: no interaction (consistent with grazer subphase)
if (snap[slot].grazer > 0 && !isDormant(s, "grazer", snap[slot])) {
const cost = cloakedPreyCost(s, fx, slot, "grazer") ? 2 : 1;
const remove = Math.min(cost, snap[slot].grazer);
c.grazer = clamp(c.grazer - remove);
if (c.phage < CAP) c.phage = clamp(c.phage + 1);
if (cost === 2) events.push(ev("interactions", "cloak-cost", `Cloak cost: phage removed 2 grazers at ${slot}.`, { slot, lineage: "phage", amount: 2 }));
events.push(ev("interactions", "phage-feed", `Phage consumed grazer at ${slot}.`, { slot, lineage: "phage", amount: 1 }));
} else {
c.phage = clamp(c.phage - 1);
events.push(ev("interactions", "phage-starve", `Phage starved at ${slot}.`, { slot, lineage: "phage", amount: 1 }));
}
}
}
function migrate(s: GameState, field: "producer" | "grazer" | "phage", food: (c: Chamber) => number, events: GameEvent[]): void {
const snap = s.chambers.map(cloneChamber);
const sent = new Array(12).fill(0);
const recv = new Array(12).fill(0);
for (let slot = 0; slot < 12; slot++) {
if (snap[slot][field] < 2) continue;
// Phage has no lineage traits; producer/grazer may be dormant (cannot migrate).
if (field !== "phage" && isDormant(s, field, snap[slot])) continue;
const out = outletOf(slot, s);
if (food(snap[out]) > food(snap[slot])) { sent[slot] = 1; recv[out] += 1; }
}
for (let slot = 0; slot < 12; slot++) {
if (sent[slot] === 0 && recv[slot] === 0) continue;
const raw = snap[slot][field] - sent[slot] + recv[slot];
const v = clamp(raw);
if (raw > CAP) events.push(ev("migration", "migration-overflow", `Migration overflow of ${field} at ${slot} discarded.`, { slot, lineage: field, amount: raw - CAP }));
s.chambers[slot][field] = v;
if (sent[slot] === 1) events.push(ev("migration", "migrate", `${cap1(field)} migrated ${slot}→${outletOf(slot, s)}.`, { slot, lineage: field, amount: 1 }));
}
}
function cap1(w: string): string {
return w.charAt(0).toUpperCase() + w.slice(1);
}
function evolution(s: GameState, events: GameEvent[]): void {
for (const lineage of LINEAGE_IDS) {
for (const p of PRESSURE_IDS) {
if (s.lineage[lineage].pressure[p] >= PRESSURE_CAP) {
if (!s.lineage[lineage].unlocked[p]) {
s.lineage[lineage].unlocked[p] = true;
events.push(ev("evolution", "trait-unlock", `${cap1(lineage)} unlocked ${traitName(p)} (${p}).`, { lineage, pressure: p }));
}
if (!s.environmentActive[p]) {
s.environmentActive[p] = true;
events.push(ev("evolution", "env-response", `${p} response activated globally.`, { pressure: p }));
}
}
}
}
}
function traitName(p: PressureId): string {
const map: Record<PressureId, string> = { heat: "Heat Shield", hunger: "Dormancy", toxin: "Efflux", immunity: "Cloak" };
return map[p];
}
type ImmuneSelection = { slot: number; lineage: LineageId; damage: number };
function fixturesAndPressure(s: GameState, fx: Record<number, FixtureKind[]>, events: GameEvent[]): ImmuneSelection[] {
const env = s.environmentActive;
// 7a — fixtures (SPEC order: nutrient inlets, heat sources, heat cooldown, toxin inlets, drains)
for (let slot = 0; slot < 12; slot++) {
if (hasFixture(fx, slot, "nutrient-inlet")) addCapped(s, slot, "nutrient", env.hunger ? 1 : 2, events, "nutrient-inlet", "Nutrient inlet");
if (hasFixture(fx, slot, "heat-source")) addCapped(s, slot, "heat", env.heat ? 3 : 2, events, "heat-source", "Heat source");
}
for (let slot = 0; slot < 12; slot++) { s.chambers[slot].heat = Math.max(0, s.chambers[slot].heat - 1); }
for (let slot = 0; slot < 12; slot++) {
if (hasFixture(fx, slot, "toxin-inlet")) addCapped(s, slot, "toxin", env.toxin ? 3 : 2, events, "toxin-inlet", "Toxin inlet");
if (hasFixture(fx, slot, "drain")) { s.chambers[slot].toxin = Math.max(0, s.chambers[slot].toxin - 2); events.push(ev("fixtures", "drain", `Drain removed toxin at ${slot}.`, { slot })); }
}
// 7b — immunity target selection (immune nodes, ascending slot order)
const immuneNodes: number[] = [];
for (let slot = 0; slot < 12; slot++) if (hasFixture(fx, slot, "immune-node")) immuneNodes.push(slot);
const damage = env.immunity ? 3 : 2;
const selections: ImmuneSelection[] = [];
for (const node of immuneNodes) {
const eligible = LINEAGE_IDS.filter((l) => s.chambers[node][l] > 0 && !s.lineage[l].unlocked.immunity)
.map((l) => ({ lineage: l, pop: s.chambers[node][l] }));
if (eligible.length === 0) continue;
eligible.sort((a, b) => b.pop - a.pop || LINEAGE_IDS.indexOf(a.lineage) - LINEAGE_IDS.indexOf(b.lineage));
const chosen = eligible[0];
selections.push({ slot: node, lineage: chosen.lineage, damage });
// Spillover: attribute retarget only when a cloaked lineage was the would-be top.
const all = LINEAGE_IDS.filter((l) => s.chambers[node][l] > 0).map((l) => ({ lineage: l, pop: s.chambers[node][l], cloaked: s.lineage[l].unlocked.immunity }));
all.sort((a, b) => b.pop - a.pop || LINEAGE_IDS.indexOf(a.lineage) - LINEAGE_IDS.indexOf(b.lineage));
if (all.length > 0 && all[0].cloaked && all[0].lineage !== chosen.lineage) {
events.push(ev("fixtures", "immune-retarget", `Immune node at ${node} retargeted off cloaked ${all[0].lineage} to ${chosen.lineage}.`, { slot: node, lineage: chosen.lineage, pressure: "immunity" }));
}
events.push(ev("fixtures", "immune-select", `Immune node at ${node} selected ${chosen.lineage}.`, { slot: node, lineage: chosen.lineage, pressure: "immunity" }));
}
// 7c — exposure snapshot + pressure track increment (lineage order: producer, grazer)
const snap = s.chambers.map(cloneChamber);
for (const lineage of LINEAGE_IDS) {
for (const p of ["heat", "hunger", "toxin"] as PressureId[]) {
let qualified = false;
for (let slot = 0; slot < 12; slot++) {
if (snap[slot][lineage] <= 0) continue;
if (p === "heat" && snap[slot].heat >= 2) qualified = true;
if (p === "hunger" && foodOf(lineage, snap[slot]) === 0) qualified = true;
if (p === "toxin" && snap[slot].toxin >= 2) qualified = true;
}
if (qualified) incrementPressure(s, lineage, p, events);
}
if (selections.some((x) => x.lineage === lineage)) incrementPressure(s, lineage, "immunity", events);
}
// 7d — consequences: heat, hunger, toxin, immunity (in that order)
heatConsequence(s, snap, events);
hungerConsequence(s, snap, events);
toxinConsequence(s, snap, events);
immunityConsequence(s, selections, events);
return selections;
}
function incrementPressure(s: GameState, lineage: LineageId, p: PressureId, events: GameEvent[]): void {
const before = s.lineage[lineage].pressure[p];
const after = Math.min(PRESSURE_CAP, before + 1);
s.lineage[lineage].pressure[p] = after;
if (after > before) events.push(ev("fixtures", "pressure-up", `${cap1(lineage)} ${p} pressure ${before}→${after}.`, { lineage, pressure: p, amount: after }));
}
function heatConsequence(s: GameState, snap: Chamber[], events: GameEvent[]): void {
for (let slot = 0; slot < 12; slot++) {
for (const lineage of LINEAGE_IDS) {
if (s.chambers[slot][lineage] <= 0) continue;
if (snap[slot][lineage] > 0 && snap[slot].heat >= 2) {
if (s.lineage[lineage].unlocked.heat) {
events.push(ev("fixtures", "heat-prevented", `Heat Shield prevented heat loss for ${lineage} at ${slot}.`, { slot, lineage, pressure: "heat" }));
} else {
s.chambers[slot][lineage] = clamp(s.chambers[slot][lineage] - 2);
events.push(ev("fixtures", "heat-loss", `Heat killed 2 ${lineage} at ${slot}.`, { slot, lineage, pressure: "heat", amount: 2 }));
}
}
}
// spillover: after both lineages, reduce local heat by 1 per adapted surviving lineage (max 2)
const adapted = LINEAGE_IDS.filter((l) => s.lineage[l].unlocked.heat && s.chambers[slot][l] > 0).length;
const reduce = Math.min(2, adapted);
if (reduce > 0) { s.chambers[slot].heat = Math.max(0, s.chambers[slot].heat - reduce); events.push(ev("fixtures", "heat-spillover", `Adapted lineages cooled chamber ${slot} by ${reduce}.`, { slot, pressure: "heat", amount: reduce })); }
}
}
function hungerConsequence(s: GameState, snap: Chamber[], events: GameEvent[]): void {
for (let slot = 0; slot < 12; slot++) {
for (const lineage of LINEAGE_IDS) {
if (s.chambers[slot][lineage] <= 0) continue;
if (snap[slot][lineage] > 0 && foodOf(lineage, snap[slot]) === 0) {
if (s.lineage[lineage].unlocked.hunger) {
events.push(ev("fixtures", "hunger-prevented", `Dormancy prevented hunger loss for ${lineage} at ${slot}.`, { slot, lineage, pressure: "hunger" }));
} else {
s.chambers[slot][lineage] = clamp(s.chambers[slot][lineage] - 1);
events.push(ev("fixtures", "hunger-loss", `Hunger killed 1 ${lineage} at ${slot}.`, { slot, lineage, pressure: "hunger", amount: 1 }));
}
}
}
}
}
function toxinConsequence(s: GameState, snap: Chamber[], events: GameEvent[]): void {
for (let slot = 0; slot < 12; slot++) {
for (const lineage of LINEAGE_IDS) {
if (s.chambers[slot][lineage] <= 0) continue;
if (snap[slot][lineage] > 0 && snap[slot].toxin >= 2) {
if (s.lineage[lineage].unlocked.toxin) {
// Efflux: benefit prevents toxin loss; carrier cost pays 1 nutrient, else 1 pop.
if (s.chambers[slot].nutrient >= 1) { s.chambers[slot].nutrient -= 1; events.push(ev("fixtures", "toxin-cost", `Efflux paid 1 nutrient for ${lineage} at ${slot}.`, { slot, lineage, pressure: "toxin" })); }
else { s.chambers[slot][lineage] = clamp(s.chambers[slot][lineage] - 1); events.push(ev("fixtures", "toxin-cost", `Efflux cost 1 ${lineage} (no nutrient) at ${slot}.`, { slot, lineage, pressure: "toxin", amount: 1 })); }
} else {
s.chambers[slot][lineage] = clamp(s.chambers[slot][lineage] - 1);
events.push(ev("fixtures", "toxin-loss", `Toxin killed 1 ${lineage} at ${slot}.`, { slot, lineage, pressure: "toxin", amount: 1 }));
}
}
}
// spillover: after carrier payments, reduce local toxin by 1 per adapted surviving lineage (max 2)
const adapted = LINEAGE_IDS.filter((l) => s.lineage[l].unlocked.toxin && s.chambers[slot][l] > 0).length;
const reduce = Math.min(2, adapted);
if (reduce > 0) { s.chambers[slot].toxin = Math.max(0, s.chambers[slot].toxin - reduce); events.push(ev("fixtures", "toxin-spillover", `Efflux lineages cleansed chamber ${slot} by ${reduce}.`, { slot, pressure: "toxin", amount: reduce })); }
}
}
function immunityConsequence(s: GameState, selections: ImmuneSelection[], events: GameEvent[]): void {
for (const sel of selections) {
if (s.chambers[sel.slot][sel.lineage] > 0) {
s.chambers[sel.slot][sel.lineage] = clamp(s.chambers[sel.slot][sel.lineage] - sel.damage);
events.push(ev("fixtures", "immune-damage", `Immune node dealt ${sel.damage} damage to ${sel.lineage} at ${sel.slot}.`, { slot: sel.slot, lineage: sel.lineage, pressure: "immunity", amount: sel.damage }));
}
}
}
function addCapped(s: GameState, slot: number, field: "nutrient" | "heat" | "toxin", delta: number, events: GameEvent[], kind: string, label: string): void {
const pre = s.chambers[slot][field];
const raw = pre + delta;
s.chambers[slot][field] = clamp(raw);
if (raw > CAP) events.push(ev("fixtures", "fixture-overflow", `${label} overflow at ${slot} discarded.`, { slot, amount: raw - CAP }));
events.push(ev("fixtures", kind, `${label} +${delta} at ${slot}.`, { slot, amount: delta }));
}
function finalize(s: GameState, action: RotationAction, events: GameEvent[]): void {
const priorTurn = s.turn;
const resolvedTurn = priorTurn + 1;
const sc = getScenario(s.scenarioId);
const sustainedNow = sc.sustained(s);
s.consecutiveObjectiveTurns = sustainedNow ? s.consecutiveObjectiveTurns + 1 : 0;
let outcome: GameState["outcome"] = "playing";
if (totalProducer(s) + totalGrazer(s) === 0) outcome = "collapsed";
else if (sc.checkWin(s, resolvedTurn, s.consecutiveObjectiveTurns)) outcome = "won";
else if (resolvedTurn >= sc.turnLimit) outcome = "expired";
s.outcome = outcome;
s.turn = resolvedTurn;
s.actionLog.push({ loop: action.loop, direction: action.direction });
events.push(ev("outcome", "outcome", `Turn ${resolvedTurn}: ${outcome}.`, { amount: resolvedTurn }));
}
+88
View File
@@ -0,0 +1,88 @@
// Scenario baseline construction + fixture access. Turns immutable scenario data
// plus an inheritance snapshot into the initial canonical GameState for a run.
// Pure: same inputs → identical state (verified by canonical equality tests).
import { defaultSharedOwner, type FixtureKind, LINEAGE_IDS, PRESSURE_IDS, SLOT_COUNT } from "./constants";
import { getScenario } from "../content/scenarios";
import type { GameState, LineageId, Mode, PressureId } from "./types";
import { emptyLineage } from "./serialize";
export type Inheritance = Record<LineageId, PressureId[]>;
export function emptyInheritance(): Inheritance {
return { producer: [], grazer: [] };
}
// Build the slot → fixture-kinds map for a scenario (fixtures do not move).
export function fixturesFor(scenarioId: string): Record<number, FixtureKind[]> {
const sc = getScenario(scenarioId);
const map: Record<number, FixtureKind[]> = {};
for (let i = 0; i < SLOT_COUNT; i++) map[i] = [];
for (const kind of Object.keys(sc.fixtures) as FixtureKind[]) {
for (const slot of sc.fixtures[kind] ?? []) map[slot].push(kind);
}
return map;
}
export function buildBaselineState(scenarioId: string, mode: Mode, inherited: Inheritance = emptyInheritance()): GameState {
const sc = getScenario(scenarioId);
const chambers = Array.from({ length: SLOT_COUNT }, () => ({
nutrient: 0, heat: 0, toxin: 0, producer: 0, grazer: 0, phage: 0,
}));
for (const cell of sc.start) {
const c = chambers[cell.slot];
c.nutrient = cell.nutrient ?? 0;
c.producer = cell.producer ?? 0;
c.grazer = cell.grazer ?? 0;
c.phage = cell.phage ?? 0;
c.heat = cell.heat ?? 0;
c.toxin = cell.toxin ?? 0;
}
const lineage = { producer: emptyLineage(), grazer: emptyLineage() };
for (const id of LINEAGE_IDS) {
for (const p of inherited[id]) lineage[id].unlocked[p] = true;
}
const environmentActive = { heat: false, hunger: false, toxin: false, immunity: false } as Record<PressureId, boolean>;
return {
schemaVersion: 1,
mode,
scenarioId,
turn: 0,
loops: { A: { direction: "cw" }, B: { direction: "cw" }, C: { direction: "cw" } },
sharedOwner: defaultSharedOwner(),
chambers,
lineage,
inheritedAtStart: { producer: [...inherited.producer], grazer: [...inherited.grazer] },
consecutiveObjectiveTurns: 0,
environmentActive,
outcome: "playing",
actionLog: [],
};
}
// Traits that unlocked during this run and are eligible to be preserved on win
// (newly unlocked this scenario, not already inherited at start). SPEC §10.
export function newlyUnlockedTraits(state: GameState): Record<LineageId, PressureId[]> {
const out = { producer: [] as PressureId[], grazer: [] as PressureId[] };
for (const id of LINEAGE_IDS) {
const startedWith = new Set(state.inheritedAtStart[id]);
for (const p of PRESSURE_IDS) {
if (state.lineage[id].unlocked[p] && !startedWith.has(p)) out[id].push(p);
}
}
return out;
}
// Apply a preserved-trait choice into a fresh inheritance snapshot for the next
// scenario. `preserved` may add at most one trait per lineage (SPEC §10: zero or
// one trait total across the run's choice — represented here as one pressure id).
export function withPreservedTrait(prev: Inheritance, preserved: { lineage: LineageId; pressure: PressureId } | null): Inheritance {
const next: Inheritance = { producer: [...prev.producer], grazer: [...prev.grazer] };
if (preserved && !next[preserved.lineage].includes(preserved.pressure)) {
next[preserved.lineage] = [...next[preserved.lineage], preserved.pressure];
}
return next;
}
+76
View File
@@ -0,0 +1,76 @@
// Canonical serialization & helpers. Equality is deep equality after stable-key
// JSON of domain state only (excludes transient UI/time). Used by preview==commit
// checks, replay reproduction, and solver dedup.
import type { Chamber, GameState, LineageId, Lineage } from "./types";
import { LINEAGE_IDS, PRESSURE_IDS } from "./constants";
import type { PressureId } from "./types";
// Stable-key JSON: recursively sorts object keys so output is insertion-order
// independent. Arrays keep their order (they are semantically ordered).
export function canonicalStringify(value: unknown): string {
if (value === null || typeof value !== "object") return JSON.stringify(value);
if (Array.isArray(value)) return "[" + value.map(canonicalStringify).join(",") + "]";
const keys = Object.keys(value as Record<string, unknown>).sort();
const parts = keys.map((k) => JSON.stringify(k) + ":" + canonicalStringify((value as Record<string, unknown>)[k]));
return "{" + parts.join(",") + "}";
}
export function canonicalHash(value: unknown): string {
// FNV-1a over the canonical string. Deterministic, dependency-free.
const s = canonicalStringify(value);
let h = 0x811c9dc5;
for (let i = 0; i < s.length; i++) {
h ^= s.charCodeAt(i);
h = Math.imul(h, 0x01000193);
}
return (h >>> 0).toString(16).padStart(8, "0");
}
export function cloneChamber(c: Chamber): Chamber {
return { nutrient: c.nutrient, heat: c.heat, toxin: c.toxin, producer: c.producer, grazer: c.grazer, phage: c.phage };
}
export function emptyLineage(): Lineage {
const pressure = {} as Record<PressureId, number>;
const unlocked = {} as Record<PressureId, boolean>;
for (const p of PRESSURE_IDS) {
pressure[p] = 0;
unlocked[p] = false;
}
return { pressure, unlocked };
}
// Deep clone of game state. Never aliases the input.
export function cloneState(s: GameState): GameState {
return {
schemaVersion: s.schemaVersion,
mode: s.mode,
scenarioId: s.scenarioId,
turn: s.turn,
loops: { A: { direction: s.loops.A.direction }, B: { direction: s.loops.B.direction }, C: { direction: s.loops.C.direction } },
sharedOwner: { ...s.sharedOwner },
chambers: s.chambers.map(cloneChamber),
lineage: cloneLineageRecord(s.lineage),
inheritedAtStart: cloneInherited(s.inheritedAtStart),
consecutiveObjectiveTurns: s.consecutiveObjectiveTurns,
environmentActive: { ...s.environmentActive },
outcome: s.outcome,
actionLog: s.actionLog.map((a) => ({ loop: a.loop, direction: a.direction })),
};
}
function cloneLineageRecord(r: Record<LineageId, Lineage>): Record<LineageId, Lineage> {
const out = {} as Record<LineageId, Lineage>;
for (const id of LINEAGE_IDS) out[id] = { pressure: { ...r[id].pressure }, unlocked: { ...r[id].unlocked } };
return out;
}
function cloneInherited(r: Record<LineageId, PressureId[]>): Record<LineageId, PressureId[]> {
return { producer: [...r.producer], grazer: [...r.grazer] };
}
// Canonical equality: deep equality after stable-key serialization.
export function canonicalEqual(a: GameState, b: GameState): boolean {
return canonicalStringify(a) === canonicalStringify(b);
}
+218
View File
@@ -0,0 +1,218 @@
// Bounded deterministic state-space search. Proves each baseline scenario has a
// winning route and a losing route, verifies every reachable campaign inheritance
// combination stays solvable, and flags route properties (ownership change,
// adaptation exploit, adaptation avoidance). Offline-only; not imported by the UI.
import { ALL_ACTIONS } from "./constants";
import { nextState } from "./pipeline";
import { buildBaselineState, emptyInheritance, newlyUnlockedTraits, type Inheritance, withPreservedTrait } from "./scenario";
import { canonicalStringify } from "./serialize";
import { getScenario, SCENARIOS } from "../content/scenarios";
import type { GameState, LineageId, PressureId, RotationAction } from "./types";
// Dedup key: a fast deterministic string over the transition-relevant fields
// (action log excluded — it never affects future transitions). Hand-rolled in a
// fixed field order so semantically-equal states collapse without a recursive
// key-sort on every node.
export function stateKey(s: GameState): string {
const c = s.chambers;
let out = `${s.scenarioId}|${s.turn}|${s.outcome}|${s.consecutiveObjectiveTurns}|`;
out += `${s.loops.A.direction}${s.loops.B.direction}${s.loops.C.direction}|`;
out += `${s.sharedOwner[2]}${s.sharedOwner[3]}${s.sharedOwner[4]}${s.sharedOwner[5]}${s.sharedOwner[8]}${s.sharedOwner[9]}|`;
out += `${s.environmentActive.heat ? 1 : 0}${s.environmentActive.hunger ? 1 : 0}${s.environmentActive.toxin ? 1 : 0}${s.environmentActive.immunity ? 1 : 0}|`;
const lp = s.lineage;
out += `${lp.producer.pressure.heat}${lp.producer.pressure.hunger}${lp.producer.pressure.toxin}${lp.producer.pressure.immunity}${Number(lp.producer.unlocked.heat)}${Number(lp.producer.unlocked.hunger)}${Number(lp.producer.unlocked.toxin)}${Number(lp.producer.unlocked.immunity)}`;
out += `${lp.grazer.pressure.heat}${lp.grazer.pressure.hunger}${lp.grazer.pressure.toxin}${lp.grazer.pressure.immunity}${Number(lp.grazer.unlocked.heat)}${Number(lp.grazer.unlocked.hunger)}${Number(lp.grazer.unlocked.toxin)}${Number(lp.grazer.unlocked.immunity)}|`;
for (let i = 0; i < c.length; i++) {
out += `${c[i].nutrient},${c[i].heat},${c[i].toxin},${c[i].producer},${c[i].grazer},${c[i].phage};`;
}
return out;
}
export type Route = {
actions: RotationAction[];
outcome: GameState["outcome"];
unlocks: Record<LineageId, PressureId[]>;
ownershipChanged: boolean;
maxPressure: number;
};
function describeRoute(base: GameState, actions: RotationAction[]): Route {
let s = base;
const seenOwners = new Set(Object.keys(s.sharedOwner).map((k) => `${k}:${s.sharedOwner[k]}`));
let ownershipChanged = false;
let maxPressure = 0;
for (const a of actions) {
const r = nextState(s, a);
s = r.state;
for (const k of Object.keys(s.sharedOwner)) {
const tag = `${k}:${s.sharedOwner[k]}`;
if (!seenOwners.has(tag)) { ownershipChanged = true; seenOwners.add(tag); }
}
for (const lin of ["producer", "grazer"] as LineageId[]) for (const p of ["heat", "hunger", "toxin", "immunity"] as PressureId[]) maxPressure = Math.max(maxPressure, s.lineage[lin].pressure[p]);
if (s.outcome !== "playing") break;
}
return {
actions,
outcome: s.outcome,
unlocks: newlyUnlockedTraits(s),
ownershipChanged,
maxPressure,
};
}
// Compact 64-bit hash for dedup (avoids storing ~300-char keys per node).
// Two FNV-1a passes with different seeds, combined into a hex string.
function hash64(s: GameState): string {
const key = stateKey(s);
let h1 = 0x811c9dc5;
let h2 = 0x1ba48dc5;
for (let i = 0; i < key.length; i++) {
const c = key.charCodeAt(i);
h1 = Math.imul(h1 ^ c, 0x01000193);
h2 = Math.imul(h2 ^ c, 0x05033143);
}
return (h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0");
}
// Recursive DFS for a winning route. Memory-bounded: no node array, no per-push
// path copy — only the live recursion path (≤ turnLimit) and a visited set of
// 64-bit hashes. Deterministic (fixed action order).
export function findWin(scenarioId: string, inherited: Inheritance = emptyInheritance(), nodeCap = 1_500_000): Route | null {
const sc = getScenario(scenarioId);
const base = buildBaselineState(scenarioId, "campaign", inherited);
const visited = new Set<string>([hash64(base)]);
let count = 0;
let result: RotationAction[] | null = null;
const path: RotationAction[] = [];
const dfs = (state: GameState): boolean => {
if (count >= nodeCap) return false;
count++;
if (state.outcome === "won") { result = path.slice(); return true; }
if (state.outcome !== "playing") return false;
if (path.length >= sc.turnLimit) return false;
for (const action of ALL_ACTIONS) {
const ns = nextState(state, action).state;
const h = hash64(ns);
if (visited.has(h)) continue;
visited.add(h);
path.push(action);
if (dfs(ns)) return true;
path.pop();
}
return false;
};
dfs(base);
return result ? describeRoute(base, result) : null;
}
// Search for a winning route that AVOIDS unlocking any adaptation (every pressure
// track stays below 3 the whole route). SPEC §8/Gate 4 require at least one such
// route. Prunes any branch where a pressure track reaches 3.
export function findWinAvoidingAdaptation(scenarioId: string, inherited: Inheritance = emptyInheritance(), nodeCap = 1_500_000): Route | null {
const sc = getScenario(scenarioId);
const base = buildBaselineState(scenarioId, "campaign", inherited);
const visited = new Set<string>([hash64(base)]);
let count = 0;
let result: RotationAction[] | null = null;
const path: RotationAction[] = [];
const pressuresHigh = (s: GameState) => {
for (const lin of ["producer", "grazer"] as LineageId[]) for (const p of ["heat", "hunger", "toxin", "immunity"] as PressureId[]) if (s.lineage[lin].pressure[p] >= 3) return true;
return false;
};
const dfs = (state: GameState): boolean => {
if (count >= nodeCap) return false;
count++;
if (state.outcome === "won") { result = path.slice(); return true; }
if (state.outcome !== "playing") return false;
if (path.length >= sc.turnLimit) return false;
for (const action of ALL_ACTIONS) {
const ns = nextState(state, action).state;
if (pressuresHigh(ns)) continue; // would unlock a trait — avoid
const h = hash64(ns);
if (visited.has(h)) continue;
visited.add(h);
path.push(action);
if (dfs(ns)) return true;
path.pop();
}
return false;
};
dfs(base);
return result ? describeRoute(base, result) : null;
}
// A losing route: a policy that reaches a non-win terminal. Try each fixed
// single-action policy; the first that expires or collapses without winning wins.
export function findLose(scenarioId: string, inherited: Inheritance = emptyInheritance()): Route | null {
const base = buildBaselineState(scenarioId, "campaign", inherited);
for (const fixed of ALL_ACTIONS) {
let s = base;
const path: RotationAction[] = [];
while (s.outcome === "playing" && path.length < getScenario(scenarioId).turnLimit) {
const r = nextState(s, fixed);
s = r.state;
path.push(fixed);
}
if (s.outcome === "collapsed" || s.outcome === "expired") return describeRoute(base, path);
}
return null;
}
// Enumerate every reachable campaign inheritance set entering each scenario and
// confirm each is solvable. SPEC §10 reachability verification.
export type ReachabilityResult = {
scenarioId: string;
inheritance: Inheritance;
solvable: boolean;
route: Route | null;
};
export function verifyReachableInheritance(
perScenarioNodeCap: Record<string, number> = {},
): { ok: boolean; results: ReachabilityResult[] } {
const results: ReachabilityResult[] = [];
// BFS over inheritance tree. Each scenario i is entered with some inheritance;
// after a win, branch by preserving 0 or 1 newly-unlocked trait.
let frontier: { scenarioIndex: number; inheritance: Inheritance }[] = [{ scenarioIndex: 0, inheritance: emptyInheritance() }];
for (let i = 0; i < SCENARIOS.length; i++) {
const sc = SCENARIOS[i];
const cap = perScenarioNodeCap[sc.id] ?? 400_000;
const nextFrontier: { scenarioIndex: number; inheritance: Inheritance }[] = [];
const seenInh = new Set<string>();
for (const f of frontier) {
const key = canonicalStringify(f.inheritance);
if (seenInh.has(key)) continue;
seenInh.add(key);
const route = findWin(sc.id, f.inheritance, cap);
const solvable = route !== null;
results.push({ scenarioId: sc.id, inheritance: f.inheritance, solvable, route });
if (i < SCENARIOS.length - 1 && solvable) {
const unlocks = route!.unlocks;
// decline
nextFrontier.push({ scenarioIndex: i + 1, inheritance: f.inheritance });
// preserve each newly unlocked trait
for (const lin of ["producer", "grazer"] as LineageId[]) {
for (const p of unlocks[lin]) {
nextFrontier.push({ scenarioIndex: i + 1, inheritance: withPreservedTrait(f.inheritance, { lineage: lin, pressure: p }) });
}
}
}
}
frontier = nextFrontier;
if (results.some((r) => !r.solvable)) break;
}
return { ok: results.every((r) => r.solvable), results };
}
export function routeProperties(routes: Route[]): {
anyOwnershipChange: boolean;
anyExploitsAdaptation: boolean;
anyAvoidsAdaptation: boolean;
} {
return {
anyOwnershipChange: routes.some((r) => r.ownershipChanged),
anyExploitsAdaptation: routes.some((r) => r.maxPressure >= 3),
anyAvoidsAdaptation: routes.some((r) => r.maxPressure < 3),
};
}
+75
View File
@@ -0,0 +1,75 @@
// Domain types — serializable plain data. No rendering, time, or UI state here.
export type LoopId = "A" | "B" | "C";
export type Direction = "cw" | "ccw";
export type LineageId = "producer" | "grazer";
export type PressureId = "heat" | "hunger" | "toxin" | "immunity";
export type Mode = "campaign" | "standalone";
export type Outcome = "playing" | "won" | "collapsed" | "expired";
// A movable chamber. Six capped (0..6) integer fields. Rotates with its loop.
export type Chamber = {
nutrient: number;
heat: number;
toxin: number;
producer: number;
grazer: number;
phage: number;
};
export type Lineage = {
pressure: Record<PressureId, number>; // 0..3
unlocked: Record<PressureId, boolean>;
};
export type RotationAction = {
loop: LoopId;
direction: Direction;
};
// Canonical game state. Everything transient (hover, focus, animation, clocks)
// is excluded — equality is deep equality after stable-key serialization.
export type GameState = {
schemaVersion: 1;
mode: Mode;
scenarioId: string;
turn: number;
loops: Record<LoopId, { direction: Direction }>;
sharedOwner: Record<string, LoopId>;
chambers: Chamber[];
lineage: Record<LineageId, Lineage>;
inheritedAtStart: Record<LineageId, PressureId[]>;
consecutiveObjectiveTurns: number;
environmentActive: Record<PressureId, boolean>;
outcome: Outcome;
actionLog: RotationAction[];
};
// Deterministic, phase-ordered event attribution. Derived from prior state +
// action; never part of canonical equality. The UI renders a subset; tests
// assert on structure/counts, never on the production algorithm.
export type EventPhase =
| "rotate"
| "flow"
| "growth"
| "interactions"
| "migration"
| "evolution"
| "fixtures"
| "outcome";
export type GameEvent = {
phase: EventPhase;
kind: string; // machine-readable tag
text: string; // human-readable, scan-friendly
slot?: number;
lineage?: LineageId | "phage";
pressure?: PressureId;
amount?: number;
};
export type TransitionResult = {
state: GameState;
events: GameEvent[];
rejected: boolean; // true when action was applied to a terminal state
};
+513
View File
@@ -0,0 +1,513 @@
// Adaptive Loop — presentation controller. Holds a Session, renders views, and
// routes every committed action through the pure domain transition (preview calls
// the same nextState on cloned state, so preview == commit). Public controls only;
// no domain state or localStorage is injected to fake gameplay.
import { ALL_ACTIONS, LINEAGE_IDS, LOOP_IDS, PRESSURE_IDS, PRESSURES, FIXTURE_META, SPECIES_NAMES, type FixtureKind } from "./domain/constants";
import { nextState, outletOf } from "./domain/pipeline";
import { cloneState } from "./domain/serialize";
import { fixturesFor, newlyUnlockedTraits } from "./domain/scenario";
import { SCENARIOS, getScenario } from "./content/scenarios";
import { totalProducer, totalGrazer, totalPhage, totalToxin } from "./domain/derived";
import { MemoryStorage, save, load, clear, type StorageAdapter } from "./persistence/save";
import { advanceAfterWin, eligiblePreservations, fromEnvelope, retry, startCampaign, startStandalone, toEnvelope } from "./session";
import { chamberXY, isShared, LOOP_COLORS, loopPoints, loopsOf, VIEWBOX } from "./presentation/geometry";
import type { Chamber, GameEvent, GameState, LineageId, LoopId, Outcome, PressureId, RotationAction, TransitionResult } from "./domain/types";
const STORAGE: StorageAdapter = typeof localStorage !== "undefined" ? localStorage : new MemoryStorage();
type View = "title" | "standalone-select" | "game" | "trait-choice" | "victory" | "malformed";
type App = {
view: View;
session: ReturnType<typeof startCampaign> | null;
selected: RotationAction | null;
preview: TransitionResult | null;
pendingChoiceSession: ReturnType<typeof startCampaign> | null; // session at moment of win, before advance
};
let app: App = { view: "title", session: null, selected: null, preview: null, pendingChoiceSession: null };
const appEl = (): HTMLElement => document.getElementById("app")!;
// ── helpers ──────────────────────────────────────────────────────────────────
function announce(text: string): void {
const el = document.querySelector('[data-region="live"]');
if (!el) return;
el.textContent = "";
// re-post so assistive tech re-announces
window.setTimeout(() => { el.textContent = text; }, 30);
}
function predictLabel(result: TransitionResult): string {
const o = result.state.outcome;
if (o === "won") return "Predicted: WIN";
if (o === "collapsed") return "Predicted: ecosystem collapse";
if (o === "expired") return "Predicted: turn limit reached";
return `Predicted turn ${result.state.turn}`;
}
function computePreview(state: GameState, action: RotationAction): TransitionResult {
return nextState(cloneState(state), action);
}
// ── rendering: title ──────────────────────────────────────────────────────────
function renderTitle(): void {
const hasSave = load(STORAGE) !== null;
appEl().innerHTML = `
<header class="topbar"><h1>Adaptive Loop</h1>
<details class="legend"><summary aria-label="How to play and legend">How to play</summary>${legendHtml()}</details>
</header>
<main id="main" class="menu">
<p class="lede">A calm deterministic strategy puzzle in a microfluidic culture dish. Rotate overlapping loops to move chambers and redirect flow; provoke adaptations, then exploit their costs.</p>
<div class="menu-buttons">
${hasSave ? `<button id="continue-btn" class="primary">Continue</button>` : `<button id="continue-btn" disabled title="No saved run">Continue</button>`}
<button id="new-campaign-btn" class="primary">New Campaign</button>
<button id="standalone-btn">Replay Standalone</button>
</div>
<section class="legend-static" aria-label="Legend">${legendHtml()}</section>
</main>
<footer data-region="live" aria-live="polite" aria-atomic="true" class="visually-hidden"></footer>`;
document.getElementById("continue-btn")?.addEventListener("click", () => {
const env = load(STORAGE);
if (!env) return;
app.session = fromEnvelope(env);
app.view = "game";
app.selected = null;
app.preview = null;
render();
});
document.getElementById("new-campaign-btn")?.addEventListener("click", () => {
if (load(STORAGE) && !confirm("Start a new campaign? Current progress will be lost.")) return;
clear(STORAGE);
app.session = startCampaign();
app.view = "game";
app.selected = null;
app.preview = null;
saveCurrent();
render();
});
document.getElementById("standalone-btn")?.addEventListener("click", () => { app.view = "standalone-select"; render(); });
}
function legendHtml(): string {
const species = `<p><strong>Species</strong> (shape + color + label):
<span class="sp producer">● P ${SPECIES_NAMES.producer}</span> eats nutrient;
<span class="sp grazer">■ G ${SPECIES_NAMES.grazer}</span> eats producer;
<span class="sp phage">▲ H ${SPECIES_NAMES.phage}</span> eats grazer.</p>`;
const pressures = `<p><strong>Pressures</strong>: ${PRESSURE_IDS.map((p) => `<span style="color:${PRESSURES[p].color}">${PRESSURES[p].glyph} ${PRESSURES[p].label} → ${PRESSURES[p].traitName}</span>`).join(" ")}</p>`;
const fixtures = `<p><strong>Fixtures</strong>: ${(Object.keys(FIXTURE_META) as FixtureKind[]).map((k) => `<span>${FIXTURE_META[k].glyph} ${FIXTURE_META[k].label}</span>`).join(" ")}</p>`;
const how = `<p><strong>How to play</strong>: Select a loop rotation (focus/hover/tap) to preview exactly one turn, then press Commit. Each rotation moves chamber payloads and reclaims that loop's shared chambers, redirecting nutrient/toxin flow. Win each scenario's objective before the turn limit; if producers + grazers all die, the ecosystem collapses.</p>`;
return `${how}${species}${pressures}${fixtures}`;
}
// ── rendering: standalone select ──────────────────────────────────────────────
function renderStandaloneSelect(): void {
// Standalone can replay any scenario with clean baseline.
appEl().innerHTML = `
<header class="topbar"><h1>Replay Standalone</h1>
<button id="menu-btn" class="link">← Menu</button></header>
<main id="main" class="menu">
<ul class="scenario-list">${SCENARIOS.map((s) => `<li><button data-scenario="${s.id}" class="scenario-pick"><strong>${s.index}. ${s.name}</strong> <span class="muted">(${s.subtitle})</span><br><span class="muted">${s.winDescription}</span></button></li>`).join("")}</ul>
</main>
<footer data-region="live" aria-live="polite" aria-atomic="true" class="visually-hidden"></footer>`;
document.getElementById("menu-btn")?.addEventListener("click", () => { app.view = "title"; render(); });
document.querySelectorAll<HTMLElement>("[data-scenario]").forEach((b) => b.addEventListener("click", () => {
app.session = startStandalone(b.dataset.scenario!);
app.view = "game";
app.selected = null;
app.preview = null;
render();
}));
}
// ── rendering: game ───────────────────────────────────────────────────────────
function renderGame(): void {
const s = app.session!;
const sc = getScenario(s.scenarioId);
appEl().innerHTML = `
<header class="topbar">
<h1>${sc.name} <span class="muted">— ${sc.subtitle}</span></h1>
<div class="topbar-actions">
<details class="legend"><summary aria-label="Legend">Legend</summary>${legendHtml()}</details>
<button id="menu-btn" class="link">Menu</button>
<button id="save-quit-btn">Save &amp; Quit</button>
</div>
</header>
<main id="main" class="layout">
<aside class="rail rail-left" aria-label="Scenario and campaign">
<section data-region="objective" class="panel"></section>
<section data-region="pressures" class="panel" aria-label="Pressures and traits"></section>
</aside>
<section class="board-wrap" aria-label="Culture board">
<svg id="board" viewBox="${VIEWBOX}" role="img" aria-label="Three interlocking hexagonal rings of culture chambers"></svg>
</section>
<aside class="rail rail-right" aria-label="Controls and events">
<section class="panel controls" aria-label="Rotation controls"><div id="controls"></div></section>
<section class="panel"><h2>Tick events</h2><div data-region="events" role="log" aria-label="Latest turn events" class="events"></div></section>
</aside>
</main>
<footer data-region="live" aria-live="polite" aria-atomic="true" class="status"></footer>`;
document.getElementById("menu-btn")?.addEventListener("click", () => { saveCurrent(); app.view = "title"; render(); });
document.getElementById("save-quit-btn")?.addEventListener("click", () => { saveCurrent(); app.view = "title"; announce("Saved."); render(); });
drawBoard();
renderObjective();
renderPressures(s.state);
renderControls();
renderEvents(lastEvents);
refreshPreview();
}
let lastEvents: GameEvent[] = [];
function renderEvents(events: GameEvent[]): void {
const el = document.querySelector('[data-region="events"]');
if (!el) return;
if (events.length === 0) { el.innerHTML = `<p class="muted">Select a rotation to preview the tick.</p>`; return; }
el.innerHTML = events.map((e) => `<p class="ev ev-${e.phase}"><span class="ev-kind">${e.kind}</span> ${escapeHtml(e.text)}</p>`).join("");
}
function escapeHtml(s: string): string {
return s.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" } as Record<string, string>)[c]);
}
function renderObjective(): void {
const el = document.querySelector('[data-region="objective"]');
if (!el || !app.session) return;
const s = app.session;
const sc = getScenario(s.scenarioId);
el.innerHTML = `
<h2>${sc.name} <span class="muted">(${sc.subtitle})</span></h2>
<p class="objective-text">${sc.winDescription}</p>
<p class="stat">Turn <strong>${s.state.turn}</strong> / ${sc.turnLimit}${terminalNote(s.state.outcome)}</p>
<p class="stat">Totals — P:${totalProducer(s.state)} G:${totalGrazer(s.state)} H:${totalPhage(s.state)} T:${totalToxin(s.state)}</p>
<p class="muted small">Mode: ${s.mode}. ${s.mode === "campaign" ? `Unlocked: ${s.unlockedScenarios.length}/${SCENARIOS.length}.` : "Standalone (clean baseline)."}</p>`;
}
function terminalNote(o: Outcome): string {
if (o === "won") return ` — <strong class="ok">WON</strong>`;
if (o === "collapsed") return ` — <strong class="bad">COLLAPSED</strong>`;
if (o === "expired") return ` — <strong class="bad">EXPIRED</strong>`;
return "";
}
function renderPressures(state: GameState): void {
const el = document.querySelector('[data-region="pressures"]');
if (!el) return;
const rows = LINEAGE_IDS.map((lin) => {
const cells = PRESSURE_IDS.map((p) => {
const meta = PRESSURES[p];
const val = state.lineage[lin].pressure[p];
const unlocked = state.lineage[lin].unlocked[p];
const env = state.environmentActive[p];
return `<span class="pcell ${unlocked ? "adapted" : ""}" style="--pc:${meta.color}" title="${meta.label} ${val}/3${unlocked ? " (unlocked)" : ""}${env ? " · response active" : ""}">
<span class="pglyph">${meta.glyph}</span><span class="pval">${val}</span>${unlocked ? '<span class="tick">✓</span>' : ""}</span>`;
}).join("");
return `<div class="prow"><span class="pline">${lin === "producer" ? SPECIES_NAMES.producer : SPECIES_NAMES.grazer}</span><span class="pcells">${cells}</span></div>`;
}).join("");
el.innerHTML = `<h2>Pressures &amp; traits</h2>${rows}<p class="muted small">Track 0–3; at 3 a trait unlocks next turn and a global response activates. ✓ = adapted.</p>`;
}
function renderControls(): void {
buildControls();
updateControlStates();
}
function buildControls(): void {
const el = document.getElementById("controls");
if (!el || !app.session) return;
const s = app.session;
const terminal = s.state.outcome !== "playing";
const buttons = ALL_ACTIONS.map((a) => {
const preview = computePreview(s.state, a);
return `<button class="rotate-btn" data-loop="${a.loop}" data-dir="${a.direction}" aria-label="Rotate loop ${a.loop} ${a.direction === "cw" ? "clockwise" : "counter-clockwise"}. ${predictLabel(preview)}" ${terminal ? "disabled" : ""}>
<span class="loop-tag" style="color:${LOOP_COLORS[a.loop]}">${a.loop}</span> ${a.direction === "cw" ? "↻" : "↺"}
</button>`;
}).join("");
el.innerHTML = `
<div class="rotate-grid">${buttons}</div>
<div class="commit-row">
<button id="commit-btn" class="primary">Commit</button>
<button id="cancel-btn">Cancel</button>
</div>
<div id="terminal-actions">${terminal ? terminalActionsHtml(s.state.outcome) : ""}</div>`;
// rotation interactions: select + preview only (commit is a separate control)
document.querySelectorAll<HTMLElement>(".rotate-btn").forEach((b) => {
const action = { loop: b.dataset.loop as LoopId, direction: b.dataset.dir as "cw" | "ccw" };
b.addEventListener("click", () => selectAction(action));
b.addEventListener("focus", () => selectAction(action));
b.addEventListener("mouseenter", () => selectAction(action));
});
document.getElementById("commit-btn")?.addEventListener("click", commit);
document.getElementById("cancel-btn")?.addEventListener("click", cancelPreview);
wireTerminalActions();
}
// Toggle selection styling + commit/cancel enabled state IN PLACE (no DOM rebuild),
// so hovering between controls never detaches the commit button mid-interaction.
function updateControlStates(): void {
if (!app.session) return;
const terminal = app.session.state.outcome !== "playing";
document.querySelectorAll<HTMLElement>(".rotate-btn").forEach((b) => {
const match = app.selected && b.dataset.loop === app.selected.loop && b.dataset.dir === app.selected.direction;
b.classList.toggle("selected", !!match);
});
const commit = document.getElementById("commit-btn") as HTMLButtonElement | null;
const cancel = document.getElementById("cancel-btn") as HTMLButtonElement | null;
if (commit) commit.disabled = !app.selected || terminal;
if (cancel) cancel.disabled = !app.selected;
const termEl = document.getElementById("terminal-actions");
if (termEl) {
const want = terminal ? terminalActionsHtml(app.session.state.outcome) : "";
if (termEl.innerHTML !== want) { termEl.innerHTML = want; wireTerminalActions(); }
}
}
function terminalActionsHtml(o: Outcome): string {
if (o === "won") {
if (app.session!.mode === "campaign") return `<p class="ok">Scenario complete!</p><button id="continue-win-btn" class="primary">Choose trait →</button>`;
return `<p class="ok">Scenario complete!</p><button id="continue-win-btn" class="primary">Continue</button>`;
}
if (o === "collapsed") return `<p class="bad">The ecosystem collapsed.</p><button id="retry-btn" class="primary">Retry</button>`;
if (o === "expired") return `<p class="bad">Turn limit reached.</p><button id="retry-btn" class="primary">Retry</button>`;
return "";
}
function wireTerminalActions(): void {
document.getElementById("retry-btn")?.addEventListener("click", () => {
if (!app.session) return;
app.session = retry(app.session);
app.selected = null;
app.preview = null;
lastEvents = [];
render();
announce("Retried scenario.");
});
document.getElementById("continue-win-btn")?.addEventListener("click", onWinContinue);
}
function onWinContinue(): void {
if (!app.session) return;
if (app.session.mode === "standalone") {
app.view = "title";
render();
return;
}
const eligible = eligiblePreservations(app.session);
if (eligible.length === 0) {
finalizeCampaignAdvance(null);
} else {
app.pendingChoiceSession = app.session;
app.view = "trait-choice";
render();
}
}
function finalizeCampaignAdvance(choice: { lineage: LineageId; pressure: PressureId } | null): void {
if (!app.session) return;
const advanced = advanceAfterWin(app.session, choice);
if (advanced === null) {
app.view = "victory";
app.session = null;
clear(STORAGE);
render();
announce("Campaign victory!");
return;
}
app.session = advanced;
app.view = "game";
app.selected = null;
app.preview = null;
lastEvents = [];
saveCurrent();
render();
}
function renderTraitChoice(): void {
const base = app.pendingChoiceSession!;
const unlocked = newlyUnlockedTraits(base.state);
const options: { lineage: LineageId; pressure: PressureId }[] = [];
for (const lin of LINEAGE_IDS) for (const p of unlocked[lin]) options.push({ lineage: lin, pressure: p });
appEl().innerHTML = `
<header class="topbar"><h1>Preserve a trait?</h1></header>
<main id="main" class="menu">
<p class="lede">A trait unlocked this scenario. Preserve one to carry its benefit — and its cost — into the next scenario.</p>
<div class="menu-buttons">
${options.map((o, i) => `<button data-trait="${i}" class="primary">Preserve ${SPECIES_NAMES[o.lineage]} ${PRESSURES[o.pressure].traitName} (${PRESSURES[o.pressure].label})</button>`).join("")}
<button id="decline-trait-btn">Decline</button>
</div>
</main>
<footer data-region="live" aria-live="polite" aria-atomic="true" class="visually-hidden"></footer>`;
document.querySelectorAll<HTMLElement>("[data-trait]").forEach((b) => b.addEventListener("click", () => finalizeCampaignAdvance(options[Number(b.dataset.trait)])));
document.getElementById("decline-trait-btn")?.addEventListener("click", () => finalizeCampaignAdvance(null));
}
function renderVictory(): void {
appEl().innerHTML = `
<header class="topbar"><h1>Campaign Complete</h1></header>
<main id="main" class="menu">
<p class="lede">You held the culture stable across all five scenarios. The Adaptive Loop is closed.</p>
<div class="menu-buttons"><button id="menu-btn" class="primary">Return to title</button></div>
</main>
<footer data-region="live" aria-live="polite" aria-atomic="true" class="visually-hidden"></footer>`;
document.getElementById("menu-btn")?.addEventListener("click", () => { app.view = "title"; render(); });
}
// ── selection / preview / commit ──────────────────────────────────────────────
function selectAction(action: RotationAction): void {
if (!app.session || app.session.state.outcome !== "playing") return;
if (app.selected && app.selected.loop === action.loop && app.selected.direction === action.direction) return; // no-op reselect
app.selected = action;
app.preview = computePreview(app.session.state, action);
refreshPreview();
updateControlStates();
}
function cancelPreview(): void {
app.selected = null;
app.preview = null;
refreshPreview();
updateControlStates();
}
function refreshPreview(): void {
drawBoard();
if (app.preview) {
renderPressures(app.preview.state); // pressure increments visible during preview (Pass-1 fix)
renderEvents(keyEvents(app.preview.events));
} else if (app.session) {
renderPressures(app.session.state);
renderEvents(lastEvents);
}
}
function keyEvents(events: GameEvent[]): GameEvent[] {
// A concise, scan-friendly subset that still surfaces movement, flow, overflow,
// pressure increments, adaptations (benefit/cost/spillover), and the outcome.
const keep = new Set([
"rotate", "nutrient-overflow", "toxin-overflow", "producer-growth", "growth-suppressed",
"grazer-feed", "grazer-denied", "phage-feed", "phage-starve", "cloak-cost", "migrate",
"trait-unlock", "env-response", "pressure-up", "heat-loss", "heat-prevented", "heat-spillover",
"hunger-loss", "hunger-prevented", "toxin-loss", "toxin-cost", "toxin-spillover",
"immune-select", "immune-retarget", "immune-damage", "fixture-overflow", "outcome",
]);
return events.filter((e) => keep.has(e.kind));
}
function commit(): void {
if (!app.session || !app.selected) return;
const before = app.session;
if (before.state.outcome !== "playing") return; // rejected
// Single pure transition: events + canonical state in one call (preview == commit).
const result = nextState(before.state, app.selected);
app.session = { ...before, state: result.state };
app.selected = null;
app.preview = null;
lastEvents = keyEvents(result.events);
saveCurrent();
render();
const o = result.state.outcome;
announce(o === "playing" ? `Turn ${result.state.turn}.` : `Turn ${result.state.turn}: ${o}.`);
}
function saveCurrent(): void {
if (app.session) save(STORAGE, toEnvelope(app.session, Date.now()));
}
// ── board SVG ─────────────────────────────────────────────────────────────────
function drawBoard(): void {
const svg = document.getElementById("board");
if (!svg || !app.session) return;
const state = app.session.state;
const previewState = app.preview?.state ?? null;
const fx = fixturesFor(state.scenarioId);
// build parts
const rings = LOOP_IDS.map((L) =>
`<polygon class="ring ring-${L}" points="${loopPoints(L)}" fill="none" stroke="${LOOP_COLORS[L]}" stroke-width="6" stroke-linejoin="round" />`).join("");
// flow arrows along owner edges — during preview, reflect the post-rotation flow
const arrows = flowArrows(previewState ?? state);
const nodes = state.chambers.map((c, slot) => chamberSvg(slot, c, fx[slot], previewState)).join("");
// selection highlight ring outline
svg.innerHTML = `${rings}${arrows}${nodes}`;
}
function flowArrows(state: GameState): string {
const drawn = new Set<string>();
const parts: string[] = [];
for (let slot = 0; slot < 12; slot++) {
const out = outletOf(slot, state);
const key = `${slot}-${out}`;
if (drawn.has(key)) continue;
drawn.add(key);
const [x1, y1] = chamberXY(slot);
const [x2, y2] = chamberXY(out);
const mx = (x1 + x2) / 2;
const my = (y1 + y2) / 2;
parts.push(`<circle class="flow-dot" cx="${mx.toFixed(1)}" cy="${my.toFixed(1)}" r="3" />`);
}
return parts.join("");
}
function chamberSvg(slot: number, c: Chamber, fixtures: FixtureKind[], preview: GameState | null): string {
const [x, y] = chamberXY(slot);
const fixtureMarks = fixtures.map((k) => `<text class="fx-glyph" y="-30">${FIXTURE_META[k].glyph}</text>`).join("");
const pops = (["producer", "grazer", "phage"] as const).map((sp) =>
c[sp] > 0 ? `<tspan class="pop pop-${sp}" dx="${sp === "producer" ? 0 : 4}">${popGlyph(sp)}${c[sp]}</tspan>` : "").join("");
const delta = preview ? populationDelta(c, preview.chambers[slot]) : "";
const res = `<text class="res" y="8">N${c.nutrient}${c.heat > 0 ? ` 🔥${c.heat}` : ""}${c.toxin > 0 ? ` ⚗${c.toxin}` : ""}</text>`;
const label = `<text class="slot-label" y="26">${slot}${isShared(slot) ? ` ${loopsOf(slot).join("")}` : ""}</text>`;
return `<g class="chamber" transform="translate(${x},${y})">
<circle r="24" class="chamber-bg" />
${fixtureMarks}
<text class="pops" y="-2">${pops}</text>
${res}${label}${delta}
</g>`;
}
function popGlyph(sp: "producer" | "grazer" | "phage"): string {
return sp === "producer" ? "●" : sp === "grazer" ? "■" : "▲";
}
function populationDelta(now: Chamber, next: Chamber): string {
const diffs: string[] = [];
(["producer", "grazer", "phage"] as const).forEach((sp) => {
const d = next[sp] - now[sp];
if (d !== 0) diffs.push(`${popGlyph(sp)}${d > 0 ? "+" : ""}${d}`);
});
["nutrient", "toxin"].forEach((f) => {
const d = (next as unknown as Record<string, number>)[f] - (now as unknown as Record<string, number>)[f];
if (d !== 0) diffs.push(`${f === "nutrient" ? "N" : "T"}${d > 0 ? "+" : ""}${d}`);
});
if (diffs.length === 0) return "";
return `<text class="delta" y="-15">${diffs.join(" ")}</text>`;
}
// ── router ────────────────────────────────────────────────────────────────────
function render(): void {
switch (app.view) {
case "title": renderTitle(); break;
case "standalone-select": renderStandaloneSelect(); break;
case "game": renderGame(); break;
case "trait-choice": renderTraitChoice(); break;
case "victory": renderVictory(); break;
default: renderTitle();
}
}
// global keyboard: Escape cancels preview
window.addEventListener("keydown", (e) => {
if (e.key === "Escape" && app.view === "game" && app.selected) { cancelPreview(); }
});
// boot
function boot(): void {
const env = load(STORAGE);
app.view = "title";
app.session = env ? fromEnvelope(env) : null;
render();
}
boot();
+95
View File
@@ -0,0 +1,95 @@
// Versioned save/load + replay. The envelope holds canonical game state plus
// campaign meta; savedAt metadata stays outside canonical comparison. A
// StorageAdapter abstracts localStorage so tests use an in-memory implementation.
// Malformed or unsupported saves fail safely (load returns null) so the UI can
// offer recovery rather than crash.
import { buildBaselineState, type Inheritance } from "../domain/scenario";
import { SCENARIO_BY_ID } from "../content/scenarios";
import { nextState } from "../domain/pipeline";
import { canonicalStringify } from "../domain/serialize";
import type { GameState, Mode, Outcome, RotationAction } from "../domain/types";
const SAVE_KEY = "adaptive-loop.save.v1";
const SCHEMA_VERSION = 1;
export type SaveEnvelope = {
schemaVersion: number;
mode: Mode;
scenarioId: string;
state: GameState;
unlockedScenarios: string[];
inheritedTraits: Inheritance;
entrySnapshot: Inheritance;
actionLog: RotationAction[];
outcome: Outcome;
savedAt: number; // metadata — excluded from canonical comparison
};
export interface StorageAdapter {
getItem(key: string): string | null;
setItem(key: string, value: string): void;
removeItem(key: string): void;
}
export class MemoryStorage implements StorageAdapter {
private store = new Map<string, string>();
getItem(key: string): string | null { return this.store.has(key) ? this.store.get(key)! : null; }
setItem(key: string, value: string): void { this.store.set(key, value); }
removeItem(key: string): void { this.store.delete(key); }
}
// Structural + value validation at the load boundary. Returns true only for a
// well-formed, supported envelope whose referenced scenario exists.
export function isValidEnvelope(x: unknown): x is SaveEnvelope {
if (typeof x !== "object" || x === null) return false;
const e = x as Record<string, unknown>;
if (e.schemaVersion !== SCHEMA_VERSION) return false;
if (typeof e.mode !== "string" || (e.mode !== "campaign" && e.mode !== "standalone")) return false;
if (typeof e.scenarioId !== "string" || !(e.scenarioId in SCENARIO_BY_ID)) return false;
if (typeof e.state !== "object" || e.state === null) return false;
if (!Array.isArray(e.unlockedScenarios)) return false;
for (const id of e.unlockedScenarios as unknown[]) if (typeof id !== "string" || !(id in SCENARIO_BY_ID)) return false;
if (typeof e.savedAt !== "number") return false;
if (!Array.isArray(e.actionLog)) return false;
if (typeof e.outcome !== "string") return false;
// shallow sanity on inheritance objects
for (const f of ["inheritedTraits", "entrySnapshot"]) {
const v = e[f] as Record<string, unknown> | undefined;
if (typeof v !== "object" || v === null || !Array.isArray(v.producer) || !Array.isArray(v.grazer)) return false;
}
return true;
}
export function save(adapter: StorageAdapter, env: SaveEnvelope): void {
adapter.setItem(SAVE_KEY, JSON.stringify(env));
}
export function load(adapter: StorageAdapter): SaveEnvelope | null {
const raw = adapter.getItem(SAVE_KEY);
if (raw === null) return null;
let parsed: unknown;
try { parsed = JSON.parse(raw); } catch { return null; }
if (!isValidEnvelope(parsed)) return null;
return parsed;
}
export function clear(adapter: StorageAdapter): void {
adapter.removeItem(SAVE_KEY);
}
// Replaying the action log from a scenario baseline plus its entry inheritance
// snapshot must reproduce the canonical current state. SPEC §11.
export function replayFromBaseline(scenarioId: string, entrySnapshot: Inheritance, actionLog: RotationAction[]): GameState {
let s = buildBaselineState(scenarioId, "campaign", entrySnapshot);
for (const a of actionLog) s = nextState(s, a).state;
return s;
}
// Two envelopes are canonically equal ignoring savedAt (metadata).
export function envelopesEqual(a: SaveEnvelope, b: SaveEnvelope): boolean {
const { savedAt: _a, ...ra } = a;
const { savedAt: _b, ...rb } = b;
void _a; void _b;
return canonicalStringify(ra) === canonicalStringify(rb);
}
@@ -0,0 +1,47 @@
// Board geometry: three interlocking hexagonal rings (SPEC §4 / docs/board-layout.md).
// 12 chamber coordinates chosen so each loop's six slots form a hexagonal ring and
// the six shared chambers coincide (rendered once at the overlap). Each loop's
// polygon is built from its six slot coordinates in cyclic order; rings overlap
// like chain links. Coordinates are in a 440×400 viewBox; the SVG scales to fit.
import { LOOP_SLOTS, SHARED_SLOTS, SLOT_LOOPS } from "../domain/constants";
import type { LoopId } from "../domain/types";
// [x, y] per slot. Uniques sit on the outer points; shared pairs sit at the
// three ring overlaps (A∩B right, A∩C left, B∩C bottom).
export const CHAMBER_COORDS: ReadonlyArray<readonly [number, number]> = [
[225, 60], // 0 (A)
[330, 110], // 1 (A)
[310, 165], // 2 (A∩B)
[250, 225], // 3 (A∩B)
[200, 225], // 4 (A∩C)
[140, 165], // 5 (A∩C)
[380, 230], // 6 (B)
[345, 315], // 7 (B)
[275, 360], // 8 (B∩C)
[210, 335], // 9 (B∩C)
[70, 230], // 10 (C)
[105, 315], // 11 (C)
];
export const LOOP_COLORS: Record<LoopId, string> = { A: "#5cc8ff", B: "#ffb45c", C: "#b98cff" };
export function chamberXY(slot: number): [number, number] {
return [CHAMBER_COORDS[slot][0], CHAMBER_COORDS[slot][1]];
}
// Polygon points string for a loop's ring outline (its six slots in cyclic order).
export function loopPoints(loop: LoopId): string {
return LOOP_SLOTS[loop].map((s) => chamberXY(s).join(",")).join(" ");
}
export function isShared(slot: number): boolean {
return SHARED_SLOTS.includes(slot);
}
export function loopsOf(slot: number): LoopId[] {
return SLOT_LOOPS[slot];
}
// Center of the board (for objective/fixture label placement offsets).
export const VIEWBOX = "0 0 440 400";
+114
View File
@@ -0,0 +1,114 @@
// Campaign + standalone session management. Pure functions over a Session value;
// the UI holds the current Session and persists it via the save module. All
// transitions route through the pure domain transition so preview == commit.
import { buildBaselineState, emptyInheritance, newlyUnlockedTraits, withPreservedTrait, type Inheritance } from "./domain/scenario";
import { SCENARIOS } from "./content/scenarios";
import { nextState } from "./domain/pipeline";
import { cloneState } from "./domain/serialize";
import type { GameState, LineageId, Mode, PressureId, RotationAction } from "./domain/types";
import type { SaveEnvelope } from "./persistence/save";
export type Session = {
mode: Mode;
scenarioId: string;
state: GameState;
unlockedScenarios: string[]; // campaign scenarios the player may enter
inheritedTraits: Inheritance; // traits carried into the current scenario
entrySnapshot: Inheritance; // inheritance at scenario entry — restored on retry
};
export type TraitChoice = { lineage: LineageId; pressure: PressureId } | null;
export function startCampaign(): Session {
const first = SCENARIOS[0];
return {
mode: "campaign",
scenarioId: first.id,
state: buildBaselineState(first.id, "campaign", emptyInheritance()),
unlockedScenarios: [first.id],
inheritedTraits: emptyInheritance(),
entrySnapshot: emptyInheritance(),
};
}
// Standalone replays a scenario with clean baseline lineages; no traits carry.
export function startStandalone(scenarioId: string): Session {
return {
mode: "standalone",
scenarioId,
state: buildBaselineState(scenarioId, "standalone", emptyInheritance()),
unlockedScenarios: [scenarioId],
inheritedTraits: emptyInheritance(),
entrySnapshot: emptyInheritance(),
};
}
export function fromEnvelope(env: SaveEnvelope): Session {
return {
mode: env.mode,
scenarioId: env.scenarioId,
state: cloneState(env.state),
unlockedScenarios: [...env.unlockedScenarios],
inheritedTraits: { producer: [...env.inheritedTraits.producer], grazer: [...env.inheritedTraits.grazer] },
entrySnapshot: { producer: [...env.entrySnapshot.producer], grazer: [...env.entrySnapshot.grazer] },
};
}
export function toEnvelope(session: Session, savedAt: number): SaveEnvelope {
return {
schemaVersion: 1,
mode: session.mode,
scenarioId: session.scenarioId,
state: cloneState(session.state),
unlockedScenarios: [...session.unlockedScenarios],
inheritedTraits: { producer: [...session.inheritedTraits.producer], grazer: [...session.inheritedTraits.grazer] },
entrySnapshot: { producer: [...session.entrySnapshot.producer], grazer: [...session.entrySnapshot.grazer] },
actionLog: session.state.actionLog.map((a) => ({ loop: a.loop, direction: a.direction })),
outcome: session.state.outcome,
savedAt,
};
}
// Apply a committed rotation. Rejected actions (terminal state) return the
// session unchanged. Preview is computed separately by the UI via nextState.
export function commitAction(session: Session, action: RotationAction): Session {
const result = nextState(session.state, action);
if (result.rejected) return session;
const state = result.state;
return { ...session, state };
}
// Retry restores the current scenario baseline with its scenario-entry inheritance.
export function retry(session: Session): Session {
return {
...session,
state: buildBaselineState(session.scenarioId, session.mode, session.entrySnapshot),
};
}
// Eligible traits the player may preserve after winning the current scenario.
export function eligiblePreservations(session: Session): TraitChoice[] {
const unlocked = newlyUnlockedTraits(session.state);
const out: TraitChoice[] = [];
for (const lin of ["producer", "grazer"] as LineageId[]) for (const p of unlocked[lin]) out.push({ lineage: lin, pressure: p });
return out;
}
// Advance after a win: preserve 0 or 1 newly-unlocked trait, unlock + enter next
// scenario. Returns null if the won scenario was the last (campaign victory).
export function advanceAfterWin(session: Session, choice: TraitChoice): Session | null {
const idx = SCENARIOS.findIndex((s) => s.id === session.scenarioId);
if (idx < 0 || idx >= SCENARIOS.length - 1) return null; // campaign victory
const nextInherited = choice ? withPreservedTrait(session.inheritedTraits, choice) : session.inheritedTraits;
const next = SCENARIOS[idx + 1];
const unlocked = session.unlockedScenarios.includes(next.id) ? session.unlockedScenarios : [...session.unlockedScenarios, next.id];
return {
mode: "campaign",
scenarioId: next.id,
state: buildBaselineState(next.id, "campaign", nextInherited),
unlockedScenarios: unlocked,
inheritedTraits: nextInherited,
entrySnapshot: nextInherited,
};
}
+187
View File
@@ -0,0 +1,187 @@
/* Adaptive Loop — dark laboratory glass aesthetic. Procedural SVG/CSS only. */
:root {
--bg: #0a0e14;
--bg-2: #11161f;
--panel: #141b26;
--ink: #e6edf3;
--muted: #8b98a9;
--accent: #5cc8ff;
--accent-2: #b98cff;
--ok: #7bd389;
--bad: #ff6b6b;
--warn: #ffb45c;
--line: #243042;
--producer: #7bd389;
--grazer: #ffb45c;
--phage: #ff8aa8;
--radius: 10px;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
background: var(--bg);
color: var(--ink);
font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
font-size: 16px;
line-height: 1.4;
}
#app { min-height: 100vh; display: flex; flex-direction: column; }
h1, h2 { margin: 0 0 0.3em; line-height: 1.15; }
h1 { font-size: 1.35rem; }
h2 { font-size: 1.05rem; }
.muted { color: var(--muted); }
.small { font-size: 0.8rem; }
.ok { color: var(--ok); }
.bad { color: var(--bad); }
.skip-link {
position: absolute; left: -9999px; top: 0; z-index: 100;
background: var(--accent); color: #001019; padding: 0.5rem 0.8rem; border-radius: 0 0 var(--radius) 0;
}
.skip-link:focus { left: 0; }
.visually-hidden {
position: absolute !important; width: 1px; height: 1px; padding: 0; margin: -1px;
overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0;
}
:focus-visible {
outline: 3px solid var(--accent);
outline-offset: 2px;
border-radius: 4px;
}
button {
font: inherit; color: var(--ink); background: var(--panel);
border: 1px solid var(--line); border-radius: var(--radius);
padding: 0.5rem 0.8rem; cursor: pointer; min-height: 40px;
}
button:hover:not(:disabled) { border-color: var(--accent); }
button:disabled { opacity: 0.45; cursor: not-allowed; }
button.primary { background: var(--accent); color: #001019; border-color: var(--accent); font-weight: 600; }
button.primary:hover:not(:disabled) { background: #7fd4ff; }
button.link { background: transparent; border: none; color: var(--accent); min-height: auto; padding: 0.3rem; }
/* ── topbar ─────────────────────────────────────── */
.topbar {
display: flex; align-items: center; justify-content: space-between; gap: 0.8rem;
padding: 0.7rem 1rem; background: var(--bg-2); border-bottom: 1px solid var(--line);
flex-wrap: wrap;
}
.topbar-actions { display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap; }
details.legend { position: relative; }
details.legend summary { cursor: pointer; padding: 0.3rem 0.6rem; border: 1px solid var(--line); border-radius: var(--radius); min-height: 40px; display: flex; align-items: center; }
details.legend[open] summary { border-color: var(--accent); }
details.legend .legend-body, details.legend p { max-width: 60ch; }
/* ── layout ─────────────────────────────────────── */
.layout {
flex: 1; display: grid; gap: 0.8rem; padding: 0.8rem;
grid-template-columns: 17rem 1fr 19rem;
align-items: start;
}
.rail { display: flex; flex-direction: column; gap: 0.8rem; min-width: 0; }
.panel {
background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius);
padding: 0.7rem 0.8rem;
}
.panel h2 { color: var(--accent); }
.objective-text { margin: 0.2em 0 0.6em; }
.stat { margin: 0.2em 0; }
.board-wrap { display: flex; align-items: flex-start; justify-content: center; }
#board { width: 100%; max-width: 520px; height: auto; }
/* ── board svg ──────────────────────────────────── */
.ring { opacity: 0.9; }
.chamber-bg { fill: #0d131c; stroke: var(--line); stroke-width: 2; }
.chamber { transition: transform 0.2s ease; }
.chamber text { text-anchor: middle; font-size: 11px; fill: var(--ink); }
.pops { font-size: 12px; font-weight: 600; }
.pop-producer { fill: var(--producer); }
.pop-grazer { fill: var(--grazer); }
.pop-phage { fill: var(--phage); }
.res { fill: var(--muted); font-size: 9.5px; }
.slot-label { fill: var(--muted); font-size: 9px; }
.fx-glyph { fill: var(--warn); font-size: 11px; }
.delta { fill: var(--accent); font-size: 10px; font-weight: 700; }
.flow-dot { fill: var(--accent); opacity: 0.5; }
/* ── controls ───────────────────────────────────── */
.rotate-grid {
display: grid; grid-template-columns: repeat(3, 1fr); gap: 0.4rem;
margin-bottom: 0.6rem;
}
.rotate-btn {
display: flex; flex-direction: column; align-items: center; gap: 0.1rem;
font-size: 1.1rem; padding: 0.6rem 0.3rem;
}
.rotate-btn .loop-tag { font-weight: 700; font-size: 0.8rem; }
.rotate-btn.selected { border-color: var(--accent); background: #16202c; box-shadow: 0 0 0 2px var(--accent) inset; }
.commit-row { display: flex; gap: 0.5rem; }
.commit-row button { flex: 1; }
/* ── pressures panel ────────────────────────────── */
.prow { display: flex; justify-content: space-between; align-items: center; gap: 0.4rem; margin: 0.2em 0; }
.pline { font-size: 0.85rem; }
.pcells { display: flex; gap: 0.3rem; }
.pcell {
display: inline-flex; align-items: center; gap: 2px; padding: 1px 5px; border-radius: 6px;
border: 1px solid var(--line); font-size: 0.8rem; background: #0d131c;
}
.pcell.adapted { border-color: var(--ok); background: #0f1a14; }
.pglyph { color: var(--pc, var(--ink)); }
.pval { font-variant-numeric: tabular-nums; }
.tick { color: var(--ok); }
/* ── events ─────────────────────────────────────── */
.events { max-height: 240px; overflow-y: auto; font-size: 0.85rem; }
.events .ev { margin: 0.15em 0; padding-left: 0.3em; border-left: 2px solid var(--line); }
.ev .ev-kind { color: var(--accent); font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.03em; }
.ev-outcome { border-left-color: var(--ok); font-weight: 600; }
/* ── menu screens ───────────────────────────────── */
.menu { padding: 1.2rem; max-width: 60ch; margin: 0 auto; }
.menu-buttons { display: flex; flex-direction: column; gap: 0.6rem; margin: 1rem 0; max-width: 24rem; }
.lede { color: var(--ink); }
.scenario-list { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 0.5rem; }
.scenario-pick { text-align: left; width: 100%; }
.legend-static p { margin: 0.4em 0; }
.sp { white-space: nowrap; }
.sp.producer { color: var(--producer); }
.sp.grazer { color: var(--grazer); }
.sp.phage { color: var(--phage); }
.status { padding: 0.4rem 1rem; background: var(--bg-2); border-top: 1px solid var(--line); color: var(--muted); font-size: 0.85rem; min-height: 1.6em; }
/* ── responsive ─────────────────────────────────── */
@media (max-width: 920px) {
.layout { grid-template-columns: 1fr; }
.board-wrap { order: -1; }
#board { max-width: 420px; }
}
@media (max-width: 410px) {
.topbar { padding: 0.5rem; }
.layout { padding: 0.4rem; gap: 0.5rem; }
.panel { padding: 0.5rem; }
h1 { font-size: 1.1rem; }
.rotate-btn { font-size: 0.95rem; padding: 0.5rem 0.2rem; }
#board { max-width: 100%; }
}
@media (min-resolution: 1.9dppx) {
.pops { font-size: 13px; }
.res, .slot-label, .delta { font-size: 10.5px; }
button { min-height: 44px; }
}
/* ── reduced motion ─────────────────────────────── */
@media (prefers-reduced-motion: reduce) {
* { transition: none !important; animation: none !important; }
.chamber { transition: none; }
}