Files
agentic-labs-challenge/adaptive-loop/dist/assets/index-B-AnQndx.js
T
AlexKucera 2c1d0fc4d0 (Adaptive Loop) Pass 3
(Adaptive Loop) Record freeze commit hash in context manifest
2026-08-13 15:23:35 +02:00

96 lines
45 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const p of r)if(p.type==="childList")for(const u of p.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&i(u)}).observe(document,{childList:!0,subtree:!0});function n(r){const p={};return r.integrity&&(p.integrity=r.integrity),r.referrerPolicy&&(p.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?p.credentials="include":r.crossOrigin==="anonymous"?p.credentials="omit":p.credentials="same-origin",p}function i(r){if(r.ep)return;r.ep=!0;const p=n(r);fetch(r.href,p)}})();const ie={middle:12,outer:18},_={heat:"Heat Shield",hunger:"Dormancy",toxin:"Efflux",immunity:"Cloak"},H={heat:{label:"Heat",color:"#ff8a4c",icon:"sun",trait:"Heat Shield",response:"Heat sources add 3"},hunger:{label:"Hunger",color:"#b388ff",icon:"crescent",trait:"Dormancy",response:"Nutrient inlets add 1"},toxin:{label:"Toxin",color:"#7fd66b",icon:"skull",trait:"Efflux",response:"Toxin inlets add 3"},immunity:{label:"Immunity",color:"#5fd0ff",icon:"shield",trait:"Cloak",response:"Immune damage 3"}},F=6;function z(e,t,n){return e<t?t:e>n?n:e}function ae(){return{nutrient:0,heat:0,toxin:0,producer:0,grazer:0,phage:0}}function te(e){return{nutrient:e.nutrient,heat:e.heat,toxin:e.toxin,producer:e.producer,grazer:e.grazer,phage:e.phage}}function Ve(e){return{schemaVersion:1,mode:e.mode,scenarioId:e.scenarioId,turn:e.turn,rings:{inner:{direction:e.rings.inner.direction,tiles:e.rings.inner.tiles.map(te)},middle:{direction:e.rings.middle.direction,tiles:e.rings.middle.tiles.map(te)},outer:{direction:e.rings.outer.direction,tiles:e.rings.outer.tiles.map(te)}},lineage:{producer:{pressure:{...e.lineage.producer.pressure},unlocked:{...e.lineage.producer.unlocked}},grazer:{pressure:{...e.lineage.grazer.pressure},unlocked:{...e.lineage.grazer.unlocked}}},inheritedAtStart:{producer:[...e.inheritedAtStart.producer],grazer:[...e.inheritedAtStart.grazer]},consecutiveObjectiveTurns:e.consecutiveObjectiveTurns,environmentActive:{...e.environmentActive},outcome:e.outcome,actionLog:e.actionLog.map(t=>({ring:t.ring,dir:t.dir}))}}function be(e,t,n){return n==="cw"?(e+1)%t:(e+t-1)%t}function De(e,t){const n=e.length,i=new Array(n);for(let r=0;r<n;r++){const p=t==="cw"?(r+1)%n:(r+n-1)%n;i[p]=e[r]}return i}function ee(e,t){return e==="inner"?t:e==="middle"?2*t%ie.middle:3*t%ie.outer}function Be(e,t){return e==="inner"?t:e==="middle"?t%2===0?t/2:-1:t%3===0?t/3:-1}function y(e){const t=e[0];return{ring:t==="I"?"inner":t==="M"?"middle":"outer",index:parseInt(e.slice(1),10)}}function v(e,t,n,i,r,p,u){return{...y(e),chamber:{nutrient:t,producer:n,grazer:i,phage:r,heat:p,toxin:u}}}const _e=[{id:"s1-heat",index:1,name:"Cultivation Quota",subtitle:"Heat",turnLimit:8,starts:[v("O0",3,2,0,0,0,0),v("O6",3,2,0,0,0,0),v("M2",2,1,0,0,0,0),v("I0",1,0,0,0,0,0)],fixtures:[{kind:"nutrientInlet",...y("O0")},{kind:"nutrientInlet",...y("O6")},{kind:"heatSource",...y("O3")},{kind:"heatSource",...y("O9")}],teaches:"Ring rotation, gate alignment, inward nutrient flow, growth, preview, and the first pressure: heat."},{id:"s2-hunger",index:2,name:"Endurance",subtitle:"Hunger",turnLimit:10,starts:[v("O0",2,3,0,0,0,0),v("M2",1,2,1,0,0,0),v("M8",2,3,1,0,0,0),v("I4",0,2,2,0,0,0)],fixtures:[{kind:"nutrientInlet",...y("O0")}],teaches:"Competition, migration through gates, dormancy, and denying predator food."},{id:"s3-toxin",index:3,name:"Cleansing",subtitle:"Toxin",turnLimit:9,starts:[v("O0",3,3,0,0,0,0),v("O3",0,0,0,0,0,3),v("M4",2,3,0,0,0,0),v("O9",0,0,0,0,0,3),v("I5",2,2,1,0,0,0)],fixtures:[{kind:"nutrientInlet",...y("O0")},{kind:"drain",...y("I1")},{kind:"drain",...y("I3")}],teaches:"Routing contaminants inward to drains, resistance payment, and shared detoxification spillover."},{id:"s4-immunity",index:4,name:"Escort",subtitle:"Immunity",turnLimit:8,starts:[v("M2",2,3,0,0,0,0),v("M8",2,3,2,0,0,0),v("M0",3,3,1,0,0,0),v("I0",0,2,1,0,0,0),v("O5",0,0,0,1,0,0),v("O11",1,0,2,1,0,0)],fixtures:[{kind:"nutrientInlet",...y("O0")},{kind:"nutrientInlet",...y("O2")},{kind:"immuneNode",...y("I1")},{kind:"immuneNode",...y("I3")},{kind:"objective",...y("I0"),label:"sanctuary"}],teaches:"Immune targeting, cloak, retargeting spillover, and predator vulnerability."},{id:"s5-convergence",index:5,name:"Stable Equilibrium",subtitle:"Convergence",turnLimit:12,starts:[v("O0",3,3,0,0,0,0),v("O1",0,1,0,0,0,0),v("O17",0,1,0,0,0,0),v("O2",0,0,0,0,0,2),v("O8",0,0,0,0,2,0),v("M0",2,2,1,0,0,0),v("M1",0,1,0,0,0,0),v("M11",0,1,0,0,0,0),v("M2",2,2,1,0,0,0),v("M8",2,2,2,1,0,0),v("I0",0,2,1,0,0,0),v("I1",0,1,0,0,0,0),v("I3",0,0,0,0,0,1),v("I5",0,1,0,0,0,0)],fixtures:[{kind:"nutrientInlet",...y("O0")},{kind:"nutrientInlet",...y("O6")},{kind:"heatSource",...y("O3")},{kind:"heatSource",...y("O9")},{kind:"drain",...y("I3")},{kind:"immuneNode",...y("I2")},{kind:"objective",...y("I0"),label:"assay"},{kind:"objective",...y("M0"),label:"assay"},{kind:"objective",...y("O0"),label:"assay"}],teaches:"All systems plus inherited gift-and-burden consequences."}];function ke(e){const t={heat:0,hunger:0,toxin:0,immunity:0},n={heat:!1,hunger:!1,toxin:!1,immunity:!1};for(const i of e)n[i]=!0;return{pressure:t,unlocked:n}}function Le(e,t,n={producer:[],grazer:[]}){const i={inner:{direction:"cw",tiles:Array.from({length:6},()=>ae())},middle:{direction:"cw",tiles:Array.from({length:12},()=>ae())},outer:{direction:"cw",tiles:Array.from({length:18},()=>ae())}};for(const r of e.starts){const p=i[r.ring].tiles[r.index];i[r.ring].tiles[r.index]={...te(p),...r.chamber}}return{schemaVersion:1,mode:t,scenarioId:e.id,turn:0,rings:i,lineage:{producer:ke(n.producer),grazer:ke(n.grazer)},inheritedAtStart:{producer:[...n.producer],grazer:[...n.grazer]},consecutiveObjectiveTurns:0,environmentActive:{heat:!1,hunger:!1,toxin:!1,immunity:!1},outcome:"playing",actionLog:[]}}function Y(e,t){const{ring:n,index:i}=y(t);return e.rings[n].tiles[i]}function W(e){let t=0;for(const n of["inner","middle","outer"])for(const i of e.rings[n].tiles)t+=i.producer;return t}function ce(e){let t=0;for(const n of["inner","middle","outer"])for(const i of e.rings[n].tiles)t+=i.grazer;return t}function Qe(e){let t=0;for(const n of["inner","middle","outer"])for(const i of e.rings[n].tiles)t+=i.phage;return t}function ye(e){let t=0;for(const n of["inner","middle","outer"])for(const i of e.rings[n].tiles)t+=i.toxin;return t}function we(e,t){let n=0;for(const i of["inner","middle","outer"])for(const r of e.rings[i].tiles)r[t]>0&&n++;return n}const C=_e.map(e=>{const t={...e,sustained:()=>!1,win:()=>!1};return e.id==="s1-heat"?t.win=({state:n})=>Y(n,"I0").producer>=4&&W(n)>=12:e.id==="s2-hunger"?t.win=({state:n,resolvedTurn:i})=>i===10&&W(n)>=8&&ce(n)>=4&&we(n,"producer")>=3&&we(n,"grazer")>=2:e.id==="s3-toxin"?t.win=({state:n,resolvedTurn:i})=>i>=6&&i<=9&&ye(n)<=4&&W(n)+ce(n)>=8:e.id==="s4-immunity"?t.win=({state:n})=>Y(n,"I0").grazer>=3&&W(n)>=6:e.id==="s5-convergence"&&(t.sustained=n=>{const i=Y(n,"I0"),r=Y(n,"M0"),p=Y(n,"O0"),k=[i.producer+i.grazer>=1,r.producer+r.grazer>=1,p.producer+p.grazer>=1].filter(Boolean).length>=2,I=W(n),b=ce(n);return k&&I>=4&&I<=30&&b>=1&&b<=10&&Qe(n)<=5&&ye(n)<=8},t.win=({resolvedTurn:n,consecutive:i})=>i>=2&&n<=12),t});function he(e){const t=C.find(n=>n.id===e)??Ye[e];if(!t)throw new Error(`Unknown scenario: ${e}`);return t}const Ye={test:{id:"test",index:0,name:"Test",subtitle:"",turnLimit:99,starts:[],fixtures:[],sustained:()=>!1,win:()=>!1,teaches:""}};function We(e){const t=new Map;for(const n of e.fixtures){const i=`${n.ring}:${n.index}`;t.has(i)||t.set(i,[]),t.get(i).push({kind:n.kind,label:n.label})}return t}const E=["outer","middle","inner"],Ke=[];function Fe(e,t){return t==="producer"?e.nutrient:t==="grazer"?e.producer:e.grazer}function Ue(e){const t=new Map;for(const n of e.fixtures){const i=`${n.ring}:${n.index}`;t.has(i)||t.set(i,[]),t.get(i).push(n.kind)}return(n,i)=>t.get(`${n}:${i}`)??Je}const Je=[];function Ae(e,t,n=!0){const i=he(e.scenarioId),r=Ve(e),p=n?[]:Ke,u=s=>{n&&p.push(s)},k=Ue(i);r.rings[t.ring].tiles=De(r.rings[t.ring].tiles,t.dir),r.rings[t.ring].direction=t.dir,u({phase:"rotate",ring:t.ring,dir:t.dir});for(const s of["nutrient","toxin"]){const l={inner:r.rings.inner.tiles.map(a=>a[s]),middle:r.rings.middle.tiles.map(a=>a[s]),outer:r.rings.outer.tiles.map(a=>a[s])},o={inner:[0,0,0,0,0,0],middle:q(12),outer:q(18)},d={inner:[0,0,0,0,0,0],middle:q(12),outer:q(18)},f={inner:[0,0,0,0,0,0],middle:q(12),outer:q(18)};for(const a of E){const g=l[a].length,x=r.rings[a].direction;for(let m=0;m<g;m++)if(l[a][m]>=1){const w=be(m,g,x);o[a][m]+=1,f[a][m]+=1,d[a][w]+=1}}for(let a=0;a<6;a++){const g=ee("outer",a),x=ee("middle",a),m=ee("inner",a);l.outer[g]>=1&&(o.outer[g]+=1,d.middle[x]+=1),l.middle[x]>=1&&(o.middle[x]+=1,d.inner[m]+=1)}for(const a of E)for(let g=0;g<l[a].length;g++){const x=l[a][g],m=z(x-o[a][g]+d[a][g],0,F);m!==x&&(r.rings[a].tiles[g][s]=m,u({phase:"flow",ring:a,index:g,field:s,delta:m-x,tangential:f[a][g],radial:o[a][g]-f[a][g]}))}}for(const s of E)for(let l=0;l<r.rings[s].tiles.length;l++){const o=r.rings[s].tiles[l];if(o.producer>=1&&o.nutrient>=1){if(r.lineage.producer.unlocked.heat&&o.heat>=2){u({phase:"growth",ring:s,index:l,gained:0,suppressed:!0});continue}o.nutrient-=1;const f=o.producer;o.producer=z(o.producer+1,0,F),u({phase:"growth",ring:s,index:l,gained:o.producer-f,suppressed:!1})}}{const s=K(r,"producer"),l=K(r,"grazer");for(const o of E)for(let d=0;d<r.rings[o].tiles.length;d++){const f=r.rings[o].tiles[d];if(l[o][d]>=1){const a=r.lineage.producer.unlocked.hunger&&f.nutrient===0,g=s[o][d]>=1&&!a,x=r.lineage.grazer.unlocked.heat&&f.heat>=2;if(g&&!x){const m=k(o,d).includes("immuneNode"),S=r.lineage.producer.unlocked.immunity&&m?2:1;f.producer=z(f.producer-S,0,F);const P=f.grazer;f.grazer=z(f.grazer+1,0,F),u({phase:"feed",ring:o,index:d,predator:"grazer",preyRemoved:S,gained:f.grazer>P})}}}}{const s=K(r,"grazer"),l=K(r,"phage");for(const o of E)for(let d=0;d<r.rings[o].tiles.length;d++){const f=r.rings[o].tiles[d];if(l[o][d]>=1){const a=r.lineage.grazer.unlocked.hunger&&f.producer===0;if(s[o][d]>=1&&!a){const x=k(o,d).includes("immuneNode"),w=r.lineage.grazer.unlocked.immunity&&x?2:1;f.grazer=z(f.grazer-w,0,F);const S=f.phage;f.phage=z(f.phage+1,0,F),u({phase:"feed",ring:o,index:d,predator:"phage",preyRemoved:w,gained:f.phage>S})}else f.phage=z(f.phage-1,0,F),u({phase:"feed",ring:o,index:d,predator:"phage",preyRemoved:0,gained:!1,phageStarve:!0})}}}for(const s of["producer","grazer","phage"]){const l=K(r,s),o=[];for(const a of E){const g=r.rings[a].tiles.length,x=r.rings[a].direction;for(let m=0;m<g;m++){if(l[a][m]<2)continue;const w=s==="producer"?r.lineage.producer:s==="grazer"?r.lineage.grazer:null,S=Fe(r.rings[a].tiles[m],s);if(w?w.unlocked.hunger&&S===0:!1)continue;const N=[];N.push({ring:a,index:be(m,g,x)});const Q=Be(a,m);if(Q>=0){const j=a==="inner"?["middle"]:a==="outer"?["middle"]:["inner","outer"];for(const A of j)N.push({ring:A,index:ee(A,Q)})}let T=null;for(const j of N){const A=Fe(r.rings[j.ring].tiles[j.index],s);A>S&&(!T||A>T.food)&&(T={ring:j.ring,index:j.index,food:A})}T&&o.push({from:a,fi:m,toRing:T.ring,toIndex:T.index})}}const d={},f=(a,g)=>`${a}:${g}`;for(const a of o)d[f(a.from,a.fi)]=(d[f(a.from,a.fi)]??0)-1,d[f(a.toRing,a.toIndex)]=(d[f(a.toRing,a.toIndex)]??0)+1;for(const[a,g]of Object.entries(d)){const[x,m]=a.split(":"),w=x,S=+m,P=r.rings[w].tiles[S];P[s]=z(P[s]+g,0,F),g!==0&&u({phase:"migrate",from:a,to:a,species:s})}}for(const s of["producer","grazer"])for(const l of["heat","hunger","toxin","immunity"])r.lineage[s].pressure[l]>=3&&!r.lineage[s].unlocked[l]&&(r.lineage[s].unlocked[l]=!0,u({phase:"evolution",lineage:s,pressure:l,unlocked:!0}));for(const s of["heat","hunger","toxin","immunity"])(r.lineage.producer.pressure[s]>=3||r.lineage.grazer.pressure[s]>=3)&&!r.environmentActive[s]&&(r.environmentActive[s]=!0,u({phase:"env",pressure:s,active:!0}));for(const s of E)for(let l=0;l<r.rings[s].tiles.length;l++){const o=k(s,l),d=r.rings[s].tiles[l];if(o.includes("nutrientInlet")){const f=r.environmentActive.hunger?1:2,a=d.nutrient;d.nutrient=z(d.nutrient+f,0,F),d.nutrient!==a&&u({phase:"fixture",ring:s,index:l,kind:"nutrientInlet",field:"nutrient",delta:d.nutrient-a})}if(o.includes("heatSource")){const f=r.environmentActive.heat?3:2,a=d.heat;d.heat=z(d.heat+f,0,F),d.heat!==a&&u({phase:"fixture",ring:s,index:l,kind:"heatSource",field:"heat",delta:d.heat-a})}if(o.includes("toxinInlet")){const f=r.environmentActive.toxin?3:2,a=d.toxin;d.toxin=z(d.toxin+f,0,F),d.toxin!==a&&u({phase:"fixture",ring:s,index:l,kind:"toxinInlet",field:"toxin",delta:d.toxin-a})}}for(const s of E)for(let l=0;l<r.rings[s].tiles.length;l++){const o=r.rings[s].tiles[l];o.heat>0&&(o.heat-=1,u({phase:"fixtureGlobal",field:"heat",delta:-1}))}for(const s of E)for(let l=0;l<r.rings[s].tiles.length;l++){const o=k(s,l),d=r.rings[s].tiles[l];if(o.includes("drain")){const f=d.toxin;d.toxin=z(d.toxin-2,0,F),d.toxin!==f&&u({phase:"fixture",ring:s,index:l,kind:"drain",field:"toxin",delta:d.toxin-f})}}const I=[];for(const s of E)for(let l=0;l<r.rings[s].tiles.length;l++){if(!k(s,l).includes("immuneNode"))continue;const o=r.rings[s].tiles[l],d=[];o.producer>=1&&!r.lineage.producer.unlocked.immunity&&d.push({lin:"producer",pop:o.producer}),o.grazer>=1&&!r.lineage.grazer.unlocked.immunity&&d.push({lin:"grazer",pop:o.grazer});const f=o.producer>=1&&r.lineage.producer.unlocked.immunity||o.grazer>=1&&r.lineage.grazer.unlocked.immunity;if(d.length===0)continue;d.sort((x,m)=>m.pop-x.pop||(x.lin==="producer"?-1:1));const a=d[0].lin,g=r.environmentActive.immunity?3:2;I.push({ring:s,index:l,lineage:a,damage:g}),u({phase:"immuneSelect",ring:s,index:l,lineage:a,damage:g,retarget:f&&d.length>=1})}const b={producer:{heat:new Set,hunger:new Set,toxin:new Set,immunity:new Set},grazer:{heat:new Set,hunger:new Set,toxin:new Set,immunity:new Set}};for(const s of E)for(let l=0;l<r.rings[s].tiles.length;l++){const o=r.rings[s].tiles[l],d=`${s}:${l}`;o.producer>=1&&(o.heat>=2&&b.producer.heat.add(d),o.nutrient===0&&b.producer.hunger.add(d),o.toxin>=2&&b.producer.toxin.add(d)),o.grazer>=1&&(o.heat>=2&&b.grazer.heat.add(d),o.producer===0&&b.grazer.hunger.add(d),o.toxin>=2&&b.grazer.toxin.add(d))}for(const s of I)b[s.lineage].immunity.add(`${s.ring}:${s.index}`);for(const s of["producer","grazer"])for(const l of["heat","hunger","toxin","immunity"])if(b[s][l].size>=1){const o=r.lineage[s].pressure[l];r.lineage[s].pressure[l]=Math.min(3,o+1),r.lineage[s].pressure[l]!==o&&u({phase:"pressureInc",lineage:s,pressure:l,to:r.lineage[s].pressure[l]})}for(const s of["producer","grazer"])for(const l of b[s].heat){const[o,d]=l.split(":"),f=+d,a=r.rings[o].tiles[f],g=s==="producer"?"producer":"grazer";if(!(a[g]<=0))if(r.lineage[s].unlocked.heat)u({phase:"consequence",ring:o,index:f,lineage:s,pressure:"heat",kind:"prevented",amount:0});else{const x=a[g];a[g]=z(a[g]-2,0,F),u({phase:"consequence",ring:o,index:f,lineage:s,pressure:"heat",kind:"loss",amount:x-a[g]})}}for(const s of ze([b.producer.heat,b.grazer.heat])){const[l,o]=s.split(":"),d=l,f=+o,a=r.rings[d].tiles[f];let g=0;r.lineage.producer.unlocked.heat&&a.producer>0&&g++,r.lineage.grazer.unlocked.heat&&a.grazer>0&&g++;const x=Math.min(2,g);if(x>0&&a.heat>0){const m=a.heat;a.heat=z(a.heat-x,0,F),u({phase:"spillover",ring:d,index:f,pressure:"heat",field:"heat",reduced:m-a.heat})}}for(const s of["producer","grazer"])for(const l of b[s].hunger){const[o,d]=l.split(":"),f=+d,a=r.rings[o].tiles[f],g=s==="producer"?"producer":"grazer";if(!(a[g]<=0))if(r.lineage[s].unlocked.hunger)u({phase:"consequence",ring:o,index:f,lineage:s,pressure:"hunger",kind:"prevented",amount:0});else{const x=a[g];a[g]=z(a[g]-1,0,F),u({phase:"consequence",ring:o,index:f,lineage:s,pressure:"hunger",kind:"loss",amount:x-a[g]})}}for(const s of ze([b.producer.toxin,b.grazer.toxin])){const[l,o]=s.split(":"),d=l,f=+o,a=r.rings[d].tiles[f];for(const m of["producer","grazer"]){const w=m==="producer"?"producer":"grazer";if(!(a[w]<=0)&&b[m].toxin.has(`${d}:${f}`))if(r.lineage[m].unlocked.toxin)if(a.nutrient>=1)a.nutrient-=1,u({phase:"consequence",ring:d,index:f,lineage:m,pressure:"toxin",kind:"payNutrient",amount:1});else{const S=a[w];a[w]=z(a[w]-1,0,F),u({phase:"consequence",ring:d,index:f,lineage:m,pressure:"toxin",kind:"payPop",amount:S-a[w]})}else{const S=a[w];a[w]=z(a[w]-1,0,F),u({phase:"consequence",ring:d,index:f,lineage:m,pressure:"toxin",kind:"loss",amount:S-a[w]})}}let g=0;r.lineage.producer.unlocked.toxin&&a.producer>0&&g++,r.lineage.grazer.unlocked.toxin&&a.grazer>0&&g++;const x=Math.min(2,g);if(x>0&&a.toxin>0){const m=a.toxin;a.toxin=z(a.toxin-x,0,F),u({phase:"spillover",ring:d,index:f,pressure:"toxin",field:"toxin",reduced:m-a.toxin})}}for(const s of I){const l=r.rings[s.ring].tiles[s.index],o=s.lineage==="producer"?"producer":"grazer";if(l[o]<=0)continue;const d=l[o];l[o]=z(l[o]-s.damage,0,F),u({phase:"consequence",ring:s.ring,index:s.index,lineage:s.lineage,pressure:"immunity",kind:"loss",amount:d-l[o]})}const M=e.turn+1,$=i.sustained(r,{state:r,resolvedTurn:M,consecutive:0,fixturesByTile:()=>[]})?e.consecutiveObjectiveTurns+1:0;r.consecutiveObjectiveTurns=$,r.turn=M,r.actionLog=[...r.actionLog,t];let h=0;for(const s of E)for(const l of r.rings[s].tiles)h+=l.producer+l.grazer;return h===0?r.outcome="collapsed":i.win({state:r,resolvedTurn:M,consecutive:$,fixturesByTile:()=>[]})?r.outcome="won":M>=i.turnLimit?r.outcome="expired":r.outcome="playing",u({phase:"outcome",outcome:r.outcome,turn:M}),{state:r,events:n?p:[]}}function q(e){return new Array(e).fill(0)}function K(e,t){return{inner:e.rings.inner.tiles.map(n=>n[t]),middle:e.rings.middle.tiles.map(n=>n[t]),outer:e.rings.outer.tiles.map(n=>n[t])}}function ze(e){const t=new Set;for(const n of e)for(const i of n)t.add(i);return[...t].sort()}const B=640,V=B/2,D=B/2,Ee={inner:96,middle:168,outer:246},le={inner:30,middle:23,outer:17.5},Te=Math.PI/180;function Se(e,t){const n=(90-60*t)*Te;return[V+e*Math.cos(n),D-e*Math.sin(n)]}function U(e,t){const n=e==="inner"?1:e==="middle"?2:3,i=Ee[e],r=Math.floor(t/n),p=t%n/n,u=Se(i,r%6),k=Se(i,(r+1)%6);return[u[0]+(k[0]-u[0])*p,u[1]+(k[1]-u[1])*p]}function de(e,t,n){const i=[];for(let r=0;r<6;r++){const p=(90-60*r)*Te;i.push(`${(e+n*Math.cos(p)).toFixed(2)},${(t-n*Math.sin(p)).toFixed(2)}`)}return i.join(" ")}function ue(e,t){return e==="inner"?t:e==="middle"?2*t%ie.middle:3*t%ie.outer}function Xe(e,t){return e==="inner"?!0:e==="middle"?t%2===0:t%3===0}function fe(e,t){return`${e==="inner"?"I":e==="middle"?"M":"O"}${t}`}const Ie={inner:"#5fd0ff",middle:"#9d7bff",outer:"#7fffd6"};function Ze(e,t,n){const i=[];for(let r=0;r<6;r++){const p=r*60*Math.PI/180,u=e+Math.cos(p)*n*.5,k=t-Math.sin(p)*n*.5;i.push(`<ellipse cx="${u.toFixed(1)}" cy="${k.toFixed(1)}" rx="${(n*.3).toFixed(1)}" ry="${(n*.16).toFixed(1)}" transform="rotate(${-r*60} ${u.toFixed(1)} ${k.toFixed(1)})" fill="#5fd97a" fill-opacity="0.85"/>`)}return`<g>${i.join("")}<circle cx="${e}" cy="${t}" r="${(n*.22).toFixed(1)}" fill="#bdf56a"/><circle cx="${e}" cy="${t}" r="${(n*.11).toFixed(1)}" fill="#2e8b3d"/></g>`}function et(e,t,n){const i=[];for(let r=0;r<3;r++){const p=(r+1)/4,u=e-n*.45+p*n*.9;i.push(`<line x1="${u.toFixed(1)}" y1="${t}" x2="${(u+n*.06).toFixed(1)}" y2="${(t+n*.42).toFixed(1)}" stroke="#e6a23c" stroke-width="${(n*.05).toFixed(1)}"/>`),i.push(`<line x1="${u.toFixed(1)}" y1="${t}" x2="${(u-n*.06).toFixed(1)}" y2="${(t+n*.42).toFixed(1)}" stroke="#e6a23c" stroke-width="${(n*.05).toFixed(1)}"/>`)}return`<g>
<path d="M ${(e-n*.5).toFixed(1)} ${t} a ${(n*.5).toFixed(1)} ${(n*.32).toFixed(1)} 0 0 0 ${n.toFixed(1)} 0 a ${(n*.34).toFixed(1)} ${(n*.22).toFixed(1)} 0 0 0 ${(-n).toFixed(1)} 0 z" fill="#f3b34a" stroke="#c97f1e" stroke-width="${(n*.05).toFixed(1)}"/>
<path d="M ${(e+n*.42).toFixed(1)} ${(t-n*.04).toFixed(1)} l ${(n*.14).toFixed(1)} ${(n*.1).toFixed(1)} l ${(-n*.14).toFixed(1)} ${(n*.1).toFixed(1)} z" fill="#7a4a08"/>
${i.join("")}
</g>`}function tt(e,t,n){const i=[];for(let p=0;p<6;p++){const u=(p*60+30)*Math.PI/180,k=e+Math.cos(u)*n*.5,I=t+Math.sin(u)*n*.5,b=e+Math.cos(u)*n*.78,M=t+Math.sin(u)*n*.78;i.push(`<line x1="${k.toFixed(1)}" y1="${I.toFixed(1)}" x2="${b.toFixed(1)}" y2="${M.toFixed(1)}" stroke="#ff6fae" stroke-width="${(n*.07).toFixed(1)}"/><circle cx="${b.toFixed(1)}" cy="${M.toFixed(1)}" r="${(n*.05).toFixed(1)}" fill="#ff6fae"/>`)}const r=[];for(let p=0;p<6;p++){const u=(90-60*p)*Math.PI/180;r.push(`${(e+Math.cos(u)*n*.45).toFixed(1)},${(t-Math.sin(u)*n*.45).toFixed(1)}`)}return`<g>${i.join("")}<polygon points="${r.join(" ")}" fill="#ff9ec7" stroke="#d63d86" stroke-width="${(n*.05).toFixed(1)}"/><polygon points="${r.slice(0,3).join(" ")}" fill="#ffd0e4" fill-opacity="0.7"/></g>`}function pe(e,t,n,i){return e==="producer"?Ze(t,n,i):e==="grazer"?et(t,n,i):tt(t,n,i)}function Me(e,t,n,i){switch(e){case"nutrientInlet":return`<g>
<rect x="${(t-i*.14).toFixed(1)}" y="${(n-i*.5).toFixed(1)}" width="${(i*.28).toFixed(1)}" height="${(i*.5).toFixed(1)}" rx="${(i*.05).toFixed(1)}" fill="#3a6ea5" stroke="#8fb8e6"/>
<polygon points="${(t-i*.14).toFixed(1)},${n} ${(t+i*.14).toFixed(1)},${n} ${t.toFixed(1)},${(n+i*.22).toFixed(1)}" fill="#6fa8dc"/>
<circle cx="${t}" cy="${(n+i*.36).toFixed(1)}" r="${(i*.12).toFixed(1)}" fill="#9fd0ff"/>
</g>`;case"heatSource":{const r=[];for(let p=0;p<8;p++){const u=p*45*Math.PI/180;r.push(`<line x1="${(t+Math.cos(u)*i*.55).toFixed(1)}" y1="${(n-Math.sin(u)*i*.55).toFixed(1)}" x2="${(t+Math.cos(u)*i*.8).toFixed(1)}" y2="${(n-Math.sin(u)*i*.8).toFixed(1)}" stroke="#ff7a3c" stroke-width="${(i*.05).toFixed(1)}"/>`)}return`<g>${r.join("")}<path d="M ${(t-i*.3).toFixed(1)} ${n} q ${(i*.3).toFixed(1)} ${(-i*.3).toFixed(1)} ${(i*.6).toFixed(1)} 0 q ${(i*.3).toFixed(1)} ${(i*.3).toFixed(1)} ${(i*.6).toFixed(1)} 0" fill="none" stroke="#ff9a5c" stroke-width="${(i*.09).toFixed(1)}"/><circle cx="${t}" cy="${n}" r="${(i*.13).toFixed(1)}" fill="#ffb347"/></g>`}case"toxinInlet":return`<g><polygon points="${(t-i*.22).toFixed(1)},${(n-i*.4).toFixed(1)} ${(t+i*.22).toFixed(1)},${(n-i*.4).toFixed(1)} ${t.toFixed(1)},${(n-i*.1).toFixed(1)}" fill="#6b8f3a" stroke="#a7d977"/><path d="M ${(t-i*.12).toFixed(1)} ${(n-i*.42).toFixed(1)} l ${(i*.24).toFixed(1)} 0 l 0 ${(-i*.18).toFixed(1)} l ${(-i*.24).toFixed(1)} 0 z" fill="#8a6fbf"/><circle cx="${t}" cy="${(n+i*.18).toFixed(1)}" r="${(i*.15).toFixed(1)}" fill="#9fe06a" stroke="#5e8a2e" stroke-width="${(i*.04).toFixed(1)}"/></g>`;case"drain":return`<g><polygon points="${(t-i*.34).toFixed(1)},${(n-i*.34).toFixed(1)} ${(t+i*.34).toFixed(1)},${(n-i*.34).toFixed(1)} ${t.toFixed(1)},${(n+i*.05).toFixed(1)}" fill="#445" stroke="#7d8aa0"/><rect x="${(t-i*.07).toFixed(1)}" y="${(n+i*.05).toFixed(1)}" width="${(i*.14).toFixed(1)}" height="${(i*.3).toFixed(1)}" fill="#6a7588"/><path d="M ${(t-i*.26).toFixed(1)} ${(n-i*.32).toFixed(1)} q ${(i*.26).toFixed(1)} ${(i*.16).toFixed(1)} ${(i*.52).toFixed(1)} 0" fill="none" stroke="#9fe06a" stroke-width="${(i*.06).toFixed(1)}"/></g>`;case"immuneNode":return`<g><ellipse cx="${t}" cy="${n}" rx="${(i*.4).toFixed(1)}" ry="${(i*.24).toFixed(1)}" fill="#10303a" stroke="#5fd0ff" stroke-width="${(i*.05).toFixed(1)}"/><circle cx="${t}" cy="${n}" r="${(i*.16).toFixed(1)}" fill="#5fd0ff"/><circle cx="${(t-i*.05).toFixed(1)}" cy="${(n-i*.05).toFixed(1)}" r="${(i*.06).toFixed(1)}" fill="#eafdff"/></g>`;case"objective":return`<g><circle cx="${t}" cy="${n}" r="${(i*.42).toFixed(1)}" fill="none" stroke="#ffd24a" stroke-width="${(i*.05).toFixed(1)}" stroke-dasharray="${(i*.14).toFixed(1)} ${(i*.1).toFixed(1)}"/><circle cx="${t}" cy="${n}" r="${(i*.1).toFixed(1)}" fill="#ffd24a"/><line x1="${(t-i*.55).toFixed(1)}" y1="${n}" x2="${(t-i*.2).toFixed(1)}" y2="${n}" stroke="#ffd24a" stroke-width="${(i*.04).toFixed(1)}"/><line x1="${(t+i*.2).toFixed(1)}" y1="${n}" x2="${(t+i*.55).toFixed(1)}" y2="${n}" stroke="#ffd24a" stroke-width="${(i*.04).toFixed(1)}"/><line x1="${t}" y1="${(n-i*.55).toFixed(1)}" x2="${t}" y2="${(n-i*.2).toFixed(1)}" stroke="#ffd24a" stroke-width="${(i*.04).toFixed(1)}"/><line x1="${t}" y1="${(n+i*.2).toFixed(1)}" x2="${t}" y2="${(n+i*.55).toFixed(1)}" stroke="#ffd24a" stroke-width="${(i*.04).toFixed(1)}"/></g>`}}function nt(e,t,n={}){const i=We(t),r=($,h)=>(i.get(`${$}:${h}`)??[]).map(s=>({kind:s.kind,label:s.label})),p=n.previewState,u=[];for(let $=0;$<6;$++){const h=U("inner",ue("inner",$));U("middle",ue("middle",$));const s=U("outer",ue("outer",$)),l=!!n.selectedRing;u.push(`<line x1="${s[0].toFixed(1)}" y1="${s[1].toFixed(1)}" x2="${h[0].toFixed(1)}" y2="${h[1].toFixed(1)}" stroke="url(#gateGlow)" stroke-width="${l?5:3}" stroke-linecap="round" opacity="0.55"/>`)}const k=[];for(const $ of["inner","middle","outer"]){const h=[];for(let s=0;s<6;s++){const l=(90-60*s)*Math.PI/180,o=Ee[$]+le[$]*.9;h.push(`${(V+o*Math.cos(l)).toFixed(1)},${(D-o*Math.sin(l)).toFixed(1)}`)}k.push(`<polygon points="${h.join(" ")}" fill="none" stroke="${Ie[$]}" stroke-width="1" stroke-dasharray="3 5" opacity="0.25"/>`)}const I=[];for(const $ of["outer","middle","inner"]){const h=le[$];for(let s=0;s<e.rings[$].tiles.length;s++){const[l,o]=U($,s),d=e.rings[$].tiles[s],f=Xe($,s),a=fe($,s),g=d.heat>0?'filter="url(#heatGlow)" ':"",x=$==="inner"?"#10243a":$==="middle"?"#152039":"#0f1c33",m=o+h*.55,w=h*1.1,S=d.nutrient/6*w,P=d.toxin/6*w,N=`clip-${$}-${s}`;let Q="";if(p){const G=p.rings[$].tiles[s],X=G.producer-d.producer,Z=G.grazer-d.grazer;(X!==0||Z!==0)&&(Q=`<text x="${l.toFixed(1)}" y="${(o-h-4).toFixed(1)}" text-anchor="middle" font-size="11" fill="#ffe08a" font-weight="700">${X!==0?`P${X>0?"+":""}${X}`:""}${Z!==0?` G${Z>0?"+":""}${Z}`:""}</text>`)}let T="";const j=h*.5;d.producer>0&&(T+=pe("producer",l-h*.32,o-h*.18,j)),d.grazer>0&&(T+=pe("grazer",l+h*.3,o-h*.18,j*.95)),d.phage>0&&(T+=pe("phage",l,o+h*.22,j*.85));const A=[];d.producer>0&&A.push(`<tspan fill="#7fff8a">P${d.producer}</tspan>`),d.grazer>0&&A.push(`<tspan fill="#ffc46a">V${d.grazer}</tspan>`),d.phage>0&&A.push(`<tspan fill="#ff9ec7">F${d.phage}</tspan>`);const He=A.length?`<text x="${l.toFixed(1)}" y="${(o+h*.95).toFixed(1)}" text-anchor="middle" font-size="${$==="inner"?12:10}" font-weight="700">${A.join(" ")}</text>`:"";let ve="";for(const G of r($,s))G.kind!=="objective"&&(ve+=Me(G.kind,l,o-h*0,h*.7));const qe=r($,s).find(G=>G.kind==="objective")?Me("objective",l,o,h*1.15):"";I.push(`
<g class="tile" data-ring="${$}" data-index="${s}">
${qe}
<polygon points="${de(l,o,h)}" ${g}fill="${x}" stroke="${f?Ie[$]:"#2a3b55"}" stroke-width="${f?2.2:1.2}"/>
<defs><clipPath id="${N}"><polygon points="${de(l,o,h*.96)}"/></clipPath></defs>
${S>0?`<rect x="${(l-h*.96).toFixed(1)}" y="${(m-S).toFixed(1)}" width="${(h*1.92).toFixed(1)}" height="${S.toFixed(1)}" fill="#1f6fd6" opacity="0.32" clip-path="url(#${N})"/>`:""}
${P>0?`<rect x="${(l-h*.96).toFixed(1)}" y="${(m-P).toFixed(1)}" width="${(h*1.92).toFixed(1)}" height="${P.toFixed(1)}" fill="#5fbf4a" opacity="0.40" clip-path="url(#${N})"/>`:""}
${d.heat>0?`<polygon points="${de(l,o,h)}" fill="none" stroke="#ff8a4c" stroke-width="${1+d.heat*.4}" opacity="${.3+d.heat*.1}"/>`:""}
${ve}
${T}
${He}
<text x="${(l-h*.78).toFixed(1)}" y="${(o-h*.82).toFixed(1)}" font-size="${$==="inner"?9:8}" fill="#6f86a8">${a}</text>
${Q}
</g>`)}}const b=`<circle cx="${V}" cy="${D}" r="34" fill="#0a1426" stroke="#2a3b55"/><text x="${V}" y="${(D+4).toFixed(1)}" text-anchor="middle" font-size="11" fill="#7d97bf">ADAPTIVE</text><text x="${V}" y="${(D+16).toFixed(1)}" text-anchor="middle" font-size="11" fill="#7d97bf">LOOP</text>`,M=[];if(n.flowEvents&&n.flowEvents.length){const $=h=>J(h);for(const h of n.flowEvents){const[s,l]=U(h.ring,h.index),o=le[h.ring],d=h.field==="nutrient"?"#5fb0ff":"#9fe06a";if(h.tangential>0){const a=$(h.ring)==="cw"?o*.5:-o*.5;M.push(`<path d="M ${(s-a).toFixed(1)} ${(l-o*.95).toFixed(1)} l ${a.toFixed(1)} ${(o*.5).toFixed(1)} l ${a.toFixed(1)} ${(-o*.5).toFixed(1)}" fill="none" stroke="${d}" stroke-width="2.2" stroke-linecap="round" opacity="0.95"><title>${h.field} tangential flow at ${fe(h.ring,h.index)}</title></path>`)}if(h.radial>0){const f=Math.atan2(D-l,V-s),a=s+Math.cos(f)*o*.4,g=l+Math.sin(f)*o*.4,x=s+Math.cos(f)*o*.95,m=l+Math.sin(f)*o*.95;M.push(`<line x1="${x.toFixed(1)}" y1="${m.toFixed(1)}" x2="${a.toFixed(1)}" y2="${g.toFixed(1)}" stroke="${d}" stroke-width="2.4" stroke-linecap="round" opacity="0.95" marker-end="url(#flowHead)"><title>${h.field} radial-inward flow at ${fe(h.ring,h.index)}</title></line>`)}}}function J($){return e.rings[$].direction}return`<svg viewBox="0 0 ${B} ${B}" role="img" aria-label="Culture board: three concentric hexagonal rings linked by six radial gates${n.flowEvents?.length?"; preview shows flow arrows":""}" class="board-svg">
<defs>
<linearGradient id="gateGlow" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#7fffd6"/><stop offset="50%" stop-color="#9d7bff"/><stop offset="100%" stop-color="#5fd0ff"/>
</linearGradient>
<filter id="heatGlow" x="-50%" y="-50%" width="200%" height="200%">
<feGaussianBlur stdDeviation="2.2" result="b"/><feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
</filter>
<marker id="flowHead" markerWidth="7" markerHeight="7" refX="3.5" refY="3.5" orient="auto"><path d="M0,0 L7,3.5 L0,7 z" fill="#9fe06a"/></marker>
</defs>
<rect x="0" y="0" width="${B}" height="${B}" fill="#070d18"/>
${k.join("")}
${u.join("")}
${I.join("")}
${M.join("")}
${b}
</svg>`}function it(e){const t=[];for(const n of["producer","grazer"]){const i=e.lineage[n],r=n==="producer"?"Lumiflora":"Vellea",p=["heat","hunger","toxin","immunity"].map(u=>{const k=i.pressure[u],I=i.unlocked[u],b="▰".repeat(k)+"▱".repeat(3-k);return`<span class="ptrack ${I?"adapted":""}" title="${u}: ${k}/3${I?" (adapted)":""}">${b}${I?"✓":""}</span>`});t.push(`<div class="lineage"><span class="lin-name">${r}</span>${p.join("")}</div>`)}return t.join("")}const re="adaptive-loop-save-v1",rt=1;function ot(e){const t={...e,savedAt:new Date().toISOString()};localStorage.setItem(re,JSON.stringify(t))}function st(){const e=localStorage.getItem(re);if(!e)return{ok:!1,reason:"No saved game found."};let t;try{t=JSON.parse(e)}catch{return{ok:!1,reason:"Saved game is corrupt (invalid JSON)."}}const n=t;return!n||typeof n!="object"?{ok:!1,reason:"Saved game is empty."}:n.schemaVersion!==rt?{ok:!1,reason:`Unsupported save version ${n.schemaVersion}.`}:!n.state||!n.scenarioId||!n.progress?{ok:!1,reason:"Saved game is missing required fields."}:at(n.state)?{ok:!0,env:n}:{ok:!1,reason:"Saved game state is invalid."}}function je(){localStorage.removeItem(re)}function Oe(){return!!localStorage.getItem(re)}function at(e){if(!e||typeof e!="object")return!1;const t=e;if(t.schemaVersion!==1||!t.rings||!["inner","middle","outer"].every(i=>Array.isArray(t.rings[i]?.tiles)))return!1;const n={inner:6,middle:12,outer:18};for(const i of["inner","middle","outer"]){if(t.rings[i].tiles.length!==n[i])return!1;for(const r of t.rings[i].tiles){const p=r;for(const u of["nutrient","heat","toxin","producer","grazer","phage"])if(typeof p[u]!="number"||p[u]<0||p[u]>6||!Number.isInteger(p[u]))return!1}}return!0}const Pe=[{ring:"inner",dir:"cw",label:"Inner ⟳",key:"1"},{ring:"inner",dir:"ccw",label:"Inner ⟲",key:"2"},{ring:"middle",dir:"cw",label:"Middle ⟳",key:"3"},{ring:"middle",dir:"ccw",label:"Middle ⟲",key:"4"},{ring:"outer",dir:"cw",label:"Outer ⟳",key:"5"},{ring:"outer",dir:"ccw",label:"Outer ⟲",key:"6"}];let c,R;function ct(e){R=e,c={view:"title",mode:"campaign",scenario:C[0],state:Le(C[0],"campaign"),progress:me(),selected:null,preview:null,lastEvents:[],announce:"",pendingNewTraits:[]},O()}function me(){return{unlocked:[C[0].id],inherited:{producer:[],grazer:[]},entrySnapshot:{producer:[],grazer:[]},victory:!1}}function O(){R.innerHTML=lt(),mt(),R.querySelector("#announce")?.setAttribute("aria-live","polite")}function lt(){return c.view==="title"?dt():c.view==="menu"?ut():c.view==="victory"?gt():c.view==="choice"?pt():ft()}function oe(e,t){return`<main class="app">
<header class="topbar"><h1>${t}</h1>
<nav class="topnav">
<button id="btnMenu" class="btn ghost" aria-label="Return to menu">Menu</button>
<button id="btnSaveQuit" class="btn ghost" aria-label="Save and quit to title">Save &amp; Quit</button>
<button id="btnHelp" class="btn ghost" aria-label="Open help and legend">Help</button>
</nav>
</header>
<div id="announce" class="announce" role="status">${c.announce}</div>
${e}
<section id="helpPanel" class="help-panel hidden" aria-hidden="true">${ht()}</section>
</main>`}function dt(){return`<main class="app title">
<div id="announce" class="announce" role="status">${c.announce}</div>
<h1>Adaptive Loop</h1>
<p class="subtitle">A calm deterministic microfluidic strategy puzzle.</p>
<p class="lede">Rotate the three concentric glass rings to align the six radial gates, route nutrient inward, and provoke — then exploit — the ecosystem's counter-adaptations.</p>
<div class="actions">
<button id="btnStart" class="btn primary">New Campaign</button>
<button id="btnContinue" class="btn" ${Oe()?"":"disabled"}>Continue</button>
<button id="btnReplay" class="btn">Replay Standalone</button>
</div>
<p class="hint">${Oe()?"A saved run is available.":"No saved run yet."}</p>
</main>`}function ut(){const e=C.map(t=>{const n=c.progress.unlocked.includes(t.id);return`<li class="${n?"":"locked"}">
<button class="btn scenario-btn" data-scid="${t.id}" ${n?"":"disabled"} aria-label="Play ${t.name}">
<span class="scn-no">${t.index}</span>
<span class="scn-name">${t.name}</span>
<span class="scn-sub">${t.subtitle}</span>
</button>
</li>`}).join("");return oe(`<section class="menu"><h2>Campaign Scenarios</h2><ul class="scn-list">${e}</ul></section>`,"Adaptive Loop — Menu")}function ft(){const e=c.scenario,t=c.state,n=t.outcome!=="playing",i=(c.preview?.events??[]).filter(o=>o.phase==="flow").map(o=>({ring:o.ring,index:o.index,field:o.field,tangential:o.tangential,radial:o.radial})),r=nt(t,e,{previewState:c.preview?.state??null,selectedRing:c.selected?.ring??null,flowEvents:i}),p=Ft(e),u=`Turn ${t.turn}/${e.turnLimit}${t.outcome!=="playing"?` — ${xe(t.outcome)}`:""}`,k=Pe.map(o=>{const d=c.selected&&c.selected.ring===o.ring&&c.selected.dir===o.dir,f=d&&c.preview?` → ${Ne(c.preview.events)}`:"";return`<button class="btn rot ${d?"selected":""}" data-ring="${o.ring}" data-dir="${o.dir}" aria-label="Rotate ${o.ring} ${o.dir==="cw"?"clockwise":"counter-clockwise"}${f}"${n?" disabled":""}><span class="key">${o.key}</span> ${o.label}</button>`}).join(""),b=`<button id="btnCommit" class="btn primary" ${n||!c.selected?"disabled":""} aria-label="Commit selected rotation">Commit</button>`,M=`<button id="btnCancel" class="btn ghost" ${c.selected?"":"disabled"} aria-label="Cancel preview">Cancel (Esc)</button>`,J=t.outcome==="collapsed"||t.outcome==="expired"?'<button id="btnRetry" class="btn">Retry</button>':"",$=St(c.preview?.events??c.lastEvents),h=it(t),s=["heat","hunger","toxin","immunity"].filter(o=>t.environmentActive[o]).map(o=>`<span class="envflag">${H[o].label} Response</span>`).join(""),l=[...c.progress.inherited.producer.map(o=>`Lumiflora:${_[o]}`),...c.progress.inherited.grazer.map(o=>`Vellea:${_[o]}`)].join(", ")||"none";return oe(`<section class="play">
<div class="board-wrap">${r}</div>
<aside class="rail">
<div class="panel obj">
<h2>${e.index}. ${e.name} <span class="scn-sub">(${e.subtitle})</span></h2>
<p class="obj-text">${p}</p>
<p class="turn">${u}</p>
${s?`<p class="env">${s}</p>`:""}
<p class="inh">Inherited: ${l}</p>
</div>
<div class="panel controls">
<h2>Rotate a ring</h2>
<div class="rot-grid">${k}</div>
<div class="commit-row">${b} ${M} ${J}</div>
<p class="sel-status">${c.selected?`Selected: ${c.selected.ring} ${c.selected.dir}. Commit enabled.`:"Select a rotation to preview."}</p>
</div>
<div class="panel traits"><h2>Pressure tracks</h2>${h}<p class="legend-mini">▰ = track step · ✓ = adapted (benefit+cost active)</p></div>
<div class="panel events"><h2>${c.preview?"Preview":"Last tick"}</h2><ol class="event-list">${$}</ol></div>
</aside>
</section>`,`Adaptive Loop — ${e.name}`)}function pt(){const e=c.pendingNewTraits.map((t,n)=>{const i=t.lin==="producer"?"Lumiflora":"Vellea",r=H[t.p];return`<button class="btn choice" data-i="${n}"><span class="ch-lin">${i}</span> · <span class="ch-trait">${_[t.p]}</span><br><span class="ch-meta">Benefit: prevents ${t.p} loss. Cost: ${zt(t.p)}. ${r.response}.</span></button>`}).join("");return oe(`<section class="choice">
<h2>Scenario won — preserve a lineage trait?</h2>
<p>The ecosystem unlocked new adaptations. Preserve one to carry its gift (and cost) forward, or decline.</p>
<div class="choice-grid">${e}</div>
<button id="btnDecline" class="btn ghost">Decline</button>
</section>`,"Lineage choice")}function gt(){return oe('<section class="victory"><h2>Campaign Victory</h2><p>You stabilized the Adaptive Loop across all five scenarios.</p><button id="btnMenu" class="btn primary">Return to Menu</button></section>',"Victory")}function ht(){const e=`<li><b>Lumiflora</b> (producer, green diatom) — consumes nutrient, grows.</li>
<li><b>Vellea</b> (grazer, amber crescent) — consumes producers, grows.</li>
<li><b>Phage</b> (pink lander) — consumes grazers; starves without prey.</li>`,t=["heat","hunger","toxin","immunity"].map(n=>`<li><b>${H[n].label}</b> → trait <b>${_[n]}</b>. Response: ${H[n].response}.</li>`).join("");return`<h2>Help &amp; Legend</h2><p>Rotate a ring (buttons or keys 1–6). A rotation moves that ring's payloads and re-aligns the gates; the tick then resolves flow, growth, feeding, migration, adaptation, and pressure. Select to preview exact deltas; Commit applies it.</p>
<h3>Species</h3><ul>${e}</ul>
<h3>Pressures &amp; adaptations</h3><ul>${t}</ul>
<p>Gate tiles glow in their ring color; nutrient fills the tile base blue, toxin green, heat warms the rim. <kbd>1</kbd>–<kbd>6</kbd> rotate, <kbd>Enter</kbd>/<kbd>Space</kbd> commits, <kbd>Esc</kbd> cancels.</p>`}function mt(){const e=(t,n,i)=>R.querySelector(t)?.addEventListener(n,i);e("#btnStart","click",xt),e("#btnContinue","click",vt),e("#btnReplay","click",()=>{c.view="menu",c.mode="standalone",c.progress={...me(),unlocked:C.map(t=>t.id)},O()}),e("#btnMenu","click",()=>{c.view="menu",O()}),e("#btnSaveQuit","click",yt),e("#btnHelp","click",wt),e("#btnDecline","click",()=>ge(null)),R.querySelectorAll(".rot").forEach(t=>{const n=t.dataset.ring,i=t.dataset.dir;t.addEventListener("click",()=>ne({ring:n,dir:i})),t.addEventListener("focus",()=>{(!c.selected||c.selected.ring!==n||c.selected.dir!==i)&&ne({ring:n,dir:i})}),t.addEventListener("mouseenter",()=>{c.selected||ne({ring:n,dir:i})})}),R.querySelectorAll(".scenario-btn").forEach(t=>{t.addEventListener("click",()=>{const n=t.dataset.scid;se(n,c.mode)})}),R.querySelectorAll(".choice").forEach(t=>{t.addEventListener("click",()=>{const n=+t.dataset.i;ge(c.pendingNewTraits[n]??null)})}),e("#btnCommit","click",Ce),e("#btnCancel","click",Re),e("#btnRetry","click",kt),document.onkeydown=$t}function $t(e){if(e.key==="Escape"){Re();return}if(c.view!=="play"||c.state.outcome!=="playing")return;const t="123456".indexOf(e.key);if(t>=0){ne(Pe[t]);return}(e.key==="Enter"||e.key===" ")&&c.selected&&(e.preventDefault(),Ce())}function xt(){c.mode="campaign",c.progress=me(),c.view="play",se(C[0].id,"campaign")}function vt(){const e=st();if(!e.ok){c.announce=e.reason,O();return}const t=e.env;c.mode=t.mode,c.progress=t.progress,c.scenario=he(t.scenarioId),c.state=t.state,c.selected=null,c.preview=null,c.lastEvents=[],c.view="play",c.announce="Resumed saved run.",O()}function se(e,t){const n=he(e);c.scenario=n,c.mode=t;const i=t==="standalone"?{producer:[],grazer:[]}:c.progress.inherited;c.state=Le(n,t,i),c.progress.entrySnapshot={producer:[...i.producer],grazer:[...i.grazer]},c.selected=null,c.preview=null,c.lastEvents=[],c.view="play",c.announce=`${n.name}: ${n.teaches}`,$e(),O()}function ne(e){if(c.state.outcome!=="playing")return;c.selected=e;const{state:t,events:n}=Ae(c.state,e,!0);c.preview={state:t,events:n},c.announce=`Previewing ${e.ring} ${e.dir}: ${Ne(n)}`,O(),R.querySelector(`.rot[data-ring="${e.ring}"][data-dir="${e.dir}"]`)?.focus()}function Re(){c.selected&&(c.selected=null,c.preview=null,c.announce="Preview cancelled.",O())}function Ce(){if(!c.selected||c.state.outcome!=="playing")return;const e=c.selected,{state:t,events:n}=Ae(c.state,e,!0);c.state=t,c.lastEvents=n,c.selected=null,c.preview=null,c.announce=`Turn ${t.turn}: ${xe(t.outcome)}.`,$e(),t.outcome==="won"?bt():O()}function bt(){if(c.mode==="standalone"){c.announce="Standalone scenario complete.",O();return}const e=c.state.inheritedAtStart,t=[];for(const r of["producer","grazer"])for(const p of["heat","hunger","toxin","immunity"])c.state.lineage[r].unlocked[p]&&!e[r].includes(p)&&!c.progress.inherited[r].includes(p)&&t.push({lin:r,p});const n=c.scenario.index,i=C[n];if(i&&!c.progress.unlocked.includes(i.id)&&c.progress.unlocked.push(i.id),!i){c.progress.victory=!0,c.view="victory",je(),O();return}if(t.length===0){ge(null);return}c.pendingNewTraits=t,c.view="choice",O()}function ge(e){e&&(c.progress.inherited[e.lin]=[...c.progress.inherited[e.lin],e.p]);const t=c.scenario.index,n=C[t];if(!n){c.progress.victory=!0,c.view="victory",je(),O();return}se(n.id,"campaign")}function kt(){c.progress.inherited={producer:[...c.progress.entrySnapshot.producer],grazer:[...c.progress.entrySnapshot.grazer]},se(c.scenario.id,c.mode)}function yt(){$e(),c.view="title",c.announce="Saved. Quit to title.",O()}function $e(){c.view==="play"&&ot({schemaVersion:1,mode:c.mode,scenarioId:c.scenario.id,state:c.state,progress:c.progress,actionLog:c.state.actionLog,outcome:c.state.outcome})}function wt(){const e=R.querySelector("#helpPanel");e&&(e.classList.toggle("hidden"),e.setAttribute("aria-hidden",e.classList.contains("hidden")?"true":"false"))}function Ft(e,t){return e.id==="s1-heat"?"Grow producers: producer at I0 ≥ 4 and total producer ≥ 12. (Tuned: see TUNING.md)":e.id==="s2-hunger"?"Endure to turn 10: total producer ≥ 8, grazer ≥ 4, across ≥3 producer tiles and ≥2 grazer tiles.":e.id==="s3-toxin"?"Cleanse: by turn 6–9 reach total toxin ≤ 4 and producer+grazer ≥ 8. (Tuned)":e.id==="s4-immunity"?"Escort: grazer at I0 (sanctuary) ≥ 3 and total producer ≥ 6. (Tuned)":e.id==="s5-convergence"?"Hold equilibrium: assay spoke + balanced ecosystem sustained for 2 consecutive turns. (Tuned)":e.teaches}function xe(e){return e==="won"?"Objective achieved":e==="collapsed"?"Ecosystem collapsed":e==="expired"?"Turn limit expired":"resolved"}function Ne(e){const t=[];for(const n of e)n.phase==="evolution"&&t.push(`unlocks ${_[n.pressure]}`),n.phase==="env"&&t.push(`${H[n.pressure].label} response`),n.phase==="outcome"&&n.outcome!=="playing"&&t.push(`→ ${n.outcome}`);return t.slice(0,3).join(", ")||"tick resolves"}function zt(e){return e==="heat"?"no growth/feeding while hot":e==="hunger"?"dormant when starving (inedible, can't migrate)":e==="toxin"?"pays 1 nutrient under toxin":"predator removes 2 cloaked prey at immune nodes"}function St(e){if(e.length===0)return'<li class="muted">Select a rotation to preview the tick.</li>';const t=[];for(const n of e){const i=It(n);i&&t.push(`<li>${i}</li>`)}return(t.length?t:['<li class="muted">No notable changes.</li>']).join("")}function It(e){switch(e.phase){case"rotate":return`<b>Rotate</b> ${e.ring} ${e.dir}.`;case"flow":return`Flow ${e.field} at ${L(e.ring,e.index)} (${e.delta>=0?"+":""}${e.delta}).`;case"growth":return e.suppressed?`Growth suppressed (heat) at ${L(e.ring,e.index)}.`:`Producer +${e.gained} at ${L(e.ring,e.index)}.`;case"feed":return e.predator==="grazer"?`Grazer ate producer at ${L(e.ring,e.index)}.`:e.phageStarve?`Phage starved at ${L(e.ring,e.index)}.`:`Phage ate grazer at ${L(e.ring,e.index)}.`;case"migrate":return`${e.species} migrated ${e.from}→${e.to}.`;case"evolution":return`<b>${e.lineage==="producer"?"Lumiflora":"Vellea"} unlocked ${_[e.pressure]}.</b>`;case"env":return`<b>${H[e.pressure].label} response active</b>: ${H[e.pressure].response}.`;case"fixture":return`${e.kind} at ${L(e.ring,e.index)}: ${e.field} ${e.delta>=0?"+":""}${e.delta}.`;case"fixtureGlobal":return null;case"immuneSelect":return`Immune node at ${L(e.ring,e.index)} targets ${e.lineage}${e.retarget?" (retarget spillover)":""}.`;case"pressureInc":return`${e.lineage} ${e.pressure} track → ${e.to}/3.`;case"consequence":return e.kind==="prevented"?`${e.lineage} ${e.pressure} loss prevented (adapted) at ${L(e.ring,e.index)}.`:e.kind==="payNutrient"?`${e.lineage} pays 1 nutrient (Efflux) at ${L(e.ring,e.index)}.`:e.kind==="payPop"?`${e.lineage} loses ${e.amount} (Efflux, no nutrient) at ${L(e.ring,e.index)}.`:`${e.lineage} loses ${e.amount} to ${e.pressure} at ${L(e.ring,e.index)}.`;case"spillover":return`Spillover: ${e.field} −${e.reduced} at ${L(e.ring,e.index)} (${e.pressure} adaptation).`;case"outcome":return e.outcome==="playing"?null:`<b>${xe(e.outcome)}.</b>`}}function L(e,t){return`${e==="inner"?"I":e==="middle"?"M":"O"}${t}`}const Ge=document.getElementById("app");if(!Ge)throw new Error("#app mount point missing");ct(Ge);