Adaptive Loop — a deterministic microfluidic strategy puzzle. Pure serializable nextState(state,action) owns every committed turn; previews call the same function on a clone. 5 handcrafted scenarios, bounded solver with verified win/lose routes + shared-ownership counterfactual, exact localStorage persistence/replay, accessible SVG interface, Vitest truth/solver/persistence tests, and Playwright black-box browser proof. Scenarios 3 and 4 retuned per SPEC §9 (provably unwinnable as originally specified); proofs and exact changes in docs/scenario-tuning.md. Invariants preserved. See CONTEXT-MANIFEST.md for the disclosure boundary and residual risks. Aggregate verified: tsc --noEmit, vitest (59), vite build, playwright (10).
233 lines
11 KiB
TypeScript
233 lines
11 KiB
TypeScript
// 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);
|
|
}
|
|
}
|
|
}
|
|
});
|
|
});
|