(Adaptive Loop) Prepare for Pass 3

This commit is contained in:
AlexKucera committed 2026-08-13 09:07:45 +02:00
1 parent 8249da7e9b
commit 72497dcdbe
40 files changed
+242 -6229

No files matched your search

File diff suppressed because it is too large. Load diff
-46
View File
@@ -1,46 +0,0 @@
// Test helpers: build minimal isolated states against the fixture-free TEST_SCENARIO
// so a single pipeline phase can be exercised without cross-phase interference.
import { buildBaselineState } from "../src/domain/scenario";
import { defaultSharedOwner } from "../src/domain/constants";
import type { Chamber, GameState, LineageId, LoopId, PressureId } from "../src/domain/types";
// (Patch still carries slot for placement; it is stripped before building chambers.)
import { emptyLineage } from "../src/domain/serialize";
export type Patch = Partial<Chamber> & { slot: number };
export function makeState(patches: Patch[] = [], opts: {
scenarioId?: string;
loops?: Partial<Record<LoopId, "cw" | "ccw">>;
sharedOwner?: Record<string, LoopId>;
unlocked?: Partial<Record<LineageId, PressureId[]>>;
pressure?: Partial<Record<LineageId, Partial<Record<PressureId, number>>>>;
env?: Partial<Record<PressureId, boolean>>;
turn?: number;
outcome?: GameState["outcome"];
consecutive?: number;
} = {}): GameState {
const base = buildBaselineState(opts.scenarioId ?? "test", "standalone");
const chambers: Chamber[] = Array.from({ length: 12 }, () => ({ nutrient: 0, heat: 0, toxin: 0, producer: 0, grazer: 0, phage: 0 }));
for (const p of patches) {
const { slot: _omit, ...rest } = p;
void _omit;
chambers[p.slot] = { nutrient: 0, heat: 0, toxin: 0, producer: 0, grazer: 0, phage: 0, ...rest };
}
base.chambers = chambers;
if (opts.loops) for (const L of ["A", "B", "C"] as LoopId[]) if (opts.loops[L]) base.loops[L].direction = opts.loops[L]!;
if (opts.sharedOwner) base.sharedOwner = { ...defaultSharedOwner(), ...opts.sharedOwner };
if (opts.unlocked) for (const id of ["producer", "grazer"] as LineageId[]) for (const p of opts.unlocked[id] ?? []) base.lineage[id].unlocked[p] = true;
if (opts.pressure) for (const id of ["producer", "grazer"] as LineageId[]) for (const p of Object.keys(opts.pressure[id] ?? {}) as PressureId[]) base.lineage[id].pressure[p] = opts.pressure[id]![p]!;
if (opts.env) base.environmentActive = { heat: false, hunger: false, toxin: false, immunity: false, ...opts.env };
if (opts.turn !== undefined) base.turn = opts.turn;
if (opts.outcome) base.outcome = opts.outcome;
if (opts.consecutive !== undefined) base.consecutiveObjectiveTurns = opts.consecutive;
return base;
}
export function chamber(state: GameState, slot: number): Chamber {
return state.chambers[slot];
}
export { emptyLineage };
-114
View File
@@ -1,114 +0,0 @@
// Gate 5 — campaign and persistence. Exact save/restore, deterministic replay,
// malformed-save recovery, campaign progression with gift-and-burden inheritance,
// and retry restoring the scenario-entry snapshot.
import { describe, it, expect } from "vitest";
import { MemoryStorage, save, load, isValidEnvelope, replayFromBaseline, type SaveEnvelope } from "../src/persistence/save";
import { startCampaign, startStandalone, commitAction, retry, advanceAfterWin, toEnvelope, fromEnvelope, eligiblePreservations } from "../src/session";
import { nextState } from "../src/domain/pipeline";
import { buildBaselineState } from "../src/domain/scenario";
import { canonicalEqual } from "../src/domain/serialize";
import { SCENARIOS } from "../src/content/scenarios";
import fixture from "./fixtures/solver-results.json";
import type { RotationAction } from "../src/domain/types";
const A = (loop: "A" | "B" | "C", direction: "cw" | "ccw"): RotationAction => ({ loop, direction });
describe("persistence — exact save/restore + replay", () => {
it("save then load restores canonical state and the exact next transition", () => {
const store = new MemoryStorage();
let session = startCampaign();
session = commitAction(session, A("A", "cw"));
session = commitAction(session, A("B", "ccw"));
save(store, toEnvelope(session, Date.now()));
const restored = load(store);
expect(restored).not.toBeNull();
const again = fromEnvelope(restored!);
expect(canonicalEqual(again.state, session.state)).toBe(true);
// exact next transition matches
const nextA = nextState(again.state, A("C", "cw")).state;
const nextB = nextState(session.state, A("C", "cw")).state;
expect(canonicalEqual(nextA, nextB)).toBe(true);
});
it("replaying the action log from baseline + entry snapshot reproduces state", () => {
let session = startCampaign();
const log: RotationAction[] = [A("A", "cw"), A("C", "cw"), A("B", "ccw")];
for (const a of log) session = commitAction(session, a);
const replayed = replayFromBaseline(session.scenarioId, session.entrySnapshot, log);
expect(canonicalEqual(replayed, session.state)).toBe(true);
});
it("malformed or unsupported saves fail safely (load returns null, no crash)", () => {
const store = new MemoryStorage();
store.setItem("adaptive-loop.save.v1", "{not json");
expect(load(store)).toBeNull();
store.setItem("adaptive-loop.save.v1", JSON.stringify({ schemaVersion: 999 }));
expect(load(store)).toBeNull();
store.setItem("adaptive-loop.save.v1", JSON.stringify({ schemaVersion: 1, mode: "campaign", scenarioId: "nope", state: {}, unlockedScenarios: [], inheritedTraits: { producer: [], grazer: [] }, entrySnapshot: { producer: [], grazer: [] }, actionLog: [], outcome: "playing", savedAt: 1 }));
expect(isValidEnvelope(JSON.parse(store.getItem("adaptive-loop.save.v1")!))).toBe(false);
expect(load(store)).toBeNull();
});
it("empty storage loads null", () => {
expect(load(new MemoryStorage())).toBeNull();
});
});
describe("campaign — unlock, inheritance gift-and-burden, retry, standalone", () => {
it("winning a scenario unlocks the next and carries a preserved trait", () => {
// Drive s1 to a win using the solver fixture route.
const s1win = (fixture.scenarios as any[]).find((s) => s.id === "s1-heat")!.win.actions as RotationAction[];
let session = startCampaign();
for (const a of s1win) session = commitAction(session, a);
expect(session.state.outcome).toBe("won");
const eligible = eligiblePreservations(session);
expect(eligible.length).toBeGreaterThan(0);
const choice = eligible[0]!;
expect(eligible.length).toBeGreaterThan(0);
const advanced = advanceAfterWin(session, choice);
expect(advanced).not.toBeNull();
expect(advanced!.scenarioId).toBe("s2-hunger");
expect(advanced!.unlockedScenarios).toContain("s2-hunger");
// preserved trait carried as a burden/gift into the next scenario
expect(advanced!.inheritedTraits[eligible[0]!.lineage]).toContain(eligible[0]!.pressure);
expect(advanced!.state.lineage[eligible[0]!.lineage].unlocked[eligible[0]!.pressure]).toBe(true);
});
it("retry restores the scenario-entry inheritance snapshot", () => {
let session = startCampaign();
const before = buildBaselineState(session.scenarioId, "campaign", session.entrySnapshot);
session = commitAction(session, A("A", "cw"));
session = retry(session);
expect(canonicalEqual(session.state, before)).toBe(true);
});
it("standalone uses a clean baseline (no carried traits)", () => {
const session = startStandalone("s3-toxin");
expect(session.mode).toBe("standalone");
expect(session.inheritedTraits.producer).toEqual([]);
expect(session.inheritedTraits.grazer).toEqual([]);
});
it("declining a trait still advances to the next scenario", () => {
const s1win = (fixture.scenarios as any[]).find((s) => s.id === "s1-heat")!.win.actions as RotationAction[];
let session = startCampaign();
for (const a of s1win) session = commitAction(session, a);
const advanced = advanceAfterWin(session, null);
expect(advanced!.scenarioId).toBe("s2-hunger");
expect(advanced!.inheritedTraits.producer).toEqual([]);
});
it("winning the final scenario yields campaign victory (no further advance)", () => {
const s5win = (fixture.scenarios as any[]).find((s) => s.id === "s5-convergence")!.win.actions as RotationAction[];
// enter s5 directly with empty inheritance for the test
let session = startStandalone("s5-convergence");
session = { ...session, mode: "campaign" };
for (const a of s5win) session = commitAction(session, a);
expect(session.state.outcome).toBe("won");
expect(advanceAfterWin({ ...session, scenarioId: SCENARIOS[SCENARIOS.length - 1].id }, null)).toBeNull();
});
});
// Ensure the SaveEnvelope type is exercised (keeps the export meaningful to tsc).
export type _EnvelopeRef = SaveEnvelope;
-82
View File
@@ -1,82 +0,0 @@
// Gate 4 — scenario solvability. Validates the precomputed solver fixtures by
// replaying each stored route from its baseline + inheritance and asserting the
// recorded outcome. Fast and deterministic (the heavy search runs once offline in
// scripts/gen-solver-fixtures.ts). Also checks the Gate 4 route-property rules.
import { describe, it, expect } from "vitest";
import { nextState } from "../src/domain/pipeline";
import { buildBaselineState, type Inheritance } from "../src/domain/scenario";
import { SCENARIOS } from "../src/content/scenarios";
import type { RotationAction } from "../src/domain/types";
import fixture from "./fixtures/solver-results.json";
type StoredRoute = { actions: RotationAction[]; outcome: string; ownershipChanged: boolean; maxPressure: number };
function replay(scenarioId: string, inheritance: Inheritance, actions: RotationAction[]) {
let s = buildBaselineState(scenarioId, "campaign", inheritance);
for (const a of actions) s = nextState(s, a).state;
return s;
}
describe("Gate 4 — solver routes (replayed from fixtures)", () => {
for (const sc of SCENARIOS) {
const entry = (fixture.scenarios as any[]).find((x) => x.id === sc.id);
it(`${sc.id} has a winning route that replays to 'won'`, () => {
expect(entry, `missing fixture for ${sc.id}`).toBeTruthy();
const win = entry.win as StoredRoute | null;
expect(win, `${sc.id} has no stored win route`).toBeTruthy();
const final = replay(sc.id, { producer: [], grazer: [] }, win!.actions);
expect(final.outcome).toBe("won");
expect(win!.actions.length).toBeLessThanOrEqual(sc.turnLimit);
});
it(`${sc.id} has a losing route that replays to a non-win terminal`, () => {
const lose = entry.lose as StoredRoute | null;
expect(lose, `${sc.id} has no stored lose route`).toBeTruthy();
const final = replay(sc.id, { producer: [], grazer: [] }, lose!.actions);
expect(final.outcome === "collapsed" || final.outcome === "expired").toBe(true);
});
}
it("at least one route requires a shared-slot ownership change", () => {
const ok = (fixture.scenarios as any[]).some((x) => x.win?.ownershipChanged);
expect(ok).toBe(true);
});
it("at least one route exploits an adaptation (pressure reaches 3)", () => {
const ok = (fixture.scenarios as any[]).some((x) => (x.win?.maxPressure ?? 0) >= 3);
expect(ok).toBe(true);
});
it("at least one route avoids unlocking any adaptation (pressure stays < 3)", () => {
const avoid = (fixture.scenarios as any[]).filter((x) => x.avoid);
expect(avoid.length, "no adaptation-avoiding route stored").toBeGreaterThan(0);
for (const x of avoid) {
const final = replay(x.id, { producer: [], grazer: [] }, x.avoid.actions as RotationAction[]);
expect(final.outcome).toBe("won");
expect((x.avoid as StoredRoute).maxPressure).toBeLessThan(3);
}
});
it("every reachable inheritance combination is solvable except the documented dormancy-burden residual risk", () => {
const reach = fixture.reachability as {
ok: boolean;
combos: { scenarioId: string; inheritance: Inheritance; solvable: boolean }[];
residualRiskCombos: { scenarioId: string; inheritance: Inheritance }[];
};
// Residual-risk combos must all be the documented dormancy-into-s5 class.
for (const r of reach.residualRiskCombos) {
expect(r.scenarioId).toBe("s5-convergence");
expect(r.inheritance.producer).toContain("hunger");
}
// Every non-residual-risk combo must be solvable.
const riskKeys = new Set(reach.residualRiskCombos.map((r) => `${r.scenarioId}|${JSON.stringify(r.inheritance)}`));
for (const c of reach.combos) {
const key = `${c.scenarioId}|${JSON.stringify(c.inheritance)}`;
if (riskKeys.has(key)) continue;
expect(c.solvable, `unsolvable non-documented combo: ${key}`).toBe(true);
}
expect(reach.ok).toBe(true);
});
});
-270
View File
@@ -1,270 +0,0 @@
// Simulation truth tests (SPEC Gate 3 / deterministic-game-core skill). Each test
// exercises a single behavior. Assertions are robust to the full 8-phase pipeline:
// movement is checked by presence, adaptations by adapted-vs-unadapted deltas,
// and flow/caps/structural checks use literal hand-computed values.
import { describe, it, expect } from "vitest";
import { nextState, outletOf } from "../src/domain/pipeline";
import { cloneState, canonicalStringify, canonicalEqual } from "../src/domain/serialize";
import { buildBaselineState } from "../src/domain/scenario";
import { ALL_ACTIONS } from "../src/domain/constants";
import { SCENARIOS } from "../src/content/scenarios";
import { makeState, chamber } from "./helpers";
import type { RotationAction } from "../src/domain/types";
const A = (loop: "A" | "B" | "C", direction: "cw" | "ccw"): RotationAction => ({ loop, direction });
describe("rotations — payload permutation + ownership", () => {
// Producers carry nutrient so they survive the tick (no starvation); we assert
// the payload LANDED at the destination slot and left the source.
it("cw: slot 0 payload lands at slot 1 (loop A)", () => {
const s = makeState([{ slot: 0, nutrient: 6, producer: 2 }]);
const { state } = nextState(s, A("A", "cw"));
expect(chamber(state, 1).producer).toBeGreaterThan(0);
expect(chamber(state, 0).producer).toBe(0);
});
it("ccw: slot 1 payload lands at slot 0 (loop A)", () => {
const s = makeState([{ slot: 1, nutrient: 6, producer: 2 }]);
const { state } = nextState(s, A("A", "ccw"));
expect(chamber(state, 0).producer).toBeGreaterThan(0);
expect(chamber(state, 1).producer).toBe(0);
});
it("cw: slot 6 payload lands at slot 7 (loop B)", () => {
const s = makeState([{ slot: 6, nutrient: 6, producer: 2 }]);
const { state } = nextState(s, A("B", "cw"));
expect(chamber(state, 7).producer).toBeGreaterThan(0);
expect(chamber(state, 6).producer).toBe(0);
});
it("cw: slot 10 payload lands at slot 11 (loop C)", () => {
const s = makeState([{ slot: 10, nutrient: 6, producer: 2 }]);
const { state } = nextState(s, A("C", "cw"));
expect(chamber(state, 11).producer).toBeGreaterThan(0);
expect(chamber(state, 10).producer).toBe(0);
});
it("rotating loop C reclaims shared slot 5 and changes its outlet", () => {
const s = makeState();
expect(outletOf(5, s)).toBe(0); // owned by A (cw): outlet = slot 0
const { state } = nextState(s, A("C", "cw"));
expect(state.sharedOwner["5"]).toBe("C");
expect(outletOf(5, state)).toBe(10); // owned by C (cw): outlet = slot 10
});
});
describe("channel flow + caps", () => {
it("flows nutrient one step downstream (literal)", () => {
const s = makeState([{ slot: 0, nutrient: 3 }]);
const { state } = nextState(s, A("A", "cw"));
// rotation slot0→slot1 (nutrient3); flow sends 1 from slot1→slot2
expect(chamber(state, 1).nutrient).toBe(2);
expect(chamber(state, 2).nutrient).toBe(1);
});
it("contention + overflow at a shared receiver (slot 2 fed by slots 1 and 9)", () => {
const s = makeState([{ slot: 0, nutrient: 3 }, { slot: 1, nutrient: 6 }, { slot: 9, nutrient: 3 }]);
const { state, events } = nextState(s, A("A", "cw"));
expect(chamber(state, 2).nutrient).toBe(6); // 6 -1 sent +2 recv = 7 → capped 6
expect(events.some((e) => e.kind === "nutrient-overflow" && (e.amount ?? 0) >= 1)).toBe(true);
expect(chamber(state, 3).nutrient).toBe(1); // slot2 forwarded its send to slot3
});
it("keeps every capped field within 0..6 after a turn", () => {
const s = makeState([
{ slot: 0, nutrient: 6, producer: 6, heat: 6, toxin: 6, grazer: 6, phage: 6 },
{ slot: 1, nutrient: 6, producer: 6 },
{ slot: 9, nutrient: 6 },
]);
const { state } = nextState(s, A("A", "cw"));
for (const c of state.chambers) {
for (const v of [c.nutrient, c.heat, c.toxin, c.producer, c.grazer, c.phage]) {
expect(v).toBeGreaterThanOrEqual(0);
expect(v).toBeLessThanOrEqual(6);
}
}
});
});
describe("producer growth + interactions", () => {
it("growth: a fed producer grows (more producers than a starved one)", () => {
const fed = makeState([{ slot: 0, nutrient: 6, producer: 2 }]);
const starved = makeState([{ slot: 0, nutrient: 0, producer: 2 }]);
const f = nextState(fed, A("A", "cw")).state;
const u = nextState(starved, A("A", "cw")).state;
expect(chamber(f, 1).producer).toBeGreaterThan(chamber(u, 1).producer);
});
it("grazer feeding reduces producers vs a no-grazer control", () => {
const withGrazer = makeState([{ slot: 0, nutrient: 6, producer: 3, grazer: 1 }]);
const noGrazer = makeState([{ slot: 0, nutrient: 6, producer: 3 }]);
const g = nextState(withGrazer, A("A", "cw")).state;
const n = nextState(noGrazer, A("A", "cw")).state;
expect(chamber(g, 1).producer).toBeLessThan(chamber(n, 1).producer);
expect(chamber(g, 1).grazer).toBeGreaterThan(chamber(n, 1).grazer);
});
it("phage eats a grazer and gains; starves without one", () => {
const eat = makeState([{ slot: 0, grazer: 3, phage: 1, nutrient: 6, producer: 3 }]);
const starve = makeState([{ slot: 0, phage: 1, nutrient: 6, producer: 3 }]);
const e = nextState(eat, A("A", "cw")).state;
const t = nextState(starve, A("A", "cw")).state;
expect(chamber(e, 1).phage).toBeGreaterThan(chamber(t, 1).phage);
});
});
describe("migration", () => {
it("moves a population unit toward strictly richer food", () => {
// slot10 producer (food=nutrient0); slot11 has nutrient (dest food). outlet10→11 (C cw).
const s = makeState([{ slot: 10, producer: 3, nutrient: 0 }, { slot: 11, nutrient: 3 }]);
const { state } = nextState(s, A("A", "cw")); // A rotation does not move 10/11
expect(chamber(state, 11).producer).toBeGreaterThan(0); // migrated in
expect(chamber(state, 10).producer).toBeLessThan(3); // sent one out
});
});
describe("heat adaptation — benefit + carrier cost (adapted vs unadapted)", () => {
// Carrier cost is isolated from heat-death by comparing two ADAPTED lineages
// that differ only in whether heat is locally present.
const adapted = (heat: number) =>
makeState([{ slot: 0, nutrient: 6, producer: 3, heat }], { unlocked: { producer: ["heat"] } });
it("carrier cost: an adapted producer in heat grows LESS than the same producer without heat", () => {
const hot = nextState(adapted(3), A("A", "cw")).state;
const cool = nextState(adapted(0), A("A", "cw")).state;
expect(chamber(hot, 1).producer).toBeLessThan(chamber(cool, 1).producer);
expect(chamber(hot, 1).producer).toBe(3); // no growth (blocked)
});
const heatState = (unlocked: boolean) =>
makeState([{ slot: 0, nutrient: 6, producer: 3, heat: 3 }], { unlocked: unlocked ? { producer: ["heat"] } : {} });
it("benefit: Heat Shield prevents heat population loss (adapted survives better)", () => {
const adapted = nextState(heatState(true), A("A", "cw")).state;
const plain = nextState(heatState(false), A("A", "cw")).state;
expect(chamber(adapted, 1).producer).toBeGreaterThan(chamber(plain, 1).producer);
});
it("heat-spillover: adapted lineages cool the chamber", () => {
const { state, events } = nextState(heatState(true), A("A", "cw"));
expect(events.some((e) => e.kind === "heat-spillover")).toBe(true);
expect(chamber(state, 1).heat).toBeLessThan(3);
});
});
describe("hunger adaptation — benefit + inedibility spillover", () => {
it("benefit: Dormancy prevents hunger loss (adapted producer survives starvation)", () => {
const adapted = makeState([{ slot: 0, producer: 3 }], { unlocked: { producer: ["hunger"] } });
const plain = makeState([{ slot: 0, producer: 3 }]);
const a = nextState(adapted, A("A", "cw")).state;
const p = nextState(plain, A("A", "cw")).state;
expect(chamber(a, 1).producer).toBeGreaterThan(chamber(p, 1).producer); // plain starves -1
expect(chamber(a, 1).producer).toBe(3);
});
it("spillover: dormant producer is inedible to grazers", () => {
const dormant = makeState([{ slot: 0, producer: 3, grazer: 1 }], { unlocked: { producer: ["hunger"] } });
const edible = makeState([{ slot: 0, producer: 3, grazer: 1 }]);
const d = nextState(dormant, A("A", "cw")).state;
const e = nextState(edible, A("A", "cw")).state;
expect(chamber(d, 1).producer).toBeGreaterThan(chamber(e, 1).producer); // dormant not eaten
expect(chamber(d, 1).grazer).toBeLessThanOrEqual(chamber(e, 1).grazer); // dormant grazer doesn't feed
});
});
describe("toxin adaptation — benefit + carrier cost + spillover", () => {
const toxinState = (unlocked: boolean) =>
makeState([{ slot: 0, nutrient: 6, producer: 3, toxin: 3 }], { unlocked: unlocked ? { producer: ["toxin"] } : {} });
it("Efflux prevents toxin loss (adapted survives better) and cleanses toxin (spillover)", () => {
const adapted = nextState(toxinState(true), A("A", "cw"));
const plain = nextState(toxinState(false), A("A", "cw"));
expect(chamber(adapted.state, 1).producer).toBeGreaterThan(chamber(plain.state, 1).producer);
expect(adapted.events.some((e) => e.kind === "toxin-spillover")).toBe(true);
expect(adapted.events.some((e) => e.kind === "toxin-cost")).toBe(true);
// adapted chamber toxin reduced by spillover relative to plain
expect(chamber(adapted.state, 1).toxin).toBeLessThanOrEqual(chamber(plain.state, 1).toxin);
});
});
describe("immunity adaptation — selection, cloak, retarget, carrier cost", () => {
it("immune node selects and damages the largest eligible lineage", () => {
const s = makeState([{ slot: 6, producer: 3, nutrient: 6 }], { scenarioId: "test-immune" });
const { state, events } = nextState(s, A("A", "cw")); // slot6 not in A, unmoved
expect(chamber(state, 6).producer).toBeLessThan(3); // took damage
expect(events.some((e) => e.kind === "immune-damage")).toBe(true);
});
it("Cloak excludes a lineage from immune selection (no immune damage)", () => {
const cloaked = makeState([{ slot: 6, producer: 3, nutrient: 6 }], { scenarioId: "test-immune", unlocked: { producer: ["immunity"] } });
const { state, events } = nextState(cloaked, A("A", "cw"));
expect(events.some((e) => e.kind === "immune-damage")).toBe(false);
expect(chamber(state, 6).producer).toBeGreaterThanOrEqual(3); // untouched by the node (may grow)
});
it("Cloak causes retarget spillover to the other lineage", () => {
// Cloaked grazer is the largest at the node; producer is selected instead.
const s = makeState([{ slot: 6, grazer: 4, producer: 2, nutrient: 6 }], { scenarioId: "test-immune", unlocked: { grazer: ["immunity"] } });
const { state, events } = nextState(s, A("A", "cw"));
expect(events.some((e) => e.kind === "immune-retarget")).toBe(true);
expect(chamber(state, 6).producer).toBeLessThanOrEqual(2); // producer (retarget target) takes damage
});
it("Cloak carrier cost: predator removes an extra prey at the immune node", () => {
const cloaked = makeState([{ slot: 6, grazer: 3, phage: 1, producer: 3, nutrient: 6 }], { scenarioId: "test-immune", unlocked: { grazer: ["immunity"] } });
const plain = makeState([{ slot: 6, grazer: 3, phage: 1, producer: 3, nutrient: 6 }], { scenarioId: "test-immune" });
const c = nextState(cloaked, A("A", "cw"));
const p = nextState(plain, A("A", "cw"));
expect(c.events.some((e) => e.kind === "cloak-cost")).toBe(true);
// cloaked grazer loses MORE to the phage than a non-cloaked one (2 vs 1 removed)
expect(chamber(c.state, 6).grazer).toBeLessThan(chamber(p.state, 6).grazer);
});
});
describe("immutability, determinism, terminal precedence", () => {
it("does not mutate its input", () => {
const s = makeState([{ slot: 0, nutrient: 3, producer: 2, grazer: 1 }]);
const before = canonicalStringify(s);
nextState(s, A("A", "cw"));
expect(canonicalStringify(s)).toBe(before);
});
it("produces identical canonical output for identical input + action", () => {
const s = makeState([{ slot: 0, nutrient: 3, producer: 2 }, { slot: 6, grazer: 2 }]);
const r1 = nextState(cloneState(s), A("A", "cw"));
const r2 = nextState(cloneState(s), A("A", "cw"));
expect(canonicalStringify(r1.state)).toBe(canonicalStringify(r2.state));
});
it("collapse takes precedence over a win condition", () => {
const s = makeState([{ slot: 0, toxin: 2 }], { scenarioId: "test-win" }); // no biomass; checkWin always true
const { state } = nextState(s, A("A", "cw"));
expect(state.outcome).toBe("collapsed");
});
it("win takes precedence over turn-limit expiration", () => {
const s = makeState([{ slot: 0, producer: 1, nutrient: 6 }], { scenarioId: "test-win", turn: 4 }); // survives; resolvedTurn 5 == limit
const { state } = nextState(s, A("A", "cw"));
expect(state.outcome).toBe("won");
});
it("expires at the turn limit when not won", () => {
const s = makeState([{ slot: 0, producer: 1, nutrient: 6 }], { turn: 98 }); // survives; resolvedTurn 99 == limit 99
const { state } = nextState(s, A("A", "cw"));
expect(state.outcome).toBe("expired");
});
it("rejects actions in a terminal state without changing domain state", () => {
const s = makeState([{ slot: 0, producer: 1 }], { outcome: "won" });
const { state, rejected } = nextState(s, A("A", "cw"));
expect(rejected).toBe(true);
expect(canonicalEqual(state, s)).toBe(true);
});
});
describe("preview == commit, and replay reproduction", () => {
it("preview equals commit for every action across all campaign baselines", () => {
for (const sc of SCENARIOS) {
const base = buildBaselineState(sc.id, "standalone");
for (const action of ALL_ACTIONS) {
const preview = nextState(cloneState(base), action).state;
const commit = nextState(cloneState(base), action).state;
expect(canonicalEqual(preview, commit)).toBe(true);
}
}
});
it("replaying an action log from baseline reproduces the final state", () => {
const base = buildBaselineState(SCENARIOS[0].id, "standalone");
let cur = cloneState(base);
const log: RotationAction[] = [];
const seq: RotationAction[] = [A("A", "cw"), A("B", "ccw"), A("C", "cw"), A("A", "ccw"), A("C", "ccw")];
for (const action of seq) {
if (cur.outcome !== "playing") break;
const { state } = nextState(cur, action);
cur = state;
log.push(action);
}
let replayed = cloneState(base);
for (const action of log) replayed = nextState(replayed, action).state;
expect(canonicalEqual(replayed, cur)).toBe(true);
});
});