(Adaptive Loop) Pass 1

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).
This commit is contained in:
AlexKucera committed 2026-08-12 22:06:09 +02:00
1 parent dc8bfd6846
commit bd7203fc9e
31 files changed
+7113

No files matched your search

+402
View File
@@ -0,0 +1,402 @@
// Adaptive Loop — bounded deterministic solver (SPEC §9, §15 Gate 4).
// Proves one winning and one losing route per scenario via canonical-state BFS,
// the shared-ownership counterfactual, and reachable campaign inheritance sets.
import { nextState, allActions } from "./pipeline";
import { createScenarioState } from "./scenario";
import { SCENARIOS } from "../content/scenarios";
import type { InheritanceSet } from "../content/scenarios";
import type { GameState, RotationAction, LineageId, PressureId, Outcome } from "./types";
import { LINEAGE_IDS, PRESSURE_IDS } from "./types";
export interface SolveResult {
win: RotationAction[] | null;
lose: RotationAction[] | null;
explored: number;
winOutcome: Outcome | null;
loseOutcome: Outcome | null;
capped: boolean;
}
const ACTIONS = allActions();
function fastHash(s: GameState): string {
// FNV-1a of raw JSON (key order is stable for cloned states built the same way).
const str = JSON.stringify(s);
let h = 0x811c9dc5;
for (let i = 0; i < str.length; i++) {
h ^= str.charCodeAt(i);
h = Math.imul(h, 0x01000193);
}
return (h >>> 0).toString(36);
}
type SolveOpts = { freezeOwnership?: boolean; maxNodes?: number; timeMs?: number; seed?: number };
function mkRng(seed: number) {
let s = seed >>> 0;
return () => {
s = (Math.imul(s, 1664525) + 1013904223) >>> 0;
return s / 0x100000000;
};
}
function shuffled<T>(arr: T[], rng: () => number): T[] {
const a = arr.slice();
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(rng() * (i + 1));
const tmp = a[i]!; a[i] = a[j]!; a[j] = tmp;
}
return a;
}
// --- heuristic scoring for guided search (health + objective proximity) ---
function totalPersistentOf(s: GameState): number {
let n = 0;
for (const c of s.chambers) n += c.producer + c.grazer;
return n;
}
function scoreState(s: GameState): number {
if (s.outcome === "won") return 1e9;
if (s.outcome !== "playing") return -1e8; // collapsed/expired
const sc = SCENARIOS.find((x) => x.id === s.scenarioId);
let occP = 0, occG = 0, totNut = 0, totTox = 0, totHeat = 0;
for (const c of s.chambers) {
if (c.producer > 0) occP++;
if (c.grazer > 0) occG++;
totNut += c.nutrient;
totTox += c.toxin;
totHeat += c.heat;
}
let score = totalPersistentOf(s) * 100 + (occP + occG) * 12 + totNut * 3 - totTox * 6 - totHeat * 2;
const w = sc?.win;
if (w) {
switch (w.kind) {
case "producerAt":
score += (s.chambers[w.slot]?.producer ?? 0) * 60;
break;
case "endurance":
score += Math.min(occP, w.producerChambersMin) * 8 + Math.min(occG, w.grazerChambersMin) * 8;
break;
case "cleanse":
score -= totTox * 25;
break;
case "escort":
score += (s.chambers[w.slot]?.grazer ?? 0) * 60 + (s.chambers[w.slot]?.phage ?? 0) * 40;
break;
case "sustained": {
const ok = s.chambers[1]!.producer + s.chambers[1]!.grazer >= 2 && s.chambers[7]!.producer + s.chambers[7]!.grazer >= 2 && s.chambers[11]!.producer + s.chambers[11]!.grazer >= 2;
score += ok ? 400 : 0;
score += s.consecutiveObjectiveTurns * 300;
break;
}
}
}
return score;
}
/** Beam search guided by scoreState. Reliably finds wins for routing/survival puzzles. */
export function beamSearch(
scenarioId: string,
inheritance: InheritanceSet,
opts: SolveOpts & { beamWidth?: number } = {},
): { route: RotationAction[] | null; explored: number; capped: boolean } {
const beamWidth = opts.beamWidth ?? 400;
const start = createScenarioState(scenarioId, "standalone", inheritance);
const limit = SCENARIOS.find((x) => x.id === scenarioId)?.turnLimit ?? 12;
type N = { s: GameState; path: RotationAction[]; score: number };
let beam: N[] = [{ s: start, path: [], score: scoreState(start) }];
let explored = 0;
const seen = new Map<string, number>();
seen.set(fastHash(start), 0);
for (let depth = 0; depth < limit; depth++) {
const cand: N[] = [];
for (const node of beam) {
for (const a of ACTIONS) {
explored++;
const ns = nextState(node.s, a, opts).state;
const path = node.path.length ? [...node.path, a] : [a];
if (ns.outcome === "won") return { route: path, explored, capped: false };
if (ns.outcome !== "playing") continue;
const h = fastHash(ns);
const prev = seen.get(h);
const minLen = path.length;
if (prev !== undefined && prev <= minLen) continue;
seen.set(h, minLen);
cand.push({ s: ns, path, score: scoreState(ns) });
}
}
if (cand.length === 0) break;
cand.sort((x, y) => y.score - x.score);
beam = cand.slice(0, beamWidth);
}
return { route: null, explored, capped: false };
}
/** Memory-light randomized DFS that finds ONE route reaching `target` outcome. */
export function findRoute(
scenarioId: string,
inheritance: InheritanceSet,
target: "won" | "lose",
opts: SolveOpts = {},
): { route: RotationAction[] | null; explored: number; capped: boolean } {
const maxNodes = opts.maxNodes ?? 1_500_000;
const timeMs = opts.timeMs ?? 90_000;
const rng = mkRng(opts.seed ?? 0xC0FFEE);
const start = createScenarioState(scenarioId, "standalone", inheritance);
const t0 = Date.now();
let explored = 0;
let capped = false;
// capped memo: dedup while small, drop once full to bound memory
const memo = new Set<string>();
const memoCap = 250_000;
let memoOn = true;
function rec(s: GameState): RotationAction[] | null {
if (s.outcome !== "playing") return null;
if (Date.now() - t0 > timeMs || explored > maxNodes) {
capped = true;
return null;
}
for (const a of shuffled(ACTIONS, rng)) {
explored++;
const ns = nextState(s, a, opts).state;
const hit = target === "won" ? ns.outcome === "won" : ns.outcome === "collapsed" || ns.outcome === "expired";
if (hit) return [a];
if (ns.outcome === "playing") {
let proceed = true;
if (memoOn) {
const h = fastHash(ns);
if (memo.has(h)) proceed = false;
else {
memo.add(h);
if (memo.size > memoCap) memoOn = false;
}
}
if (proceed) {
const sub = rec(ns);
if (sub) return [a, ...sub];
if (capped) return null;
}
}
}
return null;
}
const route = rec(start);
return { route, explored, capped };
}
/** Bounded BFS over canonical states. Returns first win route and first lose route. */
export function solve(
scenarioId: string,
inheritance: InheritanceSet = {},
opts: SolveOpts = {},
): SolveResult {
const maxNodes = opts.maxNodes ?? 500_000;
const timeMs = opts.timeMs ?? 60_000;
const start = createScenarioState(scenarioId, "standalone", inheritance);
const seen = new Set<string>([fastHash(start)]);
type Node = { s: GameState; path: RotationAction[] };
const queue: Node[] = [{ s: start, path: [] }];
let head = 0;
let explored = 0;
let win: RotationAction[] | null = null;
let lose: RotationAction[] | null = null;
let winOutcome: Outcome | null = null;
let loseOutcome: Outcome | null = null;
let capped = false;
const t0 = Date.now();
while (head < queue.length) {
const { s, path } = queue[head++]!;
explored++;
if (explored > maxNodes || Date.now() - t0 > timeMs) {
capped = true;
break;
}
for (const a of ACTIONS) {
const ns = nextState(s, a, opts).state;
const npath = path.length ? [...path, a] : [a];
if (ns.outcome === "won" && !win) {
win = npath;
winOutcome = "won";
} else if ((ns.outcome === "collapsed" || ns.outcome === "expired") && !lose) {
lose = npath;
loseOutcome = ns.outcome;
}
if (win && lose) {
return { win, lose, explored, winOutcome, loseOutcome, capped: false };
}
if (ns.outcome === "playing") {
const h = fastHash(ns);
if (!seen.has(h)) {
seen.add(h);
queue.push({ s: ns, path: npath });
}
}
}
}
queue.length = 0;
return { win, lose, explored, winOutcome, loseOutcome, capped };
}
/**
* Memory-light EXHAUSTIVE DFS (stores only state hashes). Visits every reachable
* state once. Returns win route if any reachable, plus statesSeen and whether the
* full reachable space was exhausted (proves unwinnable when win=null & complete=true).
*/
export function exhaust(
scenarioId: string,
inheritance: InheritanceSet = {},
opts: { freezeOwnership?: boolean; maxStates?: number } = {},
): { win: RotationAction[] | null; statesSeen: number; complete: boolean } {
const maxStates = opts.maxStates ?? 4_000_000;
const start = createScenarioState(scenarioId, "standalone", inheritance);
const seen = new Set<string>();
let win: RotationAction[] | null = null;
let complete = true;
// iterative DFS (bounded stack; safe for very large state spaces)
type Frame = { s: GameState; path: RotationAction[]; ai: number };
const stack: Frame[] = [];
function consider(s: GameState, path: RotationAction[]): boolean {
if (s.outcome === "won") {
win = path;
return true;
}
if (s.outcome !== "playing") return false;
const h = fastHash(s);
if (seen.has(h)) return false;
if (seen.size >= maxStates) {
complete = false;
return true; // signal stop
}
seen.add(h);
stack.push({ s, path, ai: 0 });
return false;
}
if (consider(start, [])) {
return { win, statesSeen: seen.size, complete };
}
while (stack.length && !win && complete) {
const top = stack[stack.length - 1]!;
if (top.ai >= ACTIONS.length) {
stack.pop();
continue;
}
const a = ACTIONS[top.ai++]!;
const ns = nextState(top.s, a, opts).state;
const npath = top.path.length ? [...top.path, a] : [a];
if (consider(ns, npath)) {
if (win || !complete) break;
}
}
return { win, statesSeen: seen.size, complete };
}
/** Which traits unlocked along a route (beyond inherited). */
export function unlockedAlong(
scenarioId: string,
inheritance: InheritanceSet,
route: RotationAction[],
): { lineage: LineageId; pressure: PressureId }[] {
let s = createScenarioState(scenarioId, "standalone", inheritance);
const inherited = new Set<string>();
for (const lid of LINEAGE_IDS)
for (const p of inheritance[lid] ?? []) inherited.add(`${lid}:${p}`);
const became = new Set<string>();
const apply = (lid: LineageId, p: PressureId) => {
if (s.lineage[lid].unlocked[p] && !inherited.has(`${lid}:${p}`)) became.add(`${lid}:${p}`);
};
for (const lid of LINEAGE_IDS) for (const p of PRESSURE_IDS) apply(lid, p);
for (const a of route) {
s = nextState(s, a).state;
for (const lid of LINEAGE_IDS) for (const p of PRESSURE_IDS) apply(lid, p);
if (s.outcome !== "playing") break;
}
return [...became].map((k) => {
const [lineage, pressure] = k.split(":") as [LineageId, PressureId];
return { lineage, pressure };
});
}
export interface ReachableSet {
set: InheritanceSet;
key: string;
}
function inheritanceKey(is: InheritanceSet): string {
return LINEAGE_IDS.map((lid) => `${lid}=(${(is[lid] ?? []).join(",")})`).join("|");
}
/**
* Enumerate reachable campaign inheritance sets by solving each scenario with
* each reachable set, then branching on 0 or 1 newly-unlocked trait from the
* found winning route. Returns the tree of sets and solvability per (scenario,set).
*/
export interface ReachabilityReport {
perScenario: {
scenarioId: string;
sets: { key: string; set: InheritanceSet; solvable: boolean; win?: RotationAction[] | null; capped?: boolean }[];
}[];
}
export function verifyReachability(opts?: { maxNodes?: number }): ReachabilityReport {
const report: ReachabilityReport = { perScenario: [] };
let frontier: ReachableSet[] = [{ set: {}, key: inheritanceKey({}) }];
for (const sc of SCENARIOS) {
const entries: ReachabilityReport["perScenario"][number]["sets"] = [];
const next: ReachableSet[] = [];
const seenKeys = new Set<string>();
for (let i = 0; i < frontier.length; i++) {
const item = frontier[i]!;
// Light win-finder (memory-bounded); fall back to exhaustive BFS if it caps.
const fr = findRoute(sc.id, item.set, "won", { ...(opts as SolveOpts), seed: 0x1234 + i });
let win: RotationAction[] | null = fr.route;
let capped = fr.capped;
if (!win && !capped) {
// confirm with exhaustive search on smaller spaces
const res = solve(sc.id, item.set, opts);
win = res.win;
capped = res.capped;
}
entries.push({ key: item.key, set: item.set, solvable: win !== null, win, capped });
if (win) {
const unlocked = unlockedAlong(sc.id, item.set, win);
// branch: keep nothing, or keep one unlocked trait
const candidates: ReachableSet[] = [{ set: item.set, key: item.key }];
for (const u of unlocked) {
const ns: InheritanceSet = {
producer: [...(item.set.producer ?? [])],
grazer: [...(item.set.grazer ?? [])],
};
ns[u.lineage] = [...new Set([...(ns[u.lineage] ?? []), u.pressure])].sort() as PressureId[];
const k = inheritanceKey(ns);
candidates.push({ set: ns, key: k });
}
for (const c of candidates) {
if (!seenKeys.has(c.key)) {
seenKeys.add(c.key);
next.push(c);
}
}
}
}
report.perScenario.push({ scenarioId: sc.id, sets: entries });
frontier = next;
if (frontier.length === 0) break; // unsolvable predecessor; stop
}
return report;
}
/** Counterfactual: freeze sharedOwner at baseline. At least one scenario must be unwinnable. */
export function counterfactualUnwinnable(
scenarioId: string,
opts?: { maxNodes?: number },
): { solvableNormal: boolean; solvableFrozen: boolean; normal: SolveResult; frozen: SolveResult } {
const normal = solve(scenarioId, {}, opts);
const frozen = solve(scenarioId, {}, { ...opts, freezeOwnership: true });
return {
solvableNormal: normal.win !== null,
solvableFrozen: frozen.win !== null,
normal,
frozen,
};
}