paracosm 0.9.1148 → 0.9.1149

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -106,11 +106,11 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
106
106
  "score": 0.82,
107
107
  "rationale": "Roles consistent with departmental authority; arithmetic checks out."
108
108
  }
109
- }`;function ym(e){e.preventDefault();let t=new URL(window.location.href);t.searchParams.set(`tab`,`settings`),t.searchParams.delete(`sub`),window.history.replaceState({},``,t.toString()),window.dispatchEvent(new PopStateEvent(`popstate`))}function bm(){return(0,x.jsxs)(`section`,{className:sa.guide,"aria-label":`How to author a RunArtifact JSON`,children:[(0,x.jsxs)(`div`,{className:sa.guideHead,children:[(0,x.jsx)(`h3`,{className:sa.guideTitle,children:`How to get a RunArtifact JSON`}),(0,x.jsxs)(`p`,{className:sa.guideSub,children:[`Studio takes a deterministic Paracosm `,(0,x.jsx)(`code`,{children:`RunArtifact`}),` — the JSON that a single sim run produces — and lets you inspect, promote to the Library, branch, or compare. Four steps to author one.`]})]}),(0,x.jsxs)(`ol`,{className:sa.guideSteps,children:[(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`strong`,{children:`Configure a scenario in Settings.`}),` Pick a built-in (Frontier AI Lab, Submarine, Corporate Quarterly, T2D Protocol) or load your own. Set turns, seed, population, time-per-turn.`]}),(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`strong`,{children:`Run the sim.`}),` Switch to the Sim tab, hit Run. The runtime emits events deterministically, the actor LLM produces dialogue and decisions, and the judge attaches a verdict at the end.`]}),(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`strong`,{children:`Download the artifact.`}),` Sim output panel has a Save button — that JSON is the RunArtifact. You can also produce one from the CLI: `,(0,x.jsx)(`code`,{children:`paracosm run scenarios/frontier-ai-lab.json --turns 20 --out run.json`}),`.`]}),(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`strong`,{children:`Drop it in the zone below.`}),` Single artifact or a bundle (array of artifacts, e.g. for branch comparisons). Max 10\xA0MB. A bundle over the server’s request limit (5\xA0MiB unless `,(0,x.jsx)(`code`,{children:`MAX_REQUEST_BODY_BYTES`}),` sets another) is promoted in parts of whole runs, snapshots included, into one Library bundle; a run that alone passes the limit is refused.`]})]}),(0,x.jsxs)(`div`,{className:sa.guideCtaRow,children:[(0,x.jsx)(`a`,{href:`?tab=settings`,onClick:ym,className:sa.guideCta,children:`Open Settings →`}),(0,x.jsx)(`a`,{href:`https://github.com/framerslab/paracosm/blob/master/docs/COOKBOOK.md`,target:`_blank`,rel:`noopener noreferrer`,className:sa.guideCtaSecondary,children:`Read the cookbook`}),(0,x.jsx)(`a`,{href:`https://github.com/framerslab/paracosm/tree/master/scenarios`,target:`_blank`,rel:`noopener noreferrer`,className:sa.guideCtaSecondary,children:`Browse example scenarios`})]}),(0,x.jsxs)(`details`,{className:sa.guideExample,children:[(0,x.jsx)(`summary`,{children:`Show an example RunArtifact`}),(0,x.jsx)(`pre`,{className:sa.guideExampleCode,children:(0,x.jsx)(`code`,{children:vm})}),(0,x.jsxs)(`p`,{className:sa.guideExampleNote,children:[`Real artifacts include the full event log, the per-turn snapshot of every actor, KPIs, and the judge verdict. The shape matches the `,(0,x.jsx)(`code`,{children:`RunArtifact`}),` Zod schema in `,(0,x.jsx)(`code`,{children:`schema/index.ts`}),`; bundles are a JSON array of artifacts.`]})]})]})}function xm(e){let{artifact:t,inline:n,onPromote:r,onCompare:i,promoteBusy:a,alreadyExisted:o}=e,s=t.metadata.mode,c=t.leader?.name??`<unnamed actor>`,l=t.metadata.scenario.name??t.metadata.scenario.id,u=b.useMemo(()=>{let e={},n=(t.trajectory?.timepoints?.[0])?.worldSnapshot?.metrics??{};for(let t of Object.keys(n))e[t]={id:t,label:t,range:[0,1]};return e},[t]);return(0,x.jsxs)(`div`,{className:sa.artifactView,children:[(0,x.jsxs)(`header`,{className:sa.artifactHead,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:sa.artifactScenario,children:l}),(0,x.jsxs)(`div`,{className:sa.artifactActor,children:[c,` · `,s]})]}),!n&&(0,x.jsxs)(`div`,{className:sa.artifactActions,children:[(0,x.jsx)(`button`,{type:`button`,className:sa.promoteBtn,onClick:r,disabled:a||o,children:o?`Already in Library`:a?`Promoting…`:`Promote to Library`}),(0,x.jsx)(`button`,{type:`button`,className:sa.compareBtn,onClick:i,children:`Compare`})]})]}),(0,x.jsx)(`div`,{className:sa.artifactBody,children:s===`turn-loop`?(0,x.jsx)(mi,{artifact:t}):(0,x.jsx)(fi,{artifact:t,metricSpecs:u})})]})}function Sm(e){let{artifacts:t,bundleId:n,onPromote:r,onCompare:i,promoteBusy:a,alreadyExisted:o}=e,[s,c]=b.useState(null);if(s!==null&&t[s]){let e=t[s];return(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`button`,{type:`button`,className:sa.bundleDrillBack,onClick:()=>c(null),children:`← Back to bundle`}),(0,x.jsx)(xm,{artifact:e,inline:!0,onPromote:()=>{},onCompare:()=>{}})]})}return(0,x.jsxs)(`div`,{children:[n&&(0,x.jsx)(`div`,{className:sa.bundleIdChip,title:n,children:n.length>32?`${n.slice(0,28)}…`:n}),(0,x.jsxs)(`div`,{className:sa.bundleActions,children:[(0,x.jsx)(`button`,{type:`button`,className:sa.promoteBtn,onClick:r,disabled:a||o,children:o?`Already in Library`:a?`Promoting…`:`Promote bundle (${t.length})`}),(0,x.jsx)(`button`,{type:`button`,className:sa.compareBtn,onClick:i,children:`Compare bundle`})]}),(0,x.jsx)(`div`,{className:sa.bundleGrid,children:t.map((e,t)=>{let n=e.leader,r=e.cost?.totalUSD,i=e.trajectory?.timepoints?.length??0;return(0,x.jsxs)(`button`,{type:`button`,className:sa.bundleCard,onClick:()=>c(t),children:[(0,x.jsx)(`div`,{className:sa.bundleCardTitle,children:n?.name??`<unnamed>`}),(0,x.jsxs)(`div`,{className:sa.bundleCardMeta,children:[n?.archetype??``,` · `,i,` turn`,i===1?``:`s`,typeof r==`number`?` · $${r.toFixed(3)}`:``]})]},e.metadata.runId)})})]})}var Cm=5242880,wm=`/api/v1/library/import`,Tm=new TextEncoder,Em=e=>Tm.encode(e).length,Dm=Em(JSON.stringify({addToBundle:`bundle_00000000-0000-0000-0000-000000000000`,artifacts:[]}));function Om(e){return Dm+e.reduce((e,t)=>e+t.bytes,0)+Math.max(0,e.length-1)}function km(e,t){let n=Dm,r=0;for(let i of e){let e=i.bytes+ +(r>0);if(r>0&&n+e>t)break;n+=e,r+=1}return e.slice(0,r)}function Am(e,t){return`${t===void 0?`{"artifacts":[`:`{"addToBundle":${JSON.stringify(t)},"artifacts":[`}${e.map(e=>e.json).join(`,`)}]}`}function jm(e){let t=typeof e==`string`?/Maximum (\d+) bytes/.exec(e):null;return t?Number(t[1]):void 0}function Mm(){let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``);return`bundle_${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var Nm=e=>`${(e/1048576).toFixed(1)} MiB`,Pm=e=>/[.!?]$/.test(e.trim())?e.trim():`${e.trim()}.`;async function Fm(e,t={}){let n=e.map(e=>{let t=JSON.stringify(e);return{runId:e.metadata.runId,json:t,bytes:Em(t)}}),r=[],i=[],a=t.addToBundle??Mm(),o=0,s=Cm,c=!1,l=e=>{let t=n.slice(o).map(e=>e.runId);return r.length===0?{ok:!1,error:e,bundleId:a,imported:[],notImported:t}:{ok:!1,error:`Imported ${r.length} of ${n.length} runs into ${a}: ${r.join(`, `)}. Not imported: ${t.join(`, `)}. ${Pm(e)} Promote again to add the rest to the same bundle.`,bundleId:a,imported:[...r],notImported:t}};for(;o<n.length;){let e=n.slice(o),u=e.filter(e=>Om([e])>s);if(u.length>0&&c){let e=u.map(e=>`${e.runId} (${Nm(e.bytes)})`).join(`, `),n=u.length===1;return l(`The server takes at most ${Nm(s)} in one request (MAX_REQUEST_BODY_BYTES), and ${n?`this run passes`:`these runs pass`} that on ${n?`its`:`their`} own: ${e}.`+(r.length===0&&t.addToBundle===void 0?` Nothing was imported.`:``))}let d=u.length>0?e:km(e,s),f;try{f=await fetch(wm,{method:`POST`,headers:{"Content-Type":`application/json`},body:Am(d,a)})}catch(e){return l(e instanceof Error?e.message:String(e))}let p=await f.json().catch(()=>({}));if(f.status===201&&p.bundleId&&p.runIds&&p.alreadyExisted){a=p.bundleId,r.push(...p.runIds),i.push(...p.alreadyExisted),o+=d.length;continue}if(f.status===413){let e=jm(p.error);if(e!==void 0&&(!c||e<s)){s=e,c=!0;continue}}let m=p.insertedSoFar?.runIds??[];return m.length>0&&p.bundleId&&(a=p.bundleId,r.push(...m),i.push(...p.insertedSoFar?.alreadyExisted??m.map(()=>!1)),o+=m.length),l(p.error??`Promote failed: HTTP ${f.status}`)}return{ok:!0,bundleId:a,runIds:r,alreadyExisted:i}}function Im(){let[e,t]=b.useState(!1),[n,r]=b.useState(null),[i,a]=b.useState(null),o=b.useRef(null);return{promoteSingle:b.useCallback(async e=>{t(!0),a(null);try{let t=await fetch(wm,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({artifact:e})});if(!t.ok){let e=await t.json().catch(()=>({}));return a(e.error??`Promote failed: HTTP ${t.status}`),null}let n={kind:`single`,...await t.json()};return r(n),n}catch(e){return a(e instanceof Error?e.message:String(e)),null}finally{t(!1)}},[]),promoteBundle:b.useCallback(async e=>{t(!0),a(null);try{let t=e.map(e=>e.metadata.runId),n=await Fm(e,{addToBundle:o.current!==null&&o.current.runIds.length===t.length&&o.current.runIds.every((e,n)=>e===t[n])?o.current.bundleId:void 0});if(!n.ok)return o.current={runIds:t,bundleId:n.bundleId},a(n.error),null;o.current=null;let i={kind:`bundle`,bundleId:n.bundleId,runIds:n.runIds,alreadyExisted:n.alreadyExisted};return r(i),i}catch(e){return a(e instanceof Error?e.message:String(e)),null}finally{t(!1)}},[]),busy:e,lastResult:n,error:i}}function Lm(){let e=Xk();return(0,b.useMemo)(()=>ce(e),[e.labels?.populationNoun,e.labels?.settlementNoun,e.labels?.timeUnitNoun,e.labels?.timeUnitNounPlural])}function Rm(e,t){return typeof e==`number`&&typeof t==`number`?t>e?`up`:t<e?`down`:`unchanged`:e===t?`unchanged`:`changed`}function zm(e,t){let n=[`metrics`,`capacities`,`statuses`,`environment`,`politics`],r=[],i=e.finalState,a=t.finalState;if(!i||!a)return r;for(let e of n){let t=i[e],n=a[e];if(t&&n)for(let i of Object.keys(t)){if(!(i in n))continue;let a=t[i],o=n[i],s=Rm(a,o);if(s===`unchanged`)continue;let c=typeof a==`number`&&typeof o==`number`?o-a:void 0;r.push({bag:e,key:i,parentValue:a,branchValue:o,delta:c,direction:s})}}return r.sort((e,t)=>e.delta!==void 0&&t.delta!==void 0?Math.abs(t.delta)-Math.abs(e.delta):e.delta===void 0?t.delta===void 0?0:1:-1)}function Bm(e){if(e.delta!==void 0){let t=e.delta>0?`+`:``,n=Math.round(e.delta*10)/10;return`${e.key} ${t}${n}`}return`${e.key}: ${e.parentValue} → ${e.branchValue}`}var Vm={tab:`_tab_e8hr7_1`,emptyState:`_emptyState_e8hr7_11`,parentCard:`_parentCard_e8hr7_48`,branchCard:`_branchCard_e8hr7_48`,branchList:`_branchList_e8hr7_77`,cardHeader:`_cardHeader_e8hr7_83`,branchMeta:`_branchMeta_e8hr7_91`,parentTitle:`_parentTitle_e8hr7_99`,branchTitle:`_branchTitle_e8hr7_99`,archetype:`_archetype_e8hr7_111`,meta:`_meta_e8hr7_117`,badge:`_badge_e8hr7_129`,status:`_status_e8hr7_143`,status_running:`_status_running_e8hr7_153`,status_complete:`_status_complete_e8hr7_158`,status_aborted:`_status_aborted_e8hr7_163`,status_error:`_status_error_e8hr7_168`,metrics:`_metrics_e8hr7_174`,metric:`_metric_e8hr7_174`,deltas:`_deltas_e8hr7_208`,delta:`_delta_e8hr7_208`,direction_up:`_direction_up_e8hr7_225`,direction_down:`_direction_down_e8hr7_229`,direction_changed:`_direction_changed_e8hr7_233`,more:`_more_e8hr7_238`,identical:`_identical_e8hr7_245`,error:`_error_e8hr7_253`};function Hm(){let{state:e}=Gn(),t=Lm(),n=eA();return!e.parent&&e.branches.length===0?(0,x.jsxs)(`div`,{className:Vm.emptyState,role:`region`,"aria-label":`Branches (empty)`,children:[(0,x.jsx)(`h2`,{children:`No branches yet`}),(0,x.jsxs)(`p`,{children:[`Run a simulation with snapshot capture enabled (default for dashboard runs), then open the `,(0,x.jsx)(`strong`,{children:`Reports`}),` tab and click`,` `,(0,x.jsxs)(`code`,{children:[`↳ Fork at `,t.Time,` N`]}),` on any completed turn to branch with a different leader.`]})]}):(0,x.jsxs)(`div`,{className:Vm.tab,role:`region`,"aria-label":`Branches`,children:[e.parent&&(0,x.jsx)(Um,{artifact:e.parent,labels:t}),(0,x.jsx)(`div`,{className:Vm.branchList,children:e.branches.map(r=>(0,x.jsx)(Wm,{branch:r,parent:e.parent,labels:t,onOpen:()=>n(`reports`)},r.localId))})]})}function Um({artifact:e,labels:t}){let n=e.finalState?.metrics??{},r=e.trajectory?.timepoints?.length??0;return(0,x.jsxs)(`section`,{className:Vm.parentCard,"aria-label":`Parent run`,children:[(0,x.jsx)(`header`,{className:Vm.cardHeader,children:(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`h3`,{className:Vm.parentTitle,children:[e.metadata.scenario.name,` (parent)`]}),(0,x.jsxs)(`span`,{className:Vm.meta,children:[r,` `,r===1?t.time:t.times,` completed · run`,` `,(0,x.jsx)(`code`,{children:e.metadata.runId})]})]})}),(0,x.jsx)(`dl`,{className:Vm.metrics,children:Object.entries(n).slice(0,6).map(([e,t])=>(0,x.jsxs)(`div`,{className:Vm.metric,children:[(0,x.jsx)(`dt`,{children:e}),(0,x.jsx)(`dd`,{children:Gm(t)})]},e))})]})}function Wm({branch:e,parent:t,labels:n,onOpen:r}){let i=(0,b.useMemo)(()=>t&&e.artifact?zm(t,e.artifact):[],[t,e.artifact]),a=e.status===`running`?`Running · ${n.Time} ${e.currentTurn}`:e.status.charAt(0).toUpperCase()+e.status.slice(1);return(0,x.jsxs)(`article`,{className:Vm.branchCard,onClick:r,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),r())},tabIndex:0,role:`button`,"aria-label":`Branch ${e.actorName}, forked at ${n.time} ${e.forkedAtTurn}`,children:[(0,x.jsxs)(`header`,{className:Vm.cardHeader,children:[(0,x.jsxs)(`div`,{className:Vm.branchMeta,children:[(0,x.jsxs)(`span`,{className:Vm.badge,children:[`Forked at `,n.Time,` `,e.forkedAtTurn]}),(0,x.jsxs)(`h4`,{className:Vm.branchTitle,children:[e.actorName,` `,(0,x.jsxs)(`span`,{className:Vm.archetype,children:[`(`,e.actorArchetype,`)`]})]})]}),(0,x.jsx)(`span`,{className:`${Vm.status} ${Vm[`status_${e.status}`]}`,children:a})]}),e.status===`complete`&&i.length>0&&(0,x.jsxs)(`ul`,{className:Vm.deltas,"aria-label":`Delta vs parent`,children:[i.slice(0,4).map(e=>(0,x.jsx)(`li`,{className:`${Vm.delta} ${Vm[`direction_${e.direction}`]}`,title:`${e.bag}: parent=${e.parentValue}, branch=${e.branchValue}`,children:Bm(e)},`${e.bag}.${e.key}`)),i.length>4&&(0,x.jsxs)(`li`,{className:Vm.more,children:[`+`,i.length-4,` more`]})]}),e.status===`complete`&&i.length===0&&(0,x.jsx)(`p`,{className:Vm.identical,children:`Identical final state. Leader overrides did not diverge.`}),e.status===`error`&&e.errorMessage&&(0,x.jsx)(`p`,{className:Vm.error,role:`alert`,children:e.errorMessage})]})}function Gm(e){return typeof e==`number`?Number.isInteger(e)?e.toString():(Math.round(e*100)/100).toString():String(e)}var Km={tablist:`_tablist_iq6lf_1`,tab:`_tab_iq6lf_1`,tabActive:`_tabActive_iq6lf_39`};function qm({options:e,active:t,onChange:n,ariaLabel:r}){return(0,x.jsx)(`div`,{role:`tablist`,"aria-label":r,className:Km.tablist,children:e.map(e=>{let r=e.id===t,i=r?`${Km.tab} ${Km.tabActive}`:Km.tab;return(0,x.jsx)(`button`,{role:`tab`,"aria-selected":r,onClick:()=>n(e.id),type:`button`,className:i,children:e.label},e.id)})})}function Jm(){return{query:``,types:new Set,leader:null,turnRange:null,toolHash:``,toolExact:!1}}function Ym(e,t){let n=t.query.toLowerCase(),r=t.types.size>0,i=t.turnRange!==null,a=t.turnRange,o=t.toolHash.toLowerCase();return e.filter(e=>{if(r&&!t.types.has(e.type)||t.leader!==null&&e.leader!==t.leader)return!1;if(i&&a){let t=Xm(e);if(t===void 0||t<a[0]||t>a[1])return!1}return!(o&&!Qm(e,o,t.toolExact)||n&&!Zm(e,n))})}function Xm(e){let t=e.data?.turn;return typeof t==`number`?t:void 0}function Zm(e,t){if(e.type.toLowerCase().includes(t)||typeof e.leader==`string`&&e.leader.toLowerCase().includes(t))return!0;let n=e.data??{};for(let e of[`title`,`summary`,`department`,`name`]){let r=n[e];if(typeof r==`string`&&r.toLowerCase().includes(t))return!0}return!1}function Qm(e,t,n){let r=e=>n?e===t:e.includes(t),i=e.data??{},a=typeof i.name==`string`?i.name.trim().toLowerCase():``;if(a&&r(a))return!0;let o=Array.isArray(i.forgedTools)?i.forgedTools:[];for(let e of o){let t=e&&typeof e==`object`&&typeof e.name==`string`?e.name.trim().toLowerCase():``;if(t&&r(t))return!0}return!1}function $m(e){let t=new Set,n=[],r=new Set,i=0;for(let a of e){a.type&&t.add(a.type),typeof a.leader==`string`&&a.leader&&!r.has(a.leader)&&(r.add(a.leader),n.push(a.leader));let e=Xm(a);e!==void 0&&e>i&&(i=e)}return{types:[...t].sort(),actors:n,maxTurn:i}}function eh(e){let t=new URLSearchParams;e.query&&t.set(`logQuery`,e.query),e.types.size>0&&t.set(`logTypes`,[...e.types].join(`,`)),e.leader!==null&&t.set(`logLeader`,e.leader),e.turnRange&&(t.set(`logTurnMin`,String(e.turnRange[0])),t.set(`logTurnMax`,String(e.turnRange[1])));let n=t.toString();return n?`?${n}`:``}var th=[`logQuery`,`logTypes`,`logLeader`,`logTurnMin`,`logTurnMax`];function nh(e,t,n){let r=new URL(e);for(let e of th)r.searchParams.delete(e);return new URLSearchParams(eh(t)).forEach((e,t)=>r.searchParams.append(t,e)),n&&(r.hash=``),r.pathname+r.search+r.hash}function rh(e,t){let n=Jm(),r=new URLSearchParams(e.startsWith(`?`)?e.slice(1):e),i=r.get(`logQuery`);i&&(n.query=i);let a=r.get(`logTypes`);if(a){let e=a.split(`,`).map(e=>e.trim()).filter(Boolean);n.types=new Set(e)}let o=r.get(`logLeader`);o&&(n.leader=o);let s=r.get(`logTurnMin`),c=r.get(`logTurnMax`);if(s!==null&&c!==null){let e=Number(s),t=Number(c);Number.isFinite(e)&&Number.isFinite(t)&&(n.turnRange=[Math.min(e,t),Math.max(e,t)])}let l=t.startsWith(`#`)?t.slice(1):t,u=l.match(/(?:^|&)log=([^&]+)/);if(u){try{n.toolHash=decodeURIComponent(u[1])}catch{n.toolHash=u[1]}n.toolExact=/(?:^|&)logExact=1(?:&|$)/.test(l)}return n}var ih=[`quickstart`,`sim`,`viz`,`settings`,`reports`,`chat`,`library`,`studio`,`about`],ah={branches:{tab:`studio`,sub:`branches`},log:{tab:`settings`,sub:`log`}};function oh(e){return!!e&&ih.includes(e)}function sh(e){let{tab:t}=ch(e);return t}function ch(e){let t=new URL(e),n=t.searchParams.get(`tab`),r=t.searchParams.get(`sub`);if(n&&ah[n])return ah[n];if(oh(n))return{tab:n,sub:r??void 0};let i=t.hash.replace(/^#/,``);return i&&ah[i]?ah[i]:oh(i)?{tab:i,sub:r??void 0}:{tab:`quickstart`}}function lh(e,t){let n=new URL(e);return n.searchParams.set(`tab`,t),n.searchParams.delete(`sub`),n.hash=``,n.toString()}function uh(e,t,n){let r=new URL(lh(e,`settings`));for(let e of th)r.searchParams.delete(e);return r.searchParams.set(`sub`,`log`),n&&r.searchParams.set(`logLeader`,n),r.hash=t?`log=${encodeURIComponent(t)}&logExact=1`:``,r.toString()}function dh(e){if(typeof window>`u`)return;let t=new URL(window.location.href);e?t.searchParams.set(`sub`,e):t.searchParams.delete(`sub`),window.history.replaceState({},``,t.toString())}function fh(e,t){if(!t)return lh(e,`sim`);let n=new URL(e),r=new URL(t,n.origin);return r.pathname===`/sim`&&!r.searchParams.has(`tab`)&&r.searchParams.set(`tab`,`sim`),r.hash=``,r.toString()}var ph=[{id:`author`,label:`Author`},{id:`branches`,label:`Branches`}];function mh({initialSubTab:e=`author`}={}){let[t,n]=b.useState(e),r=b.useCallback(e=>{n(e),dh(e===`author`?null:e)},[]),[i,a]=b.useState(null),[o,s]=b.useState(!1),c=Im(),l=b.useCallback((e,t)=>{e.kind!==`error`&&a({input:e,filename:t,promote:null})},[]),u=b.useCallback(async()=>{if(!i||i.input.kind!==`single`)return;let e=await c.promoteSingle(i.input.artifact);e&&a(t=>t&&{...t,promote:e})},[i,c]),d=b.useCallback(async()=>{if(!i||i.input.kind!==`bundle`)return;let e=await c.promoteBundle(i.input.artifacts);e&&a(t=>t&&{...t,promote:e})},[i,c]),f=b.useCallback(()=>s(!0),[]),p=b.useCallback(()=>{a(null),s(!1)},[]),m=(()=>{if(i)return i.input.kind===`single`?[i.input.artifact]:i.input.artifacts})(),h=i?.promote?.kind===`bundle`?i.promote.bundleId:null;return(0,x.jsxs)(`div`,{className:sa.tab,children:[(0,x.jsx)(qm,{options:ph,active:t,onChange:r,ariaLabel:`Studio sub-navigation`}),t===`branches`&&(0,x.jsx)(Hm,{}),t===`author`&&!i&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(bm,{}),(0,x.jsx)(_m,{onLoaded:l})]}),t===`author`&&i&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:sa.loadedBar,children:[(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`strong`,{children:i.filename}),` · `,i.input.kind===`single`?`single artifact`:`bundle of ${i.input.artifacts.length}`,i.promote&&(i.promote.kind===`single`?i.promote.alreadyExisted?` · already in Library`:` · added to Library`:` · added to Library (${i.promote.runIds.length} runs)`)]}),(0,x.jsx)(`button`,{type:`button`,className:sa.bundleDrillBack,onClick:p,children:`Drop another`})]}),c.error&&(0,x.jsx)(`div`,{className:sa.errorBanner,role:`alert`,children:c.error}),i.input.kind===`single`&&(0,x.jsx)(xm,{artifact:i.input.artifact,onPromote:u,onCompare:f,promoteBusy:c.busy,alreadyExisted:i.promote?.kind===`single`&&i.promote.alreadyExisted}),i.input.kind===`bundle`&&(0,x.jsx)(Sm,{artifacts:i.input.artifacts,bundleId:i.input.bundleId,onPromote:d,onCompare:f,promoteBusy:c.busy,alreadyExisted:i.promote?.kind===`bundle`&&i.promote.alreadyExisted.every(Boolean)})]}),(0,x.jsx)(ra,{bundleId:h,extraArtifacts:m,open:o,onClose:()=>s(!1)})]})}function hh(e){let t=e.trim();if(!t)return{ok:!1,error:`URL is empty.`};if(t.length>2048)return{ok:!1,error:`URL exceeds 2048 characters.`};let n;try{n=new URL(t)}catch{return{ok:!1,error:`Not a valid URL.`}}return n.protocol!==`http:`&&n.protocol!==`https:`?{ok:!1,error:`Unsupported scheme ${n.protocol}. Use http or https.`}:{ok:!0,url:n}}function gh(e,t=200,n=5e4){let r=e.trim();return r?r.length<t?{ok:!1,reason:`too-short`}:r.length>n?{ok:!1,reason:`too-long`}:{ok:!0}:{ok:!1,reason:`empty`}}function _h(e,t){let n=[`metrics`,`capacities`,`statuses`,`environment`,`politics`],r=e.finalState;if(!r||t.length===0)return[];let i=[];for(let e of n){let n=r[e];if(n)for(let r of Object.keys(n)){let a=n[r],o=t.map(t=>t.finalState?.[e]?.[r]).filter(e=>e!==void 0);if(o.length!==0){if(typeof a==`number`&&o.every(e=>typeof e==`number`)){let t=[...o].sort((e,t)=>e-t),n=t.length%2==0?(t[t.length/2-1]+t[t.length/2])/2:t[(t.length-1)/2],s=a-n;if(s===0)continue;i.push({bag:e,key:r,parentValue:n,branchValue:a,delta:s,direction:s>0?`up`:`down`})}else{let t=o.find(e=>e!==a);if(t===void 0)continue;i.push({bag:e,key:r,parentValue:t,branchValue:a,direction:`changed`})}}}}return i.sort((e,t)=>e.delta!==void 0&&t.delta!==void 0?Math.abs(t.delta)-Math.abs(e.delta):e.delta===void 0?t.delta===void 0?0:1:-1)}function vh(e,t,n=`viz`){return Ot(e,t,n)}function yh(e,t){let n=new Blob([JSON.stringify(e,null,2)],{type:`application/json`}),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=t,document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(r),1e3)}var bh=`/assets/pdf.worker.min-CIqJB0yW.mjs`,xh=`modulepreload`,Sh=function(e){return`/`+e},Ch={},wh=function(e){return e.pathname.endsWith(`.css`)},Th=function(e,t,n){if(t in e)return e[t];let r=n();if(!r){e[t]=void 0;return}let i=r.then(()=>{e[t]=void 0},n=>{throw e[t]=void 0,n});return e[t]=i,i},Eh=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=Sh(t,n);let r=s(t),i=wh(r);return Th(Ch,r.href,()=>{if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let t=document.createElement(`link`);if(t.rel=i?`stylesheet`:xh,i||(t.as=`script`),t.crossOrigin=``,t.href=r.href,a&&t.setAttribute(`nonce`,a),document.head.appendChild(t),i)return new Promise((e,n)=>{let i=a=>{t.removeEventListener(`load`,i),t.removeEventListener(`error`,i),a.type===`error`?n(Error(`Unable to preload CSS for ${r}`)):e(a)};t.addEventListener(`load`,i),t.addEventListener(`error`,i)})})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})};function Dh(){if(typeof window>`u`)return bh;try{return new URL(bh,window.location.origin).toString()}catch{return bh}}var Oh=null;async function kh(){if(Oh)return Oh;let e=await Eh(()=>import(`./pdf-YwugTw7Y.js`),[]);return e.GlobalWorkerOptions.workerSrc=Dh(),Oh=e,e}async function Ah(e,t={}){let{maxBytes:n=5e4,maxPages:r=100}=t;if(!e.name.toLowerCase().endsWith(`.pdf`)&&e.type!==`application/pdf`)throw Error(`File is not a PDF: ${e.name}`);let i=await kh(),a=await e.arrayBuffer(),o=i.getDocument({data:a}),s=[],c=0,l=!1;try{let e=await o.promise,t=Math.min(e.numPages,r);for(let r=1;r<=t;r++){let t=(await(await e.getPage(r)).getTextContent()).items.map(e=>e.str??``).join(` `).replace(/\s+/g,` `).trim(),i=new Blob([t]).size;if(c+i>n){let e=n-c;if(e>0){let r=new TextEncoder().encode(t).slice(0,e),i=new TextDecoder(`utf-8`,{fatal:!1}).decode(r).replace(/�$/,``);s.push(i),c=n}l=!0;break}s.push(t),c+=i}let i=s.join(`
109
+ }`;function ym(e){e.preventDefault();let t=new URL(window.location.href);t.searchParams.set(`tab`,`settings`),t.searchParams.delete(`sub`),window.history.replaceState({},``,t.toString()),window.dispatchEvent(new PopStateEvent(`popstate`))}function bm(){return(0,x.jsxs)(`section`,{className:sa.guide,"aria-label":`How to author a RunArtifact JSON`,children:[(0,x.jsxs)(`div`,{className:sa.guideHead,children:[(0,x.jsx)(`h3`,{className:sa.guideTitle,children:`How to get a RunArtifact JSON`}),(0,x.jsxs)(`p`,{className:sa.guideSub,children:[`Studio takes a deterministic Paracosm `,(0,x.jsx)(`code`,{children:`RunArtifact`}),` — the JSON that a single sim run produces — and lets you inspect, promote to the Library, branch, or compare. Four steps to author one.`]})]}),(0,x.jsxs)(`ol`,{className:sa.guideSteps,children:[(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`strong`,{children:`Configure a scenario in Settings.`}),` Pick a built-in (Frontier AI Lab, Submarine, Corporate Quarterly, T2D Protocol) or load your own. Set turns, seed, population, time-per-turn.`]}),(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`strong`,{children:`Run the sim.`}),` Switch to the Sim tab, hit Run. The runtime emits events deterministically, the actor LLM produces dialogue and decisions, and the judge attaches a verdict at the end.`]}),(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`strong`,{children:`Download the artifact.`}),` Sim output panel has a Save button — that JSON is the RunArtifact. You can also produce one from the CLI: `,(0,x.jsx)(`code`,{children:`paracosm run scenarios/frontier-ai-lab.json --turns 20 --out run.json`}),`.`]}),(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`strong`,{children:`Drop it in the zone below.`}),` Single artifact or a bundle (array of artifacts, e.g. for branch comparisons). Max 10\xA0MB. A bundle over the server’s request limit (5\xA0MiB unless `,(0,x.jsx)(`code`,{children:`MAX_REQUEST_BODY_BYTES`}),` sets another) is promoted in parts of whole runs, snapshots included, into one Library bundle; a run that alone passes the limit is refused.`]})]}),(0,x.jsxs)(`div`,{className:sa.guideCtaRow,children:[(0,x.jsx)(`a`,{href:`?tab=settings`,onClick:ym,className:sa.guideCta,children:`Open Settings →`}),(0,x.jsx)(`a`,{href:`https://github.com/framerslab/paracosm/blob/master/docs/COOKBOOK.md`,target:`_blank`,rel:`noopener noreferrer`,className:sa.guideCtaSecondary,children:`Read the cookbook`}),(0,x.jsx)(`a`,{href:`https://github.com/framerslab/paracosm/tree/master/scenarios`,target:`_blank`,rel:`noopener noreferrer`,className:sa.guideCtaSecondary,children:`Browse example scenarios`})]}),(0,x.jsxs)(`details`,{className:sa.guideExample,children:[(0,x.jsx)(`summary`,{children:`Show an example RunArtifact`}),(0,x.jsx)(`pre`,{className:sa.guideExampleCode,children:(0,x.jsx)(`code`,{children:vm})}),(0,x.jsxs)(`p`,{className:sa.guideExampleNote,children:[`Real artifacts include the full event log, the per-turn snapshot of every actor, KPIs, and the judge verdict. The shape matches the `,(0,x.jsx)(`code`,{children:`RunArtifact`}),` Zod schema in `,(0,x.jsx)(`code`,{children:`schema/index.ts`}),`; bundles are a JSON array of artifacts.`]})]})]})}function xm(e){let{artifact:t,inline:n,onPromote:r,onCompare:i,promoteBusy:a,alreadyExisted:o}=e,s=t.metadata.mode,c=t.leader?.name??`<unnamed actor>`,l=t.metadata.scenario.name??t.metadata.scenario.id,u=b.useMemo(()=>{let e={},n=(t.trajectory?.timepoints?.[0])?.worldSnapshot?.metrics??{};for(let t of Object.keys(n))e[t]={id:t,label:t,range:[0,1]};return e},[t]);return(0,x.jsxs)(`div`,{className:sa.artifactView,children:[(0,x.jsxs)(`header`,{className:sa.artifactHead,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:sa.artifactScenario,children:l}),(0,x.jsxs)(`div`,{className:sa.artifactActor,children:[c,` · `,s]})]}),!n&&(0,x.jsxs)(`div`,{className:sa.artifactActions,children:[(0,x.jsx)(`button`,{type:`button`,className:sa.promoteBtn,onClick:r,disabled:a||o,children:o?`Already in Library`:a?`Promoting…`:`Promote to Library`}),(0,x.jsx)(`button`,{type:`button`,className:sa.compareBtn,onClick:i,children:`Compare`})]})]}),(0,x.jsx)(`div`,{className:sa.artifactBody,children:s===`turn-loop`?(0,x.jsx)(mi,{artifact:t}):(0,x.jsx)(fi,{artifact:t,metricSpecs:u})})]})}function Sm(e){let{artifacts:t,bundleId:n,onPromote:r,onCompare:i,promoteBusy:a,alreadyExisted:o}=e,[s,c]=b.useState(null);if(s!==null&&t[s]){let e=t[s];return(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`button`,{type:`button`,className:sa.bundleDrillBack,onClick:()=>c(null),children:`← Back to bundle`}),(0,x.jsx)(xm,{artifact:e,inline:!0,onPromote:()=>{},onCompare:()=>{}})]})}return(0,x.jsxs)(`div`,{children:[n&&(0,x.jsx)(`div`,{className:sa.bundleIdChip,title:n,children:n.length>32?`${n.slice(0,28)}…`:n}),(0,x.jsxs)(`div`,{className:sa.bundleActions,children:[(0,x.jsx)(`button`,{type:`button`,className:sa.promoteBtn,onClick:r,disabled:a||o,children:o?`Already in Library`:a?`Promoting…`:`Promote bundle (${t.length})`}),(0,x.jsx)(`button`,{type:`button`,className:sa.compareBtn,onClick:i,children:`Compare bundle`})]}),(0,x.jsx)(`div`,{className:sa.bundleGrid,children:t.map((e,t)=>{let n=e.leader,r=e.cost?.totalUSD,i=e.trajectory?.timepoints?.length??0;return(0,x.jsxs)(`button`,{type:`button`,className:sa.bundleCard,onClick:()=>c(t),children:[(0,x.jsx)(`div`,{className:sa.bundleCardTitle,children:n?.name??`<unnamed>`}),(0,x.jsxs)(`div`,{className:sa.bundleCardMeta,children:[n?.archetype??``,` · `,i,` turn`,i===1?``:`s`,typeof r==`number`?` · $${r.toFixed(3)}`:``]})]},e.metadata.runId)})})]})}var Cm=5242880,wm=`/api/v1/library/import`,Tm=new TextEncoder,Em=e=>Tm.encode(e).length,Dm=Em(JSON.stringify({addToBundle:`bundle_00000000-0000-0000-0000-000000000000`,artifacts:[]}));function Om(e){return Dm+e.reduce((e,t)=>e+t.bytes,0)+Math.max(0,e.length-1)}function km(e,t){let n=Dm,r=0;for(let i of e){let e=i.bytes+ +(r>0);if(r>0&&n+e>t)break;n+=e,r+=1}return e.slice(0,r)}function Am(e,t){return`${t===void 0?`{"artifacts":[`:`{"addToBundle":${JSON.stringify(t)},"artifacts":[`}${e.map(e=>e.json).join(`,`)}]}`}function jm(e){let t=typeof e==`string`?/Maximum (\d+) bytes/.exec(e):null;return t?Number(t[1]):void 0}function Mm(){let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``);return`bundle_${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var Nm=e=>`${(e/1048576).toFixed(1)} MiB`,Pm=e=>/[.!?]$/.test(e.trim())?e.trim():`${e.trim()}.`;async function Fm(e,t={}){let n=e.map(e=>{let t=JSON.stringify(e);return{runId:e.metadata.runId,json:t,bytes:Em(t)}}),r=[],i=[],a=t.addToBundle??Mm(),o=0,s=Cm,c=!1,l=e=>{let t=n.slice(o).map(e=>e.runId);return r.length===0?{ok:!1,error:e,bundleId:a,imported:[],notImported:t}:{ok:!1,error:`Imported ${r.length} of ${n.length} runs into ${a}: ${r.join(`, `)}. Not imported: ${t.join(`, `)}. ${Pm(e)} Promote again to add the rest to the same bundle.`,bundleId:a,imported:[...r],notImported:t}};for(;o<n.length;){let e=n.slice(o),u=e.filter(e=>Om([e])>s);if(u.length>0&&c){let e=u.map(e=>`${e.runId} (${Nm(e.bytes)})`).join(`, `),n=u.length===1;return l(`The server takes at most ${Nm(s)} in one request (MAX_REQUEST_BODY_BYTES), and ${n?`this run passes`:`these runs pass`} that on ${n?`its`:`their`} own: ${e}.`+(r.length===0&&t.addToBundle===void 0?` Nothing was imported.`:``))}let d=u.length>0?e:km(e,s),f;try{f=await fetch(wm,{method:`POST`,headers:{"Content-Type":`application/json`},body:Am(d,a)})}catch(e){return l(e instanceof Error?e.message:String(e))}let p=await f.json().catch(()=>({}));if(f.status===201&&p.bundleId&&p.runIds&&p.alreadyExisted){a=p.bundleId,r.push(...p.runIds),i.push(...p.alreadyExisted),o+=d.length;continue}if(f.status===413){let e=jm(p.error);if(e!==void 0&&(!c||e<s)){s=e,c=!0;continue}}let m=p.insertedSoFar?.runIds??[];return m.length>0&&p.bundleId&&(a=p.bundleId,r.push(...m),i.push(...p.insertedSoFar?.alreadyExisted??m.map(()=>!1)),o+=m.length),l(p.error??`Promote failed: HTTP ${f.status}`)}return{ok:!0,bundleId:a,runIds:r,alreadyExisted:i}}function Im(){let[e,t]=b.useState(!1),[n,r]=b.useState(null),[i,a]=b.useState(null),o=b.useRef(null);return{promoteSingle:b.useCallback(async e=>{t(!0),a(null);try{let t=await fetch(wm,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({artifact:e})});if(!t.ok){let e=await t.json().catch(()=>({}));return a(e.error??`Promote failed: HTTP ${t.status}`),null}let n={kind:`single`,...await t.json()};return r(n),n}catch(e){return a(e instanceof Error?e.message:String(e)),null}finally{t(!1)}},[]),promoteBundle:b.useCallback(async e=>{t(!0),a(null);try{let t=e.map(e=>e.metadata.runId),n=await Fm(e,{addToBundle:o.current!==null&&o.current.runIds.length===t.length&&o.current.runIds.every((e,n)=>e===t[n])?o.current.bundleId:void 0});if(!n.ok)return o.current={runIds:t,bundleId:n.bundleId},a(n.error),null;o.current=null;let i={kind:`bundle`,bundleId:n.bundleId,runIds:n.runIds,alreadyExisted:n.alreadyExisted};return r(i),i}catch(e){return a(e instanceof Error?e.message:String(e)),null}finally{t(!1)}},[]),busy:e,lastResult:n,error:i}}function Lm(){let e=Qk();return(0,b.useMemo)(()=>ce(e),[e.labels?.populationNoun,e.labels?.settlementNoun,e.labels?.timeUnitNoun,e.labels?.timeUnitNounPlural])}function Rm(e,t){return typeof e==`number`&&typeof t==`number`?t>e?`up`:t<e?`down`:`unchanged`:e===t?`unchanged`:`changed`}function zm(e,t){let n=[`metrics`,`capacities`,`statuses`,`environment`,`politics`],r=[],i=e.finalState,a=t.finalState;if(!i||!a)return r;for(let e of n){let t=i[e],n=a[e];if(t&&n)for(let i of Object.keys(t)){if(!(i in n))continue;let a=t[i],o=n[i],s=Rm(a,o);if(s===`unchanged`)continue;let c=typeof a==`number`&&typeof o==`number`?o-a:void 0;r.push({bag:e,key:i,parentValue:a,branchValue:o,delta:c,direction:s})}}return r.sort((e,t)=>e.delta!==void 0&&t.delta!==void 0?Math.abs(t.delta)-Math.abs(e.delta):e.delta===void 0?t.delta===void 0?0:1:-1)}function Bm(e){if(e.delta!==void 0){let t=e.delta>0?`+`:``,n=Math.round(e.delta*10)/10;return`${e.key} ${t}${n}`}return`${e.key}: ${e.parentValue} → ${e.branchValue}`}var Vm={tab:`_tab_e8hr7_1`,emptyState:`_emptyState_e8hr7_11`,parentCard:`_parentCard_e8hr7_48`,branchCard:`_branchCard_e8hr7_48`,branchList:`_branchList_e8hr7_77`,cardHeader:`_cardHeader_e8hr7_83`,branchMeta:`_branchMeta_e8hr7_91`,parentTitle:`_parentTitle_e8hr7_99`,branchTitle:`_branchTitle_e8hr7_99`,archetype:`_archetype_e8hr7_111`,meta:`_meta_e8hr7_117`,badge:`_badge_e8hr7_129`,status:`_status_e8hr7_143`,status_running:`_status_running_e8hr7_153`,status_complete:`_status_complete_e8hr7_158`,status_aborted:`_status_aborted_e8hr7_163`,status_error:`_status_error_e8hr7_168`,metrics:`_metrics_e8hr7_174`,metric:`_metric_e8hr7_174`,deltas:`_deltas_e8hr7_208`,delta:`_delta_e8hr7_208`,direction_up:`_direction_up_e8hr7_225`,direction_down:`_direction_down_e8hr7_229`,direction_changed:`_direction_changed_e8hr7_233`,more:`_more_e8hr7_238`,identical:`_identical_e8hr7_245`,error:`_error_e8hr7_253`};function Hm(){let{state:e}=Gn(),t=Lm(),n=nA();return!e.parent&&e.branches.length===0?(0,x.jsxs)(`div`,{className:Vm.emptyState,role:`region`,"aria-label":`Branches (empty)`,children:[(0,x.jsx)(`h2`,{children:`No branches yet`}),(0,x.jsxs)(`p`,{children:[`Run a simulation with snapshot capture enabled (default for dashboard runs), then open the `,(0,x.jsx)(`strong`,{children:`Reports`}),` tab and click`,` `,(0,x.jsxs)(`code`,{children:[`↳ Fork at `,t.Time,` N`]}),` on any completed turn to branch with a different leader.`]})]}):(0,x.jsxs)(`div`,{className:Vm.tab,role:`region`,"aria-label":`Branches`,children:[e.parent&&(0,x.jsx)(Um,{artifact:e.parent,labels:t}),(0,x.jsx)(`div`,{className:Vm.branchList,children:e.branches.map(r=>(0,x.jsx)(Wm,{branch:r,parent:e.parent,labels:t,onOpen:()=>n(`reports`)},r.localId))})]})}function Um({artifact:e,labels:t}){let n=e.finalState?.metrics??{},r=e.trajectory?.timepoints?.length??0;return(0,x.jsxs)(`section`,{className:Vm.parentCard,"aria-label":`Parent run`,children:[(0,x.jsx)(`header`,{className:Vm.cardHeader,children:(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`h3`,{className:Vm.parentTitle,children:[e.metadata.scenario.name,` (parent)`]}),(0,x.jsxs)(`span`,{className:Vm.meta,children:[r,` `,r===1?t.time:t.times,` completed · run`,` `,(0,x.jsx)(`code`,{children:e.metadata.runId})]})]})}),(0,x.jsx)(`dl`,{className:Vm.metrics,children:Object.entries(n).slice(0,6).map(([e,t])=>(0,x.jsxs)(`div`,{className:Vm.metric,children:[(0,x.jsx)(`dt`,{children:e}),(0,x.jsx)(`dd`,{children:Gm(t)})]},e))})]})}function Wm({branch:e,parent:t,labels:n,onOpen:r}){let i=(0,b.useMemo)(()=>t&&e.artifact?zm(t,e.artifact):[],[t,e.artifact]),a=e.status===`running`?`Running · ${n.Time} ${e.currentTurn}`:e.status.charAt(0).toUpperCase()+e.status.slice(1);return(0,x.jsxs)(`article`,{className:Vm.branchCard,onClick:r,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),r())},tabIndex:0,role:`button`,"aria-label":`Branch ${e.actorName}, forked at ${n.time} ${e.forkedAtTurn}`,children:[(0,x.jsxs)(`header`,{className:Vm.cardHeader,children:[(0,x.jsxs)(`div`,{className:Vm.branchMeta,children:[(0,x.jsxs)(`span`,{className:Vm.badge,children:[`Forked at `,n.Time,` `,e.forkedAtTurn]}),(0,x.jsxs)(`h4`,{className:Vm.branchTitle,children:[e.actorName,` `,(0,x.jsxs)(`span`,{className:Vm.archetype,children:[`(`,e.actorArchetype,`)`]})]})]}),(0,x.jsx)(`span`,{className:`${Vm.status} ${Vm[`status_${e.status}`]}`,children:a})]}),e.status===`complete`&&i.length>0&&(0,x.jsxs)(`ul`,{className:Vm.deltas,"aria-label":`Delta vs parent`,children:[i.slice(0,4).map(e=>(0,x.jsx)(`li`,{className:`${Vm.delta} ${Vm[`direction_${e.direction}`]}`,title:`${e.bag}: parent=${e.parentValue}, branch=${e.branchValue}`,children:Bm(e)},`${e.bag}.${e.key}`)),i.length>4&&(0,x.jsxs)(`li`,{className:Vm.more,children:[`+`,i.length-4,` more`]})]}),e.status===`complete`&&i.length===0&&(0,x.jsx)(`p`,{className:Vm.identical,children:`Identical final state. Leader overrides did not diverge.`}),e.status===`error`&&e.errorMessage&&(0,x.jsx)(`p`,{className:Vm.error,role:`alert`,children:e.errorMessage})]})}function Gm(e){return typeof e==`number`?Number.isInteger(e)?e.toString():(Math.round(e*100)/100).toString():String(e)}var Km={tablist:`_tablist_iq6lf_1`,tab:`_tab_iq6lf_1`,tabActive:`_tabActive_iq6lf_39`};function qm({options:e,active:t,onChange:n,ariaLabel:r}){return(0,x.jsx)(`div`,{role:`tablist`,"aria-label":r,className:Km.tablist,children:e.map(e=>{let r=e.id===t,i=r?`${Km.tab} ${Km.tabActive}`:Km.tab;return(0,x.jsx)(`button`,{role:`tab`,"aria-selected":r,onClick:()=>n(e.id),type:`button`,className:i,children:e.label},e.id)})})}function Jm(){return{query:``,types:new Set,leader:null,turnRange:null,toolHash:``,toolExact:!1}}function Ym(e,t){let n=t.query.toLowerCase(),r=t.types.size>0,i=t.turnRange!==null,a=t.turnRange,o=t.toolHash.toLowerCase();return e.filter(e=>{if(r&&!t.types.has(e.type)||t.leader!==null&&e.leader!==t.leader)return!1;if(i&&a){let t=Xm(e);if(t===void 0||t<a[0]||t>a[1])return!1}return!(o&&!Qm(e,o,t.toolExact)||n&&!Zm(e,n))})}function Xm(e){let t=e.data?.turn;return typeof t==`number`?t:void 0}function Zm(e,t){if(e.type.toLowerCase().includes(t)||typeof e.leader==`string`&&e.leader.toLowerCase().includes(t))return!0;let n=e.data??{};for(let e of[`title`,`summary`,`department`,`name`]){let r=n[e];if(typeof r==`string`&&r.toLowerCase().includes(t))return!0}return!1}function Qm(e,t,n){let r=e=>n?e===t:e.includes(t),i=e.data??{},a=typeof i.name==`string`?i.name.trim().toLowerCase():``;if(a&&r(a))return!0;let o=Array.isArray(i.forgedTools)?i.forgedTools:[];for(let e of o){let t=e&&typeof e==`object`&&typeof e.name==`string`?e.name.trim().toLowerCase():``;if(t&&r(t))return!0}return!1}function $m(e){let t=new Set,n=[],r=new Set,i=0;for(let a of e){a.type&&t.add(a.type),typeof a.leader==`string`&&a.leader&&!r.has(a.leader)&&(r.add(a.leader),n.push(a.leader));let e=Xm(a);e!==void 0&&e>i&&(i=e)}return{types:[...t].sort(),actors:n,maxTurn:i}}function eh(e){let t=new URLSearchParams;e.query&&t.set(`logQuery`,e.query),e.types.size>0&&t.set(`logTypes`,[...e.types].join(`,`)),e.leader!==null&&t.set(`logLeader`,e.leader),e.turnRange&&(t.set(`logTurnMin`,String(e.turnRange[0])),t.set(`logTurnMax`,String(e.turnRange[1])));let n=t.toString();return n?`?${n}`:``}var th=[`logQuery`,`logTypes`,`logLeader`,`logTurnMin`,`logTurnMax`];function nh(e,t,n){let r=new URL(e);for(let e of th)r.searchParams.delete(e);return new URLSearchParams(eh(t)).forEach((e,t)=>r.searchParams.append(t,e)),n&&(r.hash=``),r.pathname+r.search+r.hash}function rh(e,t){let n=Jm(),r=new URLSearchParams(e.startsWith(`?`)?e.slice(1):e),i=r.get(`logQuery`);i&&(n.query=i);let a=r.get(`logTypes`);if(a){let e=a.split(`,`).map(e=>e.trim()).filter(Boolean);n.types=new Set(e)}let o=r.get(`logLeader`);o&&(n.leader=o);let s=r.get(`logTurnMin`),c=r.get(`logTurnMax`);if(s!==null&&c!==null){let e=Number(s),t=Number(c);Number.isFinite(e)&&Number.isFinite(t)&&(n.turnRange=[Math.min(e,t),Math.max(e,t)])}let l=t.startsWith(`#`)?t.slice(1):t,u=l.match(/(?:^|&)log=([^&]+)/);if(u){try{n.toolHash=decodeURIComponent(u[1])}catch{n.toolHash=u[1]}n.toolExact=/(?:^|&)logExact=1(?:&|$)/.test(l)}return n}var ih=[`quickstart`,`sim`,`viz`,`settings`,`reports`,`chat`,`library`,`studio`,`about`],ah={branches:{tab:`studio`,sub:`branches`},log:{tab:`settings`,sub:`log`}};function oh(e){return!!e&&ih.includes(e)}function sh(e){let{tab:t}=ch(e);return t}function ch(e){let t=new URL(e),n=t.searchParams.get(`tab`),r=t.searchParams.get(`sub`);if(n&&ah[n])return ah[n];if(oh(n))return{tab:n,sub:r??void 0};let i=t.hash.replace(/^#/,``);return i&&ah[i]?ah[i]:oh(i)?{tab:i,sub:r??void 0}:{tab:`quickstart`}}function lh(e,t){let n=new URL(e);return n.searchParams.set(`tab`,t),n.searchParams.delete(`sub`),n.hash=``,n.toString()}function uh(e,t,n){let r=new URL(lh(e,`settings`));for(let e of th)r.searchParams.delete(e);return r.searchParams.set(`sub`,`log`),n&&r.searchParams.set(`logLeader`,n),r.hash=t?`log=${encodeURIComponent(t)}&logExact=1`:``,r.toString()}function dh(e){if(typeof window>`u`)return;let t=new URL(window.location.href);e?t.searchParams.set(`sub`,e):t.searchParams.delete(`sub`),window.history.replaceState({},``,t.toString())}function fh(e,t){if(!t)return lh(e,`sim`);let n=new URL(e),r=new URL(t,n.origin);return r.pathname===`/sim`&&!r.searchParams.has(`tab`)&&r.searchParams.set(`tab`,`sim`),r.hash=``,r.toString()}var ph=[{id:`author`,label:`Author`},{id:`branches`,label:`Branches`}];function mh({initialSubTab:e=`author`}={}){let[t,n]=b.useState(e),r=b.useCallback(e=>{n(e),dh(e===`author`?null:e)},[]),[i,a]=b.useState(null),[o,s]=b.useState(!1),c=Im(),l=b.useCallback((e,t)=>{e.kind!==`error`&&a({input:e,filename:t,promote:null})},[]),u=b.useCallback(async()=>{if(!i||i.input.kind!==`single`)return;let e=await c.promoteSingle(i.input.artifact);e&&a(t=>t&&{...t,promote:e})},[i,c]),d=b.useCallback(async()=>{if(!i||i.input.kind!==`bundle`)return;let e=await c.promoteBundle(i.input.artifacts);e&&a(t=>t&&{...t,promote:e})},[i,c]),f=b.useCallback(()=>s(!0),[]),p=b.useCallback(()=>{a(null),s(!1)},[]),m=(()=>{if(i)return i.input.kind===`single`?[i.input.artifact]:i.input.artifacts})(),h=i?.promote?.kind===`bundle`?i.promote.bundleId:null;return(0,x.jsxs)(`div`,{className:sa.tab,children:[(0,x.jsx)(qm,{options:ph,active:t,onChange:r,ariaLabel:`Studio sub-navigation`}),t===`branches`&&(0,x.jsx)(Hm,{}),t===`author`&&!i&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(bm,{}),(0,x.jsx)(_m,{onLoaded:l})]}),t===`author`&&i&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:sa.loadedBar,children:[(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`strong`,{children:i.filename}),` · `,i.input.kind===`single`?`single artifact`:`bundle of ${i.input.artifacts.length}`,i.promote&&(i.promote.kind===`single`?i.promote.alreadyExisted?` · already in Library`:` · added to Library`:` · added to Library (${i.promote.runIds.length} runs)`)]}),(0,x.jsx)(`button`,{type:`button`,className:sa.bundleDrillBack,onClick:p,children:`Drop another`})]}),c.error&&(0,x.jsx)(`div`,{className:sa.errorBanner,role:`alert`,children:c.error}),i.input.kind===`single`&&(0,x.jsx)(xm,{artifact:i.input.artifact,onPromote:u,onCompare:f,promoteBusy:c.busy,alreadyExisted:i.promote?.kind===`single`&&i.promote.alreadyExisted}),i.input.kind===`bundle`&&(0,x.jsx)(Sm,{artifacts:i.input.artifacts,bundleId:i.input.bundleId,onPromote:d,onCompare:f,promoteBusy:c.busy,alreadyExisted:i.promote?.kind===`bundle`&&i.promote.alreadyExisted.every(Boolean)})]}),(0,x.jsx)(ra,{bundleId:h,extraArtifacts:m,open:o,onClose:()=>s(!1)})]})}function hh(e){let t=e.trim();if(!t)return{ok:!1,error:`URL is empty.`};if(t.length>2048)return{ok:!1,error:`URL exceeds 2048 characters.`};let n;try{n=new URL(t)}catch{return{ok:!1,error:`Not a valid URL.`}}return n.protocol!==`http:`&&n.protocol!==`https:`?{ok:!1,error:`Unsupported scheme ${n.protocol}. Use http or https.`}:{ok:!0,url:n}}function gh(e,t=200,n=5e4){let r=e.trim();return r?r.length<t?{ok:!1,reason:`too-short`}:r.length>n?{ok:!1,reason:`too-long`}:{ok:!0}:{ok:!1,reason:`empty`}}function _h(e,t){let n=[`metrics`,`capacities`,`statuses`,`environment`,`politics`],r=e.finalState;if(!r||t.length===0)return[];let i=[];for(let e of n){let n=r[e];if(n)for(let r of Object.keys(n)){let a=n[r],o=t.map(t=>t.finalState?.[e]?.[r]).filter(e=>e!==void 0);if(o.length!==0){if(typeof a==`number`&&o.every(e=>typeof e==`number`)){let t=[...o].sort((e,t)=>e-t),n=t.length%2==0?(t[t.length/2-1]+t[t.length/2])/2:t[(t.length-1)/2],s=a-n;if(s===0)continue;i.push({bag:e,key:r,parentValue:n,branchValue:a,delta:s,direction:s>0?`up`:`down`})}else{let t=o.find(e=>e!==a);if(t===void 0)continue;i.push({bag:e,key:r,parentValue:t,branchValue:a,direction:`changed`})}}}}return i.sort((e,t)=>e.delta!==void 0&&t.delta!==void 0?Math.abs(t.delta)-Math.abs(e.delta):e.delta===void 0?t.delta===void 0?0:1:-1)}function vh(e,t,n=`viz`){return Ot(e,t,n)}function yh(e,t){let n=new Blob([JSON.stringify(e,null,2)],{type:`application/json`}),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=t,document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(r),1e3)}var bh=`/assets/pdf.worker.min-CIqJB0yW.mjs`,xh=`modulepreload`,Sh=function(e){return`/`+e},Ch={},wh=function(e){return e.pathname.endsWith(`.css`)},Th=function(e,t,n){if(t in e)return e[t];let r=n();if(!r){e[t]=void 0;return}let i=r.then(()=>{e[t]=void 0},n=>{throw e[t]=void 0,n});return e[t]=i,i},Eh=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=Sh(t,n);let r=s(t),i=wh(r);return Th(Ch,r.href,()=>{if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let t=document.createElement(`link`);if(t.rel=i?`stylesheet`:xh,i||(t.as=`script`),t.crossOrigin=``,t.href=r.href,a&&t.setAttribute(`nonce`,a),document.head.appendChild(t),i)return new Promise((e,n)=>{let i=a=>{t.removeEventListener(`load`,i),t.removeEventListener(`error`,i),a.type===`error`?n(Error(`Unable to preload CSS for ${r}`)):e(a)};t.addEventListener(`load`,i),t.addEventListener(`error`,i)})})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})};function Dh(){if(typeof window>`u`)return bh;try{return new URL(bh,window.location.origin).toString()}catch{return bh}}var Oh=null;async function kh(){if(Oh)return Oh;let e=await Eh(()=>import(`./pdf-YwugTw7Y.js`),[]);return e.GlobalWorkerOptions.workerSrc=Dh(),Oh=e,e}async function Ah(e,t={}){let{maxBytes:n=5e4,maxPages:r=100}=t;if(!e.name.toLowerCase().endsWith(`.pdf`)&&e.type!==`application/pdf`)throw Error(`File is not a PDF: ${e.name}`);let i=await kh(),a=await e.arrayBuffer(),o=i.getDocument({data:a}),s=[],c=0,l=!1;try{let e=await o.promise,t=Math.min(e.numPages,r);for(let r=1;r<=t;r++){let t=(await(await e.getPage(r)).getTextContent()).items.map(e=>e.str??``).join(` `).replace(/\s+/g,` `).trim(),i=new Blob([t]).size;if(c+i>n){let e=n-c;if(e>0){let r=new TextEncoder().encode(t).slice(0,e),i=new TextDecoder(`utf-8`,{fatal:!1}).decode(r).replace(/�$/,``);s.push(i),c=n}l=!0;break}s.push(t),c+=i}let i=s.join(`
110
110
 
111
111
  `);if(i.trim().length===0){let e=Error(`PDF contains no extractable text. It may be a scanned image without OCR.`);throw e.code=`PDF_NO_TEXT`,e}return{text:i,pages:e.numPages,truncated:l}}finally{try{await o.destroy()}catch{}}}function jh(e){let t=Mh(e.seedText.length>0?e.seedText:`<paste your scenario above>`),n=[];return n.push(`// Recreate this Quickstart run from your code.`),n.push(`import { runMany } from 'paracosm';`),n.push(``),e.sourceUrl&&e.sourceUrl.length>0?(n.push(`const { runs } = await runMany(`),n.push(` new URL('${Nh(e.sourceUrl)}'),`),n.push(` { count: ${e.actorCount} },`),n.push(`);`)):(n.push(`const { runs } = await runMany(`),n.push(` \`${t}\`,`),n.push(` { count: ${e.actorCount} },`),n.push(`);`)),n.push(``),n.push(`runs.forEach(({ actor, artifact }) => console.log(actor.name, artifact.fingerprint));`),n.join(`
112
112
  `)}function Mh(e){return e.replace(/\\/g,`\\\\`).replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}function Nh(e){return e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`)}function Ph(e){let t={seedText:e.seedText.length>0?e.seedText:`<paste your scenario above>`};e.domainHint&&e.domainHint.trim().length>0&&(t.domainHint=e.domainHint),e.actorCount!==2&&(t.actorCount=e.actorCount);let n=`'${JSON.stringify(t).replace(/'/g,`'\\''`)}'`,r=[];return r.push(`# This compiles a typed ScenarioPackage from your prompt.`),r.push(`# For the full flow (auto-generate HEXACO leaders + simulate),`),r.push(`# install paracosm and use the TypeScript tab.`),r.push(`curl -X POST https://paracosm.agentos.sh/api/quickstart/compile-from-seed \\`),r.push(` -H 'Content-Type: application/json' \\`),r.push(` -d ${n}`),r.join(`
113
- `)}var Fh={wrap:`_wrap_5ldo7_1`,toggle:`_toggle_5ldo7_6`,panel:`_panel_5ldo7_34`,tabRow:`_tabRow_5ldo7_42`,tabPill:`_tabPill_5ldo7_51`,copyBtn:`_copyBtn_5ldo7_74`,code:`_code_5ldo7_97`};function Ih(e){let{disabled:t,initiallyExpanded:n=!1,initialTab:r=`ts`,...i}=e,[a,o]=(0,b.useState)(n),[s,c]=(0,b.useState)(r),[l,u]=(0,b.useState)(`idle`),d=(0,b.useMemo)(()=>jh(i),[i.seedText,i.domainHint,i.sourceUrl,i.actorCount]),f=(0,b.useMemo)(()=>Ph(i),[i.seedText,i.domainHint,i.sourceUrl,i.actorCount]),p=s===`ts`?d:f,m=(0,b.useCallback)(async()=>{try{await navigator.clipboard.writeText(p),u(`ok`)}catch{u(`fail`)}window.setTimeout(()=>u(`idle`),1500)},[p]),h=`quickstart-view-as-code-panel`,g=`quickstart-view-as-code-tab-ts`,_=`quickstart-view-as-code-tab-curl`,v=s===`ts`?g:_;return(0,x.jsxs)(`div`,{className:Fh.wrap,children:[(0,x.jsx)(`button`,{type:`button`,className:Fh.toggle,"aria-expanded":a,"aria-controls":h,disabled:t,onClick:()=>o(e=>!e),children:a?`▾ Hide code`:`▸ View as code`}),a&&(0,x.jsxs)(`div`,{id:h,role:`tabpanel`,"aria-labelledby":v,className:Fh.panel,children:[(0,x.jsxs)(`div`,{className:Fh.tabRow,role:`tablist`,"aria-label":`Recipe language`,children:[(0,x.jsx)(`button`,{type:`button`,id:g,role:`tab`,"aria-pressed":s===`ts`,"aria-selected":s===`ts`,"aria-controls":h,className:Fh.tabPill,onClick:()=>c(`ts`),children:`TypeScript`}),(0,x.jsx)(`button`,{type:`button`,id:_,role:`tab`,"aria-pressed":s===`curl`,"aria-selected":s===`curl`,"aria-controls":h,className:Fh.tabPill,onClick:()=>c(`curl`),children:`curl`}),(0,x.jsx)(`button`,{type:`button`,className:Fh.copyBtn,onClick:m,"aria-label":`Copy ${s===`ts`?`TypeScript`:`curl`} recipe`,children:l===`ok`?`Copied ✓`:l===`fail`?`Press ⌘C`:`Copy`})]}),(0,x.jsx)(`pre`,{className:Fh.code,children:(0,x.jsx)(`code`,{children:p})})]})]})}var Lh={card:`_card_srwu8_2`,heading:`_heading_srwu8_15`,subline:`_subline_srwu8_25`,scenarioPickerRow:`_scenarioPickerRow_srwu8_34`,scenarioPickerLabel:`_scenarioPickerLabel_srwu8_45`,scenarioPickerSelect:`_scenarioPickerSelect_srwu8_54`,scenarioPickerHint:`_scenarioPickerHint_srwu8_66`,actorRow:`_actorRow_srwu8_73`,actorLabel:`_actorLabel_srwu8_82`,actorSlider:`_actorSlider_srwu8_91`,actorValue:`_actorValue_srwu8_96`,runButton:`_runButton_srwu8_102`,runButtonFull:`_runButtonFull_srwu8_134`,runButtonCompact:`_runButtonCompact_srwu8_138`,tagline:`_tagline_srwu8_144`,tradeoff:`_tradeoff_srwu8_154`};function Rh(e){let t=Date.parse(e);if(!Number.isFinite(t))return``;let n=Date.now()-t;if(n<0)return`just now`;let r=Math.floor(n/6e4);if(r<1)return`just now`;if(r<60)return`${r}m ago`;let i=Math.floor(r/60);if(i<24)return`${i}h ago`;let a=Math.floor(i/24);if(a<7)return`${a}d ago`;let o=Math.floor(a/7);if(o<5)return`${o}w ago`;let s=Math.floor(a/30);return s<12?`${s}mo ago`:new Date(e).getFullYear().toString()}function zh({onRunStart:e,disabled:t=!1,initialActorCount:n=2}){let r=Xk(),i=!Qk()||t,[a,o]=(0,b.useState)(n),[s,c]=(0,b.useState)(!1),[l,u]=(0,b.useState)([]),[d,f]=(0,b.useState)(!1),p=(0,b.useRef)(!0);(0,b.useEffect)(()=>{let e=!1;return fetch(`/scenarios`).then(e=>e.ok?e.json():null).then(t=>{e||u(t?.scenarios??[])}).catch(()=>{}),()=>{e=!0,p.current=!1}},[]);let m=async e=>{if(!(e===r.id||d)){f(!0);try{(await fetch(`/scenario/switch`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:e})})).ok?(te(),window.location.reload()):p.current&&f(!1)}catch{p.current&&f(!1)}}},h=r.presets[0]?.leaders??r.presets[0]?.actors??[],g=h.length,_=g>=2,v=a>g,y=r.labels.name,S=r.labels.tagline?.trim(),C=_?`${h[0].name} (${h[0].archetype}) vs ${h[1].name} (${h[1].archetype})`:`Auto-generated leaders (no preset)`,w=`loaded-scenario-cta-heading`,T=`loaded-scenario-actor-count`,E=()=>{s||i||(c(!0),e(a))},D=`${a} ${a===1?`actor`:`actors`}`,O=s?`Launching...`:`Run ${D} against ${y}`,k=s?`Launching...`:`${O} ->`,A=s?`Launching...`:`Run ${D}`,j=`loaded-scenario-cta-picker`;return(0,x.jsxs)(`section`,{className:Lh.card,"aria-labelledby":w,children:[(0,x.jsxs)(`h2`,{className:Lh.heading,id:w,children:[`▶ Run with the loaded scenario: `,y]}),S&&(0,x.jsx)(`p`,{className:Lh.tagline,children:S}),(0,x.jsx)(`div`,{className:Lh.subline,children:C}),l.length>=2&&(()=>{let e=l.some(e=>e.id===r.id)?l:[...l,{id:r.id,name:r.labels.name||r.id,source:`active`}];return(0,x.jsxs)(`div`,{className:Lh.scenarioPickerRow,children:[(0,x.jsx)(`label`,{className:Lh.scenarioPickerLabel,htmlFor:j,children:`Scenario`}),(0,x.jsx)(`select`,{id:j,className:Lh.scenarioPickerSelect,value:r.id,onChange:e=>m(e.target.value),disabled:i||s||d,"aria-label":`Switch active scenario`,children:e.map(e=>{let t=e.source===`builtin`?`[builtin]`:e.source===`disk`?`[disk]`:e.source===`compiled`?`[compiled]`:e.source===`active`?`[active]`:``,n=[];if(t&&n.push(t),typeof e.runCount==`number`&&e.runCount>0&&n.push(`${e.runCount} run${e.runCount===1?``:`s`}`),e.compiledAt){let t=Rh(e.compiledAt);t&&n.push(t)}let r=n.length>0?` · ${n.join(` · `)}`:``;return(0,x.jsxs)(`option`,{value:e.id,children:[e.name,r]},e.id)})}),d&&(0,x.jsx)(`span`,{className:Lh.scenarioPickerHint,children:`Switching…`})]})})(),(0,x.jsxs)(`div`,{className:Lh.actorRow,children:[(0,x.jsx)(`label`,{className:Lh.actorLabel,htmlFor:T,children:`Actors`}),(0,x.jsx)(`input`,{id:T,type:`range`,min:1,max:300,value:a,onChange:e=>o(parseInt(e.target.value,10)),disabled:i||s,className:Lh.actorSlider,"aria-label":`Number of parallel actors`}),(0,x.jsx)(`span`,{className:Lh.actorValue,children:a})]}),(0,x.jsxs)(`button`,{type:`button`,className:Lh.runButton,onClick:E,disabled:i||s,"aria-busy":s,"aria-label":O,children:[(0,x.jsx)(`span`,{className:Lh.runButtonFull,"aria-hidden":`true`,children:k}),(0,x.jsx)(`span`,{className:Lh.runButtonCompact,"aria-hidden":`true`,children:A})]}),(0,x.jsxs)(`div`,{className:Lh.tradeoff,children:[_&&!v&&`Same scenario, fresh seed: skips the compile step.`,_&&v&&`Same scenario; ${a} LLM-generated actors replace the preset leaders for this run (~30s for generation).`,!_&&`Same scenario; ~30s for actor generation since no preset is defined.`]})]})}var W={backdrop:`_backdrop_nucmo_1`,backdropFadeIn:`_backdropFadeIn_nucmo_1`,drawer:`_drawer_nucmo_17`,open:`_open_nucmo_34`,header:`_header_nucmo_38`,closeBtn:`_closeBtn_nucmo_50`,sourceBadge:`_sourceBadge_nucmo_63`,summary:`_summary_nucmo_86`,nameRow:`_nameRow_nucmo_94`,name:`_name_nucmo_94`,nameEditBtn:`_nameEditBtn_nucmo_110`,nameEditForm:`_nameEditForm_nucmo_129`,nameEditInput:`_nameEditInput_nucmo_135`,nameEditActions:`_nameEditActions_nucmo_150`,nameEditSave:`_nameEditSave_nucmo_155`,nameEditCancel:`_nameEditCancel_nucmo_173`,nameEditError:`_nameEditError_nucmo_195`,description:`_description_nucmo_202`,metaGrid:`_metaGrid_nucmo_209`,meta:`_meta_nucmo_209`,sectionHeading:`_sectionHeading_nucmo_235`,seedSection:`_seedSection_nucmo_245`,seedHint:`_seedHint_nucmo_250`,seedBody:`_seedBody_nucmo_257`,presetsSection:`_presetsSection_nucmo_273`,departmentsSection:`_departmentsSection_nucmo_274`,sectionHint:`_sectionHint_nucmo_279`,sectionCount:`_sectionCount_nucmo_287`,presetList:`_presetList_nucmo_294`,presetCard:`_presetCard_nucmo_303`,presetHeader:`_presetHeader_nucmo_313`,presetName:`_presetName_nucmo_320`,presetArchetype:`_presetArchetype_nucmo_327`,presetUnit:`_presetUnit_nucmo_340`,hexacoList:`_hexacoList_nucmo_347`,hexacoRow:`_hexacoRow_nucmo_356`,hexacoAxis:`_hexacoAxis_nucmo_364`,hexacoBar:`_hexacoBar_nucmo_372`,hexacoFill:`_hexacoFill_nucmo_380`,hexacoValue:`_hexacoValue_nucmo_386`,presetInstructions:`_presetInstructions_nucmo_393`,deptChips:`_deptChips_nucmo_401`,deptChip:`_deptChip_nucmo_401`,deptIcon:`_deptIcon_nucmo_423`,deptRole:`_deptRole_nucmo_427`,recentSection:`_recentSection_nucmo_431`,statusLine:`_statusLine_nucmo_438`,error:`_error_nucmo_445`,recentList:`_recentList_nucmo_449`,recentRow:`_recentRow_nucmo_458`,recentTitle:`_recentTitle_nucmo_468`,recentArchetype:`_recentArchetype_nucmo_475`,recentMeta:`_recentMeta_nucmo_480`,footer:`_footer_nucmo_486`,actorRow:`_actorRow_nucmo_497`,actorLabel:`_actorLabel_nucmo_505`,actorSlider:`_actorSlider_nucmo_514`,actorValue:`_actorValue_nucmo_519`,runButton:`_runButton_nucmo_527`,deleteButton:`_deleteButton_nucmo_549`,deleteError:`_deleteError_nucmo_572`},Bh=`Admin token refused and cleared. ${R}`,Vh=(e,t)=>`The server refused the admin token this ${e} was sent with. A newer token is saved in this browser; press ${t} to try again with it.`,Hh=`scenario-rename-error`;function Uh(e){let t=Date.parse(e);if(!Number.isFinite(t))return``;let n=Date.now()-t;if(n<0)return`just now`;let r=Math.floor(n/6e4);if(r<1)return`just now`;if(r<60)return`${r}m ago`;let i=Math.floor(r/60);if(i<24)return`${i}h ago`;let a=Math.floor(i/24);if(a<7)return`${a}d ago`;let o=Math.floor(a/7);if(o<5)return`${o}w ago`;let s=Math.floor(a/30);return s<12?`${s}mo ago`:new Date(e).getFullYear().toString()}function Wh(e){return typeof e!=`number`||!Number.isFinite(e)?`—`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Gh(e){if(typeof e!=`number`||!Number.isFinite(e)||e<=0)return`—`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r>0?`${n}m ${r}s`:`${n}m`}function Kh(e){return e?Array.from(e.querySelectorAll(`button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`)).filter(e=>!e.hasAttribute(`disabled`)&&e.getAttribute(`aria-hidden`)!==`true`):[]}function qh(e){let{scenario:t,disabled:n=!1,initialActorCount:r=2,onRunScenario:i,onClose:a,onDeleted:o,onRenamed:s}=e,c=t!==null,[l,u]=(0,b.useState)(r),[d,f]=(0,b.useState)([]),[p,m]=(0,b.useState)(!1),[h,g]=(0,b.useState)(null),[_,v]=(0,b.useState)(null),[y,S]=(0,b.useState)(!1),[C,w]=(0,b.useState)(!1),[T,E]=(0,b.useState)(null),[D,O]=(0,b.useState)(!1),[k,A]=(0,b.useState)(``),[j,ee]=(0,b.useState)(!1),[te,M]=(0,b.useState)(null),[N,ne]=(0,b.useState)(null);(0,b.useEffect)(()=>{ne(null),O(!1),M(null)},[t?.id]);let[P,re]=(0,b.useState)(null);(0,b.useEffect)(()=>{if(c)return E(null),re(B()||null),Se(()=>re(B()||null))},[c]);let ie=!!P&&t?.source===`compiled`,F=!!P&&t?.source===`compiled`,I=(0,b.useRef)(null),ae=(0,b.useRef)(null);if((0,b.useEffect)(()=>{if(!t){f([]),g(null),v(null);return}let e=!1;return m(!0),g(null),S(!0),v(null),fetch(`/api/v1/runs?scenario=${encodeURIComponent(t.id)}&limit=5`).then(async t=>{if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();e||f(n.runs??[])}).catch(t=>{e||(g(t instanceof Error?t.message:String(t)),f([]))}).finally(()=>{e||m(!1)}),fetch(`/scenarios/${encodeURIComponent(t.id)}`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return e.json()}).then(t=>{e||v(t)}).catch(()=>{e||v(null)}).finally(()=>{e||S(!1)}),()=>{e=!0}},[t?.id]),(0,b.useEffect)(()=>{c?(ae.current=document.activeElement,requestAnimationFrame(()=>{(I.current?.querySelector(`button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])`))?.focus()})):ae.current?.focus()},[c]),(0,b.useEffect)(()=>{if(!c)return;function e(e){if(e.key===`Escape`)e.preventDefault(),a();else if(e.key===`Tab`){let t=Kh(I.current);if(t.length===0){e.preventDefault();return}let n=t[0],r=t[t.length-1],i=document.activeElement;!i||!I.current?.contains(i)?(e.preventDefault(),n.focus()):e.shiftKey&&i===n?(e.preventDefault(),r.focus()):!e.shiftKey&&i===r&&(e.preventDefault(),n.focus())}}return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[c,a]),!t)return null;let oe=`scenario-detail-actor-count`,se=()=>{t&&F&&(A(N??t.name),O(!0),M(null))},ce=()=>{O(!1),A(``),M(null)},le=async()=>{if(!t||!P||j)return;let e=k.trim();if(e.length===0){M(`Name cannot be empty.`);return}if(e===(N??t.name)){O(!1);return}let n=xe(P);if(n)M(n),re(B()||null);else{ee(!0),M(null);try{let n=await fetch(`/scenarios/${encodeURIComponent(t.id)}/rename`,{method:`POST`,headers:{"Content-Type":`application/json`,[fe]:P},body:JSON.stringify({name:e})});if(n.status===401){be(P);let e=B()||null;re(e),M(e?Vh(`rename`,`Save`):Bh);return}if(!n.ok){let e=await n.json().catch(()=>({}));M(e.message??e.error??`Rename failed: HTTP ${n.status}`);return}let r=(await n.json()).name??e;ne(r),O(!1),A(``),s?.(t.id,r)}catch(e){M(e instanceof Error?e.message:String(e))}finally{ee(!1)}}};return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{className:W.backdrop,onClick:a,role:`presentation`}),(0,x.jsxs)(`aside`,{ref:I,className:`${W.drawer} ${c?W.open:``}`,role:`dialog`,"aria-label":`Scenario detail: ${t.name}`,"aria-modal":`true`,children:[(0,x.jsxs)(`header`,{className:W.header,children:[(0,x.jsx)(`button`,{type:`button`,onClick:a,className:W.closeBtn,"aria-label":`Close scenario detail`,children:`×`}),(0,x.jsx)(`span`,{className:W.sourceBadge,"data-source":t.source??`other`,children:Jh(t.source)})]}),(0,x.jsxs)(`section`,{className:W.summary,children:[D?(0,x.jsxs)(`form`,{className:W.nameEditForm,onSubmit:e=>{e.preventDefault(),le()},children:[(0,x.jsx)(`input`,{type:`text`,value:k,onChange:e=>A(e.target.value),onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),ce())},disabled:j,maxLength:100,autoFocus:!0,className:W.nameEditInput,"aria-label":`New scenario name`}),(0,x.jsxs)(`div`,{className:W.nameEditActions,children:[(0,x.jsx)(`button`,{type:`submit`,className:W.nameEditSave,disabled:j||!P||k.trim().length===0,"aria-describedby":te?Hh:void 0,children:j?`Saving…`:`Save`}),(0,x.jsx)(`button`,{type:`button`,className:W.nameEditCancel,onClick:ce,disabled:j,children:`Cancel`})]}),te&&(0,x.jsx)(`p`,{id:Hh,className:W.nameEditError,role:`alert`,children:te})]}):(0,x.jsxs)(`div`,{className:W.nameRow,children:[(0,x.jsx)(`h2`,{className:W.name,children:N??t.name}),F&&(0,x.jsx)(`button`,{type:`button`,className:W.nameEditBtn,onClick:se,"aria-label":`Rename ${N??t.name}`,title:`Rename scenario`,children:`✎`})]}),t.description&&(0,x.jsx)(`p`,{className:W.description,children:t.description}),(0,x.jsxs)(`dl`,{className:W.metaGrid,children:[typeof t.runCount==`number`&&(0,x.jsxs)(`div`,{className:W.meta,children:[(0,x.jsx)(`dt`,{children:`Total runs`}),(0,x.jsx)(`dd`,{children:t.runCount.toLocaleString()})]}),typeof t.departments==`number`&&(0,x.jsxs)(`div`,{className:W.meta,children:[(0,x.jsx)(`dt`,{children:`Departments`}),(0,x.jsx)(`dd`,{children:t.departments})]}),t.compiledAt&&(0,x.jsxs)(`div`,{className:W.meta,children:[(0,x.jsx)(`dt`,{children:`Compiled`}),(0,x.jsx)(`dd`,{title:t.compiledAt,children:Uh(t.compiledAt)})]}),(0,x.jsxs)(`div`,{className:W.meta,children:[(0,x.jsx)(`dt`,{children:`Source`}),(0,x.jsx)(`dd`,{children:Jh(t.source)})]})]})]}),t.seedText&&(0,x.jsxs)(`section`,{className:W.seedSection,"aria-labelledby":`scenario-detail-seed-heading`,children:[(0,x.jsx)(`h3`,{className:W.sectionHeading,id:`scenario-detail-seed-heading`,children:`Seed prompt`}),(0,x.jsx)(`p`,{className:W.seedHint,children:`Original brief that compile-from-seed turned into this scenario. Truncated to 1KB at persist time so very long sources read as their leading section.`}),(0,x.jsx)(`pre`,{className:W.seedBody,children:t.seedText})]}),_&&_.presets.length>0&&_.presets[0].leaders.length>0&&(0,x.jsxs)(`section`,{className:W.presetsSection,"aria-labelledby":`scenario-detail-presets-heading`,children:[(0,x.jsx)(`h3`,{className:W.sectionHeading,id:`scenario-detail-presets-heading`,children:`Leader presets`}),(0,x.jsx)(`p`,{className:W.sectionHint,children:`Default leader pair the scenario ships with. Picking Run with the slot count below fills these in first; extra slots beyond the preset get LLM-generated.`}),(0,x.jsx)(`ul`,{className:W.presetList,role:`list`,children:_.presets[0].leaders.map((e,t)=>(0,x.jsxs)(`li`,{className:W.presetCard,children:[(0,x.jsxs)(`div`,{className:W.presetHeader,children:[(0,x.jsx)(`span`,{className:W.presetName,children:e.name}),e.archetype&&(0,x.jsx)(`span`,{className:W.presetArchetype,children:e.archetype})]}),e.unit&&(0,x.jsx)(`span`,{className:W.presetUnit,children:e.unit}),e.hexaco&&Object.keys(e.hexaco).length>0&&(0,x.jsx)(`ul`,{className:W.hexacoList,"aria-label":`HEXACO profile for ${e.name}`,children:Object.entries(e.hexaco).slice(0,6).map(([e,t])=>{let n=Math.round((Number(t)||0)*100);return(0,x.jsxs)(`li`,{className:W.hexacoRow,children:[(0,x.jsx)(`span`,{className:W.hexacoAxis,children:e.length>6?e.slice(0,6):e}),(0,x.jsx)(`span`,{className:W.hexacoBar,role:`img`,"aria-label":`${e} ${n}%`,children:(0,x.jsx)(`span`,{className:W.hexacoFill,style:{width:`${n}%`}})}),(0,x.jsx)(`span`,{className:W.hexacoValue,children:n})]},e)})}),e.instructions&&(0,x.jsx)(`p`,{className:W.presetInstructions,title:e.instructions,children:e.instructions.length>220?`${e.instructions.slice(0,220)}…`:e.instructions})]},`${e.name}-${t}`))})]}),_&&_.departments.length>0&&(0,x.jsxs)(`section`,{className:W.departmentsSection,"aria-labelledby":`scenario-detail-depts-heading`,children:[(0,x.jsxs)(`h3`,{className:W.sectionHeading,id:`scenario-detail-depts-heading`,children:[`Departments `,(0,x.jsxs)(`span`,{className:W.sectionCount,children:[`· `,_.departments.length]})]}),(0,x.jsx)(`ul`,{className:W.deptChips,role:`list`,children:_.departments.map(e=>(0,x.jsxs)(`li`,{className:W.deptChip,children:[e.icon&&(0,x.jsx)(`span`,{className:W.deptIcon,"aria-hidden":`true`,children:e.icon}),(0,x.jsx)(`span`,{children:e.label}),e.role&&(0,x.jsxs)(`span`,{className:W.deptRole,children:[`· `,e.role]})]},e.id))})]}),y&&!_&&(0,x.jsx)(`p`,{className:W.statusLine,style:{padding:`0 18px`},children:`Loading scenario detail…`}),(0,x.jsxs)(`section`,{className:W.recentSection,"aria-labelledby":`scenario-detail-recent-heading`,children:[(0,x.jsx)(`h3`,{className:W.sectionHeading,id:`scenario-detail-recent-heading`,children:`Recent runs`}),p&&(0,x.jsx)(`p`,{className:W.statusLine,children:`Loading recent runs…`}),h&&!p&&(0,x.jsxs)(`p`,{className:`${W.statusLine} ${W.error}`,role:`alert`,children:[`Failed to load recent runs: `,h]}),!p&&!h&&d.length===0&&(0,x.jsx)(`p`,{className:W.statusLine,children:`No runs yet on this scenario.`}),d.length>0&&(0,x.jsx)(`ul`,{className:W.recentList,role:`list`,children:d.map(e=>(0,x.jsxs)(`li`,{className:W.recentRow,children:[(0,x.jsxs)(`span`,{className:W.recentTitle,children:[e.actorName??`Unknown leader`,e.actorArchetype&&(0,x.jsxs)(`span`,{className:W.recentArchetype,children:[` · `,e.actorArchetype]})]}),(0,x.jsxs)(`span`,{className:W.recentMeta,children:[Uh(e.createdAt),` · `,Wh(e.costUSD),` · `,Gh(e.durationMs)]})]},e.runId))})]}),(0,x.jsxs)(`footer`,{className:W.footer,children:[(0,x.jsxs)(`div`,{className:W.actorRow,children:[(0,x.jsx)(`label`,{htmlFor:oe,className:W.actorLabel,children:`Actors`}),(0,x.jsx)(`input`,{id:oe,type:`range`,min:1,max:300,value:l,onChange:e=>u(parseInt(e.target.value,10)),disabled:n,className:W.actorSlider,"aria-label":`Number of parallel actors`}),(0,x.jsx)(`span`,{className:W.actorValue,children:l})]}),(0,x.jsxs)(`button`,{type:`button`,className:W.runButton,onClick:()=>i(t.id,l),disabled:n||C,"aria-label":`Run ${l} actor${l===1?``:`s`} against ${t.name}`,children:[`Run `,l,` `,l===1?`actor`:`actors`,` →`]}),ie&&(0,x.jsx)(`button`,{type:`button`,className:W.deleteButton,onClick:async()=>{if(!t||!P||C||!(typeof window<`u`&&window.confirm(`Delete this scenario?\n\n"${t.name}"\n\nRemoves the scenario from disk + the live catalog. Past runs are kept (they live in run-history). Cannot be undone.`)))return;let e=xe(P);if(e)E(e),re(B()||null);else{w(!0),E(null);try{let e=await fetch(`/admin/scenarios/${encodeURIComponent(t.id)}`,{method:`DELETE`,headers:{[fe]:P}});if(e.status===401){be(P);let e=B()||null;re(e),E(e?Vh(`delete`,`Delete`):Bh);return}if(!e.ok){let t=await e.json().catch(()=>({}));E(t.message??t.error??`Delete failed: HTTP ${e.status}`);return}o?.(t.id),a()}catch(e){E(e instanceof Error?e.message:String(e))}finally{w(!1)}}},disabled:C||n,"aria-label":`Delete scenario ${t.name}`,children:C?`Deleting…`:`Delete (admin)`}),T&&(0,x.jsx)(`p`,{className:W.deleteError,role:`alert`,children:T})]})]})]})}function Jh(e){return e===`builtin`?`Built-in`:e===`disk`?`Saved`:e===`compiled`?`Custom`:e===`memory`?`Memory`:e??`Unknown`}var Yh={section:`_section_1l91i_1`,header:`_header_1l91i_5`,heading:`_heading_1l91i_14`,count:`_count_1l91i_24`,statusLine:`_statusLine_1l91i_32`,error:`_error_1l91i_39`,actorRow:`_actorRow_1l91i_43`,actorLabel:`_actorLabel_1l91i_54`,actorSlider:`_actorSlider_1l91i_63`,actorValue:`_actorValue_1l91i_68`,filterRow:`_filterRow_1l91i_76`,searchLabel:`_searchLabel_1l91i_84`,searchInput:`_searchInput_1l91i_90`,chipGroup:`_chipGroup_1l91i_108`,chip:`_chip_1l91i_108`,chipActive:`_chipActive_1l91i_133`,chipCount:`_chipCount_1l91i_139`,sortLabel:`_sortLabel_1l91i_145`,sortSelect:`_sortSelect_1l91i_150`,emptyMatches:`_emptyMatches_1l91i_165`,clearFiltersBtn:`_clearFiltersBtn_1l91i_176`,grid:`_grid_1l91i_187`,card:`_card_1l91i_196`,cardBody:`_cardBody_1l91i_211`,cardActive:`_cardActive_1l91i_231`,cardHeader:`_cardHeader_1l91i_236`,sourceBadge:`_sourceBadge_1l91i_243`,badge_builtin:`_badge_builtin_1l91i_254`,badge_disk:`_badge_disk_1l91i_258`,badge_compiled:`_badge_compiled_1l91i_262`,badge_memory:`_badge_memory_1l91i_262`,badge_other:`_badge_other_1l91i_266`,activeBadge:`_activeBadge_1l91i_270`,cardName:`_cardName_1l91i_282`,cardSeed:`_cardSeed_1l91i_292`,cardStats:`_cardStats_1l91i_303`,stat:`_stat_1l91i_32`,statKey:`_statKey_1l91i_317`,statValue:`_statValue_1l91i_324`,runButton:`_runButton_1l91i_331`};function Xh(e){let t=Date.parse(e);if(!Number.isFinite(t))return``;let n=Date.now()-t;if(n<0)return`just now`;let r=Math.floor(n/6e4);if(r<1)return`just now`;if(r<60)return`${r}m ago`;let i=Math.floor(r/60);if(i<24)return`${i}h ago`;let a=Math.floor(i/24);if(a<7)return`${a}d ago`;let o=Math.floor(a/7);if(o<5)return`${o}w ago`;let s=Math.floor(a/30);return s<12?`${s}mo ago`:new Date(e).getFullYear().toString()}function Zh(e){return e===`builtin`?`builtin`:e===`disk`?`disk`:e===`compiled`?`compiled`:e===`memory`?`memory`:`other`}function Qh(e){return e===`builtin`?`Built-in`:e===`disk`?`Saved`:e===`compiled`?`Custom`:e===`memory`?`Memory`:e??`Unknown`}function $h(e){let{disabled:t=!1,onRunScenario:n}=e,r=Xk(),i=!Qk()||t,a=r.id,[o,s]=(0,b.useState)([]),[c,l]=(0,b.useState)(2),[u,d]=(0,b.useState)(!0),[f,p]=(0,b.useState)(null),[m,h]=(0,b.useState)(``),[g,_]=(0,b.useState)(``);(0,b.useEffect)(()=>{let e=setTimeout(()=>_(m),120);return()=>clearTimeout(e)},[m]);let[v,y]=(0,b.useState)(`all`),[S,C]=(0,b.useState)(`curated`),[w,T]=(0,b.useState)(null);if((0,b.useEffect)(()=>{let e=!1,t=null,n=async()=>{try{let t=await fetch(`/scenarios`);if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();if(e)return;s(n.scenarios??[]),p(null)}catch(t){if(e)return;p(t instanceof Error?t.message:String(t))}finally{e||d(!1)}};return n(),t=setInterval(n,3e4),()=>{e=!0,t&&clearInterval(t)}},[]),u&&o.length===0)return(0,x.jsxs)(`section`,{className:Yh.section,"aria-labelledby":`scenario-catalog-heading`,children:[(0,x.jsx)(`h3`,{className:Yh.heading,id:`scenario-catalog-heading`,children:`All scenarios`}),(0,x.jsx)(`p`,{className:Yh.statusLine,children:`Loading catalog…`})]});if(f&&o.length===0)return(0,x.jsxs)(`section`,{className:Yh.section,"aria-labelledby":`scenario-catalog-heading`,children:[(0,x.jsx)(`h3`,{className:Yh.heading,id:`scenario-catalog-heading`,children:`All scenarios`}),(0,x.jsxs)(`p`,{className:`${Yh.statusLine} ${Yh.error}`,role:`alert`,children:[`Failed to load catalog: `,f]})]});if(o.length<2)return null;let E=`scenario-catalog-actor-count`,D=`scenario-catalog-search`,O=g.trim().length>0||v!==`all`,k=g.trim().toLowerCase(),A=[...o.filter(e=>e.id===a?!0:v!==`all`&&e.source!==v?!1:k.length===0||[e.name,e.id,e.seedText??``,e.description??``].join(` `).toLowerCase().includes(k))].sort((e,t)=>{if(e.id===a)return-1;if(t.id===a)return 1;if(S===`most-runs`){let n=(t.runCount??0)-(e.runCount??0);if(n!==0)return n}else if(S===`newest`){let n=e.compiledAt?Date.parse(e.compiledAt):0,r=t.compiledAt?Date.parse(t.compiledAt):0;if(n!==r)return r-n}else if(S===`alphabetical`)return e.name.localeCompare(t.name);else{let n=(t.runCount??0)-(e.runCount??0);if(n!==0)return n;if(e.compiledAt&&t.compiledAt){let n=Date.parse(e.compiledAt),r=Date.parse(t.compiledAt);if(Number.isFinite(n)&&Number.isFinite(r)&&n!==r)return r-n}}return e.name.localeCompare(t.name)}),j=o.reduce((e,t)=>{let n=t.source??`other`;return e[n]=(e[n]??0)+1,e},{});return(0,x.jsxs)(`section`,{className:Yh.section,"aria-labelledby":`scenario-catalog-heading`,children:[(0,x.jsxs)(`header`,{className:Yh.header,children:[(0,x.jsxs)(`h3`,{className:Yh.heading,id:`scenario-catalog-heading`,children:[`All scenarios`,` `,(0,x.jsxs)(`span`,{className:Yh.count,children:[`· `,O?`${A.length} of ${o.length}`:o.length]})]}),(0,x.jsxs)(`div`,{className:Yh.actorRow,children:[(0,x.jsx)(`label`,{className:Yh.actorLabel,htmlFor:E,children:`Actors`}),(0,x.jsx)(`input`,{id:E,type:`range`,min:1,max:300,value:c,onChange:e=>l(parseInt(e.target.value,10)),disabled:i,className:Yh.actorSlider,"aria-label":`Number of parallel actors per scenario run`}),(0,x.jsx)(`span`,{className:Yh.actorValue,children:c})]})]}),(0,x.jsxs)(`div`,{className:Yh.filterRow,children:[(0,x.jsxs)(`label`,{className:Yh.searchLabel,htmlFor:D,children:[(0,x.jsx)(`span`,{className:`sr-only`,children:`Search scenarios`}),(0,x.jsx)(`input`,{id:D,type:`search`,value:m,onChange:e=>h(e.target.value),placeholder:`Search by name or seed text…`,className:Yh.searchInput,"aria-label":`Filter catalog by name or seed text`})]}),(0,x.jsx)(`div`,{className:Yh.chipGroup,role:`group`,"aria-label":`Filter by scenario source`,children:[{key:`all`,label:`All`},{key:`builtin`,label:`Built-in`},{key:`disk`,label:`Saved`},{key:`compiled`,label:`Custom`}].map(e=>{let t=e.key===`all`?o.length:j[e.key]??0,n=v===e.key;return e.key!==`all`&&t===0?null:(0,x.jsxs)(`button`,{type:`button`,onClick:()=>y(e.key),className:`${Yh.chip} ${n?Yh.chipActive:``}`,"aria-pressed":n,children:[e.label,` `,(0,x.jsx)(`span`,{className:Yh.chipCount,children:t})]},e.key)})}),(0,x.jsxs)(`label`,{className:Yh.sortLabel,children:[(0,x.jsx)(`span`,{className:`sr-only`,children:`Sort scenarios`}),(0,x.jsxs)(`select`,{value:S,onChange:e=>C(e.target.value),className:Yh.sortSelect,"aria-label":`Sort catalog`,children:[(0,x.jsx)(`option`,{value:`curated`,children:`Sort: Curated`}),(0,x.jsx)(`option`,{value:`most-runs`,children:`Sort: Most runs`}),(0,x.jsx)(`option`,{value:`newest`,children:`Sort: Newest first`}),(0,x.jsx)(`option`,{value:`alphabetical`,children:`Sort: A → Z`})]})]})]}),A.length===0?(0,x.jsxs)(`div`,{className:Yh.emptyMatches,role:`status`,"aria-live":`polite`,children:[`No scenarios match your filter.`,` `,(0,x.jsx)(`button`,{type:`button`,className:Yh.clearFiltersBtn,onClick:()=>{h(``),y(`all`)},children:`Clear filters`})]}):(0,x.jsx)(`ul`,{className:Yh.grid,role:`list`,children:A.map(e=>{let t=Zh(e.source),r=e.id===a;return(0,x.jsxs)(`li`,{className:`${Yh.card} ${Yh[`tone_${t}`]??``} ${r?Yh.cardActive:``}`.trim(),children:[(0,x.jsxs)(`button`,{type:`button`,className:Yh.cardBody,onClick:()=>T(e),"aria-label":`View detail for ${e.name}`,children:[(0,x.jsxs)(`div`,{className:Yh.cardHeader,children:[(0,x.jsx)(`span`,{className:`${Yh.sourceBadge} ${Yh[`badge_${t}`]??``}`,children:Qh(e.source)}),r&&(0,x.jsx)(`span`,{className:Yh.activeBadge,children:`Loaded`})]}),(0,x.jsx)(`h4`,{className:Yh.cardName,children:e.name}),e.seedText&&(0,x.jsxs)(`p`,{className:Yh.cardSeed,title:e.seedText,children:[e.seedText.slice(0,140),e.seedText.length>140?`…`:``]}),(0,x.jsxs)(`dl`,{className:Yh.cardStats,children:[typeof e.runCount==`number`&&e.runCount>0&&(0,x.jsxs)(`div`,{className:Yh.stat,children:[(0,x.jsx)(`dt`,{className:Yh.statKey,children:`Runs`}),(0,x.jsx)(`dd`,{className:Yh.statValue,children:e.runCount.toLocaleString()})]}),typeof e.departments==`number`&&e.departments>0&&(0,x.jsxs)(`div`,{className:Yh.stat,children:[(0,x.jsx)(`dt`,{className:Yh.statKey,children:`Depts`}),(0,x.jsx)(`dd`,{className:Yh.statValue,children:e.departments})]}),e.compiledAt&&(0,x.jsxs)(`div`,{className:Yh.stat,children:[(0,x.jsx)(`dt`,{className:Yh.statKey,children:`Compiled`}),(0,x.jsx)(`dd`,{className:Yh.statValue,children:Xh(e.compiledAt)||e.compiledAt.slice(0,10)})]})]})]}),(0,x.jsxs)(`button`,{type:`button`,className:Yh.runButton,onClick:t=>{t.stopPropagation(),n(e.id,c)},disabled:i,"aria-label":`Run ${c} actor${c===1?``:`s`} against ${e.name}`,children:[`Run `,c,` `,c===1?`actor`:`actors`,` →`]})]},e.id)})}),(0,x.jsx)(qh,{scenario:w,disabled:i,initialActorCount:c,onRunScenario:(e,t)=>{T(null),n(e,t)},onClose:()=>T(null),onDeleted:e=>{s(t=>t.filter(t=>t.id!==e))},onRenamed:(e,t)=>{s(n=>n.map(n=>n.id===e?{...n,name:t}:n)),T(n=>n&&n.id===e?{...n,name:t}:n)}})]})}var eg=[{id:`hurricane-evacuation`,label:`What if a coastal mayor has 36 hours to evacuate before a hurricane?`,seedText:`A coastal metro of 800,000 has 36 hours before a Category 4 hurricane landfall. The mayor must decide a phased evacuation across three districts served by a single causeway bridge, with a regional hospital, a fuel depot, and an aging levee system in play. Departments involved: emergency management, public health, transportation, utilities, communications.`},{id:`saas-mid-tier`,label:`What if a developer-tools SaaS adds a $14 mid-tier?`,seedText:`StackPulse, a developer-focused observability SaaS (logs + metrics + tracing aimed at series-B-to-D startup engineering teams of 5-50 people), introduces a new $14/month "Builder" tier between the free Sandbox plan and the existing $29 Pro plan. The 180,000-user paid base is mostly engineering managers and SREs at venture-backed startups; their #1 jobs-to-be-done are debugging production incidents under 15 minutes and proving reliability SLAs to enterprise customers. Builder caps log retention at 7 days (Pro keeps 30) and limits trace sampling to 10% (Pro is full). Existing Pro subs get 90-day grandfathering. Competitors: Datadog (incumbent, 10x the price), Honeycomb (premium tier), self-hosted Grafana stacks. Test the impact on Free-to-Paid conversion, Pro downgrade rate, net ARPU, and churn over six months. Departments: pricing, growth, success, finance, engineering.`},{id:`ai-lab-early-release`,label:`What if an AI lab releases a frontier model six weeks early?`,seedText:`An AI lab decides whether to release a frontier multimodal model six weeks early. Two evaluators flag a 4.2% specification-gaming rate on long-horizon agentic tasks and early mesa-objective signals under DPO. A rival lab's weaker model ships on schedule, capturing $240M ARR in enterprise deals. Council: alignment, capability, policy, infra, comms.`},{id:`generation-ship-fuel-leak`,label:`What if a generation ship discovers a fuel leak at year 18?`,seedText:`A generation ship with 2,400 passengers at year 18 of a 40-year interstellar transit discovers a slow fuel leak on the main reactor. Reactor crew wants to EVA-repair (non-zero fatality risk); bridge wants to coast at reduced thrust and accept a 14-year transit extension. Departments: engineering, life support, medical, psych, command.`},{id:`city-congestion-pricing`,label:`What if a city pilots congestion pricing for 12 months?`,seedText:`A mid-size city of 650,000 pilots downtown congestion pricing for 12 months. $9 peak / $3 off-peak on vehicles entering the central business district 6am-7pm Mon-Fri. Revenue funds two BRT lines and a 30% transit fare cut for low-income riders. Test VMT, transit ridership, small-business revenue, equity outcomes.`}];function tg(e){return .1+.6*e}var ng={pendingSeedNotice:`_pendingSeedNotice_1rh83_1`,dividerWrap:`_dividerWrap_1rh83_15`,dividerLine:`_dividerLine_1rh83_27`,seedInput:`_seedInput_1rh83_33`,templatePicker:`_templatePicker_1rh83_48`,templatePickerLabel:`_templatePickerLabel_1rh83_55`,templatePickerSelect:`_templatePickerSelect_1rh83_65`,tabs:`_tabs_1rh83_90`,tab:`_tab_1rh83_90`,tabActive:`_tabActive_1rh83_119`,textarea:`_textarea_1rh83_124`,input:`_input_1rh83_125`,urlRow:`_urlRow_1rh83_142`,fetchButton:`_fetchButton_1rh83_150`,runButton:`_runButton_1rh83_151`,dropZone:`_dropZone_1rh83_185`,hint:`_hint_1rh83_205`,charCount:`_charCount_1rh83_218`,error:`_error_1rh83_225`,actorCountRow:`_actorCountRow_1rh83_235`,actorCountLabel:`_actorCountLabel_1rh83_246`,actorCountSlider:`_actorCountSlider_1rh83_257`,actorCountPreview:`_actorCountPreview_1rh83_313`};function rg(){if(typeof window>`u`)return``;try{let e=new URLSearchParams(window.location.search).get(`prompt`);return e?e.trim():``}catch{return``}}function ig({onSeedReady:e,onLoadedScenarioRunStart:t,onCatalogRunStart:n,disabled:r=!1}){let[i,a]=(0,b.useState)(`paste`),[o,s]=(0,b.useState)(rg),[c,l]=(0,b.useState)(``),[u,d]=(0,b.useState)(void 0),[f,p]=(0,b.useState)(``),[m,h]=(0,b.useState)(null),[g,_]=(0,b.useState)(!1),[v,y]=(0,b.useState)(2),S=(0,b.useRef)(null),C=(0,b.useCallback)(()=>{let t=o.trim(),n=gh(t);n.ok?(h(null),e({seedText:t,sourceUrl:u,domainHint:f.trim()||void 0,actorCount:v})):h(n.reason===`too-short`?`Paste at least 200 characters of source material.`:n.reason===`too-long`?`Source material exceeds 50 000 characters.`:`Source material is empty.`)},[o,u,f,v,e]),w=(0,b.useCallback)(async()=>{let e=hh(c);if(!e.ok)h(e.error);else{_(!0),h(null);try{let t=await fetch(`/api/quickstart/fetch-seed`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({url:e.url.toString()})});if(!t.ok){let e=await t.json().catch(()=>({}));h(e.error??`Fetch failed: HTTP ${t.status}`);return}let n=await t.json();s(n.text),d(n.sourceUrl??e.url.toString()),a(`paste`)}catch(e){let t=e?.message??String(e),n=/Failed to fetch|NetworkError|ERR_/i.test(t)?`Couldn't reach the server. Check your connection and try again.`:`URL fetch failed: ${t}`;h(n)}finally{_(!1)}}},[c]),T=(0,b.useCallback)(async e=>{if(e.size>10485760)h(`PDF exceeds 10 MB limit.`);else if(e.type!==`application/pdf`&&!e.name.toLowerCase().endsWith(`.pdf`))h(`File is not a PDF: ${e.name}`);else{_(!0),h(null);try{let{text:t,truncated:n}=await Ah(e);s(n?`${t}\n\n[Truncated to first 50 KB.]`:t),d(void 0),a(`paste`)}catch(e){let t=e?.code,n=String(e?.message??e),r;r=t===`PDF_NO_TEXT`?`No text found in this PDF. It looks like a scanned image — try a text-based PDF, or paste the content into WRITE.`:/InvalidPDFException|invalid pdf|corrupt/i.test(n)?`This PDF appears to be corrupted or password-protected. Try a different file or paste the text directly.`:/worker|GlobalWorkerOptions/i.test(n)?`Couldn't load the PDF parser (${n}). Try a different file, or paste the text into WRITE.`:`Couldn't read this PDF (${n}). Try paste-text or a different file.`,h(r)}finally{_(!1)}}},[]),E={paste:`WRITE`,url:`URL`,pdf:`PDF`},D=o.trim().length>=200;return(0,x.jsxs)(`div`,{className:ng.seedInput,children:[t&&(0,x.jsxs)(x.Fragment,{children:[D&&(0,x.jsx)(`p`,{className:ng.pendingSeedNotice,role:`status`,"aria-live":`polite`,children:`You have draft seed text below. Submit it to compile a new scenario, or clear it to run the loaded one.`}),(0,x.jsx)(zh,{onRunStart:t,disabled:r||g||D}),n&&(0,x.jsx)($h,{onRunScenario:n,disabled:r||g||D}),(0,x.jsxs)(`div`,{className:ng.dividerWrap,children:[(0,x.jsx)(`span`,{className:ng.dividerLine,"aria-hidden":`true`}),(0,x.jsx)(`span`,{children:`or paste a new scenario`}),(0,x.jsx)(`span`,{className:ng.dividerLine,"aria-hidden":`true`})]})]}),(0,x.jsxs)(`label`,{className:ng.templatePicker,children:[(0,x.jsx)(`span`,{className:ng.templatePickerLabel,children:`Try a template`}),(0,x.jsxs)(`select`,{className:ng.templatePickerSelect,value:``,disabled:r,onChange:e=>{let t=e.target.value;if(!t)return;let n=eg.find(e=>e.id===t);n&&(a(`paste`),s(n.seedText),h(null),e.target.value=``)},children:[(0,x.jsx)(`option`,{value:``,children:`Pick a sample scenario…`}),eg.map(e=>(0,x.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),(0,x.jsx)(`div`,{className:ng.tabs,role:`tablist`,children:[`paste`,`url`,`pdf`].map(e=>(0,x.jsx)(`button`,{role:`tab`,"aria-selected":i===e,className:`${ng.tab} ${i===e?ng.tabActive:``}`,onClick:()=>{a(e),h(null)},disabled:r,type:`button`,children:E[e]},e))}),i===`paste`&&(0,x.jsx)(`textarea`,{"data-quickstart-seed":!0,className:ng.textarea,placeholder:`Type or paste a brief, article, meeting notes, or any domain-specific source material (at least 200 characters).`,value:o,onChange:e=>s(e.target.value),rows:6,disabled:r}),i===`url`&&(0,x.jsxs)(`div`,{className:ng.urlRow,children:[(0,x.jsx)(`input`,{type:`url`,className:ng.input,placeholder:`https://example.com/article`,value:c,onChange:e=>l(e.target.value),disabled:r||g}),(0,x.jsx)(`button`,{type:`button`,className:ng.fetchButton,onClick:w,disabled:r||g||!c,children:g?`Fetching...`:`Fetch`})]}),i===`pdf`&&(0,x.jsxs)(`div`,{className:ng.dropZone,"data-paracosm-local-dropzone":`pdf`,onClick:()=>{r||S.current?.click()},onDragOver:e=>e.preventDefault(),onDrop:e=>{if(e.preventDefault(),r)return;let t=e.dataTransfer.files[0];t&&T(t)},role:`button`,tabIndex:r?-1:0,"aria-disabled":r,onKeyDown:e=>{r||(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),S.current?.click())},children:[(0,x.jsx)(`input`,{ref:S,type:`file`,accept:`application/pdf,.pdf`,onChange:e=>{let t=e.target.files?.[0];t&&T(t)},hidden:!0}),g?`Extracting text...`:`Drop a PDF or click to upload (max 10 MB, first 50 KB of text used)`]}),(0,x.jsxs)(`div`,{className:ng.hint,children:[(0,x.jsx)(`label`,{htmlFor:`quickstart-domain-hint`,children:`Domain hint (optional)`}),(0,x.jsx)(`input`,{id:`quickstart-domain-hint`,className:ng.input,type:`text`,placeholder:`e.g., "clinical trial decision" or "startup growth"`,value:f,onChange:e=>p(e.target.value),maxLength:80,disabled:r})]}),m&&(0,x.jsx)(`p`,{className:ng.error,role:`alert`,children:m}),(0,x.jsxs)(`div`,{className:ng.charCount,children:[o.length.toLocaleString(),` / 50,000 characters`]}),(0,x.jsxs)(`div`,{className:ng.actorCountRow,children:[(0,x.jsxs)(`label`,{htmlFor:`quickstart-actor-count`,className:ng.actorCountLabel,children:[`Actors: `,(0,x.jsx)(`strong`,{children:v})]}),(0,x.jsx)(`input`,{id:`quickstart-actor-count`,type:`range`,min:1,max:300,value:v,onChange:e=>y(parseInt(e.target.value,10)),disabled:r,className:ng.actorCountSlider,"aria-label":`Number of parallel actors to run`}),(0,x.jsxs)(`span`,{className:ng.actorCountPreview,"aria-live":`polite`,children:[`~$`,tg(v).toFixed(2),` · `,ag(v)]})]}),(0,x.jsx)(Ih,{seedText:o,domainHint:f,sourceUrl:u,actorCount:v,disabled:r}),(0,x.jsxs)(`button`,{type:`button`,className:ng.runButton,onClick:C,disabled:r||o.trim().length<200,children:[`Generate + Run `,v,` `,v===1?`Actor`:`Actors`,` (~$`,tg(v).toFixed(2),`)`]})]})}function ag(e){if(e<=0)return`—`;let t=2+5*Math.max(1,Math.ceil(e/8));return`${t}–${Math.ceil(t*1.5)} min`}var G={card:`_card_182vb_1`,heading:`_heading_182vb_15`,title:`_title_182vb_23`,eyebrow:`_eyebrow_182vb_35`,copy:`_copy_182vb_43`,presetRow:`_presetRow_182vb_50`,presetLabel:`_presetLabel_182vb_61`,presetButton:`_presetButton_182vb_71`,presetButtonActive:`_presetButtonActive_182vb_91`,presetClear:`_presetClear_182vb_97`,presetBlurb:`_presetBlurb_182vb_118`,formGrid:`_formGrid_182vb_126`,formCell:`_formCell_182vb_137`,formLegend:`_formLegend_182vb_152`,field:`_field_182vb_165`,fieldRow:`_fieldRow_182vb_171`,fieldThird:`_fieldThird_182vb_177`,fieldLabel:`_fieldLabel_182vb_182`,input:`_input_182vb_191`,textarea:`_textarea_182vb_212`,mono:`_mono_182vb_235`,actions:`_actions_182vb_240`,button:`_button_182vb_248`,helper:`_helper_182vb_270`,spinner:`_spinner_182vb_276`,"idc-spin":`_idc-spin_182vb_1`,timer:`_timer_182vb_288`},og=`paracosm:lastLaunchConfig`,sg=`paracosm:keyOverrides`,cg=`paracosm:activeRunActors`,lg=`paracosm:activeRunScenarioId`,ug=950;function dg(e){try{let t=e.getItem(og);if(!t)return null;let n=JSON.parse(t);return n&&typeof n==`object`&&!Array.isArray(n)?n:null}catch{return null}}function fg(e,t){return e.scenarioId===t}function pg(e,t){try{e.setItem(og,JSON.stringify(t))}catch{}}function mg(e,t,n){try{e.setItem(cg,JSON.stringify(t)),n?e.setItem(lg,n):e.removeItem?.(lg)}catch{}}function hg(e){try{return e.getItem(`paracosm:activeRunScenarioId`)||null}catch{return null}}function gg(e){try{let t=e.getItem(cg);if(!t)return null;let n=JSON.parse(t);return Array.isArray(n)?n.filter(e=>!!e&&typeof e==`object`&&!Array.isArray(e)):null}catch{return null}}function _g(e){try{let t=e.getItem(sg);if(!t)return{};let n=JSON.parse(t);return!n||typeof n!=`object`||Array.isArray(n)?{}:n}catch{return{}}}function vg(e,t){let n=(typeof e.seed==`number`?e.seed:ug)+1,r={...e,seed:n};return t.openai&&(r.apiKey=t.openai),t.anthropic&&(r.anthropicKey=t.anthropic),t.serper&&(r.serperKey=t.serper),t.firecrawl&&(r.firecrawlKey=t.firecrawl),t.tavily&&(r.tavilyKey=t.tavily),t.cohere&&(r.cohereKey=t.cohere),r}function yg(e){if(typeof e!=`string`)return;let t=e.trim();if(t&&!t.includes(`...`))return t}function bg(e){let t=yg(e.openai),n=yg(e.anthropic);return{...t?{apiKey:t}:{},...n?{anthropicKey:n}:{}}}function xg(e){let t=bg(e);return t.apiKey!==void 0||t.anthropicKey!==void 0}var Sg={id:``,name:``,description:``,profileJson:`{}`},Cg={id:``,name:``,description:``,durationValue:`12`,durationUnit:`weeks`,adherence:`0.85`},wg={medical:{label:`Patient · treatment`,blurb:`Type 2 diabetes patient on a 12-week semaglutide + lifestyle protocol.`,subject:{id:`patient-maria-2026`,name:`Maria Chen`,description:`58 y/o T2D for 4 yrs, sedentary, family hx CVD, on metformin.`,profileJson:JSON.stringify({age:58,yearsWithT2D:4,bmi:31,a1cBaseline:7.8,weightLb:178,fastingGlucose:156,sleepHoursBaseline:6.2,exerciseMinPerWeek:0,comorbidities:`hypertension, dyslipidemia`},null,2)},intervention:{id:`glp1-12wk-protocol`,name:`12-week semaglutide + lifestyle protocol`,description:`Initiate semaglutide 0.25mg weekly, titrate to 1.0mg by week 4. Pair with dietitian-led nutrition plan and 150min/wk graded exercise. Behavioral health checkpoints biweekly. Monitor for GI side effects, gallbladder, pancreatitis.`,durationValue:`84`,durationUnit:`days`,adherence:`0.85`},signalsJson:JSON.stringify([{label:`HbA1c`,value:7.8,unit:`%`,recordedAt:`2026-09-15T00:00:00Z`},{label:`Fasting glucose`,value:156,unit:`mg/dL`,recordedAt:`2026-09-15T00:00:00Z`},{label:`Weight`,value:178,unit:`lb`,recordedAt:`2026-09-15T00:00:00Z`},{label:`BMI`,value:31,unit:`kg/m²`,recordedAt:`2026-09-15T00:00:00Z`}],null,2)},policy:{label:`Jurisdiction · ordinance`,blurb:`A mid-size city pilots downtown congestion pricing for 12 months.`,subject:{id:`city-portland-2026`,name:`Portland Metro`,description:`Pacific Northwest mid-size city with dense urban core, mature transit, organized downtown business association.`,profileJson:JSON.stringify({population:65e4,downtownEmployment:11e4,modeShareTransit:.18,modeShareCar:.62,modeShareActive:.14,avgPeakSpeedMph:14.2,annualCO2Tons:182e4,unemploymentRate:.044},null,2)},intervention:{id:`congestion-pricing-12mo`,name:`Downtown congestion pricing pilot`,description:`Charge $9/peak-hour ($3 off-peak) on vehicles entering the central business district 6am-7pm Mon-Fri. Revenue funds two new BRT lines and a 30% transit fare cut for low-income riders. Pilot runs 12 months with quarterly review.`,durationValue:`12`,durationUnit:`months`,adherence:`0.78`},signalsJson:JSON.stringify([{label:`Downtown VMT`,value:1.42,unit:`million-mi/day`,recordedAt:`2026-04-01T00:00:00Z`},{label:`Transit ridership`,value:118e3,unit:`boardings/day`,recordedAt:`2026-04-01T00:00:00Z`},{label:`Peak speed`,value:14.2,unit:`mph`,recordedAt:`2026-04-01T00:00:00Z`}],null,2)},product:{label:`Market · launch`,blurb:`A SaaS launches a new mid-tier price point against a price-sensitive prosumer segment.`,subject:{id:`segment-prosumer-creators`,name:`Prosumer creators`,description:`Independent creators earning $40k-$120k/yr who self-fund their tooling. Cross-tool stackers; price-sensitive within 20% bands.`,profileJson:JSON.stringify({addressableUsers:18e5,currentPaidConversion:.034,avgARPU_USD:22,churnMonthly:.038,npsCurrent:41,topCompetitorPriceUSD:18,topCompetitorMarketShare:.31},null,2)},intervention:{id:`mid-tier-pricing-launch`,name:`New $14/mo mid-tier launch`,description:`Introduce a third pricing tier at $14/mo (between Free and the existing $29/mo Pro), unlocking 60% of Pro features. Bundle with 90-day grandfathering for current Pro subs and a quarterly migration check-in. 6-month pilot before deciding to globalize.`,durationValue:`6`,durationUnit:`months`,adherence:`0.72`},signalsJson:JSON.stringify([{label:`Free → Paid conversion`,value:.034,unit:`rate`,recordedAt:`2026-04-01T00:00:00Z`},{label:`Monthly churn`,value:.038,unit:`rate`,recordedAt:`2026-04-01T00:00:00Z`},{label:`NPS`,value:41,unit:`score`,recordedAt:`2026-04-01T00:00:00Z`}],null,2)}};function Tg(e,t){if(!e||!e.trim())return t;try{return JSON.parse(e)}catch{return t}}function Eg(){return globalThis.crypto?.randomUUID?.()??`run-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function Dg({onResult:e,onError:t,onRunStart:n}){let[r,i]=(0,b.useState)(Sg),[a,o]=(0,b.useState)(Cg),[s,c]=(0,b.useState)(`[]`),[l,u]=(0,b.useState)(!1),[d,f]=(0,b.useState)(0),[p,m]=(0,b.useState)(null),h=e=>{let t=wg[e];t&&(i(t.subject),o(t.intervention),c(t.signalsJson),m(e))},g=()=>{i(Sg),o(Cg),c(`[]`),m(null)},_=r.id.trim().length>0&&r.name.trim().length>0&&a.id.trim().length>0&&a.name.trim().length>0&&a.description.trim().length>0;return(0,x.jsxs)(`div`,{className:G.card,children:[(0,x.jsxs)(`div`,{className:G.heading,children:[(0,x.jsx)(`h3`,{className:G.title,children:`Run a digital twin`}),(0,x.jsx)(`span`,{className:G.eyebrow,children:`any subject · any intervention`})]}),(0,x.jsx)(`p`,{className:G.copy,children:`Define a subject (patient, market segment, jurisdiction, vehicle, anything) and an intervention to apply to it. Paracosm runs a real LLM-driven simulation across a five-department analysis team and returns a typed RunArtifact with the trajectory.`}),(0,x.jsxs)(`div`,{className:G.presetRow,children:[(0,x.jsx)(`span`,{className:G.presetLabel,children:`Examples`}),Object.entries(wg).map(([e,t])=>(0,x.jsx)(`button`,{type:`button`,onClick:()=>h(e),className:`${G.presetButton} ${p===e?G.presetButtonActive:``}`,disabled:l,children:t.label},e)),(0,x.jsx)(`button`,{type:`button`,onClick:g,className:G.presetClear,disabled:l,children:`Clear`})]}),p&&(0,x.jsx)(`p`,{className:G.presetBlurb,children:wg[p].blurb}),(0,x.jsxs)(`div`,{className:G.formGrid,children:[(0,x.jsxs)(`fieldset`,{className:G.formCell,disabled:l,children:[(0,x.jsx)(`legend`,{className:G.formLegend,children:`Subject`}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`ID`}),(0,x.jsx)(`input`,{type:`text`,value:r.id,onChange:e=>i(t=>({...t,id:e.target.value})),placeholder:`patient-001`,className:G.input})]}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Name`}),(0,x.jsx)(`input`,{type:`text`,value:r.name,onChange:e=>i(t=>({...t,name:e.target.value})),placeholder:`Maria Chen`,className:G.input})]}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Description`}),(0,x.jsx)(`textarea`,{value:r.description,onChange:e=>i(t=>({...t,description:e.target.value})),placeholder:`Age, key attributes, baseline state.`,className:G.textarea,rows:3})]}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Profile (JSON)`}),(0,x.jsx)(`textarea`,{value:r.profileJson,onChange:e=>i(t=>({...t,profileJson:e.target.value})),placeholder:`{"age": 58, "bmi": 31}`,className:`${G.textarea} ${G.mono}`,rows:5,spellCheck:!1})]}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Signals (JSON)`}),(0,x.jsx)(`textarea`,{value:s,onChange:e=>c(e.target.value),placeholder:`[{"label":"HbA1c","value":7.8,"unit":"%"}]`,className:`${G.textarea} ${G.mono}`,rows:4,spellCheck:!1})]})]}),(0,x.jsxs)(`fieldset`,{className:G.formCell,disabled:l,children:[(0,x.jsx)(`legend`,{className:G.formLegend,children:`Intervention`}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`ID`}),(0,x.jsx)(`input`,{type:`text`,value:a.id,onChange:e=>o(t=>({...t,id:e.target.value})),placeholder:`semaglutide-12wk`,className:G.input})]}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Name`}),(0,x.jsx)(`input`,{type:`text`,value:a.name,onChange:e=>o(t=>({...t,name:e.target.value})),placeholder:`12-week semaglutide protocol`,className:G.input})]}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Description`}),(0,x.jsx)(`textarea`,{value:a.description,onChange:e=>o(t=>({...t,description:e.target.value})),placeholder:`What is being applied, by whom, with what monitoring.`,className:G.textarea,rows:5})]}),(0,x.jsxs)(`div`,{className:G.fieldRow,children:[(0,x.jsxs)(`label`,{className:`${G.field} ${G.fieldThird}`,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Duration`}),(0,x.jsx)(`input`,{type:`number`,min:`1`,value:a.durationValue,onChange:e=>o(t=>({...t,durationValue:e.target.value})),className:G.input})]}),(0,x.jsxs)(`label`,{className:`${G.field} ${G.fieldThird}`,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Unit`}),(0,x.jsxs)(`select`,{value:a.durationUnit,onChange:e=>o(t=>({...t,durationUnit:e.target.value})),className:G.input,children:[(0,x.jsx)(`option`,{value:`days`,children:`days`}),(0,x.jsx)(`option`,{value:`weeks`,children:`weeks`}),(0,x.jsx)(`option`,{value:`months`,children:`months`}),(0,x.jsx)(`option`,{value:`quarters`,children:`quarters`}),(0,x.jsx)(`option`,{value:`years`,children:`years`})]})]}),(0,x.jsxs)(`label`,{className:`${G.field} ${G.fieldThird}`,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Adherence`}),(0,x.jsx)(`input`,{type:`number`,min:`0`,max:`1`,step:`0.05`,value:a.adherence,onChange:e=>o(t=>({...t,adherence:e.target.value})),className:G.input})]})]})]})]}),(0,x.jsxs)(`div`,{className:G.actions,children:[(0,x.jsx)(`button`,{onClick:async()=>{if(l||!_)return;let i=Tg(r.profileJson,{}),o=Tg(s,[]),c={id:r.id.trim(),name:r.name.trim(),profile:r.description.trim()?{...i,description:r.description.trim()}:i,signals:o,markers:[]},d=Number(a.durationValue),p=Number(a.adherence),m={id:a.id.trim(),name:a.name.trim(),description:a.description.trim(),duration:Number.isFinite(d)&&d>0?{value:d,unit:a.durationUnit.trim()||`weeks`}:void 0,adherenceProfile:Number.isFinite(p)?{expected:Math.max(0,Math.min(1,p))}:void 0};u(!0),f(0);let h=Date.now(),g=window.setInterval(()=>{f(Math.round((Date.now()-h)/1e3))},500),v=Eg();await n?.({runKey:v,subject:{id:c.id,name:c.name,profile:c.profile},intervention:{id:m.id,name:m.name,description:m.description,duration:m.duration}});try{let t=await fetch(`/api/quickstart/simulate-intervention`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({subject:c,intervention:m,runKey:v,options:{maxTurns:2,seed:11,costPreset:`economy`},...bg(_g(window.localStorage))})});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.error??`Digital twin run failed: HTTP ${t.status}`)}let n=await t.json();k(window,n.visitorId),e(n.artifact,v)}catch(e){t?.(e instanceof Error?e.message:String(e),v)}finally{window.clearInterval(g),u(!1)}},disabled:l||!_,className:G.button,children:l?`Running…`:`Run digital twin`}),l?(0,x.jsxs)(`span`,{className:G.timer,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:G.spinner,"aria-hidden":`true`}),d,`s elapsed · 2 turns × LLM decisions, typically 40-90s`]}):(0,x.jsx)(`span`,{className:G.helper,children:`2 turns · seed 11 · economy preset`})]})]})}function Og(e,t){return e===`loading`?`loading`:e===`error`?`error`:e===`unavailable`?`unavailable`:t.length===0?`empty`:`cards`}function kg(e,t){let n=new URL(e);return n.searchParams.set(`replay`,t),n.searchParams.set(`tab`,`sim`),n.toString()}var Ag={card:`_card_1qdw6_1`,eyebrow:`_eyebrow_1qdw6_27`,row:`_row_1qdw6_36`,actor:`_actor_1qdw6_45`,arrow:`_arrow_1qdw6_56`,meta:`_meta_1qdw6_62`};function jg(){let{sessions:e}=Oe(),t=e[0]?.id?e[0]:null;if(!t)return null;let n=typeof window<`u`?kg(window.location.href,t.id):`?replay=${encodeURIComponent(t.id)}`,r=t.seedText?t.seedText.length>70?`${t.seedText.slice(0,70).trim()}…`:t.seedText.trim():null,i=Rn(t,3),a=t.title||t.scenarioName||i||r||t.id,o=[t.scenarioName&&t.scenarioName!==a?t.scenarioName:null,typeof t.eventCount==`number`?`${t.eventCount} events`:null,typeof t.durationMs==`number`?`${Math.round(t.durationMs/1e3)}s`:null,typeof t.createdAt==`number`?new Date(t.createdAt).toISOString().slice(0,10):null].filter(e=>typeof e==`string`&&e.length>0).join(` · `);return(0,x.jsxs)(`a`,{className:Ag.card,href:n,"aria-label":`Replay last run: ${a}`,children:[(0,x.jsx)(`span`,{className:Ag.eyebrow,children:`Replay last run`}),(0,x.jsxs)(`span`,{className:Ag.row,children:[(0,x.jsx)(`span`,{className:Ag.actor,children:a}),(0,x.jsx)(`span`,{className:Ag.arrow,"aria-hidden":`true`,children:`▶`})]}),o&&(0,x.jsx)(`span`,{className:Ag.meta,children:o})]})}var Mg={card:`_card_14dqa_7`,statusPending:`_statusPending_14dqa_18`,statusActive:`_statusActive_14dqa_22`,statusDone:`_statusDone_14dqa_27`,header:`_header_14dqa_31`,marker:`_marker_14dqa_60`,pulseDot:`_pulseDot_14dqa_1`,label:`_label_14dqa_93`,duration:`_duration_14dqa_100`,count:`_count_14dqa_121`,chevron:`_chevron_14dqa_137`,chevronOpen:`_chevronOpen_14dqa_148`,actorChips:`_actorChips_14dqa_164`,actorChip:`_actorChip_14dqa_164`,actorChipName:`_actorChipName_14dqa_190`,actorChipState:`_actorChipState_14dqa_194`,actor_running:`_actor_running_14dqa_203`,actor_complete:`_actor_complete_14dqa_212`,actor_error:`_actor_error_14dqa_221`,actor_aborted:`_actor_aborted_14dqa_230`,body:`_body_14dqa_241`,line:`_line_14dqa_266`,lineTs:`_lineTs_14dqa_283`,lineGlyph:`_lineGlyph_14dqa_290`,lineTag:`_lineTag_14dqa_296`,lineActor:`_lineActor_14dqa_309`,lineBody:`_lineBody_14dqa_324`,tonePending:`_tonePending_14dqa_332`,toneInfo:`_toneInfo_14dqa_336`,toneActive:`_toneActive_14dqa_345`,toneDone:`_toneDone_14dqa_358`,toneWarn:`_toneWarn_14dqa_367`,toneError:`_toneError_14dqa_380`},Ng={running:`RUNNING`,complete:`COMPLETE`,error:`ERROR`,aborted:`ABORTED`};function Pg({stageId:e,label:t,status:n,logLines:r,duration:i,actors:a}){let[o,s]=(0,b.useState)(n!==`pending`),c=(0,b.useRef)(null),l=(0,b.useRef)(!0);(0,b.useEffect)(()=>{(n===`active`||n===`done`)&&s(e=>e||!0)},[n]);let u=()=>{let e=c.current;e&&(l.current=e.scrollHeight-e.scrollTop-e.clientHeight<40)};(0,b.useEffect)(()=>{if(!l.current)return;let e=c.current;e&&(e.scrollTop=e.scrollHeight)},[r.length]);let d=n===`done`?`✓`:n===`active`?`●`:`○`,f=n===`done`?Mg.statusDone:n===`active`?Mg.statusActive:Mg.statusPending,p=e===`running`,m=r.length;return(0,x.jsxs)(`div`,{className:`${Mg.card} ${f}`,"data-stage":e,"data-status":n,children:[(0,x.jsxs)(`button`,{type:`button`,className:Mg.header,"aria-expanded":o,"aria-controls":`stage-${e}-body`,onClick:()=>s(e=>!e),children:[(0,x.jsx)(`span`,{className:Mg.marker,"aria-hidden":`true`,children:d}),(0,x.jsx)(`span`,{className:Mg.label,children:t}),i&&(0,x.jsx)(`span`,{className:Mg.duration,children:i}),m>0&&(0,x.jsx)(`span`,{className:Mg.count,"aria-label":`${m} events`,children:m}),(0,x.jsx)(`span`,{className:`${Mg.chevron} ${o?Mg.chevronOpen:``}`,"aria-hidden":`true`})]}),p&&a&&a.length>0&&(0,x.jsx)(`div`,{className:Mg.actorChips,children:a.map(e=>(0,x.jsxs)(`span`,{className:`${Mg.actorChip} ${Mg[`actor_${e.status}`]}`,title:`${e.name} · ${e.archetype}`,children:[(0,x.jsx)(`span`,{className:Mg.actorChipName,children:e.name}),(0,x.jsx)(`span`,{className:Mg.actorChipState,children:e.status===`running`?`T${e.currentTurn}/${e.maxTurns}`:Ng[e.status]})]},e.name))}),o&&(0,x.jsxs)(`div`,{id:`stage-${e}-body`,className:Mg.body,ref:c,onScroll:u,role:`log`,"aria-live":n===`active`?`polite`:`off`,"aria-label":`${t} log`,children:[r.length===0&&(0,x.jsxs)(`div`,{className:`${Mg.line} ${Mg.tonePending}`,children:[(0,x.jsx)(`span`,{className:Mg.lineTs,children:`—`}),(0,x.jsx)(`span`,{className:Mg.lineGlyph,children:`·`}),(0,x.jsx)(`span`,{className:Mg.lineBody,children:n===`pending`?`Waiting for previous stage…`:`No events yet.`})]}),r.map((e,t)=>(0,x.jsxs)(`div`,{className:`${Mg.line} ${Mg[`tone${Fg(e.tone)}`]}`,children:[(0,x.jsx)(`span`,{className:Mg.lineTs,children:e.ts}),(0,x.jsx)(`span`,{className:Mg.lineGlyph,children:e.glyph}),e.tag&&(0,x.jsx)(`span`,{className:Mg.lineTag,children:e.tag}),e.actor&&(0,x.jsx)(`span`,{className:Mg.lineActor,children:e.actor}),(0,x.jsx)(`span`,{className:Mg.lineBody,children:e.body})]},t))]})]})}function Fg(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Ig(e){(!Number.isFinite(e)||e<0)&&(e=0);let t=e/1e3,n=Math.floor(t/60),r=Math.floor(t%60),i=Math.floor(t*10%10);return`${n}:${String(r).padStart(2,`0`)}.${i}`}function Lg(e){return e===`turn_start`||e===`turn_done`?`active`:e===`specialist_done`||e===`sim_complete`||e===`agent_reactions`?`done`:e===`decision_pending`||e===`decision_made`||e===`outcome`?`info`:e===`sim_aborted`||e===`provider_error`||e===`validation_fallback`?`warn`:`info`}function Rg(e){switch(e){case`turn_start`:return`TURN`;case`turn_done`:return`TURN`;case`specialist_start`:return`SPEC`;case`specialist_done`:return`SPEC`;case`decision_pending`:return`DEC`;case`decision_made`:return`DEC`;case`outcome`:return`OUT`;case`agent_reactions`:return`REACT`;case`bulletin`:return`NEWS`;case`promotion`:return`PROMO`;case`systems_snapshot`:return`SNAP`;case`drift`:return`DRIFT`;case`personality_drift`:return`DRIFT`;case`sim_aborted`:return`ABORT`;case`provider_error`:return`ERR`;case`validation_fallback`:return`FALLBACK`;case`sim_complete`:return`DONE`;default:return e.toUpperCase().slice(0,8)}}function zg(e){let t=e.data??{};return(typeof t.summary==`string`?t.summary:``)||(typeof t.department==`string`?t.department:typeof t.title==`string`?t.title:typeof t.decision==`string`?t.decision:typeof t.outcome==`string`?t.outcome:typeof t.eventType==`string`?t.eventType:typeof t.tool==`string`?t.tool:``)}function Bg(e){if(e.type===`status`)return null;let t=e.turn??e.data?.turn,n=e.leader||e.data?.actor,r=zg(e)||`${e.type} fired`;return{ts:typeof t==`number`?`T${t}`:`—`,glyph:e.type===`turn_done`?`✓`:e.type===`turn_start`?`→`:`·`,tag:e.type===`validation_fallback`&&e.data?.salvaged===!0?`SALVAGE`:Rg(e.type),body:r,tone:Lg(e.type),actor:typeof n==`string`?n:void 0}}function Vg(e){let{stage:t,startMs:n,phaseTransitionMs:r}=e,i=[],a=r?.compile??n;i.push({ts:Ig(a-n),glyph:`→`,tag:`POST`,body:`/api/quickstart/compile-from-seed`,tone:t===`compile`?`active`:`info`});let o=r?.research;return o&&i.push({ts:Ig(o-n),glyph:`✓`,tag:`OK`,body:`ScenarioPackage validated · departments + crisis templates derived`,tone:`done`}),i}function Hg(e){let{stage:t,startMs:n,phaseTransitionMs:r,groundingSummary:i}=e,a=[],o=r?.research;if(!o)return a;let s=Ig(o-n);if(i?.skipped)return a.push({ts:s,glyph:`⚠`,tag:`SKIP`,body:`Deep research skipped: ${i.reason??`unknown`}`,tone:`warn`}),a;if(i?.citations&&i.citations.length>0){let e=i.providersUsed?.length?` · providers: ${i.providersUsed.join(` + `)}`:``;a.push({ts:s,glyph:`→`,tag:`POST`,body:`/api/quickstart/ground-scenario · ${i.citations.length} queries${e}`,tone:t===`research`?`active`:`info`});for(let e of i.providersFailed??[])a.push({ts:s,glyph:`⚠`,tag:e.provider.toUpperCase().slice(0,8),body:`provider unavailable: ${e.reason.slice(0,120)}`,tone:`warn`});for(let e of i.citations){a.push({ts:s,glyph:`·`,tag:`QUERY`,body:`"${e.query}" → ${e.sources.length} source${e.sources.length===1?``:`s`}`,tone:`info`});for(let t of e.sources.slice(0,3)){let e=(t.provider??``).toUpperCase()||t.domain.toUpperCase().slice(0,16)||`SRC`;a.push({ts:s,glyph:`·`,tag:e,body:t.title,tone:`done`})}}if(typeof i.totalSources==`number`){let e=typeof i.durationMs==`number`?` · ${(i.durationMs/1e3).toFixed(1)}s`:``;a.push({ts:s,glyph:`✓`,tag:`OK`,body:`${i.totalSources} unique sources attached to ScenarioPackage${e}`,tone:`done`})}return a}a.push({ts:s,glyph:`·`,tag:`NOTE`,body:`Grounding scenario with web research…`,tone:t===`research`?`active`:`info`});let c=r?.actors;return c&&a.push({ts:Ig(c-n),glyph:`✓`,tag:`OK`,body:`Citations attached to ScenarioPackage`,tone:`done`}),a}function Ug(e){let{stage:t,startMs:n,phaseTransitionMs:r,actorCount:i}=e,a=[],o=r?.actors;if(!o)return a;a.push({ts:Ig(o-n),glyph:`→`,tag:`POST`,body:`/api/quickstart/generate-actors · count=${i}`,tone:t===`actors`?`active`:`info`});let s=r?.running;return s&&a.push({ts:Ig(s-n),glyph:`✓`,tag:`OK`,body:`${i} actor${i===1?``:`s`} generated · HEXACO traits + archetypes validated`,tone:`done`}),a}function Wg(e){return e.events.map(e=>Bg(e)).filter(e=>!!e)}function Gg(e,t){switch(e){case`compile`:return Vg(t);case`research`:return Hg(t);case`actors`:return Ug(t);case`running`:return Wg(t);case`done`:return[]}}function Kg(e,t){let n=[`compile`,`research`,`actors`,`running`,`done`],r=n.indexOf(e),i=t.phaseTransitionMs?.[e],a=n[r+1],o=a?t.phaseTransitionMs?.[a]:void 0;if(!i)return``;let s=((o??Date.now())-i)/1e3;return s<1?`${Math.max(1,Math.round(s*1e3))}ms`:s<10?`${s.toFixed(1)}s`:`${Math.round(s)}s`}var qg={progress:`_progress_5dmny_6`,heading:`_heading_5dmny_19`,title:`_title_5dmny_26`,subtitle:`_subtitle_5dmny_35`,stageList:`_stageList_5dmny_43`,stageItem:`_stageItem_5dmny_55`,cancel:`_cancel_5dmny_59`,jumpToSim:`_jumpToSim_5dmny_84`},Jg=[`compile`,`research`,`actors`,`running`,`done`];function Yg(e,t){let n=Jg.indexOf(e),r=Jg.indexOf(t);return n>r?`done`:n===r?`active`:`pending`}function Xg({stage:e,actors:t,events:n,actorCount:r,groundingSummary:i,onCancel:a}){let o=(0,b.useRef)(Date.now()),[s,c]=(0,b.useState)(()=>({compile:Date.now()})),l=(0,b.useRef)(e);(0,b.useEffect)(()=>{l.current!==e&&(l.current=e,c(t=>t[e]?t:{...t,[e]:Date.now()}))},[e]);let[,u]=(0,b.useState)(0);(0,b.useEffect)(()=>{if(e===`done`)return;let t=setInterval(()=>u(e=>(e+1)%1e6),1e3);return()=>clearInterval(t)},[e]);let d=r??t?.length??3,f=eA(),p=(0,b.useMemo)(()=>({stage:e,startMs:o.current,phaseTransitionMs:s,actorCount:d,events:n??[],groundingSummary:i??null}),[e,s,d,n,i]),m=[{id:`compile`,label:`Compile scenario`},{id:`research`,label:`Ground with citations`},{id:`actors`,label:`Generate ${d} actor${d===1?``:`s`}`},{id:`running`,label:`Run ${d} simulation${d===1?``:`s`}`}];return(0,x.jsxs)(`section`,{className:qg.progress,role:`region`,"aria-label":`Quickstart progress`,children:[(0,x.jsxs)(`header`,{className:qg.heading,children:[(0,x.jsx)(`span`,{className:qg.title,children:`Quickstart run`}),(0,x.jsx)(`span`,{className:qg.subtitle,children:`Live trace of every step from seed text to ready-to-explore artifacts.`})]}),(0,x.jsx)(`ol`,{className:qg.stageList,children:m.map(n=>{let r=Yg(e,n.id);return(0,x.jsx)(`li`,{className:qg.stageItem,children:(0,x.jsx)(Pg,{stageId:n.id,label:n.label,status:r,logLines:Gg(n.id,p),duration:Kg(n.id,p),actors:n.id===`running`?t:void 0})},n.id)})}),(e===`running`||e===`done`)&&(0,x.jsx)(`button`,{type:`button`,className:qg.jumpToSim,onClick:()=>f(`sim`),children:`Jump to live SIM →`}),a&&e!==`done`&&(0,x.jsx)(`button`,{type:`button`,className:qg.cancel,onClick:a,children:`Cancel run`})]})}var Zg=Object.freeze({visionary:{id:`visionary`,name:`Aria Okafor`,archetype:`The Visionary`,description:`Bets on bold experiments. Tolerates ambiguity. Casts a wide pattern net.`,hexaco:{openness:.95,conscientiousness:.35,extraversion:.85,agreeableness:.55,emotionality:.3,honestyHumility:.65}},pragmatist:{id:`pragmatist`,name:`Marcus Reyes`,archetype:`The Pragmatist`,description:`Leads by protocol and evidence. Safety margins first.`,hexaco:{openness:.4,conscientiousness:.9,extraversion:.35,agreeableness:.6,emotionality:.5,honestyHumility:.85}},innovator:{id:`innovator`,name:`Yuki Tanaka`,archetype:`The Innovator`,description:`Pushes novel tool forging. Accepts higher variance.`,hexaco:{openness:.9,conscientiousness:.4,extraversion:.7,agreeableness:.45,emotionality:.35,honestyHumility:.55}},stabilizer:{id:`stabilizer`,name:`Elena Voss`,archetype:`The Stabilizer`,description:`Holds the line. Protects existing capacity. Change-averse.`,hexaco:{openness:.3,conscientiousness:.85,extraversion:.4,agreeableness:.75,emotionality:.55,honestyHumility:.7}},"crisis-manager":{id:`crisis-manager`,name:`Nadia Chen`,archetype:`The Crisis Manager`,description:`Thrives under pressure. Decisive. Low emotional reactivity.`,hexaco:{openness:.55,conscientiousness:.8,extraversion:.75,agreeableness:.45,emotionality:.25,honestyHumility:.6}},"growth-optimist":{id:`growth-optimist`,name:`Diego Santoro`,archetype:`The Growth Optimist`,description:`Chases expansion. High risk tolerance. Charismatic rally-er.`,hexaco:{openness:.8,conscientiousness:.5,extraversion:.9,agreeableness:.55,emotionality:.35,honestyHumility:.4}},"protocol-builder":{id:`protocol-builder`,name:`Priya Rao`,archetype:`The Protocol Builder`,description:`Codifies everything. Demands evidence. Slow to decide, hard to dislodge.`,hexaco:{openness:.5,conscientiousness:.95,extraversion:.35,agreeableness:.6,emotionality:.45,honestyHumility:.9}},"social-architect":{id:`social-architect`,name:`Kai Rivers`,archetype:`The Social Architect`,description:`Builds coalitions. Manages morale. Relationship-first.`,hexaco:{openness:.6,conscientiousness:.65,extraversion:.8,agreeableness:.9,emotionality:.55,honestyHumility:.7}},"cost-cutter":{id:`cost-cutter`,name:`Hannah Novak`,archetype:`The Cost Cutter`,description:`Optimizes ruthlessly. Will trade morale for capacity.`,hexaco:{openness:.35,conscientiousness:.9,extraversion:.45,agreeableness:.3,emotionality:.25,honestyHumility:.55}},"compliance-hawk":{id:`compliance-hawk`,name:`Owen Ibarra`,archetype:`The Compliance Hawk`,description:`Audits every decision. Never cuts corners. Reports failures transparently.`,hexaco:{openness:.4,conscientiousness:.9,extraversion:.45,agreeableness:.65,emotionality:.5,honestyHumility:.95}}}),Qg={backdrop:`_backdrop_fgbmo_1`,dialog:`_dialog_fgbmo_12`,header:`_header_fgbmo_23`,list:`_list_fgbmo_47`,preset:`_preset_fgbmo_56`,archetype:`_archetype_fgbmo_82`,description:`_description_fgbmo_87`};function $g({onSelect:e,onClose:t}){let n=Pt(!0);return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Swap leader`,className:Qg.backdrop,onClick:t,children:(0,x.jsxs)(`div`,{ref:n,tabIndex:-1,className:Qg.dialog,onClick:e=>e.stopPropagation(),children:[(0,x.jsxs)(`header`,{className:Qg.header,children:[(0,x.jsx)(`h3`,{children:`Swap leader`}),(0,x.jsx)(`button`,{type:`button`,onClick:t,"aria-label":`Close`,children:`×`})]}),(0,x.jsx)(`ul`,{className:Qg.list,children:Object.values(Zg).map(t=>(0,x.jsx)(`li`,{children:(0,x.jsxs)(`button`,{type:`button`,onClick:()=>e(t),className:Qg.preset,children:[(0,x.jsx)(`strong`,{children:t.name}),(0,x.jsx)(`span`,{className:Qg.archetype,children:t.archetype}),(0,x.jsx)(`span`,{className:Qg.description,children:t.description})]})},t.id))})]})})}var e_={results:`_results_8jenm_2`,runSummary:`_runSummary_8jenm_15`,summaryStat:`_summaryStat_8jenm_26`,summaryNum:`_summaryNum_8jenm_40`,summaryLabel:`_summaryLabel_8jenm_50`,grid:`_grid_8jenm_61`,card:`_card_8jenm_81`,cardHeader:`_cardHeader_8jenm_92`,actorName:`_actorName_8jenm_106`,archetype:`_archetype_8jenm_110`,swap:`_swap_8jenm_119`,hexaco:`_hexaco_8jenm_142`,trait:`_trait_8jenm_151`,traitLabel:`_traitLabel_8jenm_160`,traitBarOuter:`_traitBarOuter_8jenm_168`,traitBarInner:`_traitBarInner_8jenm_175`,fingerprint:`_fingerprint_8jenm_180`,deltas:`_deltas_8jenm_192`,delta:`_delta_8jenm_192`,direction_up:`_direction_up_8jenm_209`,direction_down:`_direction_down_8jenm_213`,direction_changed:`_direction_changed_8jenm_217`,actions:`_actions_8jenm_222`,forkButton:`_forkButton_8jenm_249`,forkHint:`_forkHint_8jenm_259`},t_=[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`];function n_({actors:e,artifacts:t,sessionId:n,onSwap:r}){let{dispatch:i}=Gn(),a=eA(),o=Lm(),[s,c]=(0,b.useState)(null),l=on(),u=l.clear,[d,f]=(0,b.useState)(null);(0,b.useEffect)(()=>{u()},[n,u]);let p=e=>{i({type:`SET_PARENT`,artifact:t[e]}),a(`studio`)},m=e=>{n&&(f(e),l.share(vh(window.location.origin,n)))},h=n=>{let r=t[n],i=e[n]??{},a=typeof i.archetype==`string`?i.archetype:``,o=typeof i.name==`string`?i.name:``;yh(r,`paracosm-quickstart-${a.toLowerCase().replace(/\s+/g,`-`)||o.toLowerCase().replace(/\s+/g,`-`)||`actor-${n}`}.json`)},g=(0,b.useMemo)(()=>({totalTools:t.reduce((e,t)=>e+(t?.forgedTools?.length??0),0),totalCitations:t.reduce((e,t)=>e+(t?.citations?.length??0),0),totalDecisions:t.reduce((e,t)=>e+(t?.decisions?.length??0),0),totalTurns:t.reduce((e,t)=>e+(t?.trajectory?.timepoints?.length??0),0),totalCostUSD:t.reduce((e,t)=>e+(t?.cost?.totalUSD??0),0)}),[t]);return(0,x.jsxs)(`div`,{className:e_.results,role:`region`,"aria-label":`Quickstart results`,children:[(0,x.jsxs)(`div`,{className:e_.runSummary,role:`region`,"aria-label":`Run summary`,children:[(0,x.jsxs)(`div`,{className:e_.summaryStat,title:`Web sources Paracosm pulled via Serper + Tavily and attached to the scenario before generating actors. Grounds the sim in real-world knowledge instead of pure LLM imagination.`,children:[(0,x.jsx)(`span`,{className:e_.summaryNum,children:g.totalCitations}),(0,x.jsx)(`span`,{className:e_.summaryLabel,children:`citations · web research`})]}),(0,x.jsxs)(`div`,{className:e_.summaryStat,title:`AgentOS tool forging: when a department needed a calculation the codebase didn't provide, it wrote one at runtime, run in a QuickJS WebAssembly sandbox. The judge reviewed each for safety + correctness before letting it enter the decision pipeline.`,children:[(0,x.jsx)(`span`,{className:e_.summaryNum,children:g.totalTools}),(0,x.jsx)(`span`,{className:e_.summaryLabel,children:`tools forged · AgentOS sandbox`})]}),(0,x.jsxs)(`div`,{className:e_.summaryStat,title:`Commander decisions across all 3 actors. Each one went through the full propose / judge / execute cycle.`,children:[(0,x.jsx)(`span`,{className:e_.summaryNum,children:g.totalDecisions}),(0,x.jsx)(`span`,{className:e_.summaryLabel,children:`commander decisions`})]}),(0,x.jsxs)(`div`,{className:e_.summaryStat,title:`Total simulation turns across all 3 parallel actors. Each turn = one decision cycle: department analysis, commander decision, kernel advance, agent reactions.`,children:[(0,x.jsx)(`span`,{className:e_.summaryNum,children:g.totalTurns}),(0,x.jsx)(`span`,{className:e_.summaryLabel,children:`turns simulated`})]}),g.totalCostUSD>0&&(0,x.jsxs)(`div`,{className:e_.summaryStat,title:`Total LLM spend across all 3 actors. Provider: gpt-5.4-mini for sims, gpt-4o for verdict.`,children:[(0,x.jsxs)(`span`,{className:e_.summaryNum,children:[`$`,g.totalCostUSD.toFixed(2)]}),(0,x.jsx)(`span`,{className:e_.summaryLabel,children:`LLM cost`})]})]}),(0,x.jsx)(`div`,{className:e_.grid,children:e.map((e,r)=>{let i=t[r];return i?(0,x.jsx)(r_,{actor:e,artifact:i,peers:t.filter((e,t)=>t!==r&&!!e),timeLabel:o.time,timeLabelCap:o.Time,shareEnabled:!!n,onDownload:()=>h(r),onShare:()=>m(r),shareNote:d===r&&l.shared?(0,x.jsx)(dn,{shared:l.shared,onClose:l.clear}):null,onFork:()=>p(r),onRequestSwap:()=>c(r)},r):null})}),s!==null&&(0,x.jsx)($g,{onSelect:e=>{r(s,e),c(null)},onClose:()=>c(null)})]})}function r_({actor:e,artifact:t,peers:n,timeLabel:r,timeLabelCap:i,shareEnabled:a,shareNote:o,onDownload:s,onShare:c,onFork:l,onRequestSwap:u}){let d=(0,b.useMemo)(()=>_h(t,n),[t,n]),f=t.trajectory?.timepoints?.length??0;return(0,x.jsxs)(`article`,{className:e_.card,children:[(0,x.jsxs)(`header`,{className:e_.cardHeader,children:[(0,x.jsx)(`h4`,{className:e_.actorName,children:e.name}),(0,x.jsx)(`span`,{className:e_.archetype,children:e.archetype}),(0,x.jsx)(`button`,{type:`button`,className:e_.swap,onClick:u,"aria-label":`Swap ${e.name}`,children:`Swap`})]}),(0,x.jsx)(`div`,{className:e_.hexaco,children:t_.map(t=>(0,x.jsxs)(`div`,{className:e_.trait,children:[(0,x.jsx)(`span`,{className:e_.traitLabel,children:t.slice(0,4).toUpperCase()}),(0,x.jsx)(`div`,{className:e_.traitBarOuter,children:(0,x.jsx)(`div`,{className:e_.traitBarInner,style:{width:`${Math.round((e.hexaco?.[t]??.5)*100)}%`}})})]},t))}),(0,x.jsxs)(`div`,{className:e_.fingerprint,children:[(0,x.jsx)(`span`,{children:`FP`}),(0,x.jsx)(`code`,{children:t.fingerprint?Object.values(t.fingerprint).slice(0,3).join(` / `):`n/a`})]}),d.length>0&&(0,x.jsx)(`ul`,{className:e_.deltas,"aria-label":`Delta vs peer median`,children:d.slice(0,4).map(e=>(0,x.jsx)(`li`,{className:`${e_.delta} ${e_[`direction_${e.direction}`]}`,children:Bm(e)},`${e.bag}.${e.key}`))}),(0,x.jsxs)(`div`,{className:e_.actions,children:[(0,x.jsx)(`button`,{type:`button`,onClick:s,children:`Download JSON`}),(0,x.jsx)(`button`,{type:`button`,onClick:c,disabled:!a,title:`Copy a deep link that opens this run on the visualization tab`,children:`Copy viz share link`}),(0,x.jsx)(`button`,{type:`button`,onClick:l,disabled:f===0,className:e_.forkButton,title:f===0?`No turns completed yet`:`Promote to fork root and open Branches tab. ${f} ${f===1?r:`${r}s`} available.`,children:`Fork in Branches →`})]}),o,(0,x.jsx)(`div`,{className:e_.forkHint,children:f>0?`${f} ${i}${f===1?``:`s`} available for forking`:``})]})}var i_=2e3,a_=3e5;function o_(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new DOMException(`Aborted`,`AbortError`));return}let i=setTimeout(()=>{t?.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),r(new DOMException(`Aborted`,`AbortError`))};t?.addEventListener(`abort`,a,{once:!0})})}async function s_(e){let t=await e.text(),n;try{n=t?JSON.parse(t):null}catch{throw Error(`Compile returned non-JSON HTTP ${e.status} response`)}if(!e.ok&&(!n||typeof n!=`object`))throw Error(`Compile failed: HTTP ${e.status}`);if(!n||typeof n!=`object`)throw Error(`Compile returned empty body`);return n}async function c_(e,t={}){let n=t.fetchImpl??fetch,r=t.pollIntervalMs??i_,i=t.timeoutMs??a_,a=t.waitImpl??o_,o=Date.now(),s=await n(`/api/quickstart/compile-from-seed`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e),signal:t.signal});if(!s.ok&&s.status!==202){let e=await s.json().catch(()=>({}));throw Error(e.error??`Compile failed: HTTP ${s.status}`)}let c=await s_(s);if(c.status===`done`&&c.scenario)return{scenario:c.scenario,scenarioId:c.scenario.id,jobId:c.jobId};if(c.status===`error`)throw Error(c.error??`Compile failed`);for(;Date.now()-o<i;){await a(r,t.signal);let e=await n(`/api/quickstart/compile-from-seed/status`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({jobId:c.jobId}),signal:t.signal});if(!e.ok){if(e.status===404)throw Error(`Compile job expired or not found. Please retry.`);let t=await e.json().catch(()=>({}));throw Error(t.error??`Compile status check failed: HTTP ${e.status}`)}let i=await s_(e);if(i.status===`done`&&i.scenario)return{scenario:i.scenario,scenarioId:i.scenario.id,jobId:i.jobId};if(i.status===`error`)throw Error(i.error??`Compile failed`)}throw Error(`Compile is taking longer than ${Math.round(i/1e3)}s. The server may still be working — please retry in a minute.`)}var l_={view:`_view_1gdit_2`,header:`_header_1gdit_12`,howItWorks:`_howItWorks_1gdit_36`,glossary:`_glossary_1gdit_43`,timingHint:`_timingHint_1gdit_44`,howItWorksSummary:`_howItWorksSummary_1gdit_60`,errorBanner:`_errorBanner_1gdit_137`,compareCta:`_compareCta_1gdit_149`};function u_(e){return/Failed to fetch|NetworkError|ERR_CONNECTION|ERR_NETWORK/i.test(e)?`Couldn't reach the server. Check your connection and try again.`:/HTTP 502|HTTP 503|HTTP 504/.test(e)?`Server is temporarily unavailable (502/503/504). Try again in a moment.`:/HTTP 429|rate.?limit/i.test(e)?`Hosted demo is rate-limited (3 runs/day). Drop your own API key in Settings to bypass — your saved keys flow into the run automatically.`:/HTTP 401|HTTP 403|unauthor/i.test(e)?`Auth error talking to the LLM provider. Check your API key in Settings.`:/Two actors required|at least 2 actors/i.test(e)?`This scenario needs at least 2 actors. Bump the slider before launching.`:/TypeError|ReferenceError|Cannot read propert|is not a function|is not iterable/i.test(e)?(typeof console<`u`&&console.error(`[quickstart] launch error:`,e),`Something went wrong starting the run. Refresh the page and try again — if it keeps happening, drop a note in the GitHub issues with what you clicked just before.`):e}function d_({sse:e,sessionId:t,onRunStarted:n,onInterventionResult:r,onInterventionStart:i,onInterventionError:a}){let o=Xk(),s=Qk(),{toast:c}=Ht(),[l,u]=(0,b.useState)({kind:`input`}),[d,f]=(0,b.useState)(null),[p,m]=(0,b.useState)(null),[h,g]=(0,b.useState)(!1),[_,v]=(0,b.useState)(null),y=`paracosm:catalogPendingRun`,S=(0,b.useCallback)(async t=>{f(null),n?.(),await e.reset();let r=typeof window<`u`?_g(window.localStorage):{},i=typeof window<`u`?dg(window.localStorage):null,a=bg(r),s={...a};r.serper&&(s.serperKey=r.serper),r.firecrawl&&(s.firecrawlKey=r.firecrawl),r.tavily&&(s.tavilyKey=r.tavily),r.cohere&&(s.cohereKey=r.cohere),i?.provider&&(s.provider=i.provider),i?.models&&typeof i.models==`object`&&(s.models=i.models),i?.economics&&typeof i.economics==`object`&&(s.economics=i.economics);let l=o.presets[0]?.leaders??o.presets[0]?.actors??[];if(l.length>=t){u({kind:`progress`,stage:`running`});let n=l.slice(0,t).map(e=>({name:e.name,archetype:e.archetype,hexaco:e.hexaco,instructions:e.instructions}));await e.reset(),typeof window<`u`&&mg(window.localStorage,n,o.id);try{let e=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...s,actors:n,turns:o.setup.defaultTurns,seed:o.setup.defaultSeed??42,captureSnapshots:!0,quickstart:{scenarioId:o.id}})});if(!e.ok){let t=await e.json().catch(()=>({}));throw Error(t.error??`Setup failed: HTTP ${e.status}`)}let t=await e.json().catch(()=>({}));if(t.redirect){try{window.localStorage.setItem(`paracosm:launchPending`,`1`)}catch{}window.location.href=fh(window.location.href,t.redirect);return}}catch(e){u({kind:`input`});let t=u_(e?.message??String(e));f(t),c(`error`,`Launch failed`,t,8e3)}}else{u({kind:`progress`,stage:`actors`});try{let n=await fetch(`/api/quickstart/generate-actors`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scenarioId:o.id,count:t,...a})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.error??`Actor generation failed: HTTP ${n.status}`)}let r=(await n.json().catch(()=>null))?.actors;if(!r||r.length===0)throw Error(`Actor generation returned no actors`);u({kind:`progress`,stage:`running`}),await e.reset(),typeof window<`u`&&mg(window.localStorage,r,o.id);let i=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...s,actors:r,turns:o.setup.defaultTurns,seed:o.setup.defaultSeed??42,captureSnapshots:!0,quickstart:{scenarioId:o.id}})});if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(e.error??`Setup failed: HTTP ${i.status}`)}let c=await i.json().catch(()=>({}));if(c.redirect){try{window.localStorage.setItem(`paracosm:launchPending`,`1`)}catch{}window.location.href=fh(window.location.href,c.redirect);return}}catch(e){u({kind:`input`});let t=u_(e?.message??String(e));f(t),c(`error`,`Launch failed`,t,8e3)}}},[o,e,n,c]),C=(0,b.useCallback)(async(e,t)=>{if(e===o.id)S(t);else{f(null),n?.();try{try{sessionStorage.setItem(y,JSON.stringify({scenarioId:e,actorCount:t,ts:Date.now()}))}catch{}let n=await fetch(`/scenario/switch`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:e})});if(!n.ok){try{sessionStorage.removeItem(y)}catch{}let e=await n.json().catch(()=>({}));throw Error(e.error??`Scenario switch failed: HTTP ${n.status}`)}te(),window.location.reload()}catch(e){try{sessionStorage.removeItem(y)}catch{}let t=u_(e?.message??String(e));f(t),c(`error`,`Scenario switch failed`,t,8e3)}}},[o.id,S,n,c]);(0,b.useEffect)(()=>{if(!s)return;let e=null;try{let t=sessionStorage.getItem(y);if(!t)return;sessionStorage.removeItem(y),e=JSON.parse(t)}catch{return}if(e?.scenarioId!==o.id){c(`error`,`Scenario changed`,`Another tab of this browser picked a different scenario before the run you picked could start, so nothing ran. Pick it in the catalog again.`,8e3);return}let t=typeof e?.actorCount==`number`&&e.actorCount>0?Math.min(300,Math.max(1,e.actorCount)):null;t!==null&&S(t)},[s]);let w=(0,b.useCallback)(async t=>{f(null),n?.(),await e.reset(),u({kind:`progress`,stage:`compile`});try{let n=typeof window<`u`?bg(_g(window.localStorage)):{},{scenario:r,scenarioId:i}=await c_({...t,...n});u({kind:`progress`,stage:`research`,scenario:r});try{let e=await fetch(`/api/quickstart/ground-scenario`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scenarioId:i})});if(e.ok){let t=await e.json();v(t)}}catch{v({skipped:!0,reason:`request failed`})}u({kind:`progress`,stage:`actors`,scenario:r});let a=Math.max(1,Math.min(300,t.actorCount??2)),o=await fetch(`/api/quickstart/generate-actors`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scenarioId:i,count:a,...n})});if(!o.ok){let e=await o.json().catch(()=>({}));throw Error(e.error??`Actor generation failed: HTTP ${o.status}`)}let s=(await o.json().catch(()=>null))?.actors;if(!s||s.length===0)throw Error(`Actor generation returned no actors`);u({kind:`progress`,stage:`running`,scenario:r,actors:s}),await e.reset(),typeof window<`u`&&mg(window.localStorage,s,i);let c=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n,actors:s,turns:r.setup.defaultTurns,seed:r.setup.defaultSeed??42,captureSnapshots:!0,quickstart:{scenarioId:i}})});if(!c.ok){let e=await c.json().catch(()=>({}));throw Error(e.error??`Setup failed: HTTP ${c.status}`)}let l=await c.json().catch(()=>({}));if(l.redirect){try{window.localStorage.setItem(`paracosm:launchPending`,`1`)}catch{}window.location.href=fh(window.location.href,l.redirect);return}}catch(e){u({kind:`input`});let t=u_(e?.message??String(e));f(t),c(`error`,`Quickstart failed`,t,8e3)}},[e,n,c]);(0,b.useEffect)(()=>{if(l.kind!==`progress`||l.stage!==`running`||!l.scenario||!l.actors)return;let t=e.results.map(e=>e.artifact).filter(e=>!!e);t.length>=l.actors.length&&u({kind:`results`,scenario:l.scenario,actors:l.actors,artifacts:t.slice(0,l.actors.length)})},[e.results,l]),(0,b.useEffect)(()=>{if(l.kind!==`results`||p!==null)return;let e=l.artifacts[0]?.metadata?.runId;if(!e)return;let t=!1;return fetch(`/api/v1/runs/${encodeURIComponent(e)}`).then(async e=>e.ok?e.json():null).then(e=>{if(t)return;let n=e?.record?.bundleId;n&&m(n)}).catch(()=>{}),()=>{t=!0}},[l,p]);let T=l.kind===`progress`&&l.stage===`running`&&l.actors?l.actors.map((t,n)=>{let r=e.events.filter(e=>e.type===`turn_done`||e.type===`turn_start`).reduce((e,t)=>{let n=t.data?.turn??0;return n>e?n:e},0),i=e.results.find(e=>e.actorIndex===n),a=e.errors.length>0&&!i?`error`:e.isAborted?`aborted`:i?`complete`:`running`;return{name:t.name,archetype:t.archetype,currentTurn:i?l.scenario?.setup.defaultTurns??r:r,maxTurns:l.scenario?.setup.defaultTurns??6,status:a}}):void 0,E=(0,b.useCallback)((e,t)=>{f(`Actor swap rerun is a v1.1 follow-up. Use "Fork in Branches" on the Branches tab to try a preset actor against this run.`)},[]);return(0,x.jsxs)(`div`,{className:l_.view,children:[l.kind===`input`&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`header`,{className:l_.header,children:[(0,x.jsx)(`h2`,{children:`Quickstart`}),(0,x.jsx)(`p`,{children:`Paste a what-if scenario. Paracosm compiles it into a typed world and runs LLM-driven decision-makers with measurable personalities against it, returning a replayable trajectory you can fork and compare.`}),(0,x.jsxs)(`details`,{className:l_.howItWorks,children:[(0,x.jsx)(`summary`,{className:l_.howItWorksSummary,children:`How it works`}),(0,x.jsxs)(`ul`,{className:l_.glossary,"aria-label":`Key terms`,children:[(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`strong`,{children:`Scenario`}),` — the world Paracosm compiles from your prompt: departments, agents, events, starting state.`]}),(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`strong`,{children:`Actor`}),` — an LLM decision-maker driving the scenario, weighted by a HEXACO personality vector.`]}),(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`strong`,{children:`Run`}),` — one actor playing the scenario turn by turn. Paracosm runs N actors in parallel against the same world so you can compare divergent outcomes.`]})]}),(0,x.jsxs)(`p`,{className:l_.timingHint,children:[(0,x.jsx)(`strong`,{children:`Heads-up:`}),` a fresh run takes `,(0,x.jsx)(`strong`,{children:`2-5 minutes`}),` (compile, ground with citations, generate actors, simulate). For instant results, replay a cached run below.`]})]})]}),d&&(0,x.jsx)(`p`,{className:l_.errorBanner,role:`alert`,children:d}),(0,x.jsx)(jg,{}),(0,x.jsx)(ig,{onSeedReady:w,onLoadedScenarioRunStart:S,onCatalogRunStart:C}),r&&(0,x.jsx)(Dg,{onResult:r,onRunStart:i,onError:(e,t)=>{a?.(e,t)!==!1&&f(e)}})]}),l.kind===`progress`&&(0,x.jsx)(Xg,{stage:l.stage,actors:T,events:e.events,actorCount:l.actors?.length??T?.length??2,groundingSummary:_}),l.kind===`results`&&(0,x.jsxs)(x.Fragment,{children:[d&&(0,x.jsx)(`p`,{className:l_.errorBanner,role:`alert`,children:d}),p&&l.artifacts.length>=2&&(0,x.jsxs)(`button`,{type:`button`,className:l_.compareCta,onClick:()=>g(!0),"aria-label":`Compare all ${l.artifacts.length} actors side-by-side`,children:[`Compare all `,l.artifacts.length,` actors →`]}),(0,x.jsx)(n_,{actors:l.actors,artifacts:l.artifacts,sessionId:t,onSwap:E}),p&&h&&(0,x.jsx)(ra,{bundleId:p,open:!0,onClose:()=>g(!1)})]})]})}var f_={getNumber:()=>0,getEntry:()=>void 0,list:[]};function p_(e){return(0,b.useMemo)(()=>{let t=new Map,n=[],r=1;for(let i of e.actorIds){let a=e.actors[i];if(a)for(let e of a.events){if(e.type!==`specialist_done`)continue;let a=String(e.data?.department||``),o=e.data?.citationList||[];for(let e of o){let o=(e.url||``).trim(),s=(e.text||``).trim();if(!o&&!s||!o&&s===`Seed document`)continue;let c=o||`text:${s}`,l=t.get(c);l||(l={n:r++,text:s||o,url:o,doi:e.doi,departments:new Set,actorNames:new Set},t.set(c,l),n.push(l)),a&&l.departments.add(a),l.actorNames.add(i),!l.doi&&e.doi&&(l.doi=e.doi)}}}return{getNumber:e=>e?(t.get(e)||t.get(`text:${e}`))?.n??0:0,getEntry:e=>t.get(e)||t.get(`text:${e}`),list:n}},[e])}var m_=(0,b.createContext)(f_);function h_(){return(0,b.useContext)(m_)}var g_=()=>({tools:0,forges:0,reforges:0,passed:0,didNotPass:0});function __(e){let t=String(e??``).trim();return t===`unnamed`?``:t}var v_=e=>Array.isArray(e)?e:[];function y_(e){if(e.type!==`specialist_done`)return!1;let t=e.data?.forgedTools;return t!=null&&!Array.isArray(t)}function b_(e,t,n,r){return{n:0,name:e,description:String(r.description||e),mode:String(r.mode||`sandbox`),firstForgedTurn:r.turn,firstForgedDepartment:r.department,departments:new Set,actorNames:new Set([n]),reuseCount:0,reforgeCount:0,rejectedReforges:0,confidence:r.confidence,approved:r.approved,inputSchema:void 0,outputSchema:void 0,sampleOutput:null,errorReason:r.errorReason,inputFields:v_(r.inputFields),outputFields:v_(r.outputFields),history:[],actorIndex:t,actorName:n,attempts:[],outcome:r.approved?`passed`:`did_not_pass`,sameNameActors:[]}}function x_(e,t,n){let r=new Map;for(let t of e){if(t.type!==`event_start`)continue;let e=`${Number(t.data?.turn??t.turn??0)}:${Number(t.data?.eventIndex??0)}`;r.has(e)||r.set(e,String(t.data?.title??``))}let i=new Map,a=[],o=new Map,s=[];for(let c of e){let e=c.data??{};if(c.type===`forge_attempt`){let o=__(e.name);if(!o)continue;let l=Number(e.turn??c.turn??0),u=Number(e.eventIndex??0),d=String(e.department??``),f=e.approved===!0,p=typeof e.confidence==`number`?e.confidence:null,m=typeof e.errorReason==`string`&&e.errorReason?e.errorReason:null,h=i.get(o);h||(h=b_(o,t,n,{description:e.description,mode:e.mode,turn:l,department:d,confidence:p??0,approved:f,errorReason:m??void 0,inputFields:e.inputFields,outputFields:e.outputFields}),i.set(o,h),a.push(h));let g={attempt:h.attempts.length+1,turn:l,time:Number(e.time??0),eventIndex:u,department:d,eventTitle:r.get(`${l}:${u}`)??``,approved:f,confidence:p,errorReason:m,description:String(e.description??``),inputFields:v_(e.inputFields),outputFields:v_(e.outputFields),eventId:c.id};h.attempts.push(g),d&&h.departments.add(d),p!==null&&p>h.confidence&&(h.confidence=p),f?(h.approved=!0,h.errorReason=void 0):!h.approved&&m&&(h.errorReason=m),s.push(f?`passed`:`did_not_pass`);continue}if(c.type!==`specialist_done`)continue;let l=Array.isArray(e._filteredTools)?e._filteredTools:[],u=String(e.department||``);for(let e of l){let r=__(e.name);if(!r)continue;let s=e.approved!==!1,l=i.get(r);if(l?(o.has(l)||(typeof e.description==`string`&&e.description&&(l.description=e.description),typeof e.mode==`string`&&e.mode&&(l.mode=e.mode),typeof e.firstForgedTurn==`number`&&(l.firstForgedTurn=e.firstForgedTurn),typeof e.firstForgedDepartment==`string`&&e.firstForgedDepartment&&(l.firstForgedDepartment=e.firstForgedDepartment),Array.isArray(e.inputFields)&&(l.inputFields=e.inputFields),Array.isArray(e.outputFields)&&(l.outputFields=e.outputFields)),typeof e.confidence==`number`&&e.confidence>l.confidence&&(l.confidence=e.confidence),s&&(l.approved=!0),l.approved?l.errorReason=void 0:typeof e.errorReason==`string`&&e.errorReason&&(l.errorReason=e.errorReason)):(l=b_(r,t,n,{description:e.description,mode:e.mode,turn:typeof e.firstForgedTurn==`number`?e.firstForgedTurn:c.turn??0,department:String(e.firstForgedDepartment||u),confidence:typeof e.confidence==`number`?e.confidence:s?.85:0,approved:s,errorReason:typeof e.errorReason==`string`?e.errorReason:void 0,inputFields:e.inputFields,outputFields:e.outputFields}),i.set(r,l),a.push(l)),typeof e.output==`string`&&(e.output||l.sampleOutput===null)&&(l.sampleOutput=e.output),!l.inputSchema&&e.inputSchema&&(l.inputSchema=e.inputSchema),!l.outputSchema&&e.outputSchema&&(l.outputSchema=e.outputSchema),u&&l.departments.add(u),o.set(l,s),Array.isArray(e.history)){let t=e.history;l.history=t.map(e=>({...e,actorName:n})),l.reuseCount=Math.max(0,t.length-1),l.reforgeCount=t.filter(e=>e.isReforge).length,l.rejectedReforges=t.filter(e=>e.isReforge&&e.rejected).length}}}for(let e of a){o.has(e)||(e.history=e.attempts.map((e,t)=>({turn:e.turn,time:e.time,eventIndex:e.eventIndex,eventTitle:e.eventTitle,department:e.department,output:null,isReforge:t>0,rejected:!e.approved,confidence:e.confidence??void 0,actorName:n})),e.reforgeCount=Math.max(0,e.attempts.length-1),e.rejectedReforges=e.attempts.filter(e=>!e.approved).length);let t=e.attempts[e.attempts.length-1];e.outcome=(t?t.approved:o.get(e)!==!1)?`passed`:`did_not_pass`}return{entries:a,strip:s}}function S_(e,t){e.tools+=t.tools,e.forges+=t.forges,e.reforges+=t.reforges,e.passed+=t.passed,e.didNotPass+=t.didNotPass}function C_(e){let t=[],n=[],r=g_(),i=new Map,a=new Map,o=(e,t)=>`${e}\u0000${t}`;e.actorIds.forEach((s,c)=>{let l=e.actors[s],u=l?.events??[],d=u.some(y_),{entries:f,strip:p}=d?{entries:[],strip:[]}:x_(u,c,s),m=g_();for(let e of f){e.n=t.length+1,t.push(e),i.set(o(c,e.name),e);let n=a.get(e.name);n?n.push(e):a.set(e.name,[e]);let r=e.attempts.filter(e=>e.approved).length;S_(m,{tools:1,forges:e.attempts.length,reforges:Math.max(0,e.attempts.length-1),passed:r,didNotPass:e.attempts.length-r})}S_(r,m),n.push({index:c,label:`A${c+1}`,name:s,archetype:l?.leader?.archetype??``,counts:m,strip:p,status:e.isComplete?`done`:u.length===0?`waiting`:`running`,unreadable:d})});for(let e of a.values())for(let t of e)t.sameNameActors=e.filter(e=>e!==t).map(e=>e.actorIndex);return{getNumber:e=>a.get(e.trim())?.[0]?.n??0,getEntry:e=>a.get(e.trim())?.[0],getEntryFor:(e,t)=>i.get(o(e,t.trim())),getEntryByNumber:e=>Number.isInteger(e)&&e>=1?t[e-1]:void 0,list:t,actors:n,counts:r}}var w_={getNumber:()=>0,getEntry:()=>void 0,getEntryFor:()=>void 0,getEntryByNumber:()=>void 0,list:[],actors:[],counts:{tools:0,forges:0,reforges:0,passed:0,didNotPass:0}};function T_(e){return(0,b.useMemo)(()=>C_(e),[e])}var E_=(0,b.createContext)(w_);function D_(){return(0,b.useContext)(E_)}var O_=[`request`,`code`,`tests`,`judge`,`added`];function k_(e){return e===`passed`?`passed`:`didNotPass`}var A_=`request`;function j_(e){return e===`passed`?{stations:{request:`reached`,code:`reached`,tests:`reached`,judge:`reached`,added:`reached`},stop:null,deciding:`judge`}:{stations:{request:`reached`,code:`unknown`,tests:`unknown`,judge:`unknown`,added:`notReached`},stop:null,deciding:`request`}}function M_(e,t){let n=e.attempts.length;return n===0?0:Number.isFinite(t)?Math.min(Math.max(Math.trunc(t),1),n):n}function N_(e,t){let n=e.attempts;if(n.length===0)return{...j_(e.outcome),spurs:[],branch:null};let r=M_(e,t),i=e=>e?`passed`:`did_not_pass`,a=n[r-1],o=n[r];return{...j_(i(a.approved)),spurs:n.slice(0,r-1).map(e=>({attempt:e.attempt,station:A_,outcome:i(e.approved)})),branch:o?{attempt:o.attempt,station:A_,outcome:i(o.approved)}:null}}function P_(e,t){return t<=2?Pe(e):`var(--forge-quiet)`}function F_(e){return e.history.slice(1).filter(e=>!e.isReforge).length}var I_={forge_toolbox_open:{from:[`sim`,`reports`,`viz`]},forge_trace_open:{from:[`toolbox`,`inspect`,`viz`,`link`]},forge_station_open:{station:O_,via:[`press`,`open_all`,`kept`]},forge_toolbox_filter:{show:[`all`,`passed`,`did_not_pass`]},forge_record_export:{what:[`toolbox`,`record_copy`,`record_download`]},forge_log_jump:{},forge_link_copy:{},forge_toolbox_group:{group:[`actor`,`department`,`none`]},forge_group_toggle:{scope:[`one`,`all`]},forge_actor_filter:{actors:[`1`,`2-4`,`5-24`,`25+`]},forge_actor_picker_open:{where:[`toolbox`,`compare`,`event_log`]}};function L_(e){return!Number.isFinite(e)||e<1?null:e===1?`1`:e<=4?`2-4`:e<=24?`5-24`:`25+`}function R_(e,t){try{let n=e.paracosmConsent;return typeof n?.allows==`function`&&n.allows(t)===!0}catch{return!1}}function z_(e){try{let{origin:t,pathname:n}=e.location;return typeof t==`string`&&typeof n==`string`?t+n:null}catch{return null}}function B_(e,t){let n=t??(typeof window>`u`?void 0:window);if(!n)return;let r=n,i=I_[e.name];if(!i)return;let a=R_(r,`measure`),o=R_(r,`record`);if(!a&&!o)return;let s={},c=e;for(let[e,t]of Object.entries(i)){let n=c[e];typeof n==`string`&&t.includes(n)&&(s[e]=n)}if(a&&typeof r.gtag==`function`){let t=z_(n);try{r.gtag(`event`,e.name,t===null?s:{...s,page_location:t})}catch{}}if(o&&typeof r.clarity==`function`)try{r.clarity(`event`,e.name)}catch{}}var V_={tool:`tool`,attempt:`attempt`,open:`open`,toolbox:`toolbox`,show:`show`,find:`find`,group:`group`,actors:`actors`},H_=Object.values(V_),U_=[V_.tool,V_.attempt,V_.open];function W_(e){if(e===null||!/^\d+$/.test(e.trim()))return null;let t=Number.parseInt(e.trim(),10);return Number.isSafeInteger(t)&&t>=1?t:null}function G_(e){let t=e.split(`,`).map(e=>e.trim().toLowerCase());return O_.filter(e=>t.includes(e))}function K_(e){let t=[];for(let n of e.split(`,`)){let e=W_(n);e!==null&&!t.includes(e)&&t.push(e)}return t}function q_(e,t,n){let r={trace:null,toolbox:{open:!1}},i=[],a;try{a=new URL(e).searchParams}catch{return{state:r,dangling:i}}r.toolbox.open=a.get(V_.toolbox)===`1`;for(let e of[V_.show,V_.find,V_.group]){let t=a.get(e);t!==null&&t!==``&&(r.toolbox[e]=t)}let o=a.get(V_.actors);if(o!==null){let e=K_(o),a=n?e.filter(e=>e<=t.actors.length):e;a.length>0?r.toolbox.actors=a:n&&i.push(V_.actors)}if(!n)return{state:r,dangling:i};let s=U_.filter(e=>a.has(e));if(s.length===0)return{state:r,dangling:i};let c=W_(a.get(V_.tool)),l=c===null?void 0:t.getEntryByNumber(c);if(!l)return i.push(...s),{state:r,dangling:i};let u;if(a.has(V_.attempt)){let e=W_(a.get(V_.attempt));if(e===null||e>l.attempts.length)return i.push(...s),{state:r,dangling:i};u=e}let d;if(a.has(V_.open)){let e=G_(a.get(V_.open)??``);e.length>0?d=e:i.push(V_.open)}return r.trace={actorIndex:l.actorIndex,toolName:l.name,...u===void 0?{}:{attempt:u},...d?{open:d}:{}},{state:r,dangling:i}}function J_(e,t,n){let r=new URL(e);for(let e of H_)r.searchParams.delete(e);let i=t.trace,a=i?n.getEntryFor(i.actorIndex,i.toolName):void 0;if(i&&a){r.searchParams.set(V_.tool,String(a.n)),i.attempt!==void 0&&i.attempt>=1&&i.attempt<a.attempts.length&&r.searchParams.set(V_.attempt,String(Math.trunc(i.attempt)));let e=O_.filter(e=>i.open?.includes(e));e.length>0&&r.searchParams.set(V_.open,e.join(`,`))}let o=t.toolbox;return o.open&&r.searchParams.set(V_.toolbox,`1`),o.show&&r.searchParams.set(V_.show,o.show),o.find&&r.searchParams.set(V_.find,o.find),o.group&&r.searchParams.set(V_.group,o.group),o.actors&&o.actors.length>0&&r.searchParams.set(V_.actors,o.actors.join(`,`)),r.toString()}function Y_(e,t){let n;try{n=new URL(e)}catch{return e}let r=[[V_.show,t.show&&t.show!==`all`?t.show:null],[V_.find,t.find?t.find:null]];if(t.open!==void 0&&r.push([V_.toolbox,t.open?`1`:null]),t.group!==void 0&&r.push([V_.group,t.group?t.group:null]),t.actors!==void 0){let e=[...new Set(t.actors)].filter(e=>Number.isInteger(e)&&e>=0).sort((e,t)=>e-t).map(e=>e+1);r.push([V_.actors,e.length>0?e.join(`,`):null])}let i=!1;for(let[e,t]of r)n.searchParams.get(e)===t&&n.searchParams.getAll(e).length<=1||(i=!0,t===null?n.searchParams.delete(e):n.searchParams.set(e,t));return i?n.toString():e}function X_(e,t){let n;try{n=new URL(e)}catch{return e}let r=(t??H_).filter(e=>n.searchParams.has(e));if(r.length===0)return e;for(let e of r)n.searchParams.delete(e);return n.toString()}function Z_(e,t,n,r,i){return J_(Ot(e,t,n),{trace:r,toolbox:{open:!1}},i)}function Q_(e){let t;try{t=sh(e)}catch{return`sim`}return t===`about`||t===`quickstart`?`sim`:t}var $_=(0,b.createContext)({openTrace:()=>{},openToolbox:()=>{},close:()=>{},showActorLog:()=>{},current:{trace:null,toolbox:!1}});function ev(){return(0,b.useContext)($_)}var tv=[`all`,`passed`,`did_not_pass`],nv=[`actor`,`department`,`none`],rv=e=>e>2?`actor`:`none`,iv={show:`all`,find:``,group:null,actors:[]},av={...iv,set:()=>{}},ov=(0,b.createContext)(av);function sv(){return(0,b.useContext)(ov)}var cv=[`run`,`tools`,`didNotPass`],lv=/^a(\d+)$/i;function uv(e,t){let n=t.trim();if(n===``)return e;let r=lv.exec(n);if(r){let t=`A${Number.parseInt(r[1],10)}`;return e.filter(e=>e.label===t)}let i=n.toLowerCase();return e.filter(e=>e.name.toLowerCase().includes(i)||e.archetype.toLowerCase().includes(i))}function dv(e,t){let n=(e,t)=>e.index-t.index,r=[...e];return t===`tools`?r.sort((e,t)=>t.counts.tools-e.counts.tools||n(e,t)):t===`didNotPass`?r.sort((e,t)=>t.counts.didNotPass-e.counts.didNotPass||n(e,t)):r.sort(n)}function fv(e,t){return t>0&&e.length===0?`error`:`ready`}function pv(e,t,n){let r=new Set(e);for(let e of t){if(n!==void 0&&r.size>=n)break;r.add(e.index)}return r}function mv(e,t){let n=[...new Set(e)].filter(e=>Number.isInteger(e)&&e>=0&&e<t).sort((e,t)=>e-t);return n.length===0||n.length>=t?null:n}var hv={request:`Request`,code:`Code`,tests:`Tests`,judge:`Judge`,added:`Added`},gv={unknown:`Unknown`,notReached:`Not reached`},_v={reached:`reached`,stopped:`stopped here`,unknown:gv.unknown,notReached:gv.notReached},vv=(e,t)=>`${hv[e]}: ${_v[t]}`,yv=`The forge's stations`,bv={passed:`Passed`,rejected:`Rejected by the judge`,notJudged:`Not judged`,refused:`Refused`,failed:`Failed`,didNotPass:`Did not pass`},xv=e=>`A${e+1}`,Sv=e=>`+${e}`,Cv=(e,t)=>`${e}, forged tool ${t}`,wv=e=>`Forged tool ${e}`,Tv=`Close the trace`,Ev={key:`Copy link to this tool`,copied:`Link copied. Anyone with it can open this tool's trace and replay the run.`,failed:`Could not copy. Select the link and copy it.`,offline:`You are offline`},Dv={toLight:`Switch to light mode`,toDark:`Switch to dark mode`},Ov=`Written by an AI model during this paracosm run`,kv={passed:`Passed. The judge approved it.`,did_not_pass:`Did not pass. The run's record does not say where the forge stopped.`},Av={heading:`The reason the run recorded`,limit:`The run's record keeps at most 240 characters of this reason.`,none:`The record gave no reason.`},jv={code:`The code was not recorded for this run.`,tests:`The tests were not recorded for this run.`},Mv=e=>`Approved · confidence ${e.toFixed(2)} out of 1`,Nv=e=>e===1?`Used 1 time`:`Used ${e} times`,Pv={open:`Open all`,close:`Close all`,openName:`Open all stations`,closeName:`Close all stations`};function Fv(e){return[e.archetype?`${e.label} ${e.name}, ${e.archetype}`:`${e.label} ${e.name}`,e.department,`turn ${e.turn}`,e.eventTitle?`for “${e.eventTitle}”`:``].filter(Boolean).join(` · `)}var Iv=e=>`Go to the event: ${e}`,Lv={whatItDoes:`What it does`,inputFields:`Input fields`,outputFields:`Output fields`,columns:[`Field`,`Type`,`Required`,`Description`],rawJson:`Raw JSON`,noInputFields:`This tool declares no input fields.`,noOutputFields:`This tool declares no output fields.`,notRecorded:`Not recorded`,yes:`Yes`,no:`No`},Rv={heading:`What the judge said`,notice:`A model's review of this code, not a security audit. Check before reuse.`,meterName:`The judge's confidence`,wordsNotRecorded:`The judge's words were not recorded for this run.`},zv=e=>`The judge's confidence: ${e.toFixed(2)} out of 1`,Bv={output:`Output the run recorded`,testNotRecorded:`This forge's test was not recorded.`,notUsed:`Not used after it was forged.`};function Vv(e,t,n){return[`Turn ${e}`,t,n?`“${n}”`:``].filter(Boolean).join(` · `)}var Hv={key:`Record`,rawRecord:`The raw record`,copy:`Copy record`,copied:`Copied`,copyFailed:`Could not copy. Select the record and copy it.`,download:`Download JSON`,downloadFailed:`Could not download. Try again, or use Copy record.`,showInEventLog:`Show in Event Log`,unreadable:`This record could not be shown.`},Uv=e=>`${e}-trace.json`,Wv={previous:`Previous attempt`,next:`Next attempt`},Gv=(e,t)=>`${e} of ${t}`,Kv=(e,t)=>`Attempt ${e} of ${t}`,qv=(e,t)=>`Attempt ${e} · ${t}`,Jv=e=>e.toLocaleString(`en-US`),Yv=(e,t,n)=>`${Jv(e)} ${e===1?t:n}`,Xv=`FORGED TOOLBOX`,Zv=e=>`Forged toolbox, ${Yv(e,`tool`,`tools`)}`,Qv=e=>`Forged toolbox · ${Jv(e)}`,$v=`Close the toolbox`;function ey(e,t){let n=e.reforges>0?` (${Yv(e.reforges,`re-forge`,`re-forges`)})`:``;return[`${Yv(e.tools,`tool`,`tools`)} from ${Yv(e.forges,`forge`,`forges`)}${n}`,e.passed>0?`${Jv(e.passed)} passed`:``,e.didNotPass>0?`${Jv(e.didNotPass)} did not pass`:``,t>2?`${Jv(t)} actors`:``].filter(Boolean).join(` · `)}var ty={name:`Show`,menuLead:`Show:`,all:`All`,passed:bv.passed,did_not_pass:bv.didNotPass},ny={label:`Find a tool`,placeholder:`Tool name…`,clear:`Clear`,clearName:`Clear the search`},ry={noTools:`No department forged a tool in this run.`,everyToolPassed:`Every tool in this run passed.`},iy=e=>`No tool matches “${e}”.`,ay=`Export JSON`,oy=`paracosm-toolbox.json`;function sy(e){return[e.department,`turn ${e.turn}`,e.uses===null?``:`used ${Yv(e.uses,`time`,`times`)}`,e.reforges>0?Yv(e.reforges,`re-forge`,`re-forges`):``].filter(Boolean).join(` · `)}function cy(e){return e.length>3?`Same name in ${Jv(e.length)} other actors`:`Same name: ${e.join(`, `)}`}function ly(e){let t=`${e.name}, ${e.outcome}, made by ${e.actorLabel} ${e.actorName}`;return e.forges>1?`${t}, forged ${Jv(e.forges)} times`:t}var uy={name:`Group`,actor:`Actor`,department:`Department`,none:`None`},dy=e=>`Group: ${uy[e]}`,fy={open:`Open all groups`,close:`Close all groups`};function py(e){return[`${Yv(e.tools,`tool`,`tools`)} from ${Yv(e.forges,`forge`,`forges`)}`,e.passed>0?`${Jv(e.passed)} passed`:``,e.didNotPass>0?`${Jv(e.didNotPass)} did not pass`:``].filter(Boolean).join(` · `)}var my=`No tools`,hy=e=>`${e}'s tools could not be read.`,gy=e=>`${Jv(e)} tools: the most one actor's registry holds`;function _y(e){let t=[`${e.label} ${e.name}`,e.archetype].filter(Boolean);return e.unreadable?[...t,hy(e.label)].join(`, `):e.tools===0?[...t,my].join(`, `):[...t,Yv(e.tools,`tool`,`tools`),e.didNotPass>0?`${Jv(e.didNotPass)} did not pass`:``].filter(Boolean).join(`, `)}function vy(e,t){return[e,Yv(t.tools,`tool`,`tools`),t.didNotPass>0?`${Jv(t.didNotPass)} did not pass`:``].filter(Boolean).join(`, `)}var yy=e=>`Exporting ${Jv(e)} tools…`,by=`Could not export. Try again.`,xy={dialogName:`Choose actors`,listName:`Actors`,findLabel:`Find an actor`,findPlaceholder:`Name, archetype or A-number…`,clearSearchName:`Clear the actor search`,sortName:`Sort`,sortLead:`Sort:`,selectShown:`Select shown`,clear:`Clear`,done:`Done`,showAll:`Show all`,waiting:`Waiting to start`,unreadable:`The actors could not be read.`},Sy={run:`Run order`,tools:`Most tools`,didNotPass:`Most forges that did not pass`},Cy=(e,t)=>e===null?`Actors: All ${Jv(t)}`:`Actors: ${Jv(e)} of ${Jv(t)}`,wy=(e,t)=>`Showing ${Jv(e)} of ${Jv(t)} actors`;function Ty(e,t,n){return`${wy(e,t)} · ${ey(n,0)}`}function Ey(e){return e.tools===0?my:[Yv(e.tools,`tool`,`tools`),e.didNotPass>0?`${Jv(e.didNotPass)} did not pass`:``].filter(Boolean).join(` · `)}var Dy=e=>`No actor matches “${e}”.`,Oy={backdrop:`_backdrop_1mlna_1`,dialog:`_dialog_1mlna_15`,"sheet-up":`_sheet-up_1mlna_1`,header:`_header_1mlna_50`,headerEnd:`_headerEnd_1mlna_62`,key:`_key_1mlna_69`,iconKey:`_iconKey_1mlna_106`,lookGlyph:`_lookGlyph_1mlna_111`,number:`_number_1mlna_116`,linkNote:`_linkNote_1mlna_135`,linkSaid:`_linkSaid_1mlna_144`,linkText:`_linkText_1mlna_151`,name:`_name_1mlna_165`,nameInRow:`_nameInRow_1mlna_184`,head:`_head_1mlna_50`,label:`_label_1mlna_195`,outcome:`_outcome_1mlna_202`,attempts:`_attempts_1mlna_219`,attemptLine:`_attemptLine_1mlna_226`,reason:`_reason_1mlna_234`,reasonHeading:`_reasonHeading_1mlna_242`,reasonText:`_reasonText_1mlna_250`,reasonNote:`_reasonNote_1mlna_263`,line:`_line_1mlna_270`,recordFoot:`_recordFoot_1mlna_274`,recordKey:`_recordKey_1mlna_283`,recordBody:`_recordBody_1mlna_288`,nameInHead:`_nameInHead_1mlna_355`,lineHead:`_lineHead_1mlna_389`};function ky(){let{resolved:e,setTheme:t}=C(),n=e===`dark`?`light`:`dark`,r=n===`light`?Dv.toLight:Dv.toDark;return(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Oy.iconKey}`,onClick:()=>t(n),"aria-label":r,title:r,children:(0,x.jsx)(`span`,{className:Oy.lookGlyph,"aria-hidden":`true`,children:e===`dark`?`☀`:`☽`})})}var Ay=m();function jy(e,t=!1){let[n,r]=(0,b.useState)(()=>typeof window>`u`||!window.matchMedia?t:window.matchMedia(e).matches);return(0,b.useEffect)(()=>{if(typeof window>`u`||!window.matchMedia)return;let t=window.matchMedia(e),n=e=>r(e.matches);return t.addEventListener(`change`,n),r(t.matches),()=>t.removeEventListener(`change`,n)},[e]),n}var My=`(max-width: 768px)`,Ny=`(max-width: 480px)`,Py=`(max-width: 899.98px)`,Fy=`(prefers-reduced-motion: reduce)`,Iy={tile:`_tile_1dw5u_1`,band:`_band_1dw5u_17`,label:`_label_1dw5u_26`},Ly={2:28,3:32,4:40};function Ry({index:e,colour:t}){let n=xv(e),r={"--tile-size":`${Ly[n.length]??Ly[4]}px`,"--tile-band":t};return(0,x.jsxs)(`span`,{className:Iy.tile,style:r,"data-actor-tile":n,translate:`no`,children:[(0,x.jsx)(`span`,{className:Iy.band,"aria-hidden":`true`}),(0,x.jsx)(`span`,{className:Iy.label,children:n})]})}var zy={strip:`_strip_1uso4_1`,cell:`_cell_1uso4_10`,more:`_more_1uso4_27`},By=20;function Vy({cells:e,max:t=By}){let n=e.slice(0,Math.max(0,t)),r=e.length-n.length;return(0,x.jsxs)(`span`,{className:zy.strip,"aria-hidden":`true`,"data-forge-strip":e.length,children:[n.map((e,t)=>(0,x.jsx)(`span`,{className:zy.cell,"data-cell":e},t)),r>0&&(0,x.jsx)(`span`,{className:zy.more,children:Sv(r)})]})}function Hy({count:e,lineHeights:t,scrollTop:n,viewport:r,overscan:i,keep:a}){if(e<=0)return{first:0,last:-1,padTop:0,padBottom:0};let o=e=>{let n=typeof t==`number`?t:t[e]??0;return Number.isFinite(n)&&n>0?n:0},s=Math.max(0,n),c=s+Math.max(0,r),l=0,u=-1,d=-1;for(let t=0;t<e;t+=1){let e=o(t);if(l>=c&&u>=0)break;u<0&&l+e>s&&(u=t),u>=0&&(d=t),l+=e}u<0&&(u=e-1,d=e-1);let f=Math.max(0,Math.floor(i)),p=Math.max(0,u-f),m=Math.min(e-1,d+f),h=(e,t)=>{let n=0;for(let r=e;r<t;r+=1)n+=o(r);return n};if(a!==void 0&&Number.isInteger(a)&&a>=0&&a<e){if(a>=p-1&&a<=m+1)p=Math.min(p,a),m=Math.max(m,a);else if(a<p)return{first:p,last:m,kept:a,gap:h(a+1,p),padTop:h(0,a),padBottom:h(m+1,e)};else return{first:p,last:m,kept:a,gap:h(m+1,a),padTop:h(0,p),padBottom:h(a+1,e)}}return{first:p,last:m,padTop:h(0,p),padBottom:h(m+1,e)}}var Uy=`button:not([disabled]), a[href], input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])`;function Wy(e){for(let t=e.parentElement;t&&t!==document.body&&t!==document.documentElement;t=t.parentElement){let{overflowY:e}=getComputedStyle(t);if((e===`auto`||e===`scroll`||e===`overlay`)&&t.scrollHeight>t.clientHeight+1)return t}return null}function Gy(e){if(!e)return{top:0,bottom:window.innerHeight,padTop:0};let t=e.getBoundingClientRect().top+e.clientTop,n=Number.parseFloat(getComputedStyle(e).scrollPaddingTop);return{top:t,bottom:t+e.clientHeight,padTop:Number.isFinite(n)?n:0}}function Ky(e){let t=e.getBoundingClientRect(),{top:n,bottom:r}=Gy(Wy(e));return{scrollTop:Math.max(0,n-t.top),viewport:Math.max(0,r-Math.max(n,t.top))}}function qy(e,t,n){let r=e.length>50,i=(0,b.useRef)(new Map),a=(0,b.useRef)(new Map),o=(0,b.useRef)(-1),[s,c]=(0,b.useState)(0),[l,u]=(0,b.useState)(()=>({scrollTop:0,viewport:typeof window>`u`?0:window.innerHeight})),d=(0,b.useMemo)(()=>e.map(e=>{let t=i.current.get(e.key);if(t!==void 0)return t;let n=a.current.get(e.kind);return n&&n.n>0?n.sum/n.n:e.estimate}),[e,s]),f=n!==null&&n>=0&&n<e.length?n:void 0,p=r?Hy({count:e.length,lineHeights:d,scrollTop:l.scrollTop,viewport:l.viewport,overscan:8,keep:f}):{first:0,last:e.length-1,padTop:0,padBottom:0},m=(0,b.useRef)({heights:d,range:p,keep:f,windowed:r});m.current={heights:d,range:p,keep:f,windowed:r};let h=(0,b.useCallback)(()=>{let e=m.current;if(!t||!e.windowed)return;let n=Ky(t),r=Hy({count:e.heights.length,lineHeights:e.heights,scrollTop:n.scrollTop,viewport:n.viewport,overscan:8,keep:e.keep});(r.first!==e.range.first||r.last!==e.range.last||r.kept!==e.range.kept)&&u(n)},[t]);(0,b.useEffect)(()=>{if(!t)return;let e=0,n=()=>{e===0&&(e=window.requestAnimationFrame(()=>{e=0,h()}))};document.addEventListener(`scroll`,n,{capture:!0,passive:!0}),window.addEventListener(`resize`,n);let r=typeof ResizeObserver>`u`?null:new ResizeObserver(n);return r?.observe(t),n(),()=>{document.removeEventListener(`scroll`,n,{capture:!0}),window.removeEventListener(`resize`,n),r?.disconnect(),e!==0&&window.cancelAnimationFrame(e)}},[t,h]),(0,b.useLayoutEffect)(()=>{if(!t)return;let n=t.clientWidth;n>0&&Math.abs(n-o.current)>1&&(i.current.clear(),a.current.clear(),o.current=n);let r=!1;for(let n of t.querySelectorAll(`[data-line]`)){let t=e[Number(n.dataset.line)];if(!t)continue;let o=n.getBoundingClientRect().height;if(!(o>0))continue;let s=i.current.get(t.key);if(s!==void 0&&Math.abs(s-o)<.5)continue;i.current.set(t.key,o);let c=a.current.get(t.kind)??{sum:0,n:0};s===void 0?(c.sum+=o,c.n+=1):c.sum+=o-s,a.current.set(t.kind,c),r=!0}r?c(e=>e+1):h()});let g=(0,b.useCallback)(e=>{let n=m.current;if(!t||e<0||e>=n.heights.length)return;let r=0;for(let t=0;t<e;t+=1)r+=n.heights[t];let i=Wy(t),{top:a,bottom:o,padTop:s}=Gy(i),c=t.getBoundingClientRect().top+r,l=c+n.heights[e],u=c<a+s?c-(a+s):l>o?l-o:0;u!==0&&(i?i.scrollTop+=u:window.scrollBy(0,u)),h()},[t,h]);return{...p,windowed:r,scrollToLine:g}}function Jy(e,t,n){for(let r=t+n;r>=0&&r<e.length;r+=n)if(e[r].focusable)return r;return-1}function Yy(e,t){return Jy(e,t===1?-1:e.length,t)}function Xy(e,t){let[n,r]=(0,b.useState)(null),[i,a]=(0,b.useState)(null),o=(0,b.useRef)(null),s=(0,b.useRef)(e);s.current=e;let c=(0,b.useRef)(0),l=(0,b.useRef)(0);(0,b.useEffect)(()=>{let e=e=>{e.key===`Tab`&&(c.current=e.shiftKey?-1:1,window.setTimeout(()=>{c.current=0},0))};return document.addEventListener(`keydown`,e,!0),()=>document.removeEventListener(`keydown`,e,!0)},[]),(0,b.useEffect)(()=>{if(!t)return;let e=e=>{let n=e instanceof Element?e.closest(`[data-line]`):null;return n&&t.contains(n)?Number(n.dataset.line):-1},n=e=>{l.current=0,a(e)},i=i=>{let a=s.current,o=e(i.target),l=a[o];if(!l)return;let u=i.relatedTarget,d=c.current;if(d!==0&&!(u instanceof Node&&t.contains(u))){let e=Yy(a,d);e>=0&&e!==o&&n(a[e].key)}r(e=>e?.key===l.key?e:{key:l.key,headKey:l.headKey})},o=e=>{let n=e.relatedTarget;n instanceof Node&&!t.contains(n)&&(t.closest(`[role="dialog"]`)??t.closest(`[data-toolbox-list]`))?.contains(n)&&r(null)},u=r=>{if(r.key!==`Tab`||r.altKey||r.ctrlKey||r.metaKey)return;let i=s.current,a=e(r.target);if(a<0)return;let o=Jy(i,a,r.shiftKey?-1:1);o<0||t.querySelector(`[data-line="${o}"]`)||(r.preventDefault(),r.stopPropagation(),n(i[o].key))};return t.addEventListener(`focusin`,i),t.addEventListener(`focusout`,o),t.addEventListener(`keydown`,u,!0),()=>{t.removeEventListener(`focusin`,i),t.removeEventListener(`focusout`,o),t.removeEventListener(`keydown`,u,!0)}},[t]),(0,b.useLayoutEffect)(()=>{if(t){if(i!==null){let n=e.findIndex(e=>e.key===i),r=n>=0?t.querySelector(`[data-line="${n}"]`):null;if(r){a(null),(r.matches(Uy)?r:r.querySelector(Uy))?.focus();return}l.current+=1,n<0||l.current>3?a(null):o.current?.(n)}else if(n&&!e.some(e=>e.key===n.key)){let t=document.activeElement;(t===null||t===document.body||!t.isConnected)&&n.headKey&&e.some(e=>e.key===n.headKey)?(l.current=0,a(n.headKey)):r(null)}}});let u=n?.key??null,d=u===null?-1:e.findIndex(e=>e.key===u);return{keep:d>=0?d:null,scrollTo:o}}var K={list:`_list_yqq00_1`,count:`_count_yqq00_15`,keyRows:`_keyRows_yqq00_23`,lead:`_lead_yqq00_30`,key:`_key_yqq00_23`,actorsMenu:`_actorsMenu_yqq00_42`,keys:`_keys_yqq00_48`,segments:`_segments_yqq00_55`,segment:`_segment_yqq00_55`,menu:`_menu_yqq00_106`,menuSelect:`_menuSelect_yqq00_135`,menuMark:`_menuMark_yqq00_158`,find:`_find_yqq00_167`,findLabel:`_findLabel_yqq00_175`,field:`_field_yqq00_183`,input:`_input_yqq00_189`,clear:`_clear_yqq00_218`,groupMenu:`_groupMenu_yqq00_276`,menuKey:`_menuKey_yqq00_282`,menuKeyMark:`_menuKeyMark_yqq00_288`,groupList:`_groupList_yqq00_293`,groupItem:`_groupItem_yqq00_306`,groupCheck:`_groupCheck_yqq00_332`,empty:`_empty_yqq00_342`,emptyWords:`_emptyWords_yqq00_350`,rows:`_rows_yqq00_357`,head:`_head_yqq00_361`,row:`_row_yqq00_357`,openAll:`_openAll_yqq00_376`,stations:`_stations_yqq00_388`,items:`_items_yqq00_411`,item:`_item_yqq00_411`,sideMark:`_sideMark_yqq00_422`,top:`_top_yqq00_456`,name:`_name_yqq00_465`,outcome:`_outcome_yqq00_476`,lineCell:`_lineCell_yqq00_488`,does:`_does_yqq00_495`,metaCell:`_metaCell_yqq00_504`,meta:`_meta_yqq00_504`,same:`_same_yqq00_512`,actor:`_actor_yqq00_42`,groups:`_groups_yqq00_525`,fold:`_fold_yqq00_529`,foldTop:`_foldTop_yqq00_533`,foldHeading:`_foldHeading_yqq00_537`,foldHead:`_foldHead_yqq00_537`,chevron:`_chevron_yqq00_577`,chevronRoom:`_chevronRoom_yqq00_578`,foldTile:`_foldTile_yqq00_590`,foldName:`_foldName_yqq00_596`,foldActor:`_foldActor_yqq00_607`,foldCount:`_foldCount_yqq00_611`,foldNote:`_foldNote_yqq00_612`,foldStrip:`_foldStrip_yqq00_621`,foldHeadDept:`_foldHeadDept_yqq00_630`,foldStill:`_foldStill_yqq00_643`,foldWay:`_foldWay_yqq00_647`,department:`_department_yqq00_651`,deptLine:`_deptLine_yqq00_655`,pageFold:`_pageFold_yqq00_664`,pageFoldSummary:`_pageFoldSummary_yqq00_670`},Zy={picker:`_picker_wqyxx_1`,"picker-up":`_picker-up_wqyxx_1`,top:`_top_wqyxx_32`,find:`_find_wqyxx_39`,sort:`_sort_wqyxx_47`,list:`_list_wqyxx_76`,rows:`_rows_wqyxx_85`,option:`_option_wqyxx_89`,box:`_box_wqyxx_118`,tile:`_tile_wqyxx_135`,who:`_who_wqyxx_141`,name:`_name_wqyxx_150`,dot:`_dot_wqyxx_155`,archetype:`_archetype_wqyxx_156`,second:`_second_wqyxx_161`,counts:`_counts_wqyxx_171`,strip:`_strip_wqyxx_178`,empty:`_empty_wqyxx_183`,emptyWords:`_emptyWords_wqyxx_192`,said:`_said_wqyxx_200`,foot:`_foot_wqyxx_212`,done:`_done_wqyxx_261`},Qy=56,$y=`button:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])`;function eb(){return(0,x.jsx)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3 8.5L6.5 12L13 4.5`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.25`,strokeLinecap:`round`,strokeLinejoin:`round`})})}function tb({actors:e,chosen:t,max:n,tools:r=0,onChange:i,onClose:a,opener:o,where:s=`toolbox`}){let c=(0,b.useId)(),l=(0,b.useRef)(null),u=(0,b.useRef)(null),[d,f]=(0,b.useState)(``),[p,m]=(0,b.useState)(`run`),[h,g]=(0,b.useState)(``),_=jy(`(min-width: 900px)`),v=jy(`(min-width: 1440px)`),y=fv(e,r),S=(0,b.useMemo)(()=>dv(uv(e,d),p),[e,d,p]),C=S.length>0&&S.every(e=>t.has(e.index)),w=n!==void 0&&t.size>=n,T=(0,b.useRef)(!1);(0,b.useEffect)(()=>{T.current||(T.current=!0,B_({name:`forge_actor_picker_open`,where:s}))},[s]),(0,b.useEffect)(()=>{u.current?.focus({preventScroll:!0})},[]);let E=(0,b.useCallback)(()=>{a(),o?.isConnected&&o.focus()},[a,o]);(0,b.useEffect)(()=>{let e=l.current;if(!e)return;let t=t=>{if(t.key===`Escape`){t.preventDefault(),t.stopPropagation(),E();return}if(t.key!==`Tab`||t.altKey||t.ctrlKey||t.metaKey)return;t.stopPropagation();let n=Array.from(e.querySelectorAll($y)).filter(e=>e.tabIndex>=0&&e.offsetParent!==null);if(n.length===0){t.preventDefault();return}let r=n.indexOf(document.activeElement);(t.shiftKey?r<=0:r===-1||r===n.length-1)&&(t.preventDefault(),n[t.shiftKey?n.length-1:0].focus())};return e.addEventListener(`keydown`,t),()=>e.removeEventListener(`keydown`,t)},[E]),(0,b.useEffect)(()=>{let e=e=>{let t=e.target;l.current?.contains(t)||o?.contains(t)||a()};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[a,o]);let[D,O]=(0,b.useState)(null);(0,b.useLayoutEffect)(()=>{if(!_||!o){O(null);return}let e=v?560:480,t=()=>{let t=o.getBoundingClientRect(),n=Math.round(t.bottom+4),r=Math.round(Math.max(8,Math.min(t.left,window.innerWidth-e-8))),i=Math.round(Math.max(240,Math.min(560,window.innerHeight-n-16)));O(e=>e&&e.top===n&&e.left===r&&e.maxHeight===i?e:{top:n,left:r,maxHeight:i})};return t(),document.addEventListener(`scroll`,t,{capture:!0,passive:!0}),window.addEventListener(`resize`,t),()=>{document.removeEventListener(`scroll`,t,{capture:!0}),window.removeEventListener(`resize`,t)}},[_,v,o]);let k=(0,b.useCallback)(t=>{i(t);let n=L_(t.size);n&&B_({name:`forge_actor_filter`,actors:n});let r=e.length;g(wy(t.size===0?r:Math.min(t.size,r),r))},[i,e.length]),A=e=>{let n=new Set(t);if(n.has(e))n.delete(e);else if(w)return;else n.add(e);k(n)},j=(0,b.useMemo)(()=>S.map(e=>({key:e.label,kind:`option`,estimate:Qy,focusable:!0})),[S]),[ee,te]=(0,b.useState)(0),[M,N]=(0,b.useState)(!1),[ne,P]=(0,b.useState)(null),re=(0,b.useRef)(null),ie=(0,b.useRef)(!1),F=Math.min(ee,Math.max(0,S.length-1)),I=qy(j,ne,M?F:null),ae=F>=I.first&&F<=I.last||F===I.kept?F:I.first;(0,b.useEffect)(()=>{te(0),re.current&&(re.current.scrollTop=0)},[d,p]),(0,b.useLayoutEffect)(()=>{if(!ie.current||!ne)return;let e=ne.querySelector(`[data-line="${F}"]`);e?(ie.current=!1,e.focus({preventScroll:!0}),e.scrollIntoView({block:`nearest`})):I.scrollToLine(F)});let oe=e=>{S.length!==0&&(ie.current=!0,te(Math.max(0,Math.min(S.length-1,e))))},se=e=>{switch(e.key){case`ArrowDown`:e.preventDefault(),oe(F+1);break;case`ArrowUp`:e.preventDefault(),oe(F-1);break;case`Home`:e.preventDefault(),oe(0);break;case`End`:e.preventDefault(),oe(S.length-1);break;case` `:case`Enter`:e.preventDefault(),S[F]&&A(S[F].index)}},ce=()=>{f(``),u.current?.focus()},le=()=>{k(new Set),E()},L=[],ue=I.kept!==void 0&&I.kept<I.first;I.kept!==void 0&&ue&&L.push(I.kept);for(let e=I.first;e<=I.last;e+=1)L.push(e);I.kept!==void 0&&!ue&&L.push(I.kept);let de=I.kept===void 0||!I.gap?-1:ue?I.first:I.kept,fe=I.windowed?{paddingTop:I.padTop,paddingBottom:I.padBottom}:void 0,R=_&&D?{top:D.top,left:D.left,maxHeight:D.maxHeight}:void 0,z=e=>{let n=S[e];if(!n)return null;let r=t.has(n.index),i=!r&&w,a=n.unreadable?hy(n.label):n.status===`waiting`?xy.waiting:Ey(n.counts);return(0,x.jsxs)(`div`,{role:`option`,"aria-selected":r,"aria-disabled":i?!0:void 0,"aria-setsize":S.length,"aria-posinset":e+1,"aria-label":_y({label:n.label,name:n.name,archetype:n.archetype,tools:n.counts.tools,didNotPass:n.counts.didNotPass,unreadable:n.unreadable}),tabIndex:e===ae?0:-1,className:Zy.option,"data-actor":n.label,"data-line":e,onClick:()=>{te(e),A(n.index)},onFocus:()=>te(e),children:[(0,x.jsx)(`span`,{className:Zy.box,"data-checked":r,"aria-hidden":`true`,children:r&&(0,x.jsx)(eb,{})}),(0,x.jsx)(`span`,{className:Zy.tile,children:(0,x.jsx)(Ry,{index:n.index,colour:Pe(n.index)})}),(0,x.jsxs)(`span`,{className:Zy.who,translate:`no`,children:[(0,x.jsx)(`span`,{className:Zy.name,"data-picker-name":!0,children:n.name}),n.archetype&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:Zy.dot,"aria-hidden":`true`,children:` · `}),(0,x.jsx)(`span`,{className:Zy.archetype,"data-picker-archetype":!0,children:n.archetype})]})]}),(0,x.jsxs)(`span`,{className:Zy.second,children:[(0,x.jsx)(`span`,{className:Zy.counts,"data-picker-counts":!0,children:a}),!n.unreadable&&(0,x.jsx)(`span`,{className:Zy.strip,children:(0,x.jsx)(Vy,{cells:n.strip,max:v?20:10})})]})]},n.label)},pe=(0,x.jsx)(`div`,{ref:l,role:`dialog`,"aria-label":xy.dialogName,className:Zy.picker,style:R,"data-actor-picker":!0,children:y===`error`?(0,x.jsxs)(`div`,{className:Zy.empty,"data-picker-error":!0,children:[(0,x.jsx)(`p`,{className:Zy.emptyWords,"data-text":`body`,children:xy.unreadable}),(0,x.jsx)(`button`,{type:`button`,className:K.key,onClick:le,children:xy.showAll})]}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:Zy.top,children:[(0,x.jsxs)(`div`,{className:Zy.find,children:[(0,x.jsx)(`label`,{className:K.findLabel,htmlFor:c,children:xy.findLabel}),(0,x.jsxs)(`span`,{className:K.field,children:[(0,x.jsx)(`input`,{id:c,ref:u,className:K.input,type:`search`,placeholder:xy.findPlaceholder,value:d,onChange:e=>f(e.target.value),spellCheck:!1,autoComplete:`off`}),d!==``&&(0,x.jsx)(`button`,{type:`button`,className:K.clear,"aria-label":xy.clearSearchName,title:xy.clearSearchName,onClick:ce,children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3 3L13 13M13 3L3 13`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`})})})]})]}),(0,x.jsxs)(`label`,{className:Zy.sort,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:xy.sortLead}),(0,x.jsx)(`select`,{className:K.menuSelect,"aria-label":xy.sortName,value:p,onChange:e=>m(e.target.value),children:cv.map(e=>(0,x.jsx)(`option`,{value:e,children:Sy[e]},e))}),(0,x.jsx)(`svg`,{className:K.menuMark,width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3.5 6L8 10.5L12.5 6`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})]})]}),S.length===0?(0,x.jsxs)(`div`,{className:Zy.empty,"data-picker-empty":!0,children:[(0,x.jsx)(`p`,{className:Zy.emptyWords,"data-text":`body`,children:Dy(d.trim())}),(0,x.jsx)(`button`,{type:`button`,className:K.key,onClick:ce,children:xy.clear})]}):(0,x.jsx)(`div`,{ref:re,role:`listbox`,"aria-multiselectable":`true`,"aria-label":xy.listName,className:Zy.list,onKeyDown:se,onFocus:()=>N(!0),onBlur:e=>{e.relatedTarget instanceof Node&&e.currentTarget.contains(e.relatedTarget)||N(!1)},children:(0,x.jsx)(`div`,{ref:P,className:Zy.rows,style:fe,"data-windowed":I.windowed,children:L.flatMap(e=>[e===de?(0,x.jsx)(`div`,{"aria-hidden":`true`,"data-lines-gap":!0,style:{height:I.gap}},`gap`):null,z(e)])})}),(0,x.jsx)(`p`,{className:Zy.said,role:`status`,children:h}),(0,x.jsxs)(`div`,{className:Zy.foot,"data-picker-foot":!0,children:[(0,x.jsx)(`button`,{type:`button`,className:K.key,"aria-disabled":C||w||S.length===0?!0:void 0,onClick:()=>{C||w||S.length===0||k(pv(t,S,n))},children:xy.selectShown}),(0,x.jsx)(`button`,{type:`button`,className:K.key,onClick:()=>k(new Set),children:xy.clear}),(0,x.jsx)(`button`,{type:`button`,className:`${K.key} ${Zy.done}`,onClick:E,children:xy.done})]})]})}),me=o?.closest(`[role="dialog"]`)??(typeof document>`u`?null:document.body);return me?(0,Ay.createPortal)(pe,me):pe}var nb=e=>e.kind===`actor`?`actor:${e.actor.label}`:`department:${e.name}`,rb=e=>e.kind===`department`||!e.actor.unreadable&&e.actor.counts.tools>0;function ib(){let e=jy(`(min-width: 1440px)`),t=jy(`(min-width: 900px)`);return e?50:t?30:1/0}function ab(){return(0,x.jsx)(`svg`,{className:K.chevron,width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M6 3.5L10.5 8L6 12.5`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})}function ob({head:e,open:t,onToggle:n,onShowInEventLog:r}){let i=(0,b.useId)(),a=ib();if(e.kind===`department`)return(0,x.jsx)(`h3`,{className:K.foldHeading,"data-fold-head":e.name,children:(0,x.jsxs)(`button`,{type:`button`,className:`${K.foldHead} ${K.foldHeadDept}`,"aria-expanded":t,"aria-label":vy(e.name,e.counts),onClick:n,children:[(0,x.jsx)(ab,{}),(0,x.jsx)(`span`,{className:K.foldName,"data-fold-name":!0,"data-text":`heading`,children:e.name}),(0,x.jsx)(`span`,{className:K.foldCount,"data-fold-count":!0,children:py(e.counts)})]})});let{actor:o}=e,s=!o.unreadable&&o.counts.tools>=50,c=(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:K.foldTile,children:(0,x.jsx)(Ry,{index:o.index,colour:Pe(o.index)})}),(0,x.jsxs)(`span`,{className:K.foldName,"data-fold-name":!0,translate:`no`,"data-text":`heading`,children:[(0,x.jsx)(`span`,{className:K.foldActor,children:o.name}),o.archetype?` · ${o.archetype}`:``]}),o.unreadable?(0,x.jsx)(`span`,{className:K.foldCount,"data-fold-error":!0,children:hy(o.label)}):(0,x.jsx)(`span`,{className:K.foldCount,"data-fold-count":!0,children:o.counts.tools===0?my:py(o.counts)}),s&&(0,x.jsx)(`span`,{id:i,className:K.foldNote,"data-fold-note":!0,children:gy(50)}),!o.unreadable&&(0,x.jsx)(`span`,{className:K.foldStrip,children:(0,x.jsx)(Vy,{cells:o.strip,max:a})})]}),l=_y({label:o.label,name:o.name,archetype:o.archetype,tools:o.counts.tools,didNotPass:o.counts.didNotPass,unreadable:o.unreadable});return rb(e)?(0,x.jsx)(`h3`,{className:K.foldHeading,"data-fold-head":o.label,children:(0,x.jsxs)(`button`,{type:`button`,className:K.foldHead,"aria-expanded":t,"aria-label":l,"aria-describedby":s?i:void 0,onClick:n,children:[(0,x.jsx)(ab,{}),c]})}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{className:K.foldHeading,"data-fold-head":o.label,children:(0,x.jsxs)(`span`,{className:`${K.foldHead} ${K.foldStill}`,children:[(0,x.jsx)(`span`,{className:K.chevronRoom,"aria-hidden":`true`}),c]})}),o.unreadable&&r&&(0,x.jsx)(`div`,{className:K.foldWay,children:(0,x.jsx)(`button`,{type:`button`,className:K.key,onClick:r,children:Hv.showInEventLog})})]})}var sb={glyph:`_glyph_bhdp0_1`,passed:`_passed_bhdp0_8`,rejected:`_rejected_bhdp0_12`,refused:`_refused_bhdp0_13`,failed:`_failed_bhdp0_14`,notJudged:`_notJudged_bhdp0_18`,didNotPass:`_didNotPass_bhdp0_22`};function cb(e,t,n){let r={fill:`none`,stroke:`currentColor`,strokeWidth:t,strokeLinecap:`round`,strokeLinejoin:`round`},i=(0,x.jsx)(`circle`,{cx:`10`,cy:`10`,r:`8.25`,...r});switch(e){case`passed`:return(0,x.jsx)(`path`,{fill:`currentColor`,fillRule:`evenodd`,d:`M1 10a9 9 0 1 0 18 0a9 9 0 1 0 -18 0Z M4.75 11.05L8.63 14.93L15.28 7.82L13.52 6.18L8.57 11.47L6.45 9.35Z`});case`rejected`:return(0,x.jsxs)(x.Fragment,{children:[i,(0,x.jsx)(`path`,{d:`M6.9 6.9L13.1 13.1M13.1 6.9L6.9 13.1`,...r})]});case`refused`:return(0,x.jsxs)(x.Fragment,{children:[i,(0,x.jsx)(`path`,{d:`M4.2 15.8L15.8 4.2`,...r})]});case`failed`:return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 2.2L18.2 16.8H1.8Z`,...r}),(0,x.jsx)(`path`,{d:`M10 7.4V12.2`,...r})]});case`notJudged`:return(0,x.jsxs)(x.Fragment,{children:[i,(0,x.jsx)(`path`,{d:`M7.7 7.9a2.4 2.4 0 1 1 3.5 2.1c-.8.4-1.2.9-1.2 1.7v.4`,...r}),(0,x.jsx)(`circle`,{cx:`10`,cy:`14.5`,r:`1.1`,fill:`currentColor`})]});case`didNotPass`:return(0,x.jsx)(`circle`,{cx:`10`,cy:`10`,r:`8.25`,...r,strokeLinecap:`butt`,strokeDasharray:n})}}function lb({kind:e,size:t}){let n=t===10?3:1.75,r=t===10?`5 4`:`2.6 2.1`;return(0,x.jsx)(`svg`,{className:`${sb.glyph} ${sb[e]}`,"data-glyph":e,width:t,height:t,viewBox:`0 0 20 20`,"aria-hidden":`true`,focusable:`false`,children:cb(e,n,r)})}var ub={cell:`_cell_1xygk_1`,trace:`_trace_1xygk_22`,station:`_station_1xygk_35`,stationKey:`_stationKey_1xygk_58`,mark:`_mark_1xygk_83`,name:`_name_1xygk_91`,result:`_result_1xygk_119`,evidence:`_evidence_1xygk_120`,fork:`_fork_1xygk_144`,forkLink:`_forkLink_1xygk_167`,forkWords:`_forkWords_1xygk_200`,chevron:`_chevron_1xygk_205`,row:`_row_1xygk_267`,spur:`_spur_1xygk_275`,rowStation:`_rowStation_1xygk_279`,segment:`_segment_1xygk_290`},db=e=>e===`reached`||e===`stopped`,fb=e=>e===void 0?void 0:db(e)?`solid`:`dashed`;function pb({model:e,station:t,size:n}){let r=e.stations[t];if(r===`stopped`){let r=e.stop;return(0,x.jsx)(lb,{kind:r&&r.station===t?r.glyph:`didNotPass`,size:n})}return(0,x.jsx)(`span`,{className:ub.cell,"data-cell":r})}function mb({mark:e,onAttempt:t,href:n}){let r=k_(e.outcome);return(0,x.jsx)(`div`,{className:ub.fork,"data-fork":e.attempt,children:(0,x.jsxs)(`a`,{className:ub.forkLink,href:n,"data-fork-attempt":e.attempt,onClick:n=>{n.defaultPrevented||n.button!==0||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey||(n.preventDefault(),t?.(e.attempt))},children:[(0,x.jsx)(lb,{kind:r,size:20}),(0,x.jsx)(`span`,{className:ub.forkWords,children:qv(e.attempt,bv[r])}),(0,x.jsx)(`svg`,{className:ub.chevron,width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M6 3.5L10.5 8L6 12.5`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})]})})}function hb(e){return e===`notReached`?gv.notReached:e===`unknown`?gv.unknown:null}function gb({model:e,size:t,colour:n,open:r,onToggle:i,stationResult:a,renderEvidence:o,onAttempt:s,attemptHref:c}){let l=(0,b.useId)(),u={"--line":n};return t===`row`?(0,x.jsx)(`span`,{className:ub.row,style:u,"aria-hidden":`true`,"data-forge-line":`row`,children:O_.map((t,n)=>{let r=e.spurs.filter(e=>e.station===t);return(0,x.jsxs)(b.Fragment,{children:[n>0&&(0,x.jsx)(`span`,{className:ub.segment,"data-rail":fb(e.stations[t])}),(0,x.jsxs)(`span`,{className:ub.rowStation,"data-station":t,"data-state":e.stations[t],children:[(0,x.jsx)(pb,{model:e,station:t,size:10}),r.length>0&&(0,x.jsx)(`span`,{className:ub.spur,"data-spurs":r.length,children:r.map(e=>(0,x.jsx)(lb,{kind:k_(e.outcome),size:10},e.attempt))})]})]},t)})}):(0,x.jsx)(`ol`,{className:ub.trace,style:u,role:`list`,"aria-label":yv,"data-forge-line":`trace`,children:O_.map((t,n)=>{let u=e.stations[t],d=o?.(t),f=d!=null&&d!==!1,p=db(u)&&f,m=p&&!!r?.has(t),h=a?.(t)??hb(u),g=`${l}-${t}-result`,_=`${l}-${t}-evidence`,v=`${l}-${t}-name`,y=u===`notReached`||u===`unknown`,b=[...e.spurs.filter(e=>e.station===t),...e.branch&&e.branch.station===t?[e.branch]:[]];return(0,x.jsxs)(`li`,{className:ub.station,"data-station":t,"data-state":u,"data-open":m||void 0,"data-rail":fb(e.stations[O_[n+1]]),children:[(0,x.jsxs)(`button`,{type:`button`,className:ub.stationKey,"aria-label":vv(t,u),"aria-expanded":p?m:void 0,"aria-controls":p?_:void 0,"aria-disabled":!p||void 0,"aria-describedby":!p&&h!=null?g:void 0,tabIndex:p?void 0:-1,onClick:p?()=>i?.(t):void 0,children:[(0,x.jsx)(`span`,{className:ub.mark,"aria-hidden":`true`,children:(0,x.jsx)(pb,{model:e,station:t,size:20})}),(0,x.jsx)(`span`,{id:v,className:ub.name,"data-text":`heading`,children:hv[t]})]}),!m&&h!=null&&(0,x.jsx)(`div`,{id:g,className:ub.result,"data-quiet":y||void 0,"data-text":y?void 0:`body`,children:h}),p&&(0,x.jsx)(`div`,{id:_,className:ub.evidence,role:`region`,"aria-labelledby":v,hidden:!m,children:m?d:null}),b.map(e=>(0,x.jsx)(mb,{mark:e,onAttempt:s,href:c?c(e.attempt):`#`},e.attempt))]},t)})})}function _b(e){let t=e.split(`_`);return t.map((e,n)=>(0,x.jsxs)(b.Fragment,{children:[n<t.length-1?`${e}_`:e,n<t.length-1&&(0,x.jsx)(`wbr`,{})]},n))}function vb({entry:e,actorCount:t,onOpen:n,line:r,setSize:i,posInSet:a}){let o=(0,b.useId)(),s=xv(e.actorIndex),c=k_(e.outcome),l=bv[c],u=e.attempts.length,d=e.description!==``&&e.description!==e.name,f=e.sameNameActors.map(xv),p={"--actor":Pe(e.actorIndex)};return(0,x.jsxs)(`li`,{className:K.item,style:p,"data-tool-row":e.n,"data-tool-name":e.name,"data-actor":s,"data-outcome":e.outcome,"data-line":r,"aria-setsize":i,"aria-posinset":a,children:[(0,x.jsx)(`span`,{className:K.sideMark,"data-side-mark":!0,"aria-hidden":`true`}),(0,x.jsxs)(`button`,{type:`button`,className:K.row,"aria-label":ly({name:e.name,outcome:l,actorLabel:s,actorName:e.actorName,forges:u}),"aria-describedby":d?`${o}-does ${o}-meta`:`${o}-meta`,onClick:e=>n(e.currentTarget),children:[(0,x.jsxs)(`span`,{className:K.top,children:[(0,x.jsxs)(`span`,{className:K.name,"data-row-name":!0,"data-text":`heading`,children:[(0,x.jsxs)(`span`,{children:[`[`,e.n,`]`]}),` `,(0,x.jsx)(`span`,{translate:`no`,children:_b(e.name)})]}),(0,x.jsxs)(`span`,{className:K.outcome,"data-row-outcome":!0,children:[(0,x.jsx)(lb,{kind:c,size:20}),(0,x.jsx)(`span`,{children:l})]})]}),(0,x.jsx)(`span`,{className:K.lineCell,children:(0,x.jsx)(gb,{model:N_(e,NaN),size:`row`,colour:P_(e.actorIndex,t)})}),d&&(0,x.jsx)(`span`,{id:`${o}-does`,className:K.does,"data-row-does":!0,"data-text":`body`,children:e.description}),(0,x.jsxs)(`span`,{id:`${o}-meta`,className:K.metaCell,children:[(0,x.jsxs)(`span`,{className:K.meta,"data-row-meta":!0,children:[(0,x.jsx)(`span`,{className:K.actor,"data-row-actor":!0,children:`${s} ${e.actorName}`}),` · ${sy({department:e.firstForgedDepartment,turn:e.firstForgedTurn,uses:e.outcome===`passed`?F_(e):null,reforges:Math.max(0,u-1)})}`]}),f.length>0&&(0,x.jsx)(`span`,{className:K.same,"data-row-same":!0,children:cy(f)})]})]})]})}function yb(e,t,n,r=null){let i=n.trim().toLowerCase(),a=r===null?null:new Set(r);return t===`all`&&i===``&&a===null?e:e.filter(e=>(a===null||a.has(e.actorIndex))&&(t===`all`||e.outcome===t)&&(i===``||e.name.toLowerCase().includes(i)))}function bb(e){let t={tools:0,forges:0,reforges:0,passed:0,didNotPass:0};for(let n of e)t.tools+=n.counts.tools,t.forges+=n.counts.forges,t.reforges+=n.counts.reforges,t.passed+=n.counts.passed,t.didNotPass+=n.counts.didNotPass;return t}var xb=e=>e.firstForgedDepartment||gv.unknown;function Sb(e,t){let n=new Map;for(let r of e){let e=t(r),i=n.get(e);i?i.push(r):n.set(e,[r])}return[...n]}function Cb(e){let t={tools:0,forges:0,reforges:0,passed:0,didNotPass:0};for(let n of e){let e=n.attempts.filter(e=>e.approved).length;t.tools+=1,t.forges+=n.attempts.length,t.reforges+=Math.max(0,n.attempts.length-1),t.passed+=e,t.didNotPass+=n.attempts.length-e}return t}function wb(e,t,n){return t===`none`?[{head:null,rows:e}]:t===`department`?Sb(e,xb).map(([e,t])=>({head:{kind:`department`,name:e,counts:Cb(t)},rows:t})):n.map(t=>{let n=e.filter(e=>e.actorIndex===t.index);return{head:{kind:`actor`,actor:t},rows:Sb(n,xb).flatMap(([,e])=>e)}})}var Tb={head:64,dept:40,row:112},Eb=e=>`${e.actorIndex}:${e.name}`,Db=e=>e.kind===`head`?null:e.dept;function Ob(e,t,n,r){let i=[];if(e===`none`)return t.forEach((e,t)=>{i.push({kind:`row`,key:Eb(e),estimate:Tb.row,focusable:!0,fold:-1,dept:null,entry:e,pos:t+1})}),{lines:i,rowCount:t.length};let a=0;return n.forEach((e,t)=>{let n=e.head;if(n===null)return;let o=nb(n),s=rb(n)&&e.rows.length>0&&r(o),c=rb(n)||n.kind===`actor`&&n.actor.unreadable;i.push({kind:`head`,key:o,estimate:Tb.head,focusable:c,fold:t});let l=n.kind===`actor`?Sb(e.rows,xb):[[null,e.rows]];for(let[e,n]of l){s&&e!==null&&i.push({kind:`dept`,key:`${o}|dept:${e}`,estimate:Tb.dept,focusable:!1,headKey:o,fold:t,dept:e});for(let r of n)a+=1,s&&i.push({kind:`row`,key:`${o}|${Eb(r)}`,estimate:Tb.row,focusable:!0,headKey:o,fold:t,dept:e,entry:r,pos:a})}}),{lines:i,rowCount:a}}var kb=8,Ab=new Set,jb=[];function Mb({value:e,onChoose:t}){let[n,r]=(0,b.useState)(!1),i=(0,b.useId)(),a=(0,b.useRef)(null),o=(0,b.useRef)(null),s=(0,b.useRef)([]);(0,b.useEffect)(()=>{n&&s.current[nv.indexOf(e)]?.focus()},[n,e]),(0,b.useEffect)(()=>{if(!n)return;let e=e=>{a.current?.contains(e.target)||r(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[n]);let c=()=>{r(!1),o.current?.focus()},l=e=>{t(e),c()},u=e=>s.current[(e+nv.length)%nv.length]?.focus();return(0,x.jsxs)(`div`,{ref:a,className:K.groupMenu,children:[(0,x.jsxs)(`button`,{ref:o,type:`button`,className:`${K.key} ${K.menuKey}`,"aria-haspopup":`menu`,"aria-expanded":n,"aria-controls":n?i:void 0,onClick:()=>r(e=>!e),onKeyDown:e=>{(e.key===`ArrowDown`||e.key===`ArrowUp`)&&(e.preventDefault(),r(!0))},children:[(0,x.jsx)(`span`,{children:dy(e)}),(0,x.jsx)(`svg`,{className:K.menuKeyMark,width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3.5 6L8 10.5L12.5 6`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})]}),n&&(0,x.jsx)(`div`,{id:i,role:`menu`,"aria-label":uy.name,className:K.groupList,onKeyDown:e=>{let t=s.current.findIndex(e=>e===document.activeElement);switch(e.key){case`ArrowDown`:e.preventDefault(),u(t+1);break;case`ArrowUp`:e.preventDefault(),u(t-1);break;case`Home`:e.preventDefault(),u(0);break;case`End`:e.preventDefault(),u(nv.length-1);break;case`Enter`:case` `:e.preventDefault(),t>=0&&l(nv[t]);break;case`Escape`:e.preventDefault(),c();break;case`Tab`:c()}},children:nv.map((t,n)=>(0,x.jsxs)(`div`,{ref:e=>{s.current[n]=e},role:`menuitemradio`,"aria-checked":t===e,tabIndex:-1,className:K.groupItem,onClick:()=>l(t),children:[(0,x.jsx)(`svg`,{className:K.groupCheck,width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3 8.5L6.5 12L13 4.5`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})}),(0,x.jsx)(`span`,{children:uy[t]})]},t))})]})}function Nb({inPage:e=!1}){let t=D_(),{show:n,find:r,group:i,actors:a,set:o}=sv(),{openTrace:s,showActorLog:c}=ev(),l=(0,b.useId)(),u=(0,b.useId)(),d=(0,b.useRef)(null),f=(0,b.useRef)(null),p=(0,b.useRef)(null),[m,h]=(0,b.useState)(!1),g=t.actors.length,_=(0,b.useMemo)(()=>mv(a,g),[a,g]),v=(0,b.useMemo)(()=>_===null?t.actors:_.map(e=>t.actors[e]),[_,t.actors]),y=(0,b.useMemo)(()=>new Set(a.filter(e=>e<g)),[a,g]),S=(0,b.useMemo)(()=>yb(t.list,`all`,``,_),[t.list,_]),C=(0,b.useMemo)(()=>yb(S,n,r),[S,n,r]),w=i??rv(g),T=n!==`all`||r.trim()!==``,E=(0,b.useMemo)(()=>{let e=S.filter(e=>e.outcome===`passed`).length;return[{id:`all`,count:S.length},{id:`passed`,count:e},{id:`did_not_pass`,count:S.length-e}].filter(e=>e.id===`all`||e.count>0||e.id===n)},[S,n]),D=(0,b.useMemo)(()=>{let e=wb(C,w,v);return T?e.filter(e=>e.head===null||e.rows.length>0||e.head.kind===`actor`&&e.head.actor.unreadable):e},[C,w,v,T]),O=_===null?ey(t.counts,g):Ty(_.length,g,bb(v)),k=(0,b.useCallback)(e=>{o({actors:[...e].sort((e,t)=>e-t)})},[o]),A=(0,b.useCallback)(()=>h(!1),[]),[j,ee]=(0,b.useState)({group:w,all:null,toggled:Ab}),te=(0,b.useMemo)(()=>j.group===w?j:{group:w,all:null,toggled:Ab},[j,w]),M=g<=kb,N=(0,b.useCallback)(e=>(te.all??M)!==te.toggled.has(e),[te,M]),ne=D.filter(e=>e.head!==null&&rb(e.head)&&e.rows.length>0),P=ne.length>0&&ne.every(e=>N(nb(e.head))),re=w===`none`||ne.length===0,ie=e=>{B_({name:`forge_group_toggle`,scope:`one`}),ee(t=>{let n=t.group===w?t:{group:w,all:null,toggled:Ab},r=new Set(n.toggled);return r.has(e)?r.delete(e):r.add(e),{...n,toggled:r}})},F=()=>{B_({name:`forge_group_toggle`,scope:`all`}),ee({group:w,all:!P,toggled:Ab})},I=e=>{e!==w&&B_({name:`forge_toolbox_group`,group:e}),o({group:e===rv(g)?null:e})},ae=e=>{e!==n&&B_({name:`forge_toolbox_filter`,show:e}),o({show:e})},oe=(0,b.useCallback)((e,t)=>{s({actorIndex:e.actorIndex,toolName:e.name},t,`toolbox`)},[s]),{lines:se,rowCount:ce}=(0,b.useMemo)(()=>Ob(w,C,D,N),[w,C,D,N]),[le,L]=(0,b.useState)(null),ue=Xy(se,le),de=qy(se,le,ue.keep);ue.scrollTo.current=de.scrollToLine;let fe=()=>{o({find:``}),f.current?.focus()},R=()=>{ae(`all`);let e=d.current?.querySelectorAll(`input[type="radio"][value="all"], select`);Array.from(e??[]).find(e=>e.offsetParent!==null)?.focus()},z=e=>`${ty[e.id]} ${Jv(e.count)}`,pe=e=>{let t=se[e];return t.kind===`row`?(0,x.jsx)(vb,{entry:t.entry,actorCount:g,onOpen:e=>oe(t.entry,e),line:e,setSize:ce,posInSet:t.pos},Eb(t.entry)):null},me=[],he=de.kept!==void 0&&de.kept<de.first;de.kept!==void 0&&he&&me.push(de.kept);for(let e=de.first;e<=de.last;e+=1)me.push(e);de.kept!==void 0&&!he&&me.push(de.kept);let ge=de.kept===void 0||!de.gap?-1:he?de.first:de.kept,_e=(e,t)=>{if(e!==ge)return null;let n={height:de.gap};return t?(0,x.jsx)(`li`,{role:`presentation`,"aria-hidden":`true`,"data-lines-gap":!0,style:n},`gap`):(0,x.jsx)(`div`,{"aria-hidden":`true`,"data-lines-gap":!0,style:n},`gap`)},B=e=>e.flatMap(e=>[_e(e,!0),pe(e)]),ve=de.windowed?{paddingTop:de.padTop,paddingBottom:de.padBottom}:void 0,ye=[];for(let e of me){let t=ye[ye.length-1];t&&t.fold===se[e].fold?t.at.push(e):ye.push({fold:se[e].fold,at:[e]})}let be=e=>{let t=[];for(let n of e){let e=Db(se[n])??``,r=t[t.length-1];r&&r.dept===e?r.at.push(n):t.push({dept:e,at:[n]})}return t};return(0,x.jsxs)(`div`,{className:K.list,"data-toolbox-list":e?`page`:`dialog`,children:[(0,x.jsx)(`p`,{className:K.count,"data-toolbox-count":!0,children:O}),t.list.length===0?(0,x.jsxs)(`div`,{className:K.empty,"data-toolbox-empty":`no-tools`,children:[(0,x.jsx)(Vy,{cells:jb}),(0,x.jsx)(`p`,{className:K.emptyWords,"data-text":`body`,children:ry.noTools})]}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:K.keyRows,children:[(0,x.jsxs)(`div`,{className:K.lead,"data-toolbox-lead":!0,children:[(0,x.jsx)(Mb,{value:w,onChoose:I}),(0,x.jsxs)(`div`,{className:K.actorsMenu,children:[(0,x.jsx)(`button`,{ref:p,type:`button`,className:K.key,"aria-haspopup":`dialog`,"aria-expanded":m,onClick:()=>h(e=>!e),children:Cy(_===null?null:_.length,g)}),m&&(0,x.jsx)(tb,{actors:t.actors,tools:t.list.length,chosen:y,onChange:k,onClose:A,opener:p.current})]})]}),(0,x.jsxs)(`div`,{ref:d,className:K.keys,"data-toolbox-keys":!0,children:[(0,x.jsx)(`div`,{className:K.segments,role:`radiogroup`,"aria-label":ty.name,children:E.map(e=>(0,x.jsxs)(`label`,{className:K.segment,"data-show":e.id,children:[(0,x.jsx)(`input`,{type:`radio`,name:u,value:e.id,checked:n===e.id,onChange:()=>ae(e.id)}),(0,x.jsx)(`span`,{children:z(e)})]},e.id))}),(0,x.jsxs)(`label`,{className:K.menu,"data-toolbox-menu":!0,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:ty.menuLead}),(0,x.jsx)(`select`,{className:K.menuSelect,"aria-label":ty.name,value:n,onChange:e=>ae(e.target.value),children:E.map(e=>(0,x.jsx)(`option`,{value:e.id,children:z(e)},e.id))}),(0,x.jsx)(`svg`,{className:K.menuMark,width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3.5 6L8 10.5L12.5 6`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})]}),(0,x.jsxs)(`div`,{className:K.find,children:[(0,x.jsx)(`label`,{className:K.findLabel,htmlFor:l,children:ny.label}),(0,x.jsxs)(`span`,{className:K.field,children:[(0,x.jsx)(`input`,{id:l,ref:f,className:K.input,type:`search`,placeholder:ny.placeholder,value:r,onChange:e=>o({find:e.target.value}),spellCheck:!1,autoComplete:`off`}),r!==``&&(0,x.jsx)(`button`,{type:`button`,className:K.clear,"aria-label":ny.clearName,title:ny.clearName,onClick:fe,children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3 3L13 13M13 3L3 13`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`})})})]})]})]})]}),C.length===0&&T?(0,x.jsx)(`div`,{className:K.empty,"data-toolbox-empty":r.trim()===``?`no-rows`:`no-match`,children:r.trim()===``?(0,x.jsxs)(x.Fragment,{children:[n===`did_not_pass`&&_===null&&(0,x.jsx)(`p`,{className:K.emptyWords,"data-text":`body`,children:ry.everyToolPassed}),(0,x.jsx)(`button`,{type:`button`,className:K.key,onClick:R,children:ty.all})]}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`p`,{className:K.emptyWords,"data-text":`body`,children:iy(r.trim())}),(0,x.jsx)(`button`,{type:`button`,className:K.key,onClick:fe,children:ny.clear})]})}):(0,x.jsxs)(`div`,{className:K.rows,children:[(0,x.jsxs)(`div`,{className:K.head,children:[(0,x.jsx)(`button`,{type:`button`,className:`${K.key} ${K.openAll}`,"aria-disabled":re?!0:void 0,tabIndex:re?-1:void 0,onClick:re?void 0:F,children:P?fy.close:fy.open}),(0,x.jsx)(`span`,{className:K.stations,"data-toolbox-stations":!0,"aria-hidden":`true`,children:O_.map(e=>(0,x.jsx)(`span`,{children:hv[e]},e))})]}),w===`none`?(0,x.jsx)(`ol`,{ref:L,className:K.items,"data-toolbox-rows":!0,"data-line-count":se.length,"data-windowed":de.windowed,style:ve,children:B(me)}):(0,x.jsx)(`div`,{ref:L,role:`list`,className:K.groups,"data-toolbox-rows":!0,"data-line-count":se.length,"data-windowed":de.windowed,style:ve,children:ye.map(({fold:e,at:t})=>{let n=D[e],r=n?.head??null;if(r===null)return null;let i=nb(r),a=rb(r)&&n.rows.length>0&&N(i),o=t.find(e=>se[e].kind===`head`),s=t.filter(e=>se[e].kind!==`head`);return(0,x.jsxs)(`div`,{role:`listitem`,"aria-setsize":D.length,"aria-posinset":e+1,className:K.fold,"data-fold":r.kind===`actor`?r.actor.label:r.name,children:[o!==void 0&&_e(o,!1),o!==void 0&&(0,x.jsx)(`div`,{className:K.foldTop,"data-line":o,children:(0,x.jsx)(ob,{head:r,open:a,onToggle:()=>ie(i),onShowInEventLog:r.kind===`actor`&&r.actor.unreadable?()=>c(r.actor.index):void 0})}),r.kind===`actor`?be(s).map(({dept:e,at:t})=>{let n=t.find(e=>se[e].kind===`dept`),r=t.filter(e=>se[e].kind===`row`);return(0,x.jsxs)(`div`,{className:K.department,children:[n!==void 0&&_e(n,!1),n!==void 0&&(0,x.jsx)(`h4`,{className:K.deptLine,"data-dept-line":!0,"data-line":n,children:e}),r.length>0&&(0,x.jsx)(`ol`,{className:K.items,children:B(r)})]},e)}):s.length>0&&(0,x.jsx)(`ol`,{className:K.items,children:B(s)})]},i)})})]})]})]})}var Pb={dialog:`_dialog_x8cpw_1`,"sheet-up":`_sheet-up_x8cpw_1`,header:`_header_x8cpw_36`,headerEnd:`_headerEnd_x8cpw_48`,title:`_title_x8cpw_55`,exportInHeader:`_exportInHeader_x8cpw_73`,exportStatus:`_exportStatus_x8cpw_77`,footStatus:`_footStatus_x8cpw_95`,body:`_body_x8cpw_106`,foot:`_foot_x8cpw_95`,exportAtFoot:`_exportAtFoot_x8cpw_114`};function Fb(e){return e.map(e=>({n:e.n,name:e.name,description:e.description,mode:e.mode,firstForgedTurn:e.firstForgedTurn,firstForgedDepartment:e.firstForgedDepartment,departments:[...e.departments],reuseCount:e.reuseCount,approved:e.approved,confidence:e.confidence,inputSchema:e.inputSchema,outputSchema:e.outputSchema,sampleOutput:e.sampleOutput,inputFields:e.inputFields,outputFields:e.outputFields,actor:xv(e.actorIndex),actorName:e.actorName}))}function Ib(e){let t=new Blob([JSON.stringify(Fb(e),null,2)],{type:`application/json`}),n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=oy,r.click(),URL.revokeObjectURL(n)}var Lb=500;function Rb({covered:e,onClose:t}){let n=D_(),{show:r,find:i,actors:a}=sv(),o=Pt(!0),s=(0,b.useRef)(null);(0,b.useEffect)(()=>{s.current?.focus()},[]);let c=(0,b.useRef)(e);c.current=e,(0,b.useEffect)(()=>{let e=e=>{e.key!==`Escape`||e.defaultPrevented||c.current||(e.preventDefault(),t())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[t]);let[l,u]=(0,b.useState)({state:`idle`}),d=()=>{B_({name:`forge_record_export`,what:`toolbox`});let e=yb(n.list,r,i,mv(a,n.actors.length)),t=()=>{try{Ib(e),u({state:`idle`})}catch{u({state:`failed`})}};e.length<=Lb?t():(u({state:`exporting`,tools:e.length}),requestAnimationFrame(()=>{window.setTimeout(t,0)}))},f=l.state===`exporting`?yy(l.tools):l.state===`failed`?by:``;return(0,x.jsx)(`div`,{className:Oy.backdrop,onMouseDown:e=>{e.target===e.currentTarget&&t()},children:(0,x.jsxs)(`div`,{ref:o,role:`dialog`,"aria-modal":`true`,"aria-label":Zv(n.list.length),tabIndex:-1,className:Pb.dialog,inert:e,children:[(0,x.jsxs)(`div`,{className:Pb.header,"data-toolbox-header":!0,children:[(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Oy.iconKey}`,onClick:()=>t(),"aria-label":$v,title:$v,children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3 3L13 13M13 3L3 13`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`})})}),(0,x.jsx)(`h2`,{ref:s,className:Pb.title,tabIndex:-1,"data-toolbox-title":!0,"data-text":`heading`,children:Xv}),(0,x.jsxs)(`span`,{className:Pb.headerEnd,children:[(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Pb.exportInHeader}`,onClick:d,children:ay}),(0,x.jsx)(ky,{})]}),(0,x.jsx)(`span`,{className:Pb.exportStatus,role:`status`,"data-export-status":!0,children:f})]}),(0,x.jsx)(`div`,{className:Pb.body,children:(0,x.jsx)(Nb,{})}),(0,x.jsxs)(`div`,{className:Pb.foot,children:[(0,x.jsx)(`p`,{className:Pb.footStatus,role:`status`,"data-export-status":!0,children:f}),(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Pb.exportAtFoot}`,onClick:d,children:ay})]})]})})}var zb=`paracosm:forgeOpenStations`,Bb=20,Vb=e=>typeof e==`string`&&O_.includes(e);function Hb(e){let t=new Map,n;try{n=e.getItem(zb)}catch{return t}if(!n)return t;let r;try{r=JSON.parse(n)}catch{return t}if(!r||typeof r!=`object`||Array.isArray(r))return t;for(let[e,n]of Object.entries(r))Array.isArray(n)&&t.set(e,O_.filter(e=>n.some(t=>Vb(t)&&t===e)));return t}function Ub(e,t){return Hb(e).get(t)??[]}function Wb(e,t,n){let r=Hb(e);r.delete(t),r.set(t,O_.filter(e=>n.includes(e)));let i=[...r.keys()];for(let e of i.slice(0,Math.max(0,i.length-Bb)))r.delete(e);try{e.setItem(zb,JSON.stringify(Object.fromEntries(r)))}catch{}}function Gb(e,t,n){let r=new Set([e.deciding]);for(let e of t)n(e)&&r.add(e);return r}function Kb(e){return t=>t===`request`||e&&(t===`judge`||t===`added`)}function qb(e,t){let n=null;try{n=new URL(e).searchParams.get(`replay`)}catch{}return n||t||`live`}var Jb={open:`_open_o8eqn_1`,part:`_part_o8eqn_11`,heading:`_heading_o8eqn_18`,body:`_body_o8eqn_26`,meta:`_meta_o8eqn_34`,quiet:`_quiet_o8eqn_42`,code:`_code_o8eqn_49`,actor:`_actor_o8eqn_62`,rule:`_rule_o8eqn_68`,actorText:`_actorText_o8eqn_74`,link:`_link_o8eqn_81`,fieldsBar:`_fieldsBar_o8eqn_105`,switch:`_switch_o8eqn_110`,switchTrack:`_switchTrack_o8eqn_139`,caption:`_caption_o8eqn_167`,fields:`_fields_o8eqn_105`,confidence:`_confidence_o8eqn_247`,meter:`_meter_o8eqn_258`,meterFill:`_meterFill_o8eqn_267`,uses:`_uses_o8eqn_275`,use:`_use_o8eqn_275`,recordKeys:`_recordKeys_o8eqn_295`,recordSaid:`_recordSaid_o8eqn_307`,record:`_record_o8eqn_295`};function Yb(e,t){let n=t.trim(),r=e=>String(e??``).trim()===n,i=[];for(let t of e){let e=t.data??{},n=t.type===`forge_attempt`&&r(e.name),a=t.type===`specialist_done`&&Array.isArray(e.forgedTools)&&e.forgedTools.some(e=>!!e&&typeof e==`object`&&r(e.name));if(!n&&!a)continue;let o={...e};delete o._filteredTools,i.push(o)}return i}function Xb(e){try{return JSON.stringify(e,null,2)}catch{return null}}var Zb=5e3;function Qb({entry:e,frames:t,onShowInEventLog:n}){let r=(0,b.useId)(),i=(0,b.useMemo)(()=>Xb(t),[t]),[a,o]=(0,b.useState)(null),s=(0,b.useRef)(null),c=(0,b.useRef)(0);(0,b.useEffect)(()=>()=>{s.current!==null&&window.clearTimeout(s.current)},[]);let l=e=>{s.current!==null&&window.clearTimeout(s.current),s.current=null,o(e),e===`copied`&&(s.current=window.setTimeout(()=>o(null),Zb))},u=()=>{if(i===null)return;B_({name:`forge_record_export`,what:`record_copy`});let e=++c.current;Dt(i).then(()=>{e===c.current&&l(`copied`)},()=>{e===c.current&&l(`copyFailed`)})},d=()=>{if(i!==null){B_({name:`forge_record_export`,what:`record_download`});try{let t=URL.createObjectURL(new Blob([i],{type:`application/json`})),n=document.createElement(`a`);n.href=t,n.download=Uv(e.name),document.body.append(n),n.click(),n.remove(),window.setTimeout(()=>URL.revokeObjectURL(t),1e3),l(null)}catch{l(`downloadFailed`)}}},f={copied:Hv.copied,copyFailed:Hv.copyFailed,downloadFailed:Hv.downloadFailed};return(0,x.jsxs)(`section`,{className:Jb.open,"data-record-panel":!0,"aria-labelledby":r,children:[(0,x.jsx)(`h3`,{id:r,className:Jb.heading,"data-text":`heading`,children:Hv.rawRecord}),i===null?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`p`,{className:Jb.body,"data-text":`body`,children:Hv.unreadable}),(0,x.jsx)(`div`,{className:Jb.recordKeys,children:(0,x.jsx)(`button`,{type:`button`,className:Jb.switch,onClick:n,children:Hv.showInEventLog})})]}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:Jb.recordKeys,children:[(0,x.jsx)(`button`,{type:`button`,className:Jb.switch,onClick:u,children:Hv.copy}),(0,x.jsx)(`button`,{type:`button`,className:Jb.switch,onClick:d,children:Hv.download}),(0,x.jsx)(`button`,{type:`button`,className:Jb.switch,onClick:n,children:Hv.showInEventLog}),(0,x.jsx)(`p`,{className:Jb.recordSaid,role:`status`,children:a?f[a]:null})]}),(0,x.jsx)(`pre`,{className:Jb.record,"data-raw-record":!0,translate:`no`,tabIndex:0,"aria-label":Hv.rawRecord,children:i})]})]})}function $b({entry:e}){let t=F_(e);return(0,x.jsxs)(`div`,{className:Jb.open,children:[(0,x.jsx)(`p`,{className:Jb.body,"data-text":`body`,children:Nv(t)}),e.history.length>0&&(0,x.jsx)(`ol`,{className:Jb.uses,children:e.history.map((e,t)=>{let n=t===0||e.isReforge;return(0,x.jsxs)(`li`,{className:Jb.use,"data-history-row":n?`forge`:`use`,children:[(0,x.jsx)(`p`,{className:Jb.meta,children:Vv(e.turn,e.department,e.eventTitle)}),e.output?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`p`,{className:Jb.meta,children:Bv.output}),(0,x.jsx)(`pre`,{className:Jb.code,translate:`no`,children:e.output})]}):null,n&&(0,x.jsx)(`p`,{className:Jb.quiet,children:Bv.testNotRecorded})]},`${e.turn}-${e.eventIndex}-${e.department}-${t}`)})}),t===0&&(0,x.jsx)(`p`,{className:Jb.quiet,children:Bv.notUsed})]})}function ex({confidence:e}){let t=Math.min(1,Math.max(0,Number(e.toFixed(2))));return(0,x.jsxs)(`div`,{className:Jb.open,children:[(0,x.jsx)(`h3`,{className:Jb.heading,"data-text":`heading`,children:Rv.heading}),(0,x.jsx)(`p`,{className:Jb.meta,children:Rv.notice}),(0,x.jsxs)(`div`,{className:Jb.confidence,children:[(0,x.jsx)(`p`,{className:Jb.body,"data-text":`body`,children:zv(e)}),(0,x.jsx)(`div`,{role:`meter`,className:Jb.meter,"aria-label":Rv.meterName,"aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":t,children:(0,x.jsx)(`span`,{className:Jb.meterFill,style:{width:`${t*100}%`},"data-meter-fill":!0})})]}),(0,x.jsx)(`p`,{className:Jb.quiet,children:Rv.wordsNotRecorded})]})}function tx({station:e}){return(0,x.jsx)(x.Fragment,{children:jv[e]})}function nx({reason:e}){let t=(0,b.useId)();return(0,x.jsxs)(`section`,{className:Oy.reason,"aria-labelledby":t,children:[(0,x.jsx)(`h3`,{id:t,className:Oy.reasonHeading,"data-text":`heading`,children:Av.heading}),e?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`pre`,{className:Oy.reasonText,translate:`no`,children:e}),(0,x.jsx)(`p`,{className:Oy.reasonNote,children:Av.limit})]}):(0,x.jsx)(`p`,{className:Oy.reasonNote,children:Av.none})]})}var rx=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function ix(e){if(!rx(e))return``;let{type:t}=e;return typeof t==`string`?t:Array.isArray(t)?t.filter(e=>typeof e==`string`).join(` | `):``}function ax(e,t){if(rx(e)&&rx(e.properties)){let t=Array.isArray(e.required)?e.required:[];return Object.entries(e.properties).map(([e,n])=>({name:e,type:ix(n),required:t.includes(e),description:rx(n)&&typeof n.description==`string`?n.description:``}))}return t.map(e=>({name:e,type:null,required:null,description:``}))}function ox(e,t){if(t.length===0||!rx(e)||!rx(e.properties))return e;let n=Object.keys(e.properties);return n.length===t.length&&t.every(e=>n.includes(e))?e:void 0}function sx(e,t,n){return[`sim-event-${e}-${t}-${n}`,`turn-row-${t}-h`].find(e=>document.getElementById(e)!==null)??null}function cx({caption:e,rows:t,none:n}){let r=(0,b.useId)(),[i,a,o,s]=Lv.columns;return t.length===0?(0,x.jsxs)(`div`,{className:Jb.part,children:[(0,x.jsx)(`p`,{className:Jb.caption,"data-text":`heading`,children:e}),(0,x.jsx)(`p`,{className:Jb.quiet,children:n})]}):(0,x.jsxs)(`table`,{className:Jb.fields,role:`table`,"aria-labelledby":r,children:[(0,x.jsx)(`caption`,{id:r,className:Jb.caption,"data-text":`heading`,children:e}),(0,x.jsx)(`thead`,{role:`rowgroup`,children:(0,x.jsx)(`tr`,{role:`row`,children:Lv.columns.map(e=>(0,x.jsx)(`th`,{role:`columnheader`,scope:`col`,children:e},e))})}),(0,x.jsx)(`tbody`,{role:`rowgroup`,children:t.map(e=>(0,x.jsxs)(`tr`,{role:`row`,children:[(0,x.jsx)(`td`,{role:`cell`,"data-label":i,"data-code":``,translate:`no`,children:e.name}),e.type===null?(0,x.jsx)(`td`,{role:`cell`,"data-label":a,"data-quiet":``,children:Lv.notRecorded}):(0,x.jsx)(`td`,{role:`cell`,"data-label":a,"data-code":``,translate:`no`,children:e.type}),(0,x.jsx)(`td`,{role:`cell`,"data-label":o,children:e.required===null?``:e.required?Lv.yes:Lv.no}),(0,x.jsx)(`td`,{role:`cell`,"data-label":s,children:e.description})]},e.name))})]})}function lx({entry:e,attempt:t,actor:n,onGoToEvent:r}){let[i,a]=(0,b.useState)(!1),o=(0,b.useId)(),s=t??e.history[0]??null,c=s?.turn??e.firstForgedTurn,l=s?.eventIndex??0,u=s?.department||e.firstForgedDepartment,d=s?.eventTitle??``,f=t?.description||e.description,[p,m]=(0,b.useState)(null);(0,b.useEffect)(()=>{m(sx(e.actorIndex,c,l))},[e.actorIndex,c,l]);let h=e=>{let t=p?document.getElementById(p):null;t&&(e.preventDefault(),r(t))},g=t&&t.inputFields.length>0?t.inputFields:e.inputFields,_=t&&t.outputFields.length>0?t.outputFields:e.outputFields,v=ox(e.inputSchema,t?t.inputFields:[]),y=ox(e.outputSchema,t?t.outputFields:[]),S=v!=null||y!=null;return(0,x.jsxs)(`div`,{className:Jb.open,children:[(0,x.jsxs)(`div`,{className:Jb.actor,style:{"--actor":n.colour},"data-actor-line":!0,children:[(0,x.jsx)(`span`,{className:Jb.rule,"aria-hidden":`true`,"data-actor-rule":!0}),(0,x.jsxs)(`div`,{className:Jb.actorText,children:[(0,x.jsx)(`p`,{className:Jb.meta,children:Fv({label:n.label,name:n.name,archetype:n.archetype,department:u,turn:c,eventTitle:d})}),p&&d&&(0,x.jsx)(`a`,{className:Jb.link,href:`#${p}`,onClick:h,children:Iv(d)})]})]}),(0,x.jsxs)(`div`,{className:Jb.part,children:[(0,x.jsx)(`h3`,{id:o,className:Jb.heading,"data-text":`heading`,children:Lv.whatItDoes}),(0,x.jsx)(`p`,{className:Jb.body,"data-text":`body`,children:f})]}),(0,x.jsxs)(`div`,{className:Jb.part,children:[S&&(0,x.jsx)(`div`,{className:Jb.fieldsBar,children:(0,x.jsxs)(`button`,{type:`button`,role:`switch`,"aria-checked":i,className:Jb.switch,onClick:()=>a(e=>!e),children:[(0,x.jsx)(`span`,{className:Jb.switchTrack,"aria-hidden":`true`}),Lv.rawJson]})}),i&&S?(0,x.jsx)(`pre`,{className:Jb.code,translate:`no`,"data-raw-json":!0,children:JSON.stringify({input:v??null,output:y??null},null,2)}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(cx,{caption:Lv.inputFields,rows:ax(v,g),none:Lv.noInputFields}),(0,x.jsx)(cx,{caption:Lv.outputFields,rows:ax(y,_),none:Lv.noOutputFields})]})]})]})}var ux=5e3;function dx(){let[e,t]=(0,b.useState)(()=>typeof navigator>`u`||navigator.onLine!==!1);return(0,b.useEffect)(()=>{let e=()=>t(navigator.onLine!==!1);return window.addEventListener(`online`,e),window.addEventListener(`offline`,e),()=>{window.removeEventListener(`online`,e),window.removeEventListener(`offline`,e)}},[]),e}function fx(){try{return window.localStorage}catch{return null}}function px({entry:e,attempt:t,open:n,actorCount:r,runKey:i,sessionId:a=null,events:o,onClose:s,onGoToEvent:c,onShowInEventLog:l,onShown:u}){let d=D_(),f=Pt(!0),p=(0,b.useRef)(null),m=(0,b.useRef)(null),h=(0,b.useId)();(0,b.useEffect)(()=>{[p.current,m.current].find(e=>e!==null&&e.offsetParent!==null)?.focus()},[]),(0,b.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.preventDefault(),s())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[s]);let[g,_]=(0,b.useState)(t),v=e.attempts.length,y=M_(e,g??NaN),S=y>0?e.attempts[y-1]:null,C=S?S.approved?`passed`:`did_not_pass`:e.outcome,w=C===`passed`,T=S?S.errorReason:e.errorReason??null,E=S?.confidence??e.confidence,D=N_(e,y),O=(0,b.useMemo)(()=>Kb(w),[w]),k=O_.filter(e=>(D.stations[e]===`reached`||D.stations[e]===`stopped`)&&O(e)),A=(0,b.useMemo)(()=>qb(window.location.href,i),[i]),[j,ee]=(0,b.useState)(()=>{let e=fx(),t=e?Ub(e,A):[];return Gb(D,[...t,...n??[]],O)}),te=(0,b.useRef)(!1);(0,b.useEffect)(()=>{if(!te.current){te.current=!0;for(let e of O_)e!==D.deciding&&j.has(e)&&B_({name:`forge_station_open`,station:e,via:`kept`})}},[D.deciding,j]);let M=e=>{ee(e);let t=fx();t&&Wb(t,A,[...e])},N=e=>{let t=new Set(j);t.has(e)?t.delete(e):(t.add(e),B_({name:`forge_station_open`,station:e,via:`press`})),M(t)},ne=k.every(e=>j.has(e)),P=()=>{if(!ne)for(let e of k)j.has(e)||B_({name:`forge_station_open`,station:e,via:`open_all`});M(new Set(ne?k.filter(e=>e===D.deciding):k))},re=(0,b.useRef)(null),ie=(t,n)=>{let r=M_(e,t);if(r===0||r===y)return;let i=e.attempts[r-1].approved;ee(Gb(N_(e,r),[...j],Kb(i))),re.current=n?y:null,_(r)},F=(0,b.useRef)(y);(0,b.useEffect)(()=>{F.current!==y&&(F.current=y,g===void 0&&ee(e=>Gb(D,[...e],O)))},[y,g,D,O]),(0,b.useEffect)(()=>{let e=re.current;re.current=null,e!==null&&(f.current?.querySelector(`[data-fork-attempt="${e}"]`)??[p.current,m.current].find(e=>e!==null&&e.offsetParent!==null))?.focus()},[y,f]),(0,b.useEffect)(()=>{u?.({attempt:y,open:O_.filter(e=>j.has(e))})},[u,y,j]);let{shared:I,share:ae,clear:oe}=on(),se=dx(),ce=(0,b.useId)();(0,b.useEffect)(()=>{if(I?.state!==`copied`)return;let e=window.setTimeout(oe,ux);return()=>window.clearTimeout(e)},[I,oe]);let le=()=>{a&&(B_({name:`forge_link_copy`}),ae(Z_(window.location.origin,a,Q_(window.location.href),{actorIndex:e.actorIndex,toolName:e.name,...y>0?{attempt:y}:{},open:O_.filter(e=>j.has(e))},d)))},L=I?.state===`refused`||I?.state===`unanswered`,[ue,de]=(0,b.useState)(!1),fe=(0,b.useMemo)(()=>ue?Yb(o,e.name):[],[ue,o,e.name]),R=()=>{B_({name:`forge_log_jump`}),l()},z=t=>{switch(t){case`request`:return S?.description||e.description;case`code`:return w?(0,x.jsx)(tx,{station:`code`}):null;case`tests`:return w?(0,x.jsx)(tx,{station:`tests`}):null;case`judge`:return w?Mv(E):null;case`added`:return w?Nv(F_(e)):null}},pe=d.actors[e.actorIndex];return(0,x.jsx)(`div`,{className:Oy.backdrop,onMouseDown:e=>{e.target===e.currentTarget&&s()},children:(0,x.jsxs)(`div`,{ref:f,role:`dialog`,"aria-modal":`true`,"aria-label":Cv(e.name,e.n),tabIndex:-1,className:Oy.dialog,children:[(0,x.jsxs)(`div`,{className:Oy.header,"data-forge-header":!0,children:[(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Oy.iconKey}`,onClick:()=>s(),"aria-label":Tv,title:Tv,children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3 3L13 13M13 3L3 13`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`})})}),(0,x.jsx)(Ry,{index:e.actorIndex,colour:Pe(e.actorIndex)}),(0,x.jsx)(`span`,{className:Oy.number,children:wv(e.n)}),(0,x.jsx)(`h2`,{ref:p,className:`${Oy.name} ${Oy.nameInRow}`,tabIndex:-1,translate:`no`,"data-text":`heading`,children:e.name}),(0,x.jsxs)(`span`,{className:Oy.headerEnd,children:[a&&(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Oy.iconKey}`,onClick:le,"aria-label":Ev.key,"aria-describedby":ce,title:Ev.key,children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M6.5 9.5L9.5 6.5M7 4.5L8.5 3a2.5 2.5 0 0 1 3.5 3.5L10.5 8M9 11.5L7.5 13A2.5 2.5 0 0 1 4 9.5L5.5 8`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.75`,strokeLinecap:`round`,strokeLinejoin:`round`})})}),(0,x.jsx)(ky,{})]})]}),a&&(0,x.jsxs)(`div`,{id:ce,className:Oy.linkNote,role:`status`,"aria-live":`polite`,"data-link-note":!0,children:[!se&&(0,x.jsx)(`p`,{className:Oy.linkSaid,children:Ev.offline}),I?.state===`copied`&&(0,x.jsx)(`p`,{className:Oy.linkSaid,children:Ev.copied}),L&&I&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`p`,{className:Oy.linkSaid,children:Ev.failed}),(0,x.jsx)(`p`,{className:Oy.linkText,"data-tool-link":!0,translate:`no`,children:I.url})]})]}),(0,x.jsxs)(`div`,{className:Oy.head,"data-forge-head":!0,children:[v>1&&(0,x.jsxs)(`div`,{className:Oy.attempts,role:`group`,"aria-label":Kv(y,v),children:[(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Oy.iconKey}`,"aria-label":Wv.previous,title:Wv.previous,"aria-disabled":y<=1||void 0,onClick:()=>{y>1&&ie(y-1,!1)},children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M10 3.5L5.5 8L10 12.5`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})}),(0,x.jsx)(`span`,{className:Oy.attemptLine,"data-attempt-line":!0,"aria-hidden":`true`,children:y===v?Gv(y,v):Kv(y,v)}),(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Oy.iconKey}`,"aria-label":Wv.next,title:Wv.next,"aria-disabled":y>=v||void 0,onClick:()=>{y<v&&ie(y+1,!1)},children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M6 3.5L10.5 8L6 12.5`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})})]}),(0,x.jsx)(`p`,{className:Oy.label,children:Ov}),(0,x.jsx)(`h2`,{ref:m,className:`${Oy.name} ${Oy.nameInHead}`,tabIndex:-1,translate:`no`,"data-text":`heading`,children:e.name}),(0,x.jsxs)(`p`,{className:Oy.outcome,"data-forge-outcome":!0,"data-text":`heading`,children:[(0,x.jsx)(lb,{kind:k_(C),size:20}),(0,x.jsx)(`span`,{children:kv[C]})]}),!w&&(0,x.jsx)(nx,{reason:T})]}),(0,x.jsxs)(`div`,{className:Oy.line,children:[k.length>1&&(0,x.jsx)(`div`,{className:Oy.lineHead,children:(0,x.jsx)(`button`,{type:`button`,className:Oy.key,"aria-label":ne?Pv.closeName:Pv.openName,onClick:P,children:ne?Pv.close:Pv.open})}),(0,x.jsx)(gb,{model:D,size:`trace`,colour:P_(e.actorIndex,r),open:j,onToggle:N,stationResult:z,renderEvidence:t=>{if(!O(t))return null;switch(t){case`request`:return(0,x.jsx)(lx,{entry:e,attempt:S,actor:{label:pe?.label??xv(e.actorIndex),name:e.actorName,archetype:pe?.archetype??``,colour:Pe(e.actorIndex)},onGoToEvent:c});case`judge`:return(0,x.jsx)(ex,{confidence:E});case`added`:return(0,x.jsx)($b,{entry:e});default:return null}},onAttempt:e=>ie(e,!0)})]}),(0,x.jsxs)(`div`,{className:Oy.recordFoot,children:[(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Oy.recordKey}`,"aria-expanded":ue,"aria-controls":h,onClick:()=>de(e=>!e),children:Hv.key}),(0,x.jsx)(`div`,{id:h,className:Oy.recordBody,hidden:!ue,children:ue&&(0,x.jsx)(Qb,{entry:e,frames:fe,onShowInEventLog:R})})]})]})})}var mx={trace:null,toolbox:!1},hx=[];function gx(e){let{show:t,find:n,group:r,actors:i}=q_(e,{getEntryByNumber:()=>void 0,actors:[]},!1).state.toolbox;return{show:tv.includes(t)?t:`all`,find:n??``,group:nv.includes(r)?r:null,actors:[...new Set((i??[]).map(e=>e-1))].sort((e,t)=>e-t)}}var _x=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),vx=(e,t)=>e.show===t.show&&e.find===t.find&&e.group===t.group&&_x(e.actors,t.actors);function yx({state:e,runKey:t,sessionId:n,showToolLog:r,children:i}){let a=D_(),[o,s]=(0,b.useState)(mx),c=(0,b.useRef)(null),l=(0,b.useRef)(null),u=(0,b.useRef)(!1),d=(0,b.useRef)(!1),f=(0,b.useRef)(0),p=(0,b.useRef)(null),m=(0,b.useRef)(null),h=(0,b.useRef)(a);h.current=a;let g=(0,b.useRef)(e.isComplete);g.current=e.isComplete;let _=(0,b.useRef)(o);_.current=o;let v=(0,b.useRef)(null),[y,S]=(0,b.useState)(null),[C,w]=(0,b.useState)(()=>typeof window>`u`?iv:gx(window.location.href)),T=(0,b.useRef)(C),E=(0,b.useCallback)(()=>{let e=window.location.href,t=Y_(e,{...u.current&&d.current?{open:!0}:{},...T.current});if(t!==e)try{window.history.replaceState(window.history.state,``,t)}catch{}},[]),D=(0,b.useCallback)(e=>{let t=T.current,n={...t,...e};vx(n,t)||(T.current=n,w(n),E())},[E]),O=(0,b.useCallback)(()=>{d.current||=(v.current=window.location.href,window.history.pushState({forgeView:!0},``),!0)},[]),k=(0,b.useCallback)((e,t,n)=>{h.current.getEntryFor(e.actorIndex,e.toolName)&&(n&&B_({name:`forge_trace_open`,from:n}),u.current?l.current=t??null:c.current=t??null,O(),S(null),s(t=>({trace:e,toolbox:t.toolbox})))},[O]),A=(0,b.useCallback)((e,t)=>{u.current||(t&&B_({name:`forge_toolbox_open`,from:t}),c.current=e??null,u.current=!0,O(),E(),s(e=>({trace:e.trace,toolbox:!0})))},[O,E]),j=(0,b.useCallback)((e,t)=>{if(e instanceof HTMLElement&&(c.current=e,p.current=e),l.current=null,u.current=!1,s(mx),d.current){d.current=!1;let e=v.current;v.current=null,e!==null&&e!==window.location.href&&window.history.replaceState(window.history.state,``,e),f.current+=1,m.current=t??null,window.history.back()}else t?.()},[]),ee=(0,b.useCallback)(()=>{if(!u.current){j();return}S(null),s({trace:null,toolbox:!0});let e=window.location.href,t=X_(e,U_);t!==e&&window.history.replaceState(window.history.state,``,t)},[j]),te=(0,b.useCallback)(()=>j(),[j]);(0,b.useEffect)(()=>{let e=()=>{if(f.current>0){--f.current,E();let e=m.current;m.current=null,e?.();let t=p.current;p.current=null,t?.isConnected&&requestAnimationFrame(()=>{t.scrollIntoView({block:`nearest`}),document.activeElement!==t&&t.focus({preventScroll:!0})})}else if(d.current)_.current.trace&&u.current?(S(null),s({trace:null,toolbox:!0}),d.current=!1,O(),E()):(d.current=!1,v.current=null,l.current=null,u.current=!1,s(mx),E());else{if(window.history.state?.forgeView!==!0)return;let{state:e}=q_(window.location.href,h.current,g.current);if(!e.trace&&!e.toolbox.open)return;d.current=!0,v.current=Y_(X_(window.location.href,U_),{open:!1,...T.current}),u.current=e.toolbox.open,S(null),s({trace:e.trace??null,toolbox:e.toolbox.open})}};return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},[O,E]);let M=o.trace,N=M?a.getEntryFor(M.actorIndex,M.toolName):void 0,ne=N?e.actors[e.actorIds[N.actorIndex]]?.events??hx:hx,P=(0,b.useCallback)(()=>{if(!N)return;let{name:e,actorName:t}=N;j(null,()=>r?.(e,t))},[N,j,r]),re=(0,b.useCallback)(t=>{let n=e.actorIds[t];n&&j(null,()=>r?.(``,n))},[e.actorIds,j,r]);(0,b.useEffect)(()=>{M&&!N&&ee()},[M,N,ee]),(0,b.useEffect)(()=>{if(!M||!N||!d.current)return;let e=window.location.href,t=J_(e,{trace:{actorIndex:N.actorIndex,toolName:N.name,...y&&y.attempt>0?{attempt:y.attempt}:{},...y?{open:y.open}:{}},toolbox:q_(e,a,!1).state.toolbox},a);t!==e&&window.history.replaceState(window.history.state,``,t)},[M,N,y,a]);let ie=e.isComplete,F=(0,b.useRef)(null);(0,b.useEffect)(()=>{if(!ie)return;let e=`${t??``}|${n??``}`;if(F.current===e)return;F.current=e;let r=window.location.href,{state:i,dangling:o}=q_(r,a,!0);o.length>0&&window.history.replaceState(window.history.state,``,X_(r,o));let s=gx(window.location.href),c={...s,actors:s.actors.filter(e=>e<a.actors.length)};if(vx(c,T.current)||(T.current=c,w(c)),_.current.trace||_.current.toolbox)return;let l=Y_(X_(window.location.href,U_),{open:!1,...c});l!==window.location.href&&window.history.replaceState(window.history.state,``,l),i.toolbox.open&&A(null),i.trace&&k(i.trace,null,`link`)},[ie,t,n,a,k,A]);let I=M!==null,ae=(0,b.useRef)(!1);(0,b.useEffect)(()=>{if(I){ae.current=!0;return}if(!ae.current||(ae.current=!1,!o.toolbox))return;let e=l.current;l.current=null,e?.isConnected?e.focus():document.querySelector(`[data-toolbox-title]`)?.focus()},[I,o.toolbox]);let oe=M!==null||o.toolbox,se=(0,b.useRef)(!1);(0,b.useEffect)(()=>{if(oe){se.current=!0;return}if(!se.current)return;se.current=!1;let e=c.current;c.current=null,e?.isConnected&&e.focus()},[oe]);let ce=(0,b.useMemo)(()=>({openTrace:k,openToolbox:A,close:j,showActorLog:re,current:o}),[k,A,j,re,o]),le=(0,b.useMemo)(()=>({...C,set:D}),[C,D]);return(0,x.jsx)($_.Provider,{value:ce,children:(0,x.jsxs)(ov.Provider,{value:le,children:[i,o.toolbox&&(0,x.jsx)(Rb,{covered:M!==null,onClose:te}),M&&N&&(0,x.jsx)(px,{entry:N,attempt:M.attempt,open:M.open,actorCount:e.actorIds.length,runKey:t,sessionId:ie?n:null,events:ne,onShown:S,onClose:ee,onGoToEvent:j,onShowInEventLog:P},`${N.actorIndex}:${N.name}`)]})})}var bx=420,xx=260;function Sx({content:e,children:t,dot:n,block:r,disabled:i=!1}){let[a,o]=(0,b.useState)(!1),[s,c]=(0,b.useState)({x:0,y:0}),l=(0,b.useRef)(null),u=(0,b.useRef)(void 0);b.useEffect(()=>{if(!a)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),o(!1))};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[a]);let d=(0,b.useCallback)(e=>{clearTimeout(u.current);let t=e.currentTarget.getBoundingClientRect(),n=Math.min(bx,window.innerWidth-20),r=t.left,i=t.top-xx-6;i<10&&(i=t.bottom+6),r+n>window.innerWidth-10&&(r=window.innerWidth-n-10),r<10&&(r=10),i+xx>window.innerHeight-10&&(i=window.innerHeight-xx-10),i<10&&(i=10),c({x:r,y:i}),o(!0)},[]),f=(0,b.useCallback)(()=>{u.current=setTimeout(()=>o(!1),100)},[]),p=a&&!i?(0,x.jsx)(`div`,{id:`paracosm-tooltip`,role:`tooltip`,onMouseEnter:()=>{clearTimeout(u.current),o(!0)},onMouseLeave:f,style:{position:`fixed`,left:s.x,top:s.y,zIndex:99999,background:`var(--bg-card)`,border:`2px solid var(--amber)`,borderRadius:`8px`,padding:`14px 18px`,fontSize:`var(--font-sm)`,color:`var(--text-1)`,lineHeight:1.6,width:`${bx}px`,maxWidth:`90vw`,maxHeight:`80vh`,overflowY:`auto`,boxShadow:`0 8px 40px rgba(0,0,0,.4)`,pointerEvents:`auto`,whiteSpace:`normal`,wordBreak:`break-word`,animation:`fadeUp 0.15s ease both`},children:e}):null;return(0,x.jsxs)(`span`,{ref:l,onMouseEnter:d,onMouseLeave:f,style:{position:`relative`,display:r?`block`:`inline-flex`,alignItems:r?void 0:`center`,width:r?`100%`:void 0,minWidth:r?0:void 0,cursor:`pointer`},tabIndex:0,"aria-describedby":a?`paracosm-tooltip`:void 0,onFocus:d,onBlur:f,children:[t,n&&(0,x.jsx)(`span`,{style:{width:`6px`,height:`6px`,borderRadius:`50%`,background:`var(--amber)`,opacity:a?.8:0,marginLeft:`3px`,transition:`opacity 0.15s`,flexShrink:0,display:`inline-block`,verticalAlign:`middle`},"aria-hidden":`true`}),p&&typeof document<`u`?(0,Ay.createPortal)(p,document.body):null]})}var Cx={root:`_root_a1e21_1`,triggerButton:`_triggerButton_a1e21_6`,triggerCaret:`_triggerCaret_a1e21_29`,menuPopover:`_menuPopover_a1e21_34`,menuButton:`_menuButton_a1e21_49`,loadFileButton:`_loadFileButton_a1e21_49`,runSavedButton:`_runSavedButton_a1e21_49`,runNewButton:`_runNewButton_a1e21_49`,menuButtonInnerLeft:`_menuButtonInnerLeft_a1e21_68`,menuButtonIcon:`_menuButtonIcon_a1e21_74`,runNewBadge:`_runNewBadge_a1e21_94`,disabled:`_disabled_a1e21_116`,runSavedBadge:`_runSavedBadge_a1e21_128`,savedCardsWrap:`_savedCardsWrap_a1e21_145`,savedStatus:`_savedStatus_a1e21_149`,savedError:`_savedError_a1e21_149`,loadFileBadge:`_loadFileBadge_a1e21_170`,sessionCard:`_sessionCard_a1e21_181`,sessionCardTitle:`_sessionCardTitle_a1e21_203`,sessionCardLine2:`_sessionCardLine2_a1e21_212`,sessionCardLine3:`_sessionCardLine3_a1e21_218`,tooltipHeading:`_tooltipHeading_a1e21_224`,historyRow:`_historyRow_a1e21_234`,historyRowLabel:`_historyRowLabel_a1e21_259`,historyRowBadge:`_historyRowBadge_a1e21_265`,historyList:`_historyList_a1e21_276`,historyCardWrap:`_historyCardWrap_a1e21_285`,historyCard:`_historyCard_a1e21_285`,historyCardTitle:`_historyCardTitle_a1e21_310`,historyCardLine2:`_historyCardLine2_a1e21_318`,historyCardLine3:`_historyCardLine3_a1e21_324`,historyDelete:`_historyDelete_a1e21_329`,historyClearAll:`_historyClearAll_a1e21_353`},wx=Cx;function Tx(e){let t=Math.max(0,Math.floor((Date.now()-e)/1e3));if(t<60)return`${t}s ago`;let n=Math.floor(t/60);if(n<60)return`${n}m ago`;let r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function Ex(e){if(!e||e<=0)return`·`;let t=Math.round(e/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function Dx(e){return e==null?`·`:e<.005?`<$0.01`:`$${e.toFixed(2)}`}function Ox({s:e,onPick:t}){let n=Rn(e),r=n?`${n}${e.scenarioName?` · ${e.scenarioName}`:``}`:e.scenarioName||`Simulation Run`,i=e.title||e.scenarioName||r,a=[n,e.title&&e.scenarioName?e.scenarioName:``,e.turnCount==null?``:`${e.turnCount} turn${e.turnCount===1?``:`s`}`].filter(Boolean).join(` · `),o=`${new Date(e.createdAt).toLocaleString()} (${Tx(e.createdAt)}) · ${Ex(e.durationMs)} · ${Dx(e.totalCostUSD)}`;return(0,x.jsxs)(`button`,{type:`button`,onClick:t,className:Cx.sessionCard,children:[(0,x.jsx)(`div`,{className:Cx.sessionCardTitle,children:i}),a&&(0,x.jsx)(`div`,{className:Cx.sessionCardLine2,children:a}),(0,x.jsx)(`div`,{className:Cx.sessionCardLine3,children:o})]})}function kx({onRun:e,onLoadFromFile:t,history:n=[],onRestoreHistory:r,onClearHistory:i,liveStateHasEvents:a=!1}){let[o,s]=(0,b.useState)(!1),[c,l]=(0,b.useState)(!1),[u,d]=(0,b.useState)(!0),f=(0,b.useRef)(null),{sessions:p,status:m,refresh:h}=Oe(),g=p.length>0,_=Qk();(0,b.useEffect)(()=>{o&&h()},[o,h]);let v=(0,b.useCallback)(()=>{s(!1),l(!1)},[]);(0,b.useEffect)(()=>{if(!o)return;let e=e=>{f.current&&!f.current.contains(e.target)&&v()},t=e=>{e.key===`Escape`&&v()};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[o,v]);let y=()=>{_&&(v(),e?.())},S=e=>{window.location.assign(kg(window.location.href,e))},C=()=>{v(),t?.()},w=Og(m,p);return(0,x.jsxs)(`div`,{ref:f,className:Cx.root,children:[(0,x.jsx)(Sx,{disabled:o,content:(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:Cx.tooltipHeading,children:`Run`}),(0,x.jsx)(`div`,{children:`Launches a fresh simulation, replays a cached one, or loads a saved JSON from disk. Click to open the menu.`})]}),children:(0,x.jsxs)(`button`,{type:`button`,onClick:()=>s(e=>!e),"aria-haspopup":`menu`,"aria-expanded":o,className:Cx.triggerButton,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`▶`}),`RUN`,(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Cx.triggerCaret,children:`▾`})]})}),o&&(0,x.jsxs)(`div`,{role:`menu`,"aria-label":`Run actions`,className:Cx.menuPopover,children:[(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:y,disabled:!_,className:Cx.runNewButton,children:[(0,x.jsxs)(`span`,{className:Cx.menuButtonInnerLeft,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Cx.menuButtonIcon,children:`▶`}),(0,x.jsx)(`span`,{children:_?`Run New Simulation`:`Loading scenario…`})]}),(0,x.jsx)(`span`,{className:Cx.runNewBadge,children:`spends credits`})]}),(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>g&&l(e=>!e),disabled:!g,className:[Cx.runSavedButton,g?``:Cx.disabled].filter(Boolean).join(` `),children:[(0,x.jsxs)(`span`,{className:Cx.menuButtonInnerLeft,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Cx.menuButtonIcon,children:`↻`}),(0,x.jsx)(`span`,{children:`Run Saved Simulation`})]}),(0,x.jsx)(`span`,{className:[Cx.runSavedBadge,g?``:Cx.disabled].filter(Boolean).join(` `),children:g?`${p.length} cached · ${c?`hide`:`pick`}`:`no cache yet`})]}),c&&g&&(0,x.jsxs)(`div`,{className:Cx.savedCardsWrap,children:[w===`cards`&&p.map(e=>(0,x.jsx)(Ox,{s:e,onPick:()=>S(e.id)},e.id)),w===`loading`&&(0,x.jsx)(`div`,{className:Cx.savedStatus,children:`Loading cached runs…`}),w===`error`&&(0,x.jsx)(`div`,{className:Cx.savedError,children:`Could not reach /sessions. Try again in a moment.`}),w===`unavailable`&&(0,x.jsx)(`div`,{className:Cx.savedStatus,children:`Session cache is disabled on this server.`})]}),n.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,className:wx.historyRow,onClick:()=>d(e=>!e),"aria-expanded":u,children:[(0,x.jsxs)(`span`,{className:wx.historyRowLabel,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`🕘`}),(0,x.jsx)(`span`,{children:`Local history`})]}),(0,x.jsxs)(`span`,{className:wx.historyRowBadge,children:[n.length,` recent · `,u?`hide`:`show`]})]}),u&&(0,x.jsxs)(`div`,{className:wx.historyList,children:[n.map(e=>{let t=Date.parse(e.createdAt)||e.id,n=(e.summary.actorNames??[]).join(` vs `)||e.scenarioShortName,i=e.summary.turnCount?`${e.summary.turnCount} turn${e.summary.turnCount===1?``:`s`}`:``,o=[n,n===e.scenarioShortName?``:e.scenarioShortName,i].filter(Boolean).join(` · `),s=`${Tx(t)} · ${e.summary.eventCount} ev · ${Dx(e.summary.totalCostUSD)}`;return(0,x.jsx)(`div`,{className:wx.historyCardWrap,children:(0,x.jsxs)(`button`,{type:`button`,className:wx.historyCard,onClick:()=>{(!a||window.confirm(`Replace current simulation with this history entry?`))&&(r?.(e),v())},children:[(0,x.jsx)(`div`,{className:wx.historyCardTitle,children:n}),(0,x.jsx)(`div`,{className:wx.historyCardLine2,children:o}),(0,x.jsx)(`div`,{className:wx.historyCardLine3,children:s})]})},e.id)}),i&&(0,x.jsx)(`button`,{type:`button`,className:wx.historyClearAll,title:`Wipe everything in this browser: saved-runs ring, event cache, current sim state. It also lets go of this browser's run on the server, stopping it if it is running. Run history, saved sessions and output files are kept: Delete server data in the ⋯ menu deletes those, where admin writes are on and an admin token is saved.`,onClick:()=>{window.confirm(`Clear all local browser state?
113
+ `)}var Fh={wrap:`_wrap_5ldo7_1`,toggle:`_toggle_5ldo7_6`,panel:`_panel_5ldo7_34`,tabRow:`_tabRow_5ldo7_42`,tabPill:`_tabPill_5ldo7_51`,copyBtn:`_copyBtn_5ldo7_74`,code:`_code_5ldo7_97`};function Ih(e){let{disabled:t,initiallyExpanded:n=!1,initialTab:r=`ts`,...i}=e,[a,o]=(0,b.useState)(n),[s,c]=(0,b.useState)(r),[l,u]=(0,b.useState)(`idle`),d=(0,b.useMemo)(()=>jh(i),[i.seedText,i.domainHint,i.sourceUrl,i.actorCount]),f=(0,b.useMemo)(()=>Ph(i),[i.seedText,i.domainHint,i.sourceUrl,i.actorCount]),p=s===`ts`?d:f,m=(0,b.useCallback)(async()=>{try{await navigator.clipboard.writeText(p),u(`ok`)}catch{u(`fail`)}window.setTimeout(()=>u(`idle`),1500)},[p]),h=`quickstart-view-as-code-panel`,g=`quickstart-view-as-code-tab-ts`,_=`quickstart-view-as-code-tab-curl`,v=s===`ts`?g:_;return(0,x.jsxs)(`div`,{className:Fh.wrap,children:[(0,x.jsx)(`button`,{type:`button`,className:Fh.toggle,"aria-expanded":a,"aria-controls":h,disabled:t,onClick:()=>o(e=>!e),children:a?`▾ Hide code`:`▸ View as code`}),a&&(0,x.jsxs)(`div`,{id:h,role:`tabpanel`,"aria-labelledby":v,className:Fh.panel,children:[(0,x.jsxs)(`div`,{className:Fh.tabRow,role:`tablist`,"aria-label":`Recipe language`,children:[(0,x.jsx)(`button`,{type:`button`,id:g,role:`tab`,"aria-pressed":s===`ts`,"aria-selected":s===`ts`,"aria-controls":h,className:Fh.tabPill,onClick:()=>c(`ts`),children:`TypeScript`}),(0,x.jsx)(`button`,{type:`button`,id:_,role:`tab`,"aria-pressed":s===`curl`,"aria-selected":s===`curl`,"aria-controls":h,className:Fh.tabPill,onClick:()=>c(`curl`),children:`curl`}),(0,x.jsx)(`button`,{type:`button`,className:Fh.copyBtn,onClick:m,"aria-label":`Copy ${s===`ts`?`TypeScript`:`curl`} recipe`,children:l===`ok`?`Copied ✓`:l===`fail`?`Press ⌘C`:`Copy`})]}),(0,x.jsx)(`pre`,{className:Fh.code,children:(0,x.jsx)(`code`,{children:p})})]})]})}var Lh={card:`_card_srwu8_2`,heading:`_heading_srwu8_15`,subline:`_subline_srwu8_25`,scenarioPickerRow:`_scenarioPickerRow_srwu8_34`,scenarioPickerLabel:`_scenarioPickerLabel_srwu8_45`,scenarioPickerSelect:`_scenarioPickerSelect_srwu8_54`,scenarioPickerHint:`_scenarioPickerHint_srwu8_66`,actorRow:`_actorRow_srwu8_73`,actorLabel:`_actorLabel_srwu8_82`,actorSlider:`_actorSlider_srwu8_91`,actorValue:`_actorValue_srwu8_96`,runButton:`_runButton_srwu8_102`,runButtonFull:`_runButtonFull_srwu8_134`,runButtonCompact:`_runButtonCompact_srwu8_138`,tagline:`_tagline_srwu8_144`,tradeoff:`_tradeoff_srwu8_154`};function Rh(e){let t=Date.parse(e);if(!Number.isFinite(t))return``;let n=Date.now()-t;if(n<0)return`just now`;let r=Math.floor(n/6e4);if(r<1)return`just now`;if(r<60)return`${r}m ago`;let i=Math.floor(r/60);if(i<24)return`${i}h ago`;let a=Math.floor(i/24);if(a<7)return`${a}d ago`;let o=Math.floor(a/7);if(o<5)return`${o}w ago`;let s=Math.floor(a/30);return s<12?`${s}mo ago`:new Date(e).getFullYear().toString()}function zh({onRunStart:e,disabled:t=!1,initialActorCount:n=2}){let r=Qk(),i=!eA()||t,[a,o]=(0,b.useState)(n),[s,c]=(0,b.useState)(!1),[l,u]=(0,b.useState)([]),[d,f]=(0,b.useState)(!1),p=(0,b.useRef)(!0);(0,b.useEffect)(()=>{let e=!1;return fetch(`/scenarios`).then(e=>e.ok?e.json():null).then(t=>{e||u(t?.scenarios??[])}).catch(()=>{}),()=>{e=!0,p.current=!1}},[]);let m=async e=>{if(!(e===r.id||d)){f(!0);try{(await fetch(`/scenario/switch`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:e})})).ok?(te(),window.location.reload()):p.current&&f(!1)}catch{p.current&&f(!1)}}},h=r.presets[0]?.leaders??r.presets[0]?.actors??[],g=h.length,_=g>=2,v=a>g,y=r.labels.name,S=r.labels.tagline?.trim(),C=_?`${h[0].name} (${h[0].archetype}) vs ${h[1].name} (${h[1].archetype})`:`Auto-generated leaders (no preset)`,w=`loaded-scenario-cta-heading`,T=`loaded-scenario-actor-count`,E=()=>{s||i||(c(!0),e(a))},D=`${a} ${a===1?`actor`:`actors`}`,O=s?`Launching...`:`Run ${D} against ${y}`,k=s?`Launching...`:`${O} ->`,A=s?`Launching...`:`Run ${D}`,j=`loaded-scenario-cta-picker`;return(0,x.jsxs)(`section`,{className:Lh.card,"aria-labelledby":w,children:[(0,x.jsxs)(`h2`,{className:Lh.heading,id:w,children:[`▶ Run with the loaded scenario: `,y]}),S&&(0,x.jsx)(`p`,{className:Lh.tagline,children:S}),(0,x.jsx)(`div`,{className:Lh.subline,children:C}),l.length>=2&&(()=>{let e=l.some(e=>e.id===r.id)?l:[...l,{id:r.id,name:r.labels.name||r.id,source:`active`}];return(0,x.jsxs)(`div`,{className:Lh.scenarioPickerRow,children:[(0,x.jsx)(`label`,{className:Lh.scenarioPickerLabel,htmlFor:j,children:`Scenario`}),(0,x.jsx)(`select`,{id:j,className:Lh.scenarioPickerSelect,value:r.id,onChange:e=>m(e.target.value),disabled:i||s||d,"aria-label":`Switch active scenario`,children:e.map(e=>{let t=e.source===`builtin`?`[builtin]`:e.source===`disk`?`[disk]`:e.source===`compiled`?`[compiled]`:e.source===`active`?`[active]`:``,n=[];if(t&&n.push(t),typeof e.runCount==`number`&&e.runCount>0&&n.push(`${e.runCount} run${e.runCount===1?``:`s`}`),e.compiledAt){let t=Rh(e.compiledAt);t&&n.push(t)}let r=n.length>0?` · ${n.join(` · `)}`:``;return(0,x.jsxs)(`option`,{value:e.id,children:[e.name,r]},e.id)})}),d&&(0,x.jsx)(`span`,{className:Lh.scenarioPickerHint,children:`Switching…`})]})})(),(0,x.jsxs)(`div`,{className:Lh.actorRow,children:[(0,x.jsx)(`label`,{className:Lh.actorLabel,htmlFor:T,children:`Actors`}),(0,x.jsx)(`input`,{id:T,type:`range`,min:1,max:300,value:a,onChange:e=>o(parseInt(e.target.value,10)),disabled:i||s,className:Lh.actorSlider,"aria-label":`Number of parallel actors`}),(0,x.jsx)(`span`,{className:Lh.actorValue,children:a})]}),(0,x.jsxs)(`button`,{type:`button`,className:Lh.runButton,onClick:E,disabled:i||s,"aria-busy":s,"aria-label":O,children:[(0,x.jsx)(`span`,{className:Lh.runButtonFull,"aria-hidden":`true`,children:k}),(0,x.jsx)(`span`,{className:Lh.runButtonCompact,"aria-hidden":`true`,children:A})]}),(0,x.jsxs)(`div`,{className:Lh.tradeoff,children:[_&&!v&&`Same scenario, fresh seed: skips the compile step.`,_&&v&&`Same scenario; ${a} LLM-generated actors replace the preset leaders for this run (~30s for generation).`,!_&&`Same scenario; ~30s for actor generation since no preset is defined.`]})]})}var W={backdrop:`_backdrop_nucmo_1`,backdropFadeIn:`_backdropFadeIn_nucmo_1`,drawer:`_drawer_nucmo_17`,open:`_open_nucmo_34`,header:`_header_nucmo_38`,closeBtn:`_closeBtn_nucmo_50`,sourceBadge:`_sourceBadge_nucmo_63`,summary:`_summary_nucmo_86`,nameRow:`_nameRow_nucmo_94`,name:`_name_nucmo_94`,nameEditBtn:`_nameEditBtn_nucmo_110`,nameEditForm:`_nameEditForm_nucmo_129`,nameEditInput:`_nameEditInput_nucmo_135`,nameEditActions:`_nameEditActions_nucmo_150`,nameEditSave:`_nameEditSave_nucmo_155`,nameEditCancel:`_nameEditCancel_nucmo_173`,nameEditError:`_nameEditError_nucmo_195`,description:`_description_nucmo_202`,metaGrid:`_metaGrid_nucmo_209`,meta:`_meta_nucmo_209`,sectionHeading:`_sectionHeading_nucmo_235`,seedSection:`_seedSection_nucmo_245`,seedHint:`_seedHint_nucmo_250`,seedBody:`_seedBody_nucmo_257`,presetsSection:`_presetsSection_nucmo_273`,departmentsSection:`_departmentsSection_nucmo_274`,sectionHint:`_sectionHint_nucmo_279`,sectionCount:`_sectionCount_nucmo_287`,presetList:`_presetList_nucmo_294`,presetCard:`_presetCard_nucmo_303`,presetHeader:`_presetHeader_nucmo_313`,presetName:`_presetName_nucmo_320`,presetArchetype:`_presetArchetype_nucmo_327`,presetUnit:`_presetUnit_nucmo_340`,hexacoList:`_hexacoList_nucmo_347`,hexacoRow:`_hexacoRow_nucmo_356`,hexacoAxis:`_hexacoAxis_nucmo_364`,hexacoBar:`_hexacoBar_nucmo_372`,hexacoFill:`_hexacoFill_nucmo_380`,hexacoValue:`_hexacoValue_nucmo_386`,presetInstructions:`_presetInstructions_nucmo_393`,deptChips:`_deptChips_nucmo_401`,deptChip:`_deptChip_nucmo_401`,deptIcon:`_deptIcon_nucmo_423`,deptRole:`_deptRole_nucmo_427`,recentSection:`_recentSection_nucmo_431`,statusLine:`_statusLine_nucmo_438`,error:`_error_nucmo_445`,recentList:`_recentList_nucmo_449`,recentRow:`_recentRow_nucmo_458`,recentTitle:`_recentTitle_nucmo_468`,recentArchetype:`_recentArchetype_nucmo_475`,recentMeta:`_recentMeta_nucmo_480`,footer:`_footer_nucmo_486`,actorRow:`_actorRow_nucmo_497`,actorLabel:`_actorLabel_nucmo_505`,actorSlider:`_actorSlider_nucmo_514`,actorValue:`_actorValue_nucmo_519`,runButton:`_runButton_nucmo_527`,deleteButton:`_deleteButton_nucmo_549`,deleteError:`_deleteError_nucmo_572`},Bh=`Admin token refused and cleared. ${R}`,Vh=(e,t)=>`The server refused the admin token this ${e} was sent with. A newer token is saved in this browser; press ${t} to try again with it.`,Hh=`scenario-rename-error`;function Uh(e){let t=Date.parse(e);if(!Number.isFinite(t))return``;let n=Date.now()-t;if(n<0)return`just now`;let r=Math.floor(n/6e4);if(r<1)return`just now`;if(r<60)return`${r}m ago`;let i=Math.floor(r/60);if(i<24)return`${i}h ago`;let a=Math.floor(i/24);if(a<7)return`${a}d ago`;let o=Math.floor(a/7);if(o<5)return`${o}w ago`;let s=Math.floor(a/30);return s<12?`${s}mo ago`:new Date(e).getFullYear().toString()}function Wh(e){return typeof e!=`number`||!Number.isFinite(e)?`—`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Gh(e){if(typeof e!=`number`||!Number.isFinite(e)||e<=0)return`—`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r>0?`${n}m ${r}s`:`${n}m`}function Kh(e){return e?Array.from(e.querySelectorAll(`button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`)).filter(e=>!e.hasAttribute(`disabled`)&&e.getAttribute(`aria-hidden`)!==`true`):[]}function qh(e){let{scenario:t,disabled:n=!1,initialActorCount:r=2,onRunScenario:i,onClose:a,onDeleted:o,onRenamed:s}=e,c=t!==null,[l,u]=(0,b.useState)(r),[d,f]=(0,b.useState)([]),[p,m]=(0,b.useState)(!1),[h,g]=(0,b.useState)(null),[_,v]=(0,b.useState)(null),[y,S]=(0,b.useState)(!1),[C,w]=(0,b.useState)(!1),[T,E]=(0,b.useState)(null),[D,O]=(0,b.useState)(!1),[k,A]=(0,b.useState)(``),[j,ee]=(0,b.useState)(!1),[te,M]=(0,b.useState)(null),[N,ne]=(0,b.useState)(null);(0,b.useEffect)(()=>{ne(null),O(!1),M(null)},[t?.id]);let[P,re]=(0,b.useState)(null);(0,b.useEffect)(()=>{if(c)return E(null),re(B()||null),Se(()=>re(B()||null))},[c]);let ie=!!P&&t?.source===`compiled`,F=!!P&&t?.source===`compiled`,I=(0,b.useRef)(null),ae=(0,b.useRef)(null);if((0,b.useEffect)(()=>{if(!t){f([]),g(null),v(null);return}let e=!1;return m(!0),g(null),S(!0),v(null),fetch(`/api/v1/runs?scenario=${encodeURIComponent(t.id)}&limit=5`).then(async t=>{if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();e||f(n.runs??[])}).catch(t=>{e||(g(t instanceof Error?t.message:String(t)),f([]))}).finally(()=>{e||m(!1)}),fetch(`/scenarios/${encodeURIComponent(t.id)}`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return e.json()}).then(t=>{e||v(t)}).catch(()=>{e||v(null)}).finally(()=>{e||S(!1)}),()=>{e=!0}},[t?.id]),(0,b.useEffect)(()=>{c?(ae.current=document.activeElement,requestAnimationFrame(()=>{(I.current?.querySelector(`button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])`))?.focus()})):ae.current?.focus()},[c]),(0,b.useEffect)(()=>{if(!c)return;function e(e){if(e.key===`Escape`)e.preventDefault(),a();else if(e.key===`Tab`){let t=Kh(I.current);if(t.length===0){e.preventDefault();return}let n=t[0],r=t[t.length-1],i=document.activeElement;!i||!I.current?.contains(i)?(e.preventDefault(),n.focus()):e.shiftKey&&i===n?(e.preventDefault(),r.focus()):!e.shiftKey&&i===r&&(e.preventDefault(),n.focus())}}return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[c,a]),!t)return null;let oe=`scenario-detail-actor-count`,se=()=>{t&&F&&(A(N??t.name),O(!0),M(null))},ce=()=>{O(!1),A(``),M(null)},le=async()=>{if(!t||!P||j)return;let e=k.trim();if(e.length===0){M(`Name cannot be empty.`);return}if(e===(N??t.name)){O(!1);return}let n=xe(P);if(n)M(n),re(B()||null);else{ee(!0),M(null);try{let n=await fetch(`/scenarios/${encodeURIComponent(t.id)}/rename`,{method:`POST`,headers:{"Content-Type":`application/json`,[fe]:P},body:JSON.stringify({name:e})});if(n.status===401){be(P);let e=B()||null;re(e),M(e?Vh(`rename`,`Save`):Bh);return}if(!n.ok){let e=await n.json().catch(()=>({}));M(e.message??e.error??`Rename failed: HTTP ${n.status}`);return}let r=(await n.json()).name??e;ne(r),O(!1),A(``),s?.(t.id,r)}catch(e){M(e instanceof Error?e.message:String(e))}finally{ee(!1)}}};return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{className:W.backdrop,onClick:a,role:`presentation`}),(0,x.jsxs)(`aside`,{ref:I,className:`${W.drawer} ${c?W.open:``}`,role:`dialog`,"aria-label":`Scenario detail: ${t.name}`,"aria-modal":`true`,children:[(0,x.jsxs)(`header`,{className:W.header,children:[(0,x.jsx)(`button`,{type:`button`,onClick:a,className:W.closeBtn,"aria-label":`Close scenario detail`,children:`×`}),(0,x.jsx)(`span`,{className:W.sourceBadge,"data-source":t.source??`other`,children:Jh(t.source)})]}),(0,x.jsxs)(`section`,{className:W.summary,children:[D?(0,x.jsxs)(`form`,{className:W.nameEditForm,onSubmit:e=>{e.preventDefault(),le()},children:[(0,x.jsx)(`input`,{type:`text`,value:k,onChange:e=>A(e.target.value),onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),ce())},disabled:j,maxLength:100,autoFocus:!0,className:W.nameEditInput,"aria-label":`New scenario name`}),(0,x.jsxs)(`div`,{className:W.nameEditActions,children:[(0,x.jsx)(`button`,{type:`submit`,className:W.nameEditSave,disabled:j||!P||k.trim().length===0,"aria-describedby":te?Hh:void 0,children:j?`Saving…`:`Save`}),(0,x.jsx)(`button`,{type:`button`,className:W.nameEditCancel,onClick:ce,disabled:j,children:`Cancel`})]}),te&&(0,x.jsx)(`p`,{id:Hh,className:W.nameEditError,role:`alert`,children:te})]}):(0,x.jsxs)(`div`,{className:W.nameRow,children:[(0,x.jsx)(`h2`,{className:W.name,children:N??t.name}),F&&(0,x.jsx)(`button`,{type:`button`,className:W.nameEditBtn,onClick:se,"aria-label":`Rename ${N??t.name}`,title:`Rename scenario`,children:`✎`})]}),t.description&&(0,x.jsx)(`p`,{className:W.description,children:t.description}),(0,x.jsxs)(`dl`,{className:W.metaGrid,children:[typeof t.runCount==`number`&&(0,x.jsxs)(`div`,{className:W.meta,children:[(0,x.jsx)(`dt`,{children:`Total runs`}),(0,x.jsx)(`dd`,{children:t.runCount.toLocaleString()})]}),typeof t.departments==`number`&&(0,x.jsxs)(`div`,{className:W.meta,children:[(0,x.jsx)(`dt`,{children:`Departments`}),(0,x.jsx)(`dd`,{children:t.departments})]}),t.compiledAt&&(0,x.jsxs)(`div`,{className:W.meta,children:[(0,x.jsx)(`dt`,{children:`Compiled`}),(0,x.jsx)(`dd`,{title:t.compiledAt,children:Uh(t.compiledAt)})]}),(0,x.jsxs)(`div`,{className:W.meta,children:[(0,x.jsx)(`dt`,{children:`Source`}),(0,x.jsx)(`dd`,{children:Jh(t.source)})]})]})]}),t.seedText&&(0,x.jsxs)(`section`,{className:W.seedSection,"aria-labelledby":`scenario-detail-seed-heading`,children:[(0,x.jsx)(`h3`,{className:W.sectionHeading,id:`scenario-detail-seed-heading`,children:`Seed prompt`}),(0,x.jsx)(`p`,{className:W.seedHint,children:`Original brief that compile-from-seed turned into this scenario. Truncated to 1KB at persist time so very long sources read as their leading section.`}),(0,x.jsx)(`pre`,{className:W.seedBody,children:t.seedText})]}),_&&_.presets.length>0&&_.presets[0].leaders.length>0&&(0,x.jsxs)(`section`,{className:W.presetsSection,"aria-labelledby":`scenario-detail-presets-heading`,children:[(0,x.jsx)(`h3`,{className:W.sectionHeading,id:`scenario-detail-presets-heading`,children:`Leader presets`}),(0,x.jsx)(`p`,{className:W.sectionHint,children:`Default leader pair the scenario ships with. Picking Run with the slot count below fills these in first; extra slots beyond the preset get LLM-generated.`}),(0,x.jsx)(`ul`,{className:W.presetList,role:`list`,children:_.presets[0].leaders.map((e,t)=>(0,x.jsxs)(`li`,{className:W.presetCard,children:[(0,x.jsxs)(`div`,{className:W.presetHeader,children:[(0,x.jsx)(`span`,{className:W.presetName,children:e.name}),e.archetype&&(0,x.jsx)(`span`,{className:W.presetArchetype,children:e.archetype})]}),e.unit&&(0,x.jsx)(`span`,{className:W.presetUnit,children:e.unit}),e.hexaco&&Object.keys(e.hexaco).length>0&&(0,x.jsx)(`ul`,{className:W.hexacoList,"aria-label":`HEXACO profile for ${e.name}`,children:Object.entries(e.hexaco).slice(0,6).map(([e,t])=>{let n=Math.round((Number(t)||0)*100);return(0,x.jsxs)(`li`,{className:W.hexacoRow,children:[(0,x.jsx)(`span`,{className:W.hexacoAxis,children:e.length>6?e.slice(0,6):e}),(0,x.jsx)(`span`,{className:W.hexacoBar,role:`img`,"aria-label":`${e} ${n}%`,children:(0,x.jsx)(`span`,{className:W.hexacoFill,style:{width:`${n}%`}})}),(0,x.jsx)(`span`,{className:W.hexacoValue,children:n})]},e)})}),e.instructions&&(0,x.jsx)(`p`,{className:W.presetInstructions,title:e.instructions,children:e.instructions.length>220?`${e.instructions.slice(0,220)}…`:e.instructions})]},`${e.name}-${t}`))})]}),_&&_.departments.length>0&&(0,x.jsxs)(`section`,{className:W.departmentsSection,"aria-labelledby":`scenario-detail-depts-heading`,children:[(0,x.jsxs)(`h3`,{className:W.sectionHeading,id:`scenario-detail-depts-heading`,children:[`Departments `,(0,x.jsxs)(`span`,{className:W.sectionCount,children:[`· `,_.departments.length]})]}),(0,x.jsx)(`ul`,{className:W.deptChips,role:`list`,children:_.departments.map(e=>(0,x.jsxs)(`li`,{className:W.deptChip,children:[e.icon&&(0,x.jsx)(`span`,{className:W.deptIcon,"aria-hidden":`true`,children:e.icon}),(0,x.jsx)(`span`,{children:e.label}),e.role&&(0,x.jsxs)(`span`,{className:W.deptRole,children:[`· `,e.role]})]},e.id))})]}),y&&!_&&(0,x.jsx)(`p`,{className:W.statusLine,style:{padding:`0 18px`},children:`Loading scenario detail…`}),(0,x.jsxs)(`section`,{className:W.recentSection,"aria-labelledby":`scenario-detail-recent-heading`,children:[(0,x.jsx)(`h3`,{className:W.sectionHeading,id:`scenario-detail-recent-heading`,children:`Recent runs`}),p&&(0,x.jsx)(`p`,{className:W.statusLine,children:`Loading recent runs…`}),h&&!p&&(0,x.jsxs)(`p`,{className:`${W.statusLine} ${W.error}`,role:`alert`,children:[`Failed to load recent runs: `,h]}),!p&&!h&&d.length===0&&(0,x.jsx)(`p`,{className:W.statusLine,children:`No runs yet on this scenario.`}),d.length>0&&(0,x.jsx)(`ul`,{className:W.recentList,role:`list`,children:d.map(e=>(0,x.jsxs)(`li`,{className:W.recentRow,children:[(0,x.jsxs)(`span`,{className:W.recentTitle,children:[e.actorName??`Unknown leader`,e.actorArchetype&&(0,x.jsxs)(`span`,{className:W.recentArchetype,children:[` · `,e.actorArchetype]})]}),(0,x.jsxs)(`span`,{className:W.recentMeta,children:[Uh(e.createdAt),` · `,Wh(e.costUSD),` · `,Gh(e.durationMs)]})]},e.runId))})]}),(0,x.jsxs)(`footer`,{className:W.footer,children:[(0,x.jsxs)(`div`,{className:W.actorRow,children:[(0,x.jsx)(`label`,{htmlFor:oe,className:W.actorLabel,children:`Actors`}),(0,x.jsx)(`input`,{id:oe,type:`range`,min:1,max:300,value:l,onChange:e=>u(parseInt(e.target.value,10)),disabled:n,className:W.actorSlider,"aria-label":`Number of parallel actors`}),(0,x.jsx)(`span`,{className:W.actorValue,children:l})]}),(0,x.jsxs)(`button`,{type:`button`,className:W.runButton,onClick:()=>i(t.id,l),disabled:n||C,"aria-label":`Run ${l} actor${l===1?``:`s`} against ${t.name}`,children:[`Run `,l,` `,l===1?`actor`:`actors`,` →`]}),ie&&(0,x.jsx)(`button`,{type:`button`,className:W.deleteButton,onClick:async()=>{if(!t||!P||C||!(typeof window<`u`&&window.confirm(`Delete this scenario?\n\n"${t.name}"\n\nRemoves the scenario from disk + the live catalog. Past runs are kept (they live in run-history). Cannot be undone.`)))return;let e=xe(P);if(e)E(e),re(B()||null);else{w(!0),E(null);try{let e=await fetch(`/admin/scenarios/${encodeURIComponent(t.id)}`,{method:`DELETE`,headers:{[fe]:P}});if(e.status===401){be(P);let e=B()||null;re(e),E(e?Vh(`delete`,`Delete`):Bh);return}if(!e.ok){let t=await e.json().catch(()=>({}));E(t.message??t.error??`Delete failed: HTTP ${e.status}`);return}o?.(t.id),a()}catch(e){E(e instanceof Error?e.message:String(e))}finally{w(!1)}}},disabled:C||n,"aria-label":`Delete scenario ${t.name}`,children:C?`Deleting…`:`Delete (admin)`}),T&&(0,x.jsx)(`p`,{className:W.deleteError,role:`alert`,children:T})]})]})]})}function Jh(e){return e===`builtin`?`Built-in`:e===`disk`?`Saved`:e===`compiled`?`Custom`:e===`memory`?`Memory`:e??`Unknown`}var Yh={section:`_section_1l91i_1`,header:`_header_1l91i_5`,heading:`_heading_1l91i_14`,count:`_count_1l91i_24`,statusLine:`_statusLine_1l91i_32`,error:`_error_1l91i_39`,actorRow:`_actorRow_1l91i_43`,actorLabel:`_actorLabel_1l91i_54`,actorSlider:`_actorSlider_1l91i_63`,actorValue:`_actorValue_1l91i_68`,filterRow:`_filterRow_1l91i_76`,searchLabel:`_searchLabel_1l91i_84`,searchInput:`_searchInput_1l91i_90`,chipGroup:`_chipGroup_1l91i_108`,chip:`_chip_1l91i_108`,chipActive:`_chipActive_1l91i_133`,chipCount:`_chipCount_1l91i_139`,sortLabel:`_sortLabel_1l91i_145`,sortSelect:`_sortSelect_1l91i_150`,emptyMatches:`_emptyMatches_1l91i_165`,clearFiltersBtn:`_clearFiltersBtn_1l91i_176`,grid:`_grid_1l91i_187`,card:`_card_1l91i_196`,cardBody:`_cardBody_1l91i_211`,cardActive:`_cardActive_1l91i_231`,cardHeader:`_cardHeader_1l91i_236`,sourceBadge:`_sourceBadge_1l91i_243`,badge_builtin:`_badge_builtin_1l91i_254`,badge_disk:`_badge_disk_1l91i_258`,badge_compiled:`_badge_compiled_1l91i_262`,badge_memory:`_badge_memory_1l91i_262`,badge_other:`_badge_other_1l91i_266`,activeBadge:`_activeBadge_1l91i_270`,cardName:`_cardName_1l91i_282`,cardSeed:`_cardSeed_1l91i_292`,cardStats:`_cardStats_1l91i_303`,stat:`_stat_1l91i_32`,statKey:`_statKey_1l91i_317`,statValue:`_statValue_1l91i_324`,runButton:`_runButton_1l91i_331`};function Xh(e){let t=Date.parse(e);if(!Number.isFinite(t))return``;let n=Date.now()-t;if(n<0)return`just now`;let r=Math.floor(n/6e4);if(r<1)return`just now`;if(r<60)return`${r}m ago`;let i=Math.floor(r/60);if(i<24)return`${i}h ago`;let a=Math.floor(i/24);if(a<7)return`${a}d ago`;let o=Math.floor(a/7);if(o<5)return`${o}w ago`;let s=Math.floor(a/30);return s<12?`${s}mo ago`:new Date(e).getFullYear().toString()}function Zh(e){return e===`builtin`?`builtin`:e===`disk`?`disk`:e===`compiled`?`compiled`:e===`memory`?`memory`:`other`}function Qh(e){return e===`builtin`?`Built-in`:e===`disk`?`Saved`:e===`compiled`?`Custom`:e===`memory`?`Memory`:e??`Unknown`}function $h(e){let{disabled:t=!1,onRunScenario:n}=e,r=Qk(),i=!eA()||t,a=r.id,[o,s]=(0,b.useState)([]),[c,l]=(0,b.useState)(2),[u,d]=(0,b.useState)(!0),[f,p]=(0,b.useState)(null),[m,h]=(0,b.useState)(``),[g,_]=(0,b.useState)(``);(0,b.useEffect)(()=>{let e=setTimeout(()=>_(m),120);return()=>clearTimeout(e)},[m]);let[v,y]=(0,b.useState)(`all`),[S,C]=(0,b.useState)(`curated`),[w,T]=(0,b.useState)(null);if((0,b.useEffect)(()=>{let e=!1,t=null,n=async()=>{try{let t=await fetch(`/scenarios`);if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();if(e)return;s(n.scenarios??[]),p(null)}catch(t){if(e)return;p(t instanceof Error?t.message:String(t))}finally{e||d(!1)}};return n(),t=setInterval(n,3e4),()=>{e=!0,t&&clearInterval(t)}},[]),u&&o.length===0)return(0,x.jsxs)(`section`,{className:Yh.section,"aria-labelledby":`scenario-catalog-heading`,children:[(0,x.jsx)(`h3`,{className:Yh.heading,id:`scenario-catalog-heading`,children:`All scenarios`}),(0,x.jsx)(`p`,{className:Yh.statusLine,children:`Loading catalog…`})]});if(f&&o.length===0)return(0,x.jsxs)(`section`,{className:Yh.section,"aria-labelledby":`scenario-catalog-heading`,children:[(0,x.jsx)(`h3`,{className:Yh.heading,id:`scenario-catalog-heading`,children:`All scenarios`}),(0,x.jsxs)(`p`,{className:`${Yh.statusLine} ${Yh.error}`,role:`alert`,children:[`Failed to load catalog: `,f]})]});if(o.length<2)return null;let E=`scenario-catalog-actor-count`,D=`scenario-catalog-search`,O=g.trim().length>0||v!==`all`,k=g.trim().toLowerCase(),A=[...o.filter(e=>e.id===a?!0:v!==`all`&&e.source!==v?!1:k.length===0||[e.name,e.id,e.seedText??``,e.description??``].join(` `).toLowerCase().includes(k))].sort((e,t)=>{if(e.id===a)return-1;if(t.id===a)return 1;if(S===`most-runs`){let n=(t.runCount??0)-(e.runCount??0);if(n!==0)return n}else if(S===`newest`){let n=e.compiledAt?Date.parse(e.compiledAt):0,r=t.compiledAt?Date.parse(t.compiledAt):0;if(n!==r)return r-n}else if(S===`alphabetical`)return e.name.localeCompare(t.name);else{let n=(t.runCount??0)-(e.runCount??0);if(n!==0)return n;if(e.compiledAt&&t.compiledAt){let n=Date.parse(e.compiledAt),r=Date.parse(t.compiledAt);if(Number.isFinite(n)&&Number.isFinite(r)&&n!==r)return r-n}}return e.name.localeCompare(t.name)}),j=o.reduce((e,t)=>{let n=t.source??`other`;return e[n]=(e[n]??0)+1,e},{});return(0,x.jsxs)(`section`,{className:Yh.section,"aria-labelledby":`scenario-catalog-heading`,children:[(0,x.jsxs)(`header`,{className:Yh.header,children:[(0,x.jsxs)(`h3`,{className:Yh.heading,id:`scenario-catalog-heading`,children:[`All scenarios`,` `,(0,x.jsxs)(`span`,{className:Yh.count,children:[`· `,O?`${A.length} of ${o.length}`:o.length]})]}),(0,x.jsxs)(`div`,{className:Yh.actorRow,children:[(0,x.jsx)(`label`,{className:Yh.actorLabel,htmlFor:E,children:`Actors`}),(0,x.jsx)(`input`,{id:E,type:`range`,min:1,max:300,value:c,onChange:e=>l(parseInt(e.target.value,10)),disabled:i,className:Yh.actorSlider,"aria-label":`Number of parallel actors per scenario run`}),(0,x.jsx)(`span`,{className:Yh.actorValue,children:c})]})]}),(0,x.jsxs)(`div`,{className:Yh.filterRow,children:[(0,x.jsxs)(`label`,{className:Yh.searchLabel,htmlFor:D,children:[(0,x.jsx)(`span`,{className:`sr-only`,children:`Search scenarios`}),(0,x.jsx)(`input`,{id:D,type:`search`,value:m,onChange:e=>h(e.target.value),placeholder:`Search by name or seed text…`,className:Yh.searchInput,"aria-label":`Filter catalog by name or seed text`})]}),(0,x.jsx)(`div`,{className:Yh.chipGroup,role:`group`,"aria-label":`Filter by scenario source`,children:[{key:`all`,label:`All`},{key:`builtin`,label:`Built-in`},{key:`disk`,label:`Saved`},{key:`compiled`,label:`Custom`}].map(e=>{let t=e.key===`all`?o.length:j[e.key]??0,n=v===e.key;return e.key!==`all`&&t===0?null:(0,x.jsxs)(`button`,{type:`button`,onClick:()=>y(e.key),className:`${Yh.chip} ${n?Yh.chipActive:``}`,"aria-pressed":n,children:[e.label,` `,(0,x.jsx)(`span`,{className:Yh.chipCount,children:t})]},e.key)})}),(0,x.jsxs)(`label`,{className:Yh.sortLabel,children:[(0,x.jsx)(`span`,{className:`sr-only`,children:`Sort scenarios`}),(0,x.jsxs)(`select`,{value:S,onChange:e=>C(e.target.value),className:Yh.sortSelect,"aria-label":`Sort catalog`,children:[(0,x.jsx)(`option`,{value:`curated`,children:`Sort: Curated`}),(0,x.jsx)(`option`,{value:`most-runs`,children:`Sort: Most runs`}),(0,x.jsx)(`option`,{value:`newest`,children:`Sort: Newest first`}),(0,x.jsx)(`option`,{value:`alphabetical`,children:`Sort: A → Z`})]})]})]}),A.length===0?(0,x.jsxs)(`div`,{className:Yh.emptyMatches,role:`status`,"aria-live":`polite`,children:[`No scenarios match your filter.`,` `,(0,x.jsx)(`button`,{type:`button`,className:Yh.clearFiltersBtn,onClick:()=>{h(``),y(`all`)},children:`Clear filters`})]}):(0,x.jsx)(`ul`,{className:Yh.grid,role:`list`,children:A.map(e=>{let t=Zh(e.source),r=e.id===a;return(0,x.jsxs)(`li`,{className:`${Yh.card} ${Yh[`tone_${t}`]??``} ${r?Yh.cardActive:``}`.trim(),children:[(0,x.jsxs)(`button`,{type:`button`,className:Yh.cardBody,onClick:()=>T(e),"aria-label":`View detail for ${e.name}`,children:[(0,x.jsxs)(`div`,{className:Yh.cardHeader,children:[(0,x.jsx)(`span`,{className:`${Yh.sourceBadge} ${Yh[`badge_${t}`]??``}`,children:Qh(e.source)}),r&&(0,x.jsx)(`span`,{className:Yh.activeBadge,children:`Loaded`})]}),(0,x.jsx)(`h4`,{className:Yh.cardName,children:e.name}),e.seedText&&(0,x.jsxs)(`p`,{className:Yh.cardSeed,title:e.seedText,children:[e.seedText.slice(0,140),e.seedText.length>140?`…`:``]}),(0,x.jsxs)(`dl`,{className:Yh.cardStats,children:[typeof e.runCount==`number`&&e.runCount>0&&(0,x.jsxs)(`div`,{className:Yh.stat,children:[(0,x.jsx)(`dt`,{className:Yh.statKey,children:`Runs`}),(0,x.jsx)(`dd`,{className:Yh.statValue,children:e.runCount.toLocaleString()})]}),typeof e.departments==`number`&&e.departments>0&&(0,x.jsxs)(`div`,{className:Yh.stat,children:[(0,x.jsx)(`dt`,{className:Yh.statKey,children:`Depts`}),(0,x.jsx)(`dd`,{className:Yh.statValue,children:e.departments})]}),e.compiledAt&&(0,x.jsxs)(`div`,{className:Yh.stat,children:[(0,x.jsx)(`dt`,{className:Yh.statKey,children:`Compiled`}),(0,x.jsx)(`dd`,{className:Yh.statValue,children:Xh(e.compiledAt)||e.compiledAt.slice(0,10)})]})]})]}),(0,x.jsxs)(`button`,{type:`button`,className:Yh.runButton,onClick:t=>{t.stopPropagation(),n(e.id,c)},disabled:i,"aria-label":`Run ${c} actor${c===1?``:`s`} against ${e.name}`,children:[`Run `,c,` `,c===1?`actor`:`actors`,` →`]})]},e.id)})}),(0,x.jsx)(qh,{scenario:w,disabled:i,initialActorCount:c,onRunScenario:(e,t)=>{T(null),n(e,t)},onClose:()=>T(null),onDeleted:e=>{s(t=>t.filter(t=>t.id!==e))},onRenamed:(e,t)=>{s(n=>n.map(n=>n.id===e?{...n,name:t}:n)),T(n=>n&&n.id===e?{...n,name:t}:n)}})]})}var eg=[{id:`hurricane-evacuation`,label:`What if a coastal mayor has 36 hours to evacuate before a hurricane?`,seedText:`A coastal metro of 800,000 has 36 hours before a Category 4 hurricane landfall. The mayor must decide a phased evacuation across three districts served by a single causeway bridge, with a regional hospital, a fuel depot, and an aging levee system in play. Departments involved: emergency management, public health, transportation, utilities, communications.`},{id:`saas-mid-tier`,label:`What if a developer-tools SaaS adds a $14 mid-tier?`,seedText:`StackPulse, a developer-focused observability SaaS (logs + metrics + tracing aimed at series-B-to-D startup engineering teams of 5-50 people), introduces a new $14/month "Builder" tier between the free Sandbox plan and the existing $29 Pro plan. The 180,000-user paid base is mostly engineering managers and SREs at venture-backed startups; their #1 jobs-to-be-done are debugging production incidents under 15 minutes and proving reliability SLAs to enterprise customers. Builder caps log retention at 7 days (Pro keeps 30) and limits trace sampling to 10% (Pro is full). Existing Pro subs get 90-day grandfathering. Competitors: Datadog (incumbent, 10x the price), Honeycomb (premium tier), self-hosted Grafana stacks. Test the impact on Free-to-Paid conversion, Pro downgrade rate, net ARPU, and churn over six months. Departments: pricing, growth, success, finance, engineering.`},{id:`ai-lab-early-release`,label:`What if an AI lab releases a frontier model six weeks early?`,seedText:`An AI lab decides whether to release a frontier multimodal model six weeks early. Two evaluators flag a 4.2% specification-gaming rate on long-horizon agentic tasks and early mesa-objective signals under DPO. A rival lab's weaker model ships on schedule, capturing $240M ARR in enterprise deals. Council: alignment, capability, policy, infra, comms.`},{id:`generation-ship-fuel-leak`,label:`What if a generation ship discovers a fuel leak at year 18?`,seedText:`A generation ship with 2,400 passengers at year 18 of a 40-year interstellar transit discovers a slow fuel leak on the main reactor. Reactor crew wants to EVA-repair (non-zero fatality risk); bridge wants to coast at reduced thrust and accept a 14-year transit extension. Departments: engineering, life support, medical, psych, command.`},{id:`city-congestion-pricing`,label:`What if a city pilots congestion pricing for 12 months?`,seedText:`A mid-size city of 650,000 pilots downtown congestion pricing for 12 months. $9 peak / $3 off-peak on vehicles entering the central business district 6am-7pm Mon-Fri. Revenue funds two BRT lines and a 30% transit fare cut for low-income riders. Test VMT, transit ridership, small-business revenue, equity outcomes.`}];function tg(e){return .1+.6*e}var ng={pendingSeedNotice:`_pendingSeedNotice_1rh83_1`,dividerWrap:`_dividerWrap_1rh83_15`,dividerLine:`_dividerLine_1rh83_27`,seedInput:`_seedInput_1rh83_33`,templatePicker:`_templatePicker_1rh83_48`,templatePickerLabel:`_templatePickerLabel_1rh83_55`,templatePickerSelect:`_templatePickerSelect_1rh83_65`,tabs:`_tabs_1rh83_90`,tab:`_tab_1rh83_90`,tabActive:`_tabActive_1rh83_119`,textarea:`_textarea_1rh83_124`,input:`_input_1rh83_125`,urlRow:`_urlRow_1rh83_142`,fetchButton:`_fetchButton_1rh83_150`,runButton:`_runButton_1rh83_151`,dropZone:`_dropZone_1rh83_185`,hint:`_hint_1rh83_205`,charCount:`_charCount_1rh83_218`,error:`_error_1rh83_225`,actorCountRow:`_actorCountRow_1rh83_235`,actorCountLabel:`_actorCountLabel_1rh83_246`,actorCountSlider:`_actorCountSlider_1rh83_257`,actorCountPreview:`_actorCountPreview_1rh83_313`};function rg(){if(typeof window>`u`)return``;try{let e=new URLSearchParams(window.location.search).get(`prompt`);return e?e.trim():``}catch{return``}}function ig({onSeedReady:e,onLoadedScenarioRunStart:t,onCatalogRunStart:n,disabled:r=!1}){let[i,a]=(0,b.useState)(`paste`),[o,s]=(0,b.useState)(rg),[c,l]=(0,b.useState)(``),[u,d]=(0,b.useState)(void 0),[f,p]=(0,b.useState)(``),[m,h]=(0,b.useState)(null),[g,_]=(0,b.useState)(!1),[v,y]=(0,b.useState)(2),S=(0,b.useRef)(null),C=(0,b.useCallback)(()=>{let t=o.trim(),n=gh(t);n.ok?(h(null),e({seedText:t,sourceUrl:u,domainHint:f.trim()||void 0,actorCount:v})):h(n.reason===`too-short`?`Paste at least 200 characters of source material.`:n.reason===`too-long`?`Source material exceeds 50 000 characters.`:`Source material is empty.`)},[o,u,f,v,e]),w=(0,b.useCallback)(async()=>{let e=hh(c);if(!e.ok)h(e.error);else{_(!0),h(null);try{let t=await fetch(`/api/quickstart/fetch-seed`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({url:e.url.toString()})});if(!t.ok){let e=await t.json().catch(()=>({}));h(e.error??`Fetch failed: HTTP ${t.status}`);return}let n=await t.json();s(n.text),d(n.sourceUrl??e.url.toString()),a(`paste`)}catch(e){let t=e?.message??String(e),n=/Failed to fetch|NetworkError|ERR_/i.test(t)?`Couldn't reach the server. Check your connection and try again.`:`URL fetch failed: ${t}`;h(n)}finally{_(!1)}}},[c]),T=(0,b.useCallback)(async e=>{if(e.size>10485760)h(`PDF exceeds 10 MB limit.`);else if(e.type!==`application/pdf`&&!e.name.toLowerCase().endsWith(`.pdf`))h(`File is not a PDF: ${e.name}`);else{_(!0),h(null);try{let{text:t,truncated:n}=await Ah(e);s(n?`${t}\n\n[Truncated to first 50 KB.]`:t),d(void 0),a(`paste`)}catch(e){let t=e?.code,n=String(e?.message??e),r;r=t===`PDF_NO_TEXT`?`No text found in this PDF. It looks like a scanned image — try a text-based PDF, or paste the content into WRITE.`:/InvalidPDFException|invalid pdf|corrupt/i.test(n)?`This PDF appears to be corrupted or password-protected. Try a different file or paste the text directly.`:/worker|GlobalWorkerOptions/i.test(n)?`Couldn't load the PDF parser (${n}). Try a different file, or paste the text into WRITE.`:`Couldn't read this PDF (${n}). Try paste-text or a different file.`,h(r)}finally{_(!1)}}},[]),E={paste:`WRITE`,url:`URL`,pdf:`PDF`},D=o.trim().length>=200;return(0,x.jsxs)(`div`,{className:ng.seedInput,children:[t&&(0,x.jsxs)(x.Fragment,{children:[D&&(0,x.jsx)(`p`,{className:ng.pendingSeedNotice,role:`status`,"aria-live":`polite`,children:`You have draft seed text below. Submit it to compile a new scenario, or clear it to run the loaded one.`}),(0,x.jsx)(zh,{onRunStart:t,disabled:r||g||D}),n&&(0,x.jsx)($h,{onRunScenario:n,disabled:r||g||D}),(0,x.jsxs)(`div`,{className:ng.dividerWrap,children:[(0,x.jsx)(`span`,{className:ng.dividerLine,"aria-hidden":`true`}),(0,x.jsx)(`span`,{children:`or paste a new scenario`}),(0,x.jsx)(`span`,{className:ng.dividerLine,"aria-hidden":`true`})]})]}),(0,x.jsxs)(`label`,{className:ng.templatePicker,children:[(0,x.jsx)(`span`,{className:ng.templatePickerLabel,children:`Try a template`}),(0,x.jsxs)(`select`,{className:ng.templatePickerSelect,value:``,disabled:r,onChange:e=>{let t=e.target.value;if(!t)return;let n=eg.find(e=>e.id===t);n&&(a(`paste`),s(n.seedText),h(null),e.target.value=``)},children:[(0,x.jsx)(`option`,{value:``,children:`Pick a sample scenario…`}),eg.map(e=>(0,x.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),(0,x.jsx)(`div`,{className:ng.tabs,role:`tablist`,children:[`paste`,`url`,`pdf`].map(e=>(0,x.jsx)(`button`,{role:`tab`,"aria-selected":i===e,className:`${ng.tab} ${i===e?ng.tabActive:``}`,onClick:()=>{a(e),h(null)},disabled:r,type:`button`,children:E[e]},e))}),i===`paste`&&(0,x.jsx)(`textarea`,{"data-quickstart-seed":!0,className:ng.textarea,placeholder:`Type or paste a brief, article, meeting notes, or any domain-specific source material (at least 200 characters).`,value:o,onChange:e=>s(e.target.value),rows:6,disabled:r}),i===`url`&&(0,x.jsxs)(`div`,{className:ng.urlRow,children:[(0,x.jsx)(`input`,{type:`url`,className:ng.input,placeholder:`https://example.com/article`,value:c,onChange:e=>l(e.target.value),disabled:r||g}),(0,x.jsx)(`button`,{type:`button`,className:ng.fetchButton,onClick:w,disabled:r||g||!c,children:g?`Fetching...`:`Fetch`})]}),i===`pdf`&&(0,x.jsxs)(`div`,{className:ng.dropZone,"data-paracosm-local-dropzone":`pdf`,onClick:()=>{r||S.current?.click()},onDragOver:e=>e.preventDefault(),onDrop:e=>{if(e.preventDefault(),r)return;let t=e.dataTransfer.files[0];t&&T(t)},role:`button`,tabIndex:r?-1:0,"aria-disabled":r,onKeyDown:e=>{r||(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),S.current?.click())},children:[(0,x.jsx)(`input`,{ref:S,type:`file`,accept:`application/pdf,.pdf`,onChange:e=>{let t=e.target.files?.[0];t&&T(t)},hidden:!0}),g?`Extracting text...`:`Drop a PDF or click to upload (max 10 MB, first 50 KB of text used)`]}),(0,x.jsxs)(`div`,{className:ng.hint,children:[(0,x.jsx)(`label`,{htmlFor:`quickstart-domain-hint`,children:`Domain hint (optional)`}),(0,x.jsx)(`input`,{id:`quickstart-domain-hint`,className:ng.input,type:`text`,placeholder:`e.g., "clinical trial decision" or "startup growth"`,value:f,onChange:e=>p(e.target.value),maxLength:80,disabled:r})]}),m&&(0,x.jsx)(`p`,{className:ng.error,role:`alert`,children:m}),(0,x.jsxs)(`div`,{className:ng.charCount,children:[o.length.toLocaleString(),` / 50,000 characters`]}),(0,x.jsxs)(`div`,{className:ng.actorCountRow,children:[(0,x.jsxs)(`label`,{htmlFor:`quickstart-actor-count`,className:ng.actorCountLabel,children:[`Actors: `,(0,x.jsx)(`strong`,{children:v})]}),(0,x.jsx)(`input`,{id:`quickstart-actor-count`,type:`range`,min:1,max:300,value:v,onChange:e=>y(parseInt(e.target.value,10)),disabled:r,className:ng.actorCountSlider,"aria-label":`Number of parallel actors to run`}),(0,x.jsxs)(`span`,{className:ng.actorCountPreview,"aria-live":`polite`,children:[`~$`,tg(v).toFixed(2),` · `,ag(v)]})]}),(0,x.jsx)(Ih,{seedText:o,domainHint:f,sourceUrl:u,actorCount:v,disabled:r}),(0,x.jsxs)(`button`,{type:`button`,className:ng.runButton,onClick:C,disabled:r||o.trim().length<200,children:[`Generate + Run `,v,` `,v===1?`Actor`:`Actors`,` (~$`,tg(v).toFixed(2),`)`]})]})}function ag(e){if(e<=0)return`—`;let t=2+5*Math.max(1,Math.ceil(e/8));return`${t}–${Math.ceil(t*1.5)} min`}var G={card:`_card_182vb_1`,heading:`_heading_182vb_15`,title:`_title_182vb_23`,eyebrow:`_eyebrow_182vb_35`,copy:`_copy_182vb_43`,presetRow:`_presetRow_182vb_50`,presetLabel:`_presetLabel_182vb_61`,presetButton:`_presetButton_182vb_71`,presetButtonActive:`_presetButtonActive_182vb_91`,presetClear:`_presetClear_182vb_97`,presetBlurb:`_presetBlurb_182vb_118`,formGrid:`_formGrid_182vb_126`,formCell:`_formCell_182vb_137`,formLegend:`_formLegend_182vb_152`,field:`_field_182vb_165`,fieldRow:`_fieldRow_182vb_171`,fieldThird:`_fieldThird_182vb_177`,fieldLabel:`_fieldLabel_182vb_182`,input:`_input_182vb_191`,textarea:`_textarea_182vb_212`,mono:`_mono_182vb_235`,actions:`_actions_182vb_240`,button:`_button_182vb_248`,helper:`_helper_182vb_270`,spinner:`_spinner_182vb_276`,"idc-spin":`_idc-spin_182vb_1`,timer:`_timer_182vb_288`},og=`paracosm:lastLaunchConfig`,sg=`paracosm:keyOverrides`,cg=`paracosm:activeRunActors`,lg=`paracosm:activeRunScenarioId`,ug=950;function dg(e){try{let t=e.getItem(og);if(!t)return null;let n=JSON.parse(t);return n&&typeof n==`object`&&!Array.isArray(n)?n:null}catch{return null}}function fg(e,t){return e.scenarioId===t}function pg(e,t){try{e.setItem(og,JSON.stringify(t))}catch{}}function mg(e,t,n){try{e.setItem(cg,JSON.stringify(t)),n?e.setItem(lg,n):e.removeItem?.(lg)}catch{}}function hg(e){try{return e.getItem(`paracosm:activeRunScenarioId`)||null}catch{return null}}function gg(e){try{let t=e.getItem(cg);if(!t)return null;let n=JSON.parse(t);return Array.isArray(n)?n.filter(e=>!!e&&typeof e==`object`&&!Array.isArray(e)):null}catch{return null}}function _g(e){try{let t=e.getItem(sg);if(!t)return{};let n=JSON.parse(t);return!n||typeof n!=`object`||Array.isArray(n)?{}:n}catch{return{}}}function vg(e,t){let n=(typeof e.seed==`number`?e.seed:ug)+1,r={...e,seed:n};return t.openai&&(r.apiKey=t.openai),t.anthropic&&(r.anthropicKey=t.anthropic),t.serper&&(r.serperKey=t.serper),t.firecrawl&&(r.firecrawlKey=t.firecrawl),t.tavily&&(r.tavilyKey=t.tavily),t.cohere&&(r.cohereKey=t.cohere),r}function yg(e){if(typeof e!=`string`)return;let t=e.trim();if(t&&!t.includes(`...`))return t}function bg(e){let t=yg(e.openai),n=yg(e.anthropic);return{...t?{apiKey:t}:{},...n?{anthropicKey:n}:{}}}function xg(e){let t=bg(e);return t.apiKey!==void 0||t.anthropicKey!==void 0}var Sg={id:``,name:``,description:``,profileJson:`{}`},Cg={id:``,name:``,description:``,durationValue:`12`,durationUnit:`weeks`,adherence:`0.85`},wg={medical:{label:`Patient · treatment`,blurb:`Type 2 diabetes patient on a 12-week semaglutide + lifestyle protocol.`,subject:{id:`patient-maria-2026`,name:`Maria Chen`,description:`58 y/o T2D for 4 yrs, sedentary, family hx CVD, on metformin.`,profileJson:JSON.stringify({age:58,yearsWithT2D:4,bmi:31,a1cBaseline:7.8,weightLb:178,fastingGlucose:156,sleepHoursBaseline:6.2,exerciseMinPerWeek:0,comorbidities:`hypertension, dyslipidemia`},null,2)},intervention:{id:`glp1-12wk-protocol`,name:`12-week semaglutide + lifestyle protocol`,description:`Initiate semaglutide 0.25mg weekly, titrate to 1.0mg by week 4. Pair with dietitian-led nutrition plan and 150min/wk graded exercise. Behavioral health checkpoints biweekly. Monitor for GI side effects, gallbladder, pancreatitis.`,durationValue:`84`,durationUnit:`days`,adherence:`0.85`},signalsJson:JSON.stringify([{label:`HbA1c`,value:7.8,unit:`%`,recordedAt:`2026-09-15T00:00:00Z`},{label:`Fasting glucose`,value:156,unit:`mg/dL`,recordedAt:`2026-09-15T00:00:00Z`},{label:`Weight`,value:178,unit:`lb`,recordedAt:`2026-09-15T00:00:00Z`},{label:`BMI`,value:31,unit:`kg/m²`,recordedAt:`2026-09-15T00:00:00Z`}],null,2)},policy:{label:`Jurisdiction · ordinance`,blurb:`A mid-size city pilots downtown congestion pricing for 12 months.`,subject:{id:`city-portland-2026`,name:`Portland Metro`,description:`Pacific Northwest mid-size city with dense urban core, mature transit, organized downtown business association.`,profileJson:JSON.stringify({population:65e4,downtownEmployment:11e4,modeShareTransit:.18,modeShareCar:.62,modeShareActive:.14,avgPeakSpeedMph:14.2,annualCO2Tons:182e4,unemploymentRate:.044},null,2)},intervention:{id:`congestion-pricing-12mo`,name:`Downtown congestion pricing pilot`,description:`Charge $9/peak-hour ($3 off-peak) on vehicles entering the central business district 6am-7pm Mon-Fri. Revenue funds two new BRT lines and a 30% transit fare cut for low-income riders. Pilot runs 12 months with quarterly review.`,durationValue:`12`,durationUnit:`months`,adherence:`0.78`},signalsJson:JSON.stringify([{label:`Downtown VMT`,value:1.42,unit:`million-mi/day`,recordedAt:`2026-04-01T00:00:00Z`},{label:`Transit ridership`,value:118e3,unit:`boardings/day`,recordedAt:`2026-04-01T00:00:00Z`},{label:`Peak speed`,value:14.2,unit:`mph`,recordedAt:`2026-04-01T00:00:00Z`}],null,2)},product:{label:`Market · launch`,blurb:`A SaaS launches a new mid-tier price point against a price-sensitive prosumer segment.`,subject:{id:`segment-prosumer-creators`,name:`Prosumer creators`,description:`Independent creators earning $40k-$120k/yr who self-fund their tooling. Cross-tool stackers; price-sensitive within 20% bands.`,profileJson:JSON.stringify({addressableUsers:18e5,currentPaidConversion:.034,avgARPU_USD:22,churnMonthly:.038,npsCurrent:41,topCompetitorPriceUSD:18,topCompetitorMarketShare:.31},null,2)},intervention:{id:`mid-tier-pricing-launch`,name:`New $14/mo mid-tier launch`,description:`Introduce a third pricing tier at $14/mo (between Free and the existing $29/mo Pro), unlocking 60% of Pro features. Bundle with 90-day grandfathering for current Pro subs and a quarterly migration check-in. 6-month pilot before deciding to globalize.`,durationValue:`6`,durationUnit:`months`,adherence:`0.72`},signalsJson:JSON.stringify([{label:`Free → Paid conversion`,value:.034,unit:`rate`,recordedAt:`2026-04-01T00:00:00Z`},{label:`Monthly churn`,value:.038,unit:`rate`,recordedAt:`2026-04-01T00:00:00Z`},{label:`NPS`,value:41,unit:`score`,recordedAt:`2026-04-01T00:00:00Z`}],null,2)}};function Tg(e,t){if(!e||!e.trim())return t;try{return JSON.parse(e)}catch{return t}}function Eg(){return globalThis.crypto?.randomUUID?.()??`run-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function Dg({onResult:e,onError:t,onRunStart:n}){let[r,i]=(0,b.useState)(Sg),[a,o]=(0,b.useState)(Cg),[s,c]=(0,b.useState)(`[]`),[l,u]=(0,b.useState)(!1),[d,f]=(0,b.useState)(0),[p,m]=(0,b.useState)(null),h=e=>{let t=wg[e];t&&(i(t.subject),o(t.intervention),c(t.signalsJson),m(e))},g=()=>{i(Sg),o(Cg),c(`[]`),m(null)},_=r.id.trim().length>0&&r.name.trim().length>0&&a.id.trim().length>0&&a.name.trim().length>0&&a.description.trim().length>0;return(0,x.jsxs)(`div`,{className:G.card,children:[(0,x.jsxs)(`div`,{className:G.heading,children:[(0,x.jsx)(`h3`,{className:G.title,children:`Run a digital twin`}),(0,x.jsx)(`span`,{className:G.eyebrow,children:`any subject · any intervention`})]}),(0,x.jsx)(`p`,{className:G.copy,children:`Define a subject (patient, market segment, jurisdiction, vehicle, anything) and an intervention to apply to it. Paracosm runs a real LLM-driven simulation across a five-department analysis team and returns a typed RunArtifact with the trajectory.`}),(0,x.jsxs)(`div`,{className:G.presetRow,children:[(0,x.jsx)(`span`,{className:G.presetLabel,children:`Examples`}),Object.entries(wg).map(([e,t])=>(0,x.jsx)(`button`,{type:`button`,onClick:()=>h(e),className:`${G.presetButton} ${p===e?G.presetButtonActive:``}`,disabled:l,children:t.label},e)),(0,x.jsx)(`button`,{type:`button`,onClick:g,className:G.presetClear,disabled:l,children:`Clear`})]}),p&&(0,x.jsx)(`p`,{className:G.presetBlurb,children:wg[p].blurb}),(0,x.jsxs)(`div`,{className:G.formGrid,children:[(0,x.jsxs)(`fieldset`,{className:G.formCell,disabled:l,children:[(0,x.jsx)(`legend`,{className:G.formLegend,children:`Subject`}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`ID`}),(0,x.jsx)(`input`,{type:`text`,value:r.id,onChange:e=>i(t=>({...t,id:e.target.value})),placeholder:`patient-001`,className:G.input})]}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Name`}),(0,x.jsx)(`input`,{type:`text`,value:r.name,onChange:e=>i(t=>({...t,name:e.target.value})),placeholder:`Maria Chen`,className:G.input})]}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Description`}),(0,x.jsx)(`textarea`,{value:r.description,onChange:e=>i(t=>({...t,description:e.target.value})),placeholder:`Age, key attributes, baseline state.`,className:G.textarea,rows:3})]}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Profile (JSON)`}),(0,x.jsx)(`textarea`,{value:r.profileJson,onChange:e=>i(t=>({...t,profileJson:e.target.value})),placeholder:`{"age": 58, "bmi": 31}`,className:`${G.textarea} ${G.mono}`,rows:5,spellCheck:!1})]}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Signals (JSON)`}),(0,x.jsx)(`textarea`,{value:s,onChange:e=>c(e.target.value),placeholder:`[{"label":"HbA1c","value":7.8,"unit":"%"}]`,className:`${G.textarea} ${G.mono}`,rows:4,spellCheck:!1})]})]}),(0,x.jsxs)(`fieldset`,{className:G.formCell,disabled:l,children:[(0,x.jsx)(`legend`,{className:G.formLegend,children:`Intervention`}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`ID`}),(0,x.jsx)(`input`,{type:`text`,value:a.id,onChange:e=>o(t=>({...t,id:e.target.value})),placeholder:`semaglutide-12wk`,className:G.input})]}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Name`}),(0,x.jsx)(`input`,{type:`text`,value:a.name,onChange:e=>o(t=>({...t,name:e.target.value})),placeholder:`12-week semaglutide protocol`,className:G.input})]}),(0,x.jsxs)(`label`,{className:G.field,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Description`}),(0,x.jsx)(`textarea`,{value:a.description,onChange:e=>o(t=>({...t,description:e.target.value})),placeholder:`What is being applied, by whom, with what monitoring.`,className:G.textarea,rows:5})]}),(0,x.jsxs)(`div`,{className:G.fieldRow,children:[(0,x.jsxs)(`label`,{className:`${G.field} ${G.fieldThird}`,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Duration`}),(0,x.jsx)(`input`,{type:`number`,min:`1`,value:a.durationValue,onChange:e=>o(t=>({...t,durationValue:e.target.value})),className:G.input})]}),(0,x.jsxs)(`label`,{className:`${G.field} ${G.fieldThird}`,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Unit`}),(0,x.jsxs)(`select`,{value:a.durationUnit,onChange:e=>o(t=>({...t,durationUnit:e.target.value})),className:G.input,children:[(0,x.jsx)(`option`,{value:`days`,children:`days`}),(0,x.jsx)(`option`,{value:`weeks`,children:`weeks`}),(0,x.jsx)(`option`,{value:`months`,children:`months`}),(0,x.jsx)(`option`,{value:`quarters`,children:`quarters`}),(0,x.jsx)(`option`,{value:`years`,children:`years`})]})]}),(0,x.jsxs)(`label`,{className:`${G.field} ${G.fieldThird}`,children:[(0,x.jsx)(`span`,{className:G.fieldLabel,children:`Adherence`}),(0,x.jsx)(`input`,{type:`number`,min:`0`,max:`1`,step:`0.05`,value:a.adherence,onChange:e=>o(t=>({...t,adherence:e.target.value})),className:G.input})]})]})]})]}),(0,x.jsxs)(`div`,{className:G.actions,children:[(0,x.jsx)(`button`,{onClick:async()=>{if(l||!_)return;let i=Tg(r.profileJson,{}),o=Tg(s,[]),c={id:r.id.trim(),name:r.name.trim(),profile:r.description.trim()?{...i,description:r.description.trim()}:i,signals:o,markers:[]},d=Number(a.durationValue),p=Number(a.adherence),m={id:a.id.trim(),name:a.name.trim(),description:a.description.trim(),duration:Number.isFinite(d)&&d>0?{value:d,unit:a.durationUnit.trim()||`weeks`}:void 0,adherenceProfile:Number.isFinite(p)?{expected:Math.max(0,Math.min(1,p))}:void 0};u(!0),f(0);let h=Date.now(),g=window.setInterval(()=>{f(Math.round((Date.now()-h)/1e3))},500),v=Eg();await n?.({runKey:v,subject:{id:c.id,name:c.name,profile:c.profile},intervention:{id:m.id,name:m.name,description:m.description,duration:m.duration}});try{let t=await fetch(`/api/quickstart/simulate-intervention`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({subject:c,intervention:m,runKey:v,options:{maxTurns:2,seed:11,costPreset:`economy`},...bg(_g(window.localStorage))})});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.error??`Digital twin run failed: HTTP ${t.status}`)}let n=await t.json();k(window,n.visitorId),e(n.artifact,v)}catch(e){t?.(e instanceof Error?e.message:String(e),v)}finally{window.clearInterval(g),u(!1)}},disabled:l||!_,className:G.button,children:l?`Running…`:`Run digital twin`}),l?(0,x.jsxs)(`span`,{className:G.timer,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:G.spinner,"aria-hidden":`true`}),d,`s elapsed · 2 turns × LLM decisions, typically 40-90s`]}):(0,x.jsx)(`span`,{className:G.helper,children:`2 turns · seed 11 · economy preset`})]})]})}function Og(e,t){return e===`loading`?`loading`:e===`error`?`error`:e===`unavailable`?`unavailable`:t.length===0?`empty`:`cards`}function kg(e,t){let n=new URL(e);return n.searchParams.set(`replay`,t),n.searchParams.set(`tab`,`sim`),n.toString()}var Ag={card:`_card_1qdw6_1`,eyebrow:`_eyebrow_1qdw6_27`,row:`_row_1qdw6_36`,actor:`_actor_1qdw6_45`,arrow:`_arrow_1qdw6_56`,meta:`_meta_1qdw6_62`};function jg(){let{sessions:e}=Oe(),t=e[0]?.id?e[0]:null;if(!t)return null;let n=typeof window<`u`?kg(window.location.href,t.id):`?replay=${encodeURIComponent(t.id)}`,r=t.seedText?t.seedText.length>70?`${t.seedText.slice(0,70).trim()}…`:t.seedText.trim():null,i=Rn(t,3),a=t.title||t.scenarioName||i||r||t.id,o=[t.scenarioName&&t.scenarioName!==a?t.scenarioName:null,typeof t.eventCount==`number`?`${t.eventCount} events`:null,typeof t.durationMs==`number`?`${Math.round(t.durationMs/1e3)}s`:null,typeof t.createdAt==`number`?new Date(t.createdAt).toISOString().slice(0,10):null].filter(e=>typeof e==`string`&&e.length>0).join(` · `);return(0,x.jsxs)(`a`,{className:Ag.card,href:n,"aria-label":`Replay last run: ${a}`,children:[(0,x.jsx)(`span`,{className:Ag.eyebrow,children:`Replay last run`}),(0,x.jsxs)(`span`,{className:Ag.row,children:[(0,x.jsx)(`span`,{className:Ag.actor,children:a}),(0,x.jsx)(`span`,{className:Ag.arrow,"aria-hidden":`true`,children:`▶`})]}),o&&(0,x.jsx)(`span`,{className:Ag.meta,children:o})]})}var Mg={card:`_card_14dqa_7`,statusPending:`_statusPending_14dqa_18`,statusActive:`_statusActive_14dqa_22`,statusDone:`_statusDone_14dqa_27`,header:`_header_14dqa_31`,marker:`_marker_14dqa_60`,pulseDot:`_pulseDot_14dqa_1`,label:`_label_14dqa_93`,duration:`_duration_14dqa_100`,count:`_count_14dqa_121`,chevron:`_chevron_14dqa_137`,chevronOpen:`_chevronOpen_14dqa_148`,actorChips:`_actorChips_14dqa_164`,actorChip:`_actorChip_14dqa_164`,actorChipName:`_actorChipName_14dqa_190`,actorChipState:`_actorChipState_14dqa_194`,actor_running:`_actor_running_14dqa_203`,actor_complete:`_actor_complete_14dqa_212`,actor_error:`_actor_error_14dqa_221`,actor_aborted:`_actor_aborted_14dqa_230`,body:`_body_14dqa_241`,line:`_line_14dqa_266`,lineTs:`_lineTs_14dqa_283`,lineGlyph:`_lineGlyph_14dqa_290`,lineTag:`_lineTag_14dqa_296`,lineActor:`_lineActor_14dqa_309`,lineBody:`_lineBody_14dqa_324`,tonePending:`_tonePending_14dqa_332`,toneInfo:`_toneInfo_14dqa_336`,toneActive:`_toneActive_14dqa_345`,toneDone:`_toneDone_14dqa_358`,toneWarn:`_toneWarn_14dqa_367`,toneError:`_toneError_14dqa_380`},Ng={running:`RUNNING`,complete:`COMPLETE`,error:`ERROR`,aborted:`ABORTED`};function Pg({stageId:e,label:t,status:n,logLines:r,duration:i,actors:a}){let[o,s]=(0,b.useState)(n!==`pending`),c=(0,b.useRef)(null),l=(0,b.useRef)(!0);(0,b.useEffect)(()=>{(n===`active`||n===`done`)&&s(e=>e||!0)},[n]);let u=()=>{let e=c.current;e&&(l.current=e.scrollHeight-e.scrollTop-e.clientHeight<40)};(0,b.useEffect)(()=>{if(!l.current)return;let e=c.current;e&&(e.scrollTop=e.scrollHeight)},[r.length]);let d=n===`done`?`✓`:n===`active`?`●`:`○`,f=n===`done`?Mg.statusDone:n===`active`?Mg.statusActive:Mg.statusPending,p=e===`running`,m=r.length;return(0,x.jsxs)(`div`,{className:`${Mg.card} ${f}`,"data-stage":e,"data-status":n,children:[(0,x.jsxs)(`button`,{type:`button`,className:Mg.header,"aria-expanded":o,"aria-controls":`stage-${e}-body`,onClick:()=>s(e=>!e),children:[(0,x.jsx)(`span`,{className:Mg.marker,"aria-hidden":`true`,children:d}),(0,x.jsx)(`span`,{className:Mg.label,children:t}),i&&(0,x.jsx)(`span`,{className:Mg.duration,children:i}),m>0&&(0,x.jsx)(`span`,{className:Mg.count,"aria-label":`${m} events`,children:m}),(0,x.jsx)(`span`,{className:`${Mg.chevron} ${o?Mg.chevronOpen:``}`,"aria-hidden":`true`})]}),p&&a&&a.length>0&&(0,x.jsx)(`div`,{className:Mg.actorChips,children:a.map(e=>(0,x.jsxs)(`span`,{className:`${Mg.actorChip} ${Mg[`actor_${e.status}`]}`,title:`${e.name} · ${e.archetype}`,children:[(0,x.jsx)(`span`,{className:Mg.actorChipName,children:e.name}),(0,x.jsx)(`span`,{className:Mg.actorChipState,children:e.status===`running`?`T${e.currentTurn}/${e.maxTurns}`:Ng[e.status]})]},e.name))}),o&&(0,x.jsxs)(`div`,{id:`stage-${e}-body`,className:Mg.body,ref:c,onScroll:u,role:`log`,"aria-live":n===`active`?`polite`:`off`,"aria-label":`${t} log`,children:[r.length===0&&(0,x.jsxs)(`div`,{className:`${Mg.line} ${Mg.tonePending}`,children:[(0,x.jsx)(`span`,{className:Mg.lineTs,children:`—`}),(0,x.jsx)(`span`,{className:Mg.lineGlyph,children:`·`}),(0,x.jsx)(`span`,{className:Mg.lineBody,children:n===`pending`?`Waiting for previous stage…`:`No events yet.`})]}),r.map((e,t)=>(0,x.jsxs)(`div`,{className:`${Mg.line} ${Mg[`tone${Fg(e.tone)}`]}`,children:[(0,x.jsx)(`span`,{className:Mg.lineTs,children:e.ts}),(0,x.jsx)(`span`,{className:Mg.lineGlyph,children:e.glyph}),e.tag&&(0,x.jsx)(`span`,{className:Mg.lineTag,children:e.tag}),e.actor&&(0,x.jsx)(`span`,{className:Mg.lineActor,children:e.actor}),(0,x.jsx)(`span`,{className:Mg.lineBody,children:e.body})]},t))]})]})}function Fg(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Ig(e){(!Number.isFinite(e)||e<0)&&(e=0);let t=e/1e3,n=Math.floor(t/60),r=Math.floor(t%60),i=Math.floor(t*10%10);return`${n}:${String(r).padStart(2,`0`)}.${i}`}function Lg(e){return e===`turn_start`||e===`turn_done`?`active`:e===`specialist_done`||e===`sim_complete`||e===`agent_reactions`?`done`:e===`decision_pending`||e===`decision_made`||e===`outcome`?`info`:e===`sim_aborted`||e===`provider_error`||e===`validation_fallback`?`warn`:`info`}function Rg(e){switch(e){case`turn_start`:return`TURN`;case`turn_done`:return`TURN`;case`specialist_start`:return`SPEC`;case`specialist_done`:return`SPEC`;case`decision_pending`:return`DEC`;case`decision_made`:return`DEC`;case`outcome`:return`OUT`;case`agent_reactions`:return`REACT`;case`bulletin`:return`NEWS`;case`promotion`:return`PROMO`;case`systems_snapshot`:return`SNAP`;case`drift`:return`DRIFT`;case`personality_drift`:return`DRIFT`;case`sim_aborted`:return`ABORT`;case`provider_error`:return`ERR`;case`validation_fallback`:return`FALLBACK`;case`sim_complete`:return`DONE`;default:return e.toUpperCase().slice(0,8)}}function zg(e){let t=e.data??{};return(typeof t.summary==`string`?t.summary:``)||(typeof t.department==`string`?t.department:typeof t.title==`string`?t.title:typeof t.decision==`string`?t.decision:typeof t.outcome==`string`?t.outcome:typeof t.eventType==`string`?t.eventType:typeof t.tool==`string`?t.tool:``)}function Bg(e){if(e.type===`status`)return null;let t=e.turn??e.data?.turn,n=e.leader||e.data?.actor,r=zg(e)||`${e.type} fired`;return{ts:typeof t==`number`?`T${t}`:`—`,glyph:e.type===`turn_done`?`✓`:e.type===`turn_start`?`→`:`·`,tag:e.type===`validation_fallback`&&e.data?.salvaged===!0?`SALVAGE`:Rg(e.type),body:r,tone:Lg(e.type),actor:typeof n==`string`?n:void 0}}function Vg(e){let{stage:t,startMs:n,phaseTransitionMs:r}=e,i=[],a=r?.compile??n;i.push({ts:Ig(a-n),glyph:`→`,tag:`POST`,body:`/api/quickstart/compile-from-seed`,tone:t===`compile`?`active`:`info`});let o=r?.research;return o&&i.push({ts:Ig(o-n),glyph:`✓`,tag:`OK`,body:`ScenarioPackage validated · departments + crisis templates derived`,tone:`done`}),i}function Hg(e){let{stage:t,startMs:n,phaseTransitionMs:r,groundingSummary:i}=e,a=[],o=r?.research;if(!o)return a;let s=Ig(o-n);if(i?.skipped)return a.push({ts:s,glyph:`⚠`,tag:`SKIP`,body:`Deep research skipped: ${i.reason??`unknown`}`,tone:`warn`}),a;if(i?.citations&&i.citations.length>0){let e=i.providersUsed?.length?` · providers: ${i.providersUsed.join(` + `)}`:``;a.push({ts:s,glyph:`→`,tag:`POST`,body:`/api/quickstart/ground-scenario · ${i.citations.length} queries${e}`,tone:t===`research`?`active`:`info`});for(let e of i.providersFailed??[])a.push({ts:s,glyph:`⚠`,tag:e.provider.toUpperCase().slice(0,8),body:`provider unavailable: ${e.reason.slice(0,120)}`,tone:`warn`});for(let e of i.citations){a.push({ts:s,glyph:`·`,tag:`QUERY`,body:`"${e.query}" → ${e.sources.length} source${e.sources.length===1?``:`s`}`,tone:`info`});for(let t of e.sources.slice(0,3)){let e=(t.provider??``).toUpperCase()||t.domain.toUpperCase().slice(0,16)||`SRC`;a.push({ts:s,glyph:`·`,tag:e,body:t.title,tone:`done`})}}if(typeof i.totalSources==`number`){let e=typeof i.durationMs==`number`?` · ${(i.durationMs/1e3).toFixed(1)}s`:``;a.push({ts:s,glyph:`✓`,tag:`OK`,body:`${i.totalSources} unique sources attached to ScenarioPackage${e}`,tone:`done`})}return a}a.push({ts:s,glyph:`·`,tag:`NOTE`,body:`Grounding scenario with web research…`,tone:t===`research`?`active`:`info`});let c=r?.actors;return c&&a.push({ts:Ig(c-n),glyph:`✓`,tag:`OK`,body:`Citations attached to ScenarioPackage`,tone:`done`}),a}function Ug(e){let{stage:t,startMs:n,phaseTransitionMs:r,actorCount:i}=e,a=[],o=r?.actors;if(!o)return a;a.push({ts:Ig(o-n),glyph:`→`,tag:`POST`,body:`/api/quickstart/generate-actors · count=${i}`,tone:t===`actors`?`active`:`info`});let s=r?.running;return s&&a.push({ts:Ig(s-n),glyph:`✓`,tag:`OK`,body:`${i} actor${i===1?``:`s`} generated · HEXACO traits + archetypes validated`,tone:`done`}),a}function Wg(e){return e.events.map(e=>Bg(e)).filter(e=>!!e)}function Gg(e,t){switch(e){case`compile`:return Vg(t);case`research`:return Hg(t);case`actors`:return Ug(t);case`running`:return Wg(t);case`done`:return[]}}function Kg(e,t){let n=[`compile`,`research`,`actors`,`running`,`done`],r=n.indexOf(e),i=t.phaseTransitionMs?.[e],a=n[r+1],o=a?t.phaseTransitionMs?.[a]:void 0;if(!i)return``;let s=((o??Date.now())-i)/1e3;return s<1?`${Math.max(1,Math.round(s*1e3))}ms`:s<10?`${s.toFixed(1)}s`:`${Math.round(s)}s`}var qg={progress:`_progress_5dmny_6`,heading:`_heading_5dmny_19`,title:`_title_5dmny_26`,subtitle:`_subtitle_5dmny_35`,stageList:`_stageList_5dmny_43`,stageItem:`_stageItem_5dmny_55`,cancel:`_cancel_5dmny_59`,jumpToSim:`_jumpToSim_5dmny_84`},Jg=[`compile`,`research`,`actors`,`running`,`done`];function Yg(e,t){let n=Jg.indexOf(e),r=Jg.indexOf(t);return n>r?`done`:n===r?`active`:`pending`}function Xg({stage:e,actors:t,events:n,actorCount:r,groundingSummary:i,onCancel:a}){let o=(0,b.useRef)(Date.now()),[s,c]=(0,b.useState)(()=>({compile:Date.now()})),l=(0,b.useRef)(e);(0,b.useEffect)(()=>{l.current!==e&&(l.current=e,c(t=>t[e]?t:{...t,[e]:Date.now()}))},[e]);let[,u]=(0,b.useState)(0);(0,b.useEffect)(()=>{if(e===`done`)return;let t=setInterval(()=>u(e=>(e+1)%1e6),1e3);return()=>clearInterval(t)},[e]);let d=r??t?.length??3,f=nA(),p=(0,b.useMemo)(()=>({stage:e,startMs:o.current,phaseTransitionMs:s,actorCount:d,events:n??[],groundingSummary:i??null}),[e,s,d,n,i]),m=[{id:`compile`,label:`Compile scenario`},{id:`research`,label:`Ground with citations`},{id:`actors`,label:`Generate ${d} actor${d===1?``:`s`}`},{id:`running`,label:`Run ${d} simulation${d===1?``:`s`}`}];return(0,x.jsxs)(`section`,{className:qg.progress,role:`region`,"aria-label":`Quickstart progress`,children:[(0,x.jsxs)(`header`,{className:qg.heading,children:[(0,x.jsx)(`span`,{className:qg.title,children:`Quickstart run`}),(0,x.jsx)(`span`,{className:qg.subtitle,children:`Live trace of every step from seed text to ready-to-explore artifacts.`})]}),(0,x.jsx)(`ol`,{className:qg.stageList,children:m.map(n=>{let r=Yg(e,n.id);return(0,x.jsx)(`li`,{className:qg.stageItem,children:(0,x.jsx)(Pg,{stageId:n.id,label:n.label,status:r,logLines:Gg(n.id,p),duration:Kg(n.id,p),actors:n.id===`running`?t:void 0})},n.id)})}),(e===`running`||e===`done`)&&(0,x.jsx)(`button`,{type:`button`,className:qg.jumpToSim,onClick:()=>f(`sim`),children:`Jump to live SIM →`}),a&&e!==`done`&&(0,x.jsx)(`button`,{type:`button`,className:qg.cancel,onClick:a,children:`Cancel run`})]})}var Zg=Object.freeze({visionary:{id:`visionary`,name:`Aria Okafor`,archetype:`The Visionary`,description:`Bets on bold experiments. Tolerates ambiguity. Casts a wide pattern net.`,hexaco:{openness:.95,conscientiousness:.35,extraversion:.85,agreeableness:.55,emotionality:.3,honestyHumility:.65}},pragmatist:{id:`pragmatist`,name:`Marcus Reyes`,archetype:`The Pragmatist`,description:`Leads by protocol and evidence. Safety margins first.`,hexaco:{openness:.4,conscientiousness:.9,extraversion:.35,agreeableness:.6,emotionality:.5,honestyHumility:.85}},innovator:{id:`innovator`,name:`Yuki Tanaka`,archetype:`The Innovator`,description:`Pushes novel tool forging. Accepts higher variance.`,hexaco:{openness:.9,conscientiousness:.4,extraversion:.7,agreeableness:.45,emotionality:.35,honestyHumility:.55}},stabilizer:{id:`stabilizer`,name:`Elena Voss`,archetype:`The Stabilizer`,description:`Holds the line. Protects existing capacity. Change-averse.`,hexaco:{openness:.3,conscientiousness:.85,extraversion:.4,agreeableness:.75,emotionality:.55,honestyHumility:.7}},"crisis-manager":{id:`crisis-manager`,name:`Nadia Chen`,archetype:`The Crisis Manager`,description:`Thrives under pressure. Decisive. Low emotional reactivity.`,hexaco:{openness:.55,conscientiousness:.8,extraversion:.75,agreeableness:.45,emotionality:.25,honestyHumility:.6}},"growth-optimist":{id:`growth-optimist`,name:`Diego Santoro`,archetype:`The Growth Optimist`,description:`Chases expansion. High risk tolerance. Charismatic rally-er.`,hexaco:{openness:.8,conscientiousness:.5,extraversion:.9,agreeableness:.55,emotionality:.35,honestyHumility:.4}},"protocol-builder":{id:`protocol-builder`,name:`Priya Rao`,archetype:`The Protocol Builder`,description:`Codifies everything. Demands evidence. Slow to decide, hard to dislodge.`,hexaco:{openness:.5,conscientiousness:.95,extraversion:.35,agreeableness:.6,emotionality:.45,honestyHumility:.9}},"social-architect":{id:`social-architect`,name:`Kai Rivers`,archetype:`The Social Architect`,description:`Builds coalitions. Manages morale. Relationship-first.`,hexaco:{openness:.6,conscientiousness:.65,extraversion:.8,agreeableness:.9,emotionality:.55,honestyHumility:.7}},"cost-cutter":{id:`cost-cutter`,name:`Hannah Novak`,archetype:`The Cost Cutter`,description:`Optimizes ruthlessly. Will trade morale for capacity.`,hexaco:{openness:.35,conscientiousness:.9,extraversion:.45,agreeableness:.3,emotionality:.25,honestyHumility:.55}},"compliance-hawk":{id:`compliance-hawk`,name:`Owen Ibarra`,archetype:`The Compliance Hawk`,description:`Audits every decision. Never cuts corners. Reports failures transparently.`,hexaco:{openness:.4,conscientiousness:.9,extraversion:.45,agreeableness:.65,emotionality:.5,honestyHumility:.95}}}),Qg={backdrop:`_backdrop_fgbmo_1`,dialog:`_dialog_fgbmo_12`,header:`_header_fgbmo_23`,list:`_list_fgbmo_47`,preset:`_preset_fgbmo_56`,archetype:`_archetype_fgbmo_82`,description:`_description_fgbmo_87`};function $g({onSelect:e,onClose:t}){let n=Pt(!0);return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Swap leader`,className:Qg.backdrop,onClick:t,children:(0,x.jsxs)(`div`,{ref:n,tabIndex:-1,className:Qg.dialog,onClick:e=>e.stopPropagation(),children:[(0,x.jsxs)(`header`,{className:Qg.header,children:[(0,x.jsx)(`h3`,{children:`Swap leader`}),(0,x.jsx)(`button`,{type:`button`,onClick:t,"aria-label":`Close`,children:`×`})]}),(0,x.jsx)(`ul`,{className:Qg.list,children:Object.values(Zg).map(t=>(0,x.jsx)(`li`,{children:(0,x.jsxs)(`button`,{type:`button`,onClick:()=>e(t),className:Qg.preset,children:[(0,x.jsx)(`strong`,{children:t.name}),(0,x.jsx)(`span`,{className:Qg.archetype,children:t.archetype}),(0,x.jsx)(`span`,{className:Qg.description,children:t.description})]})},t.id))})]})})}var e_={results:`_results_8jenm_2`,runSummary:`_runSummary_8jenm_15`,summaryStat:`_summaryStat_8jenm_26`,summaryNum:`_summaryNum_8jenm_40`,summaryLabel:`_summaryLabel_8jenm_50`,grid:`_grid_8jenm_61`,card:`_card_8jenm_81`,cardHeader:`_cardHeader_8jenm_92`,actorName:`_actorName_8jenm_106`,archetype:`_archetype_8jenm_110`,swap:`_swap_8jenm_119`,hexaco:`_hexaco_8jenm_142`,trait:`_trait_8jenm_151`,traitLabel:`_traitLabel_8jenm_160`,traitBarOuter:`_traitBarOuter_8jenm_168`,traitBarInner:`_traitBarInner_8jenm_175`,fingerprint:`_fingerprint_8jenm_180`,deltas:`_deltas_8jenm_192`,delta:`_delta_8jenm_192`,direction_up:`_direction_up_8jenm_209`,direction_down:`_direction_down_8jenm_213`,direction_changed:`_direction_changed_8jenm_217`,actions:`_actions_8jenm_222`,forkButton:`_forkButton_8jenm_249`,forkHint:`_forkHint_8jenm_259`},t_=[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`];function n_({actors:e,artifacts:t,sessionId:n,onSwap:r}){let{dispatch:i}=Gn(),a=nA(),o=Lm(),[s,c]=(0,b.useState)(null),l=on(),u=l.clear,[d,f]=(0,b.useState)(null);(0,b.useEffect)(()=>{u()},[n,u]);let p=e=>{i({type:`SET_PARENT`,artifact:t[e]}),a(`studio`)},m=e=>{n&&(f(e),l.share(vh(window.location.origin,n)))},h=n=>{let r=t[n],i=e[n]??{},a=typeof i.archetype==`string`?i.archetype:``,o=typeof i.name==`string`?i.name:``;yh(r,`paracosm-quickstart-${a.toLowerCase().replace(/\s+/g,`-`)||o.toLowerCase().replace(/\s+/g,`-`)||`actor-${n}`}.json`)},g=(0,b.useMemo)(()=>({totalTools:t.reduce((e,t)=>e+(t?.forgedTools?.length??0),0),totalCitations:t.reduce((e,t)=>e+(t?.citations?.length??0),0),totalDecisions:t.reduce((e,t)=>e+(t?.decisions?.length??0),0),totalTurns:t.reduce((e,t)=>e+(t?.trajectory?.timepoints?.length??0),0),totalCostUSD:t.reduce((e,t)=>e+(t?.cost?.totalUSD??0),0)}),[t]);return(0,x.jsxs)(`div`,{className:e_.results,role:`region`,"aria-label":`Quickstart results`,children:[(0,x.jsxs)(`div`,{className:e_.runSummary,role:`region`,"aria-label":`Run summary`,children:[(0,x.jsxs)(`div`,{className:e_.summaryStat,title:`Web sources Paracosm pulled via Serper + Tavily and attached to the scenario before generating actors. Grounds the sim in real-world knowledge instead of pure LLM imagination.`,children:[(0,x.jsx)(`span`,{className:e_.summaryNum,children:g.totalCitations}),(0,x.jsx)(`span`,{className:e_.summaryLabel,children:`citations · web research`})]}),(0,x.jsxs)(`div`,{className:e_.summaryStat,title:`AgentOS tool forging: when a department needed a calculation the codebase didn't provide, it wrote one at runtime, run in a QuickJS WebAssembly sandbox. The judge reviewed each for safety + correctness before letting it enter the decision pipeline.`,children:[(0,x.jsx)(`span`,{className:e_.summaryNum,children:g.totalTools}),(0,x.jsx)(`span`,{className:e_.summaryLabel,children:`tools forged · AgentOS sandbox`})]}),(0,x.jsxs)(`div`,{className:e_.summaryStat,title:`Commander decisions across all 3 actors. Each one went through the full propose / judge / execute cycle.`,children:[(0,x.jsx)(`span`,{className:e_.summaryNum,children:g.totalDecisions}),(0,x.jsx)(`span`,{className:e_.summaryLabel,children:`commander decisions`})]}),(0,x.jsxs)(`div`,{className:e_.summaryStat,title:`Total simulation turns across all 3 parallel actors. Each turn = one decision cycle: department analysis, commander decision, kernel advance, agent reactions.`,children:[(0,x.jsx)(`span`,{className:e_.summaryNum,children:g.totalTurns}),(0,x.jsx)(`span`,{className:e_.summaryLabel,children:`turns simulated`})]}),g.totalCostUSD>0&&(0,x.jsxs)(`div`,{className:e_.summaryStat,title:`Total LLM spend across all 3 actors. Provider: gpt-5.4-mini for sims, gpt-4o for verdict.`,children:[(0,x.jsxs)(`span`,{className:e_.summaryNum,children:[`$`,g.totalCostUSD.toFixed(2)]}),(0,x.jsx)(`span`,{className:e_.summaryLabel,children:`LLM cost`})]})]}),(0,x.jsx)(`div`,{className:e_.grid,children:e.map((e,r)=>{let i=t[r];return i?(0,x.jsx)(r_,{actor:e,artifact:i,peers:t.filter((e,t)=>t!==r&&!!e),timeLabel:o.time,timeLabelCap:o.Time,shareEnabled:!!n,onDownload:()=>h(r),onShare:()=>m(r),shareNote:d===r&&l.shared?(0,x.jsx)(dn,{shared:l.shared,onClose:l.clear}):null,onFork:()=>p(r),onRequestSwap:()=>c(r)},r):null})}),s!==null&&(0,x.jsx)($g,{onSelect:e=>{r(s,e),c(null)},onClose:()=>c(null)})]})}function r_({actor:e,artifact:t,peers:n,timeLabel:r,timeLabelCap:i,shareEnabled:a,shareNote:o,onDownload:s,onShare:c,onFork:l,onRequestSwap:u}){let d=(0,b.useMemo)(()=>_h(t,n),[t,n]),f=t.trajectory?.timepoints?.length??0;return(0,x.jsxs)(`article`,{className:e_.card,children:[(0,x.jsxs)(`header`,{className:e_.cardHeader,children:[(0,x.jsx)(`h4`,{className:e_.actorName,children:e.name}),(0,x.jsx)(`span`,{className:e_.archetype,children:e.archetype}),(0,x.jsx)(`button`,{type:`button`,className:e_.swap,onClick:u,"aria-label":`Swap ${e.name}`,children:`Swap`})]}),(0,x.jsx)(`div`,{className:e_.hexaco,children:t_.map(t=>(0,x.jsxs)(`div`,{className:e_.trait,children:[(0,x.jsx)(`span`,{className:e_.traitLabel,children:t.slice(0,4).toUpperCase()}),(0,x.jsx)(`div`,{className:e_.traitBarOuter,children:(0,x.jsx)(`div`,{className:e_.traitBarInner,style:{width:`${Math.round((e.hexaco?.[t]??.5)*100)}%`}})})]},t))}),(0,x.jsxs)(`div`,{className:e_.fingerprint,children:[(0,x.jsx)(`span`,{children:`FP`}),(0,x.jsx)(`code`,{children:t.fingerprint?Object.values(t.fingerprint).slice(0,3).join(` / `):`n/a`})]}),d.length>0&&(0,x.jsx)(`ul`,{className:e_.deltas,"aria-label":`Delta vs peer median`,children:d.slice(0,4).map(e=>(0,x.jsx)(`li`,{className:`${e_.delta} ${e_[`direction_${e.direction}`]}`,children:Bm(e)},`${e.bag}.${e.key}`))}),(0,x.jsxs)(`div`,{className:e_.actions,children:[(0,x.jsx)(`button`,{type:`button`,onClick:s,children:`Download JSON`}),(0,x.jsx)(`button`,{type:`button`,onClick:c,disabled:!a,title:`Copy a deep link that opens this run on the visualization tab`,children:`Copy viz share link`}),(0,x.jsx)(`button`,{type:`button`,onClick:l,disabled:f===0,className:e_.forkButton,title:f===0?`No turns completed yet`:`Promote to fork root and open Branches tab. ${f} ${f===1?r:`${r}s`} available.`,children:`Fork in Branches →`})]}),o,(0,x.jsx)(`div`,{className:e_.forkHint,children:f>0?`${f} ${i}${f===1?``:`s`} available for forking`:``})]})}var i_=2e3,a_=3e5;function o_(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new DOMException(`Aborted`,`AbortError`));return}let i=setTimeout(()=>{t?.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),r(new DOMException(`Aborted`,`AbortError`))};t?.addEventListener(`abort`,a,{once:!0})})}async function s_(e){let t=await e.text(),n;try{n=t?JSON.parse(t):null}catch{throw Error(`Compile returned non-JSON HTTP ${e.status} response`)}if(!e.ok&&(!n||typeof n!=`object`))throw Error(`Compile failed: HTTP ${e.status}`);if(!n||typeof n!=`object`)throw Error(`Compile returned empty body`);return n}async function c_(e,t={}){let n=t.fetchImpl??fetch,r=t.pollIntervalMs??i_,i=t.timeoutMs??a_,a=t.waitImpl??o_,o=Date.now(),s=await n(`/api/quickstart/compile-from-seed`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e),signal:t.signal});if(!s.ok&&s.status!==202){let e=await s.json().catch(()=>({}));throw Error(e.error??`Compile failed: HTTP ${s.status}`)}let c=await s_(s);if(c.status===`done`&&c.scenario)return{scenario:c.scenario,scenarioId:c.scenario.id,jobId:c.jobId};if(c.status===`error`)throw Error(c.error??`Compile failed`);for(;Date.now()-o<i;){await a(r,t.signal);let e=await n(`/api/quickstart/compile-from-seed/status`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({jobId:c.jobId}),signal:t.signal});if(!e.ok){if(e.status===404)throw Error(`Compile job expired or not found. Please retry.`);let t=await e.json().catch(()=>({}));throw Error(t.error??`Compile status check failed: HTTP ${e.status}`)}let i=await s_(e);if(i.status===`done`&&i.scenario)return{scenario:i.scenario,scenarioId:i.scenario.id,jobId:i.jobId};if(i.status===`error`)throw Error(i.error??`Compile failed`)}throw Error(`Compile is taking longer than ${Math.round(i/1e3)}s. The server may still be working — please retry in a minute.`)}var l_={view:`_view_1gdit_2`,header:`_header_1gdit_12`,howItWorks:`_howItWorks_1gdit_36`,glossary:`_glossary_1gdit_43`,timingHint:`_timingHint_1gdit_44`,howItWorksSummary:`_howItWorksSummary_1gdit_60`,errorBanner:`_errorBanner_1gdit_137`,compareCta:`_compareCta_1gdit_149`};function u_(e){return/Failed to fetch|NetworkError|ERR_CONNECTION|ERR_NETWORK/i.test(e)?`Couldn't reach the server. Check your connection and try again.`:/HTTP 502|HTTP 503|HTTP 504/.test(e)?`Server is temporarily unavailable (502/503/504). Try again in a moment.`:/HTTP 429|rate.?limit/i.test(e)?`Hosted demo is rate-limited (3 runs/day). Drop your own API key in Settings to bypass — your saved keys flow into the run automatically.`:/HTTP 401|HTTP 403|unauthor/i.test(e)?`Auth error talking to the LLM provider. Check your API key in Settings.`:/Two actors required|at least 2 actors/i.test(e)?`This scenario needs at least 2 actors. Bump the slider before launching.`:/TypeError|ReferenceError|Cannot read propert|is not a function|is not iterable/i.test(e)?(typeof console<`u`&&console.error(`[quickstart] launch error:`,e),`Something went wrong starting the run. Refresh the page and try again — if it keeps happening, drop a note in the GitHub issues with what you clicked just before.`):e}function d_({sse:e,sessionId:t,onRunStarted:n,onInterventionResult:r,onInterventionStart:i,onInterventionError:a}){let o=Qk(),s=eA(),{toast:c}=Ht(),[l,u]=(0,b.useState)({kind:`input`}),[d,f]=(0,b.useState)(null),[p,m]=(0,b.useState)(null),[h,g]=(0,b.useState)(!1),[_,v]=(0,b.useState)(null),y=`paracosm:catalogPendingRun`,S=(0,b.useCallback)(async t=>{f(null),n?.(),await e.reset();let r=typeof window<`u`?_g(window.localStorage):{},i=typeof window<`u`?dg(window.localStorage):null,a=bg(r),s={...a};r.serper&&(s.serperKey=r.serper),r.firecrawl&&(s.firecrawlKey=r.firecrawl),r.tavily&&(s.tavilyKey=r.tavily),r.cohere&&(s.cohereKey=r.cohere),i?.provider&&(s.provider=i.provider),i?.models&&typeof i.models==`object`&&(s.models=i.models),i?.economics&&typeof i.economics==`object`&&(s.economics=i.economics);let l=o.presets[0]?.leaders??o.presets[0]?.actors??[];if(l.length>=t){u({kind:`progress`,stage:`running`});let n=l.slice(0,t).map(e=>({name:e.name,archetype:e.archetype,hexaco:e.hexaco,instructions:e.instructions}));await e.reset(),typeof window<`u`&&mg(window.localStorage,n,o.id);try{let e=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...s,actors:n,turns:o.setup.defaultTurns,seed:o.setup.defaultSeed??42,captureSnapshots:!0,quickstart:{scenarioId:o.id}})});if(!e.ok){let t=await e.json().catch(()=>({}));throw Error(t.error??`Setup failed: HTTP ${e.status}`)}let t=await e.json().catch(()=>({}));if(t.redirect){try{window.localStorage.setItem(`paracosm:launchPending`,`1`)}catch{}window.location.href=fh(window.location.href,t.redirect);return}}catch(e){u({kind:`input`});let t=u_(e?.message??String(e));f(t),c(`error`,`Launch failed`,t,8e3)}}else{u({kind:`progress`,stage:`actors`});try{let n=await fetch(`/api/quickstart/generate-actors`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scenarioId:o.id,count:t,...a})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.error??`Actor generation failed: HTTP ${n.status}`)}let r=(await n.json().catch(()=>null))?.actors;if(!r||r.length===0)throw Error(`Actor generation returned no actors`);u({kind:`progress`,stage:`running`}),await e.reset(),typeof window<`u`&&mg(window.localStorage,r,o.id);let i=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...s,actors:r,turns:o.setup.defaultTurns,seed:o.setup.defaultSeed??42,captureSnapshots:!0,quickstart:{scenarioId:o.id}})});if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(e.error??`Setup failed: HTTP ${i.status}`)}let c=await i.json().catch(()=>({}));if(c.redirect){try{window.localStorage.setItem(`paracosm:launchPending`,`1`)}catch{}window.location.href=fh(window.location.href,c.redirect);return}}catch(e){u({kind:`input`});let t=u_(e?.message??String(e));f(t),c(`error`,`Launch failed`,t,8e3)}}},[o,e,n,c]),C=(0,b.useCallback)(async(e,t)=>{if(e===o.id)S(t);else{f(null),n?.();try{try{sessionStorage.setItem(y,JSON.stringify({scenarioId:e,actorCount:t,ts:Date.now()}))}catch{}let n=await fetch(`/scenario/switch`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:e})});if(!n.ok){try{sessionStorage.removeItem(y)}catch{}let e=await n.json().catch(()=>({}));throw Error(e.error??`Scenario switch failed: HTTP ${n.status}`)}te(),window.location.reload()}catch(e){try{sessionStorage.removeItem(y)}catch{}let t=u_(e?.message??String(e));f(t),c(`error`,`Scenario switch failed`,t,8e3)}}},[o.id,S,n,c]);(0,b.useEffect)(()=>{if(!s)return;let e=null;try{let t=sessionStorage.getItem(y);if(!t)return;sessionStorage.removeItem(y),e=JSON.parse(t)}catch{return}if(e?.scenarioId!==o.id){c(`error`,`Scenario changed`,`Another tab of this browser picked a different scenario before the run you picked could start, so nothing ran. Pick it in the catalog again.`,8e3);return}let t=typeof e?.actorCount==`number`&&e.actorCount>0?Math.min(300,Math.max(1,e.actorCount)):null;t!==null&&S(t)},[s]);let w=(0,b.useCallback)(async t=>{f(null),n?.(),await e.reset(),u({kind:`progress`,stage:`compile`});try{let n=typeof window<`u`?bg(_g(window.localStorage)):{},{scenario:r,scenarioId:i}=await c_({...t,...n});u({kind:`progress`,stage:`research`,scenario:r});try{let e=await fetch(`/api/quickstart/ground-scenario`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scenarioId:i})});if(e.ok){let t=await e.json();v(t)}}catch{v({skipped:!0,reason:`request failed`})}u({kind:`progress`,stage:`actors`,scenario:r});let a=Math.max(1,Math.min(300,t.actorCount??2)),o=await fetch(`/api/quickstart/generate-actors`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scenarioId:i,count:a,...n})});if(!o.ok){let e=await o.json().catch(()=>({}));throw Error(e.error??`Actor generation failed: HTTP ${o.status}`)}let s=(await o.json().catch(()=>null))?.actors;if(!s||s.length===0)throw Error(`Actor generation returned no actors`);u({kind:`progress`,stage:`running`,scenario:r,actors:s}),await e.reset(),typeof window<`u`&&mg(window.localStorage,s,i);let c=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n,actors:s,turns:r.setup.defaultTurns,seed:r.setup.defaultSeed??42,captureSnapshots:!0,quickstart:{scenarioId:i}})});if(!c.ok){let e=await c.json().catch(()=>({}));throw Error(e.error??`Setup failed: HTTP ${c.status}`)}let l=await c.json().catch(()=>({}));if(l.redirect){try{window.localStorage.setItem(`paracosm:launchPending`,`1`)}catch{}window.location.href=fh(window.location.href,l.redirect);return}}catch(e){u({kind:`input`});let t=u_(e?.message??String(e));f(t),c(`error`,`Quickstart failed`,t,8e3)}},[e,n,c]);(0,b.useEffect)(()=>{if(l.kind!==`progress`||l.stage!==`running`||!l.scenario||!l.actors)return;let t=e.results.map(e=>e.artifact).filter(e=>!!e);t.length>=l.actors.length&&u({kind:`results`,scenario:l.scenario,actors:l.actors,artifacts:t.slice(0,l.actors.length)})},[e.results,l]),(0,b.useEffect)(()=>{if(l.kind!==`results`||p!==null)return;let e=l.artifacts[0]?.metadata?.runId;if(!e)return;let t=!1;return fetch(`/api/v1/runs/${encodeURIComponent(e)}`).then(async e=>e.ok?e.json():null).then(e=>{if(t)return;let n=e?.record?.bundleId;n&&m(n)}).catch(()=>{}),()=>{t=!0}},[l,p]);let T=l.kind===`progress`&&l.stage===`running`&&l.actors?l.actors.map((t,n)=>{let r=e.events.filter(e=>e.type===`turn_done`||e.type===`turn_start`).reduce((e,t)=>{let n=t.data?.turn??0;return n>e?n:e},0),i=e.results.find(e=>e.actorIndex===n),a=e.errors.length>0&&!i?`error`:e.isAborted?`aborted`:i?`complete`:`running`;return{name:t.name,archetype:t.archetype,currentTurn:i?l.scenario?.setup.defaultTurns??r:r,maxTurns:l.scenario?.setup.defaultTurns??6,status:a}}):void 0,E=(0,b.useCallback)((e,t)=>{f(`Actor swap rerun is a v1.1 follow-up. Use "Fork in Branches" on the Branches tab to try a preset actor against this run.`)},[]);return(0,x.jsxs)(`div`,{className:l_.view,children:[l.kind===`input`&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`header`,{className:l_.header,children:[(0,x.jsx)(`h2`,{children:`Quickstart`}),(0,x.jsx)(`p`,{children:`Paste a what-if scenario. Paracosm compiles it into a typed world and runs LLM-driven decision-makers with measurable personalities against it, returning a replayable trajectory you can fork and compare.`}),(0,x.jsxs)(`details`,{className:l_.howItWorks,children:[(0,x.jsx)(`summary`,{className:l_.howItWorksSummary,children:`How it works`}),(0,x.jsxs)(`ul`,{className:l_.glossary,"aria-label":`Key terms`,children:[(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`strong`,{children:`Scenario`}),` — the world Paracosm compiles from your prompt: departments, agents, events, starting state.`]}),(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`strong`,{children:`Actor`}),` — an LLM decision-maker driving the scenario, weighted by a HEXACO personality vector.`]}),(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`strong`,{children:`Run`}),` — one actor playing the scenario turn by turn. Paracosm runs N actors in parallel against the same world so you can compare divergent outcomes.`]})]}),(0,x.jsxs)(`p`,{className:l_.timingHint,children:[(0,x.jsx)(`strong`,{children:`Heads-up:`}),` a fresh run takes `,(0,x.jsx)(`strong`,{children:`2-5 minutes`}),` (compile, ground with citations, generate actors, simulate). For instant results, replay a cached run below.`]})]})]}),d&&(0,x.jsx)(`p`,{className:l_.errorBanner,role:`alert`,children:d}),(0,x.jsx)(jg,{}),(0,x.jsx)(ig,{onSeedReady:w,onLoadedScenarioRunStart:S,onCatalogRunStart:C}),r&&(0,x.jsx)(Dg,{onResult:r,onRunStart:i,onError:(e,t)=>{a?.(e,t)!==!1&&f(e)}})]}),l.kind===`progress`&&(0,x.jsx)(Xg,{stage:l.stage,actors:T,events:e.events,actorCount:l.actors?.length??T?.length??2,groundingSummary:_}),l.kind===`results`&&(0,x.jsxs)(x.Fragment,{children:[d&&(0,x.jsx)(`p`,{className:l_.errorBanner,role:`alert`,children:d}),p&&l.artifacts.length>=2&&(0,x.jsxs)(`button`,{type:`button`,className:l_.compareCta,onClick:()=>g(!0),"aria-label":`Compare all ${l.artifacts.length} actors side-by-side`,children:[`Compare all `,l.artifacts.length,` actors →`]}),(0,x.jsx)(n_,{actors:l.actors,artifacts:l.artifacts,sessionId:t,onSwap:E}),p&&h&&(0,x.jsx)(ra,{bundleId:p,open:!0,onClose:()=>g(!1)})]})]})}var f_={getNumber:()=>0,getEntry:()=>void 0,list:[]};function p_(e){return(0,b.useMemo)(()=>{let t=new Map,n=[],r=1;for(let i of e.actorIds){let a=e.actors[i];if(a)for(let e of a.events){if(e.type!==`specialist_done`)continue;let a=String(e.data?.department||``),o=e.data?.citationList||[];for(let e of o){let o=(e.url||``).trim(),s=(e.text||``).trim();if(!o&&!s||!o&&s===`Seed document`)continue;let c=o||`text:${s}`,l=t.get(c);l||(l={n:r++,text:s||o,url:o,doi:e.doi,departments:new Set,actorNames:new Set},t.set(c,l),n.push(l)),a&&l.departments.add(a),l.actorNames.add(i),!l.doi&&e.doi&&(l.doi=e.doi)}}}return{getNumber:e=>e?(t.get(e)||t.get(`text:${e}`))?.n??0:0,getEntry:e=>t.get(e)||t.get(`text:${e}`),list:n}},[e])}var m_=(0,b.createContext)(f_);function h_(){return(0,b.useContext)(m_)}var g_=()=>({tools:0,forges:0,reforges:0,passed:0,didNotPass:0});function __(e){let t=String(e??``).trim();return t===`unnamed`?``:t}var v_=e=>Array.isArray(e)?e:[];function y_(e){if(e.type!==`specialist_done`)return!1;let t=e.data?.forgedTools;return t!=null&&!Array.isArray(t)}function b_(e,t,n,r){return{n:0,name:e,description:String(r.description||e),mode:String(r.mode||`sandbox`),firstForgedTurn:r.turn,firstForgedDepartment:r.department,departments:new Set,actorNames:new Set([n]),reuseCount:0,reforgeCount:0,rejectedReforges:0,confidence:r.confidence,approved:r.approved,inputSchema:void 0,outputSchema:void 0,sampleOutput:null,errorReason:r.errorReason,inputFields:v_(r.inputFields),outputFields:v_(r.outputFields),history:[],actorIndex:t,actorName:n,attempts:[],outcome:r.approved?`passed`:`did_not_pass`,sameNameActors:[]}}function x_(e,t,n){let r=new Map;for(let t of e){if(t.type!==`event_start`)continue;let e=`${Number(t.data?.turn??t.turn??0)}:${Number(t.data?.eventIndex??0)}`;r.has(e)||r.set(e,String(t.data?.title??``))}let i=new Map,a=[],o=new Map,s=[];for(let c of e){let e=c.data??{};if(c.type===`forge_attempt`){let o=__(e.name);if(!o)continue;let l=Number(e.turn??c.turn??0),u=Number(e.eventIndex??0),d=String(e.department??``),f=e.approved===!0,p=typeof e.confidence==`number`?e.confidence:null,m=typeof e.errorReason==`string`&&e.errorReason?e.errorReason:null,h=i.get(o);h||(h=b_(o,t,n,{description:e.description,mode:e.mode,turn:l,department:d,confidence:p??0,approved:f,errorReason:m??void 0,inputFields:e.inputFields,outputFields:e.outputFields}),i.set(o,h),a.push(h));let g={attempt:h.attempts.length+1,turn:l,time:Number(e.time??0),eventIndex:u,department:d,eventTitle:r.get(`${l}:${u}`)??``,approved:f,confidence:p,errorReason:m,description:String(e.description??``),inputFields:v_(e.inputFields),outputFields:v_(e.outputFields),eventId:c.id};h.attempts.push(g),d&&h.departments.add(d),p!==null&&p>h.confidence&&(h.confidence=p),f?(h.approved=!0,h.errorReason=void 0):!h.approved&&m&&(h.errorReason=m),s.push(f?`passed`:`did_not_pass`);continue}if(c.type!==`specialist_done`)continue;let l=Array.isArray(e._filteredTools)?e._filteredTools:[],u=String(e.department||``);for(let e of l){let r=__(e.name);if(!r)continue;let s=e.approved!==!1,l=i.get(r);if(l?(o.has(l)||(typeof e.description==`string`&&e.description&&(l.description=e.description),typeof e.mode==`string`&&e.mode&&(l.mode=e.mode),typeof e.firstForgedTurn==`number`&&(l.firstForgedTurn=e.firstForgedTurn),typeof e.firstForgedDepartment==`string`&&e.firstForgedDepartment&&(l.firstForgedDepartment=e.firstForgedDepartment),Array.isArray(e.inputFields)&&(l.inputFields=e.inputFields),Array.isArray(e.outputFields)&&(l.outputFields=e.outputFields)),typeof e.confidence==`number`&&e.confidence>l.confidence&&(l.confidence=e.confidence),s&&(l.approved=!0),l.approved?l.errorReason=void 0:typeof e.errorReason==`string`&&e.errorReason&&(l.errorReason=e.errorReason)):(l=b_(r,t,n,{description:e.description,mode:e.mode,turn:typeof e.firstForgedTurn==`number`?e.firstForgedTurn:c.turn??0,department:String(e.firstForgedDepartment||u),confidence:typeof e.confidence==`number`?e.confidence:s?.85:0,approved:s,errorReason:typeof e.errorReason==`string`?e.errorReason:void 0,inputFields:e.inputFields,outputFields:e.outputFields}),i.set(r,l),a.push(l)),typeof e.output==`string`&&(e.output||l.sampleOutput===null)&&(l.sampleOutput=e.output),!l.inputSchema&&e.inputSchema&&(l.inputSchema=e.inputSchema),!l.outputSchema&&e.outputSchema&&(l.outputSchema=e.outputSchema),u&&l.departments.add(u),o.set(l,s),Array.isArray(e.history)){let t=e.history;l.history=t.map(e=>({...e,actorName:n})),l.reuseCount=Math.max(0,t.length-1),l.reforgeCount=t.filter(e=>e.isReforge).length,l.rejectedReforges=t.filter(e=>e.isReforge&&e.rejected).length}}}for(let e of a){o.has(e)||(e.history=e.attempts.map((e,t)=>({turn:e.turn,time:e.time,eventIndex:e.eventIndex,eventTitle:e.eventTitle,department:e.department,output:null,isReforge:t>0,rejected:!e.approved,confidence:e.confidence??void 0,actorName:n})),e.reforgeCount=Math.max(0,e.attempts.length-1),e.rejectedReforges=e.attempts.filter(e=>!e.approved).length);let t=e.attempts[e.attempts.length-1];e.outcome=(t?t.approved:o.get(e)!==!1)?`passed`:`did_not_pass`}return{entries:a,strip:s}}function S_(e,t){e.tools+=t.tools,e.forges+=t.forges,e.reforges+=t.reforges,e.passed+=t.passed,e.didNotPass+=t.didNotPass}function C_(e){let t=[],n=[],r=g_(),i=new Map,a=new Map,o=(e,t)=>`${e}\u0000${t}`;e.actorIds.forEach((s,c)=>{let l=e.actors[s],u=l?.events??[],d=u.some(y_),{entries:f,strip:p}=d?{entries:[],strip:[]}:x_(u,c,s),m=g_();for(let e of f){e.n=t.length+1,t.push(e),i.set(o(c,e.name),e);let n=a.get(e.name);n?n.push(e):a.set(e.name,[e]);let r=e.attempts.filter(e=>e.approved).length;S_(m,{tools:1,forges:e.attempts.length,reforges:Math.max(0,e.attempts.length-1),passed:r,didNotPass:e.attempts.length-r})}S_(r,m),n.push({index:c,label:`A${c+1}`,name:s,archetype:l?.leader?.archetype??``,counts:m,strip:p,status:e.isComplete?`done`:u.length===0?`waiting`:`running`,unreadable:d})});for(let e of a.values())for(let t of e)t.sameNameActors=e.filter(e=>e!==t).map(e=>e.actorIndex);return{getNumber:e=>a.get(e.trim())?.[0]?.n??0,getEntry:e=>a.get(e.trim())?.[0],getEntryFor:(e,t)=>i.get(o(e,t.trim())),getEntryByNumber:e=>Number.isInteger(e)&&e>=1?t[e-1]:void 0,list:t,actors:n,counts:r}}var w_={getNumber:()=>0,getEntry:()=>void 0,getEntryFor:()=>void 0,getEntryByNumber:()=>void 0,list:[],actors:[],counts:{tools:0,forges:0,reforges:0,passed:0,didNotPass:0}};function T_(e){return(0,b.useMemo)(()=>C_(e),[e])}var E_=(0,b.createContext)(w_);function D_(){return(0,b.useContext)(E_)}var O_=[`request`,`code`,`tests`,`judge`,`added`];function k_(e){return e===`passed`?`passed`:`didNotPass`}var A_=`request`;function j_(e){return e===`passed`?{stations:{request:`reached`,code:`reached`,tests:`reached`,judge:`reached`,added:`reached`},stop:null,deciding:`judge`}:{stations:{request:`reached`,code:`unknown`,tests:`unknown`,judge:`unknown`,added:`notReached`},stop:null,deciding:`request`}}function M_(e,t){let n=e.attempts.length;return n===0?0:Number.isFinite(t)?Math.min(Math.max(Math.trunc(t),1),n):n}function N_(e,t){let n=e.attempts;if(n.length===0)return{...j_(e.outcome),spurs:[],branch:null};let r=M_(e,t),i=e=>e?`passed`:`did_not_pass`,a=n[r-1],o=n[r];return{...j_(i(a.approved)),spurs:n.slice(0,r-1).map(e=>({attempt:e.attempt,station:A_,outcome:i(e.approved)})),branch:o?{attempt:o.attempt,station:A_,outcome:i(o.approved)}:null}}function P_(e,t){return t<=2?Pe(e):`var(--forge-quiet)`}function F_(e){return e.history.slice(1).filter(e=>!e.isReforge).length}var I_={forge_toolbox_open:{from:[`sim`,`reports`,`viz`]},forge_trace_open:{from:[`toolbox`,`inspect`,`viz`,`link`]},forge_station_open:{station:O_,via:[`press`,`open_all`,`kept`]},forge_toolbox_filter:{show:[`all`,`passed`,`did_not_pass`]},forge_record_export:{what:[`toolbox`,`record_copy`,`record_download`]},forge_log_jump:{},forge_link_copy:{},forge_toolbox_group:{group:[`actor`,`department`,`none`]},forge_group_toggle:{scope:[`one`,`all`]},forge_actor_filter:{actors:[`1`,`2-4`,`5-24`,`25+`]},forge_actor_picker_open:{where:[`toolbox`,`compare`,`event_log`]}};function L_(e){return!Number.isFinite(e)||e<1?null:e===1?`1`:e<=4?`2-4`:e<=24?`5-24`:`25+`}function R_(e,t){try{let n=e.paracosmConsent;return typeof n?.allows==`function`&&n.allows(t)===!0}catch{return!1}}function z_(e){try{let{origin:t,pathname:n}=e.location;return typeof t==`string`&&typeof n==`string`?t+n:null}catch{return null}}function B_(e,t){let n=t??(typeof window>`u`?void 0:window);if(!n)return;let r=n,i=I_[e.name];if(!i)return;let a=R_(r,`measure`),o=R_(r,`record`);if(!a&&!o)return;let s={},c=e;for(let[e,t]of Object.entries(i)){let n=c[e];typeof n==`string`&&t.includes(n)&&(s[e]=n)}if(a&&typeof r.gtag==`function`){let t=z_(n);try{r.gtag(`event`,e.name,t===null?s:{...s,page_location:t})}catch{}}if(o&&typeof r.clarity==`function`)try{r.clarity(`event`,e.name)}catch{}}var V_={tool:`tool`,attempt:`attempt`,open:`open`,toolbox:`toolbox`,show:`show`,find:`find`,group:`group`,actors:`actors`},H_=Object.values(V_),U_=[V_.tool,V_.attempt,V_.open];function W_(e){if(e===null||!/^\d+$/.test(e.trim()))return null;let t=Number.parseInt(e.trim(),10);return Number.isSafeInteger(t)&&t>=1?t:null}function G_(e){let t=e.split(`,`).map(e=>e.trim().toLowerCase());return O_.filter(e=>t.includes(e))}function K_(e){let t=[];for(let n of e.split(`,`)){let e=W_(n);e!==null&&!t.includes(e)&&t.push(e)}return t}function q_(e,t,n){let r={trace:null,toolbox:{open:!1}},i=[],a;try{a=new URL(e).searchParams}catch{return{state:r,dangling:i}}r.toolbox.open=a.get(V_.toolbox)===`1`;for(let e of[V_.show,V_.find,V_.group]){let t=a.get(e);t!==null&&t!==``&&(r.toolbox[e]=t)}let o=a.get(V_.actors);if(o!==null){let e=K_(o),a=n?e.filter(e=>e<=t.actors.length):e;a.length>0?r.toolbox.actors=a:n&&i.push(V_.actors)}if(!n)return{state:r,dangling:i};let s=U_.filter(e=>a.has(e));if(s.length===0)return{state:r,dangling:i};let c=W_(a.get(V_.tool)),l=c===null?void 0:t.getEntryByNumber(c);if(!l)return i.push(...s),{state:r,dangling:i};let u;if(a.has(V_.attempt)){let e=W_(a.get(V_.attempt));if(e===null||e>l.attempts.length)return i.push(...s),{state:r,dangling:i};u=e}let d;if(a.has(V_.open)){let e=G_(a.get(V_.open)??``);e.length>0?d=e:i.push(V_.open)}return r.trace={actorIndex:l.actorIndex,toolName:l.name,...u===void 0?{}:{attempt:u},...d?{open:d}:{}},{state:r,dangling:i}}function J_(e,t,n){let r=new URL(e);for(let e of H_)r.searchParams.delete(e);let i=t.trace,a=i?n.getEntryFor(i.actorIndex,i.toolName):void 0;if(i&&a){r.searchParams.set(V_.tool,String(a.n)),i.attempt!==void 0&&i.attempt>=1&&i.attempt<a.attempts.length&&r.searchParams.set(V_.attempt,String(Math.trunc(i.attempt)));let e=O_.filter(e=>i.open?.includes(e));e.length>0&&r.searchParams.set(V_.open,e.join(`,`))}let o=t.toolbox;return o.open&&r.searchParams.set(V_.toolbox,`1`),o.show&&r.searchParams.set(V_.show,o.show),o.find&&r.searchParams.set(V_.find,o.find),o.group&&r.searchParams.set(V_.group,o.group),o.actors&&o.actors.length>0&&r.searchParams.set(V_.actors,o.actors.join(`,`)),r.toString()}function Y_(e,t){let n;try{n=new URL(e)}catch{return e}let r=[[V_.show,t.show&&t.show!==`all`?t.show:null],[V_.find,t.find?t.find:null]];if(t.open!==void 0&&r.push([V_.toolbox,t.open?`1`:null]),t.group!==void 0&&r.push([V_.group,t.group?t.group:null]),t.actors!==void 0){let e=[...new Set(t.actors)].filter(e=>Number.isInteger(e)&&e>=0).sort((e,t)=>e-t).map(e=>e+1);r.push([V_.actors,e.length>0?e.join(`,`):null])}let i=!1;for(let[e,t]of r)n.searchParams.get(e)===t&&n.searchParams.getAll(e).length<=1||(i=!0,t===null?n.searchParams.delete(e):n.searchParams.set(e,t));return i?n.toString():e}function X_(e,t){let n;try{n=new URL(e)}catch{return e}let r=(t??H_).filter(e=>n.searchParams.has(e));if(r.length===0)return e;for(let e of r)n.searchParams.delete(e);return n.toString()}function Z_(e,t,n,r,i){return J_(Ot(e,t,n),{trace:r,toolbox:{open:!1}},i)}function Q_(e){let t;try{t=sh(e)}catch{return`sim`}return t===`about`||t===`quickstart`?`sim`:t}var $_=(0,b.createContext)({openTrace:()=>{},openToolbox:()=>{},close:()=>{},showActorLog:()=>{},current:{trace:null,toolbox:!1}});function ev(){return(0,b.useContext)($_)}var tv=[`all`,`passed`,`did_not_pass`],nv=[`actor`,`department`,`none`],rv=e=>e>2?`actor`:`none`,iv={show:`all`,find:``,group:null,actors:[]},av={...iv,set:()=>{}},ov=(0,b.createContext)(av);function sv(){return(0,b.useContext)(ov)}var cv=[`run`,`tools`,`didNotPass`],lv=/^a(\d+)$/i;function uv(e,t){let n=t.trim();if(n===``)return e;let r=lv.exec(n);if(r){let t=`A${Number.parseInt(r[1],10)}`;return e.filter(e=>e.label===t)}let i=n.toLowerCase();return e.filter(e=>e.name.toLowerCase().includes(i)||e.archetype.toLowerCase().includes(i))}function dv(e,t){let n=(e,t)=>e.index-t.index,r=[...e];return t===`tools`?r.sort((e,t)=>t.counts.tools-e.counts.tools||n(e,t)):t===`didNotPass`?r.sort((e,t)=>t.counts.didNotPass-e.counts.didNotPass||n(e,t)):r.sort(n)}function fv(e,t){return t>0&&e.length===0?`error`:`ready`}function pv(e,t,n){let r=new Set(e);for(let e of t){if(n!==void 0&&r.size>=n)break;r.add(e.index)}return r}function mv(e,t){let n=[...new Set(e)].filter(e=>Number.isInteger(e)&&e>=0&&e<t).sort((e,t)=>e-t);return n.length===0||n.length>=t?null:n}var hv={request:`Request`,code:`Code`,tests:`Tests`,judge:`Judge`,added:`Added`},gv={unknown:`Unknown`,notReached:`Not reached`},_v={reached:`reached`,stopped:`stopped here`,unknown:gv.unknown,notReached:gv.notReached},vv=(e,t)=>`${hv[e]}: ${_v[t]}`,yv=`The forge's stations`,bv={passed:`Passed`,rejected:`Rejected by the judge`,notJudged:`Not judged`,refused:`Refused`,failed:`Failed`,didNotPass:`Did not pass`},xv=e=>`A${e+1}`,Sv=e=>`+${e}`,Cv=(e,t)=>`${e}, forged tool ${t}`,wv=e=>`Forged tool ${e}`,Tv=`Close the trace`,Ev={key:`Copy link to this tool`,copied:`Link copied. Anyone with it can open this tool's trace and replay the run.`,failed:`Could not copy. Select the link and copy it.`,offline:`You are offline`},Dv={toLight:`Switch to light mode`,toDark:`Switch to dark mode`},Ov=`Written by an AI model during this paracosm run`,kv={passed:`Passed. The judge approved it.`,did_not_pass:`Did not pass. The run's record does not say where the forge stopped.`},Av={heading:`The reason the run recorded`,limit:`The run's record keeps at most 240 characters of this reason.`,none:`The record gave no reason.`},jv={code:`The code was not recorded for this run.`,tests:`The tests were not recorded for this run.`},Mv=e=>`Approved · confidence ${e.toFixed(2)} out of 1`,Nv=e=>e===1?`Used 1 time`:`Used ${e} times`,Pv={open:`Open all`,close:`Close all`,openName:`Open all stations`,closeName:`Close all stations`};function Fv(e){return[e.archetype?`${e.label} ${e.name}, ${e.archetype}`:`${e.label} ${e.name}`,e.department,`turn ${e.turn}`,e.eventTitle?`for “${e.eventTitle}”`:``].filter(Boolean).join(` · `)}var Iv=e=>`Go to the event: ${e}`,Lv={whatItDoes:`What it does`,inputFields:`Input fields`,outputFields:`Output fields`,columns:[`Field`,`Type`,`Required`,`Description`],rawJson:`Raw JSON`,noInputFields:`This tool declares no input fields.`,noOutputFields:`This tool declares no output fields.`,notRecorded:`Not recorded`,yes:`Yes`,no:`No`},Rv={heading:`What the judge said`,notice:`A model's review of this code, not a security audit. Check before reuse.`,meterName:`The judge's confidence`,wordsNotRecorded:`The judge's words were not recorded for this run.`},zv=e=>`The judge's confidence: ${e.toFixed(2)} out of 1`,Bv={output:`Output the run recorded`,testNotRecorded:`This forge's test was not recorded.`,notUsed:`Not used after it was forged.`};function Vv(e,t,n){return[`Turn ${e}`,t,n?`“${n}”`:``].filter(Boolean).join(` · `)}var Hv={key:`Record`,rawRecord:`The raw record`,copy:`Copy record`,copied:`Copied`,copyFailed:`Could not copy. Select the record and copy it.`,download:`Download JSON`,downloadFailed:`Could not download. Try again, or use Copy record.`,showInEventLog:`Show in Event Log`,unreadable:`This record could not be shown.`},Uv=e=>`${e}-trace.json`,Wv={previous:`Previous attempt`,next:`Next attempt`},Gv=(e,t)=>`${e} of ${t}`,Kv=(e,t)=>`Attempt ${e} of ${t}`,qv=(e,t)=>`Attempt ${e} · ${t}`,Jv=e=>e.toLocaleString(`en-US`),Yv=(e,t,n)=>`${Jv(e)} ${e===1?t:n}`,Xv=`FORGED TOOLBOX`,Zv=e=>`Forged toolbox, ${Yv(e,`tool`,`tools`)}`,Qv=e=>`Forged toolbox · ${Jv(e)}`,$v=`Close the toolbox`;function ey(e,t){let n=e.reforges>0?` (${Yv(e.reforges,`re-forge`,`re-forges`)})`:``;return[`${Yv(e.tools,`tool`,`tools`)} from ${Yv(e.forges,`forge`,`forges`)}${n}`,e.passed>0?`${Jv(e.passed)} passed`:``,e.didNotPass>0?`${Jv(e.didNotPass)} did not pass`:``,t>2?`${Jv(t)} actors`:``].filter(Boolean).join(` · `)}var ty={name:`Show`,menuLead:`Show:`,all:`All`,passed:bv.passed,did_not_pass:bv.didNotPass},ny={label:`Find a tool`,placeholder:`Tool name…`,clear:`Clear`,clearName:`Clear the search`},ry={noTools:`No department forged a tool in this run.`,everyToolPassed:`Every tool in this run passed.`},iy=e=>`No tool matches “${e}”.`,ay=`Export JSON`,oy=`paracosm-toolbox.json`;function sy(e){return[e.department,`turn ${e.turn}`,e.uses===null?``:`used ${Yv(e.uses,`time`,`times`)}`,e.reforges>0?Yv(e.reforges,`re-forge`,`re-forges`):``].filter(Boolean).join(` · `)}function cy(e){return e.length>3?`Same name in ${Jv(e.length)} other actors`:`Same name: ${e.join(`, `)}`}function ly(e){let t=`${e.name}, ${e.outcome}, made by ${e.actorLabel} ${e.actorName}`;return e.forges>1?`${t}, forged ${Jv(e.forges)} times`:t}var uy={name:`Group`,actor:`Actor`,department:`Department`,none:`None`},dy=e=>`Group: ${uy[e]}`,fy={open:`Open all groups`,close:`Close all groups`};function py(e){return[`${Yv(e.tools,`tool`,`tools`)} from ${Yv(e.forges,`forge`,`forges`)}`,e.passed>0?`${Jv(e.passed)} passed`:``,e.didNotPass>0?`${Jv(e.didNotPass)} did not pass`:``].filter(Boolean).join(` · `)}var my=`No tools`,hy=e=>`${e}'s tools could not be read.`,gy=e=>`${Jv(e)} tools: the most one actor's registry holds`;function _y(e){let t=[`${e.label} ${e.name}`,e.archetype].filter(Boolean);return e.unreadable?[...t,hy(e.label)].join(`, `):e.tools===0?[...t,my].join(`, `):[...t,Yv(e.tools,`tool`,`tools`),e.didNotPass>0?`${Jv(e.didNotPass)} did not pass`:``].filter(Boolean).join(`, `)}function vy(e,t){return[e,Yv(t.tools,`tool`,`tools`),t.didNotPass>0?`${Jv(t.didNotPass)} did not pass`:``].filter(Boolean).join(`, `)}var yy=e=>`Exporting ${Jv(e)} tools…`,by=`Could not export. Try again.`,xy={dialogName:`Choose actors`,listName:`Actors`,findLabel:`Find an actor`,findPlaceholder:`Name, archetype or A-number…`,clearSearchName:`Clear the actor search`,sortName:`Sort`,sortLead:`Sort:`,selectShown:`Select shown`,clear:`Clear`,done:`Done`,showAll:`Show all`,waiting:`Waiting to start`,unreadable:`The actors could not be read.`},Sy={run:`Run order`,tools:`Most tools`,didNotPass:`Most forges that did not pass`},Cy=(e,t)=>e===null?`Actors: All ${Jv(t)}`:`Actors: ${Jv(e)} of ${Jv(t)}`,wy=(e,t)=>`Showing ${Jv(e)} of ${Jv(t)} actors`;function Ty(e,t,n){return`${wy(e,t)} · ${ey(n,0)}`}function Ey(e){return e.tools===0?my:[Yv(e.tools,`tool`,`tools`),e.didNotPass>0?`${Jv(e.didNotPass)} did not pass`:``].filter(Boolean).join(` · `)}var Dy=e=>`No actor matches “${e}”.`,Oy={backdrop:`_backdrop_1mlna_1`,dialog:`_dialog_1mlna_15`,"sheet-up":`_sheet-up_1mlna_1`,header:`_header_1mlna_50`,headerEnd:`_headerEnd_1mlna_62`,key:`_key_1mlna_69`,iconKey:`_iconKey_1mlna_106`,lookGlyph:`_lookGlyph_1mlna_111`,number:`_number_1mlna_116`,linkNote:`_linkNote_1mlna_135`,linkSaid:`_linkSaid_1mlna_144`,linkText:`_linkText_1mlna_151`,name:`_name_1mlna_165`,nameInRow:`_nameInRow_1mlna_184`,head:`_head_1mlna_50`,label:`_label_1mlna_195`,outcome:`_outcome_1mlna_202`,attempts:`_attempts_1mlna_219`,attemptLine:`_attemptLine_1mlna_226`,reason:`_reason_1mlna_234`,reasonHeading:`_reasonHeading_1mlna_242`,reasonText:`_reasonText_1mlna_250`,reasonNote:`_reasonNote_1mlna_263`,line:`_line_1mlna_270`,recordFoot:`_recordFoot_1mlna_274`,recordKey:`_recordKey_1mlna_283`,recordBody:`_recordBody_1mlna_288`,nameInHead:`_nameInHead_1mlna_355`,lineHead:`_lineHead_1mlna_389`};function ky(){let{resolved:e,setTheme:t}=C(),n=e===`dark`?`light`:`dark`,r=n===`light`?Dv.toLight:Dv.toDark;return(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Oy.iconKey}`,onClick:()=>t(n),"aria-label":r,title:r,children:(0,x.jsx)(`span`,{className:Oy.lookGlyph,"aria-hidden":`true`,children:e===`dark`?`☀`:`☽`})})}var Ay=m();function jy(e,t=!1){let[n,r]=(0,b.useState)(()=>typeof window>`u`||!window.matchMedia?t:window.matchMedia(e).matches);return(0,b.useEffect)(()=>{if(typeof window>`u`||!window.matchMedia)return;let t=window.matchMedia(e),n=e=>r(e.matches);return t.addEventListener(`change`,n),r(t.matches),()=>t.removeEventListener(`change`,n)},[e]),n}var My=`(max-width: 768px)`,Ny=`(max-width: 480px)`,Py=`(max-width: 899.98px)`,Fy=`(prefers-reduced-motion: reduce)`,Iy={tile:`_tile_1dw5u_1`,band:`_band_1dw5u_17`,label:`_label_1dw5u_26`},Ly={2:28,3:32,4:40};function Ry({index:e,colour:t}){let n=xv(e),r={"--tile-size":`${Ly[n.length]??Ly[4]}px`,"--tile-band":t};return(0,x.jsxs)(`span`,{className:Iy.tile,style:r,"data-actor-tile":n,translate:`no`,children:[(0,x.jsx)(`span`,{className:Iy.band,"aria-hidden":`true`}),(0,x.jsx)(`span`,{className:Iy.label,children:n})]})}var zy={strip:`_strip_1uso4_1`,cell:`_cell_1uso4_10`,more:`_more_1uso4_27`},By=20;function Vy({cells:e,max:t=By}){let n=e.slice(0,Math.max(0,t)),r=e.length-n.length;return(0,x.jsxs)(`span`,{className:zy.strip,"aria-hidden":`true`,"data-forge-strip":e.length,children:[n.map((e,t)=>(0,x.jsx)(`span`,{className:zy.cell,"data-cell":e},t)),r>0&&(0,x.jsx)(`span`,{className:zy.more,children:Sv(r)})]})}function Hy({count:e,lineHeights:t,scrollTop:n,viewport:r,overscan:i,keep:a}){if(e<=0)return{first:0,last:-1,padTop:0,padBottom:0};let o=e=>{let n=typeof t==`number`?t:t[e]??0;return Number.isFinite(n)&&n>0?n:0},s=Math.max(0,n),c=s+Math.max(0,r),l=0,u=-1,d=-1;for(let t=0;t<e;t+=1){let e=o(t);if(l>=c&&u>=0)break;u<0&&l+e>s&&(u=t),u>=0&&(d=t),l+=e}u<0&&(u=e-1,d=e-1);let f=Math.max(0,Math.floor(i)),p=Math.max(0,u-f),m=Math.min(e-1,d+f),h=(e,t)=>{let n=0;for(let r=e;r<t;r+=1)n+=o(r);return n};if(a!==void 0&&Number.isInteger(a)&&a>=0&&a<e){if(a>=p-1&&a<=m+1)p=Math.min(p,a),m=Math.max(m,a);else if(a<p)return{first:p,last:m,kept:a,gap:h(a+1,p),padTop:h(0,a),padBottom:h(m+1,e)};else return{first:p,last:m,kept:a,gap:h(m+1,a),padTop:h(0,p),padBottom:h(a+1,e)}}return{first:p,last:m,padTop:h(0,p),padBottom:h(m+1,e)}}var Uy=`button:not([disabled]), a[href], input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])`;function Wy(e){for(let t=e.parentElement;t&&t!==document.body&&t!==document.documentElement;t=t.parentElement){let{overflowY:e}=getComputedStyle(t);if((e===`auto`||e===`scroll`||e===`overlay`)&&t.scrollHeight>t.clientHeight+1)return t}return null}function Gy(e){if(!e)return{top:0,bottom:window.innerHeight,padTop:0};let t=e.getBoundingClientRect().top+e.clientTop,n=Number.parseFloat(getComputedStyle(e).scrollPaddingTop);return{top:t,bottom:t+e.clientHeight,padTop:Number.isFinite(n)?n:0}}function Ky(e){let t=e.getBoundingClientRect(),{top:n,bottom:r}=Gy(Wy(e));return{scrollTop:Math.max(0,n-t.top),viewport:Math.max(0,r-Math.max(n,t.top))}}function qy(e,t,n){let r=e.length>50,i=(0,b.useRef)(new Map),a=(0,b.useRef)(new Map),o=(0,b.useRef)(-1),[s,c]=(0,b.useState)(0),[l,u]=(0,b.useState)(()=>({scrollTop:0,viewport:typeof window>`u`?0:window.innerHeight})),d=(0,b.useMemo)(()=>e.map(e=>{let t=i.current.get(e.key);if(t!==void 0)return t;let n=a.current.get(e.kind);return n&&n.n>0?n.sum/n.n:e.estimate}),[e,s]),f=n!==null&&n>=0&&n<e.length?n:void 0,p=r?Hy({count:e.length,lineHeights:d,scrollTop:l.scrollTop,viewport:l.viewport,overscan:8,keep:f}):{first:0,last:e.length-1,padTop:0,padBottom:0},m=(0,b.useRef)({heights:d,range:p,keep:f,windowed:r});m.current={heights:d,range:p,keep:f,windowed:r};let h=(0,b.useCallback)(()=>{let e=m.current;if(!t||!e.windowed)return;let n=Ky(t),r=Hy({count:e.heights.length,lineHeights:e.heights,scrollTop:n.scrollTop,viewport:n.viewport,overscan:8,keep:e.keep});(r.first!==e.range.first||r.last!==e.range.last||r.kept!==e.range.kept)&&u(n)},[t]);(0,b.useEffect)(()=>{if(!t)return;let e=0,n=()=>{e===0&&(e=window.requestAnimationFrame(()=>{e=0,h()}))};document.addEventListener(`scroll`,n,{capture:!0,passive:!0}),window.addEventListener(`resize`,n);let r=typeof ResizeObserver>`u`?null:new ResizeObserver(n);return r?.observe(t),n(),()=>{document.removeEventListener(`scroll`,n,{capture:!0}),window.removeEventListener(`resize`,n),r?.disconnect(),e!==0&&window.cancelAnimationFrame(e)}},[t,h]),(0,b.useLayoutEffect)(()=>{if(!t)return;let n=t.clientWidth;n>0&&Math.abs(n-o.current)>1&&(i.current.clear(),a.current.clear(),o.current=n);let r=!1;for(let n of t.querySelectorAll(`[data-line]`)){let t=e[Number(n.dataset.line)];if(!t)continue;let o=n.getBoundingClientRect().height;if(!(o>0))continue;let s=i.current.get(t.key);if(s!==void 0&&Math.abs(s-o)<.5)continue;i.current.set(t.key,o);let c=a.current.get(t.kind)??{sum:0,n:0};s===void 0?(c.sum+=o,c.n+=1):c.sum+=o-s,a.current.set(t.kind,c),r=!0}r?c(e=>e+1):h()});let g=(0,b.useCallback)(e=>{let n=m.current;if(!t||e<0||e>=n.heights.length)return;let r=0;for(let t=0;t<e;t+=1)r+=n.heights[t];let i=Wy(t),{top:a,bottom:o,padTop:s}=Gy(i),c=t.getBoundingClientRect().top+r,l=c+n.heights[e],u=c<a+s?c-(a+s):l>o?l-o:0;u!==0&&(i?i.scrollTop+=u:window.scrollBy(0,u)),h()},[t,h]);return{...p,windowed:r,scrollToLine:g}}function Jy(e,t,n){for(let r=t+n;r>=0&&r<e.length;r+=n)if(e[r].focusable)return r;return-1}function Yy(e,t){return Jy(e,t===1?-1:e.length,t)}function Xy(e,t){let[n,r]=(0,b.useState)(null),[i,a]=(0,b.useState)(null),o=(0,b.useRef)(null),s=(0,b.useRef)(e);s.current=e;let c=(0,b.useRef)(0),l=(0,b.useRef)(0);(0,b.useEffect)(()=>{let e=e=>{e.key===`Tab`&&(c.current=e.shiftKey?-1:1,window.setTimeout(()=>{c.current=0},0))};return document.addEventListener(`keydown`,e,!0),()=>document.removeEventListener(`keydown`,e,!0)},[]),(0,b.useEffect)(()=>{if(!t)return;let e=e=>{let n=e instanceof Element?e.closest(`[data-line]`):null;return n&&t.contains(n)?Number(n.dataset.line):-1},n=e=>{l.current=0,a(e)},i=i=>{let a=s.current,o=e(i.target),l=a[o];if(!l)return;let u=i.relatedTarget,d=c.current;if(d!==0&&!(u instanceof Node&&t.contains(u))){let e=Yy(a,d);e>=0&&e!==o&&n(a[e].key)}r(e=>e?.key===l.key?e:{key:l.key,headKey:l.headKey})},o=e=>{let n=e.relatedTarget;n instanceof Node&&!t.contains(n)&&(t.closest(`[role="dialog"]`)??t.closest(`[data-toolbox-list]`))?.contains(n)&&r(null)},u=r=>{if(r.key!==`Tab`||r.altKey||r.ctrlKey||r.metaKey)return;let i=s.current,a=e(r.target);if(a<0)return;let o=Jy(i,a,r.shiftKey?-1:1);o<0||t.querySelector(`[data-line="${o}"]`)||(r.preventDefault(),r.stopPropagation(),n(i[o].key))};return t.addEventListener(`focusin`,i),t.addEventListener(`focusout`,o),t.addEventListener(`keydown`,u,!0),()=>{t.removeEventListener(`focusin`,i),t.removeEventListener(`focusout`,o),t.removeEventListener(`keydown`,u,!0)}},[t]),(0,b.useLayoutEffect)(()=>{if(t){if(i!==null){let n=e.findIndex(e=>e.key===i),r=n>=0?t.querySelector(`[data-line="${n}"]`):null;if(r){a(null),(r.matches(Uy)?r:r.querySelector(Uy))?.focus();return}l.current+=1,n<0||l.current>3?a(null):o.current?.(n)}else if(n&&!e.some(e=>e.key===n.key)){let t=document.activeElement;(t===null||t===document.body||!t.isConnected)&&n.headKey&&e.some(e=>e.key===n.headKey)?(l.current=0,a(n.headKey)):r(null)}}});let u=n?.key??null,d=u===null?-1:e.findIndex(e=>e.key===u);return{keep:d>=0?d:null,scrollTo:o}}var K={list:`_list_yqq00_1`,count:`_count_yqq00_15`,keyRows:`_keyRows_yqq00_23`,lead:`_lead_yqq00_30`,key:`_key_yqq00_23`,actorsMenu:`_actorsMenu_yqq00_42`,keys:`_keys_yqq00_48`,segments:`_segments_yqq00_55`,segment:`_segment_yqq00_55`,menu:`_menu_yqq00_106`,menuSelect:`_menuSelect_yqq00_135`,menuMark:`_menuMark_yqq00_158`,find:`_find_yqq00_167`,findLabel:`_findLabel_yqq00_175`,field:`_field_yqq00_183`,input:`_input_yqq00_189`,clear:`_clear_yqq00_218`,groupMenu:`_groupMenu_yqq00_276`,menuKey:`_menuKey_yqq00_282`,menuKeyMark:`_menuKeyMark_yqq00_288`,groupList:`_groupList_yqq00_293`,groupItem:`_groupItem_yqq00_306`,groupCheck:`_groupCheck_yqq00_332`,empty:`_empty_yqq00_342`,emptyWords:`_emptyWords_yqq00_350`,rows:`_rows_yqq00_357`,head:`_head_yqq00_361`,row:`_row_yqq00_357`,openAll:`_openAll_yqq00_376`,stations:`_stations_yqq00_388`,items:`_items_yqq00_411`,item:`_item_yqq00_411`,sideMark:`_sideMark_yqq00_422`,top:`_top_yqq00_456`,name:`_name_yqq00_465`,outcome:`_outcome_yqq00_476`,lineCell:`_lineCell_yqq00_488`,does:`_does_yqq00_495`,metaCell:`_metaCell_yqq00_504`,meta:`_meta_yqq00_504`,same:`_same_yqq00_512`,actor:`_actor_yqq00_42`,groups:`_groups_yqq00_525`,fold:`_fold_yqq00_529`,foldTop:`_foldTop_yqq00_533`,foldHeading:`_foldHeading_yqq00_537`,foldHead:`_foldHead_yqq00_537`,chevron:`_chevron_yqq00_577`,chevronRoom:`_chevronRoom_yqq00_578`,foldTile:`_foldTile_yqq00_590`,foldName:`_foldName_yqq00_596`,foldActor:`_foldActor_yqq00_607`,foldCount:`_foldCount_yqq00_611`,foldNote:`_foldNote_yqq00_612`,foldStrip:`_foldStrip_yqq00_621`,foldHeadDept:`_foldHeadDept_yqq00_630`,foldStill:`_foldStill_yqq00_643`,foldWay:`_foldWay_yqq00_647`,department:`_department_yqq00_651`,deptLine:`_deptLine_yqq00_655`,pageFold:`_pageFold_yqq00_664`,pageFoldSummary:`_pageFoldSummary_yqq00_670`},Zy={picker:`_picker_wqyxx_1`,"picker-up":`_picker-up_wqyxx_1`,top:`_top_wqyxx_32`,find:`_find_wqyxx_39`,sort:`_sort_wqyxx_47`,list:`_list_wqyxx_76`,rows:`_rows_wqyxx_85`,option:`_option_wqyxx_89`,box:`_box_wqyxx_118`,tile:`_tile_wqyxx_135`,who:`_who_wqyxx_141`,name:`_name_wqyxx_150`,dot:`_dot_wqyxx_155`,archetype:`_archetype_wqyxx_156`,second:`_second_wqyxx_161`,counts:`_counts_wqyxx_171`,strip:`_strip_wqyxx_178`,empty:`_empty_wqyxx_183`,emptyWords:`_emptyWords_wqyxx_192`,said:`_said_wqyxx_200`,foot:`_foot_wqyxx_212`,done:`_done_wqyxx_261`},Qy=56,$y=`button:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])`;function eb(){return(0,x.jsx)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3 8.5L6.5 12L13 4.5`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.25`,strokeLinecap:`round`,strokeLinejoin:`round`})})}function tb({actors:e,chosen:t,max:n,tools:r=0,onChange:i,onClose:a,opener:o,where:s=`toolbox`}){let c=(0,b.useId)(),l=(0,b.useRef)(null),u=(0,b.useRef)(null),[d,f]=(0,b.useState)(``),[p,m]=(0,b.useState)(`run`),[h,g]=(0,b.useState)(``),_=jy(`(min-width: 900px)`),v=jy(`(min-width: 1440px)`),y=fv(e,r),S=(0,b.useMemo)(()=>dv(uv(e,d),p),[e,d,p]),C=S.length>0&&S.every(e=>t.has(e.index)),w=n!==void 0&&t.size>=n,T=(0,b.useRef)(!1);(0,b.useEffect)(()=>{T.current||(T.current=!0,B_({name:`forge_actor_picker_open`,where:s}))},[s]),(0,b.useEffect)(()=>{u.current?.focus({preventScroll:!0})},[]);let E=(0,b.useCallback)(()=>{a(),o?.isConnected&&o.focus()},[a,o]);(0,b.useEffect)(()=>{let e=l.current;if(!e)return;let t=t=>{if(t.key===`Escape`){t.preventDefault(),t.stopPropagation(),E();return}if(t.key!==`Tab`||t.altKey||t.ctrlKey||t.metaKey)return;t.stopPropagation();let n=Array.from(e.querySelectorAll($y)).filter(e=>e.tabIndex>=0&&e.offsetParent!==null);if(n.length===0){t.preventDefault();return}let r=n.indexOf(document.activeElement);(t.shiftKey?r<=0:r===-1||r===n.length-1)&&(t.preventDefault(),n[t.shiftKey?n.length-1:0].focus())};return e.addEventListener(`keydown`,t),()=>e.removeEventListener(`keydown`,t)},[E]),(0,b.useEffect)(()=>{let e=e=>{let t=e.target;l.current?.contains(t)||o?.contains(t)||a()};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[a,o]);let[D,O]=(0,b.useState)(null);(0,b.useLayoutEffect)(()=>{if(!_||!o){O(null);return}let e=v?560:480,t=()=>{let t=o.getBoundingClientRect(),n=Math.round(t.bottom+4),r=Math.round(Math.max(8,Math.min(t.left,window.innerWidth-e-8))),i=Math.round(Math.max(240,Math.min(560,window.innerHeight-n-16)));O(e=>e&&e.top===n&&e.left===r&&e.maxHeight===i?e:{top:n,left:r,maxHeight:i})};return t(),document.addEventListener(`scroll`,t,{capture:!0,passive:!0}),window.addEventListener(`resize`,t),()=>{document.removeEventListener(`scroll`,t,{capture:!0}),window.removeEventListener(`resize`,t)}},[_,v,o]);let k=(0,b.useCallback)(t=>{i(t);let n=L_(t.size);n&&B_({name:`forge_actor_filter`,actors:n});let r=e.length;g(wy(t.size===0?r:Math.min(t.size,r),r))},[i,e.length]),A=e=>{let n=new Set(t);if(n.has(e))n.delete(e);else if(w)return;else n.add(e);k(n)},j=(0,b.useMemo)(()=>S.map(e=>({key:e.label,kind:`option`,estimate:Qy,focusable:!0})),[S]),[ee,te]=(0,b.useState)(0),[M,N]=(0,b.useState)(!1),[ne,P]=(0,b.useState)(null),re=(0,b.useRef)(null),ie=(0,b.useRef)(!1),F=Math.min(ee,Math.max(0,S.length-1)),I=qy(j,ne,M?F:null),ae=F>=I.first&&F<=I.last||F===I.kept?F:I.first;(0,b.useEffect)(()=>{te(0),re.current&&(re.current.scrollTop=0)},[d,p]),(0,b.useLayoutEffect)(()=>{if(!ie.current||!ne)return;let e=ne.querySelector(`[data-line="${F}"]`);e?(ie.current=!1,e.focus({preventScroll:!0}),e.scrollIntoView({block:`nearest`})):I.scrollToLine(F)});let oe=e=>{S.length!==0&&(ie.current=!0,te(Math.max(0,Math.min(S.length-1,e))))},se=e=>{switch(e.key){case`ArrowDown`:e.preventDefault(),oe(F+1);break;case`ArrowUp`:e.preventDefault(),oe(F-1);break;case`Home`:e.preventDefault(),oe(0);break;case`End`:e.preventDefault(),oe(S.length-1);break;case` `:case`Enter`:e.preventDefault(),S[F]&&A(S[F].index)}},ce=()=>{f(``),u.current?.focus()},le=()=>{k(new Set),E()},L=[],ue=I.kept!==void 0&&I.kept<I.first;I.kept!==void 0&&ue&&L.push(I.kept);for(let e=I.first;e<=I.last;e+=1)L.push(e);I.kept!==void 0&&!ue&&L.push(I.kept);let de=I.kept===void 0||!I.gap?-1:ue?I.first:I.kept,fe=I.windowed?{paddingTop:I.padTop,paddingBottom:I.padBottom}:void 0,R=_&&D?{top:D.top,left:D.left,maxHeight:D.maxHeight}:void 0,z=e=>{let n=S[e];if(!n)return null;let r=t.has(n.index),i=!r&&w,a=n.unreadable?hy(n.label):n.status===`waiting`?xy.waiting:Ey(n.counts);return(0,x.jsxs)(`div`,{role:`option`,"aria-selected":r,"aria-disabled":i?!0:void 0,"aria-setsize":S.length,"aria-posinset":e+1,"aria-label":_y({label:n.label,name:n.name,archetype:n.archetype,tools:n.counts.tools,didNotPass:n.counts.didNotPass,unreadable:n.unreadable}),tabIndex:e===ae?0:-1,className:Zy.option,"data-actor":n.label,"data-line":e,onClick:()=>{te(e),A(n.index)},onFocus:()=>te(e),children:[(0,x.jsx)(`span`,{className:Zy.box,"data-checked":r,"aria-hidden":`true`,children:r&&(0,x.jsx)(eb,{})}),(0,x.jsx)(`span`,{className:Zy.tile,children:(0,x.jsx)(Ry,{index:n.index,colour:Pe(n.index)})}),(0,x.jsxs)(`span`,{className:Zy.who,translate:`no`,children:[(0,x.jsx)(`span`,{className:Zy.name,"data-picker-name":!0,children:n.name}),n.archetype&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:Zy.dot,"aria-hidden":`true`,children:` · `}),(0,x.jsx)(`span`,{className:Zy.archetype,"data-picker-archetype":!0,children:n.archetype})]})]}),(0,x.jsxs)(`span`,{className:Zy.second,children:[(0,x.jsx)(`span`,{className:Zy.counts,"data-picker-counts":!0,children:a}),!n.unreadable&&(0,x.jsx)(`span`,{className:Zy.strip,children:(0,x.jsx)(Vy,{cells:n.strip,max:v?20:10})})]})]},n.label)},pe=(0,x.jsx)(`div`,{ref:l,role:`dialog`,"aria-label":xy.dialogName,className:Zy.picker,style:R,"data-actor-picker":!0,children:y===`error`?(0,x.jsxs)(`div`,{className:Zy.empty,"data-picker-error":!0,children:[(0,x.jsx)(`p`,{className:Zy.emptyWords,"data-text":`body`,children:xy.unreadable}),(0,x.jsx)(`button`,{type:`button`,className:K.key,onClick:le,children:xy.showAll})]}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:Zy.top,children:[(0,x.jsxs)(`div`,{className:Zy.find,children:[(0,x.jsx)(`label`,{className:K.findLabel,htmlFor:c,children:xy.findLabel}),(0,x.jsxs)(`span`,{className:K.field,children:[(0,x.jsx)(`input`,{id:c,ref:u,className:K.input,type:`search`,placeholder:xy.findPlaceholder,value:d,onChange:e=>f(e.target.value),spellCheck:!1,autoComplete:`off`}),d!==``&&(0,x.jsx)(`button`,{type:`button`,className:K.clear,"aria-label":xy.clearSearchName,title:xy.clearSearchName,onClick:ce,children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3 3L13 13M13 3L3 13`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`})})})]})]}),(0,x.jsxs)(`label`,{className:Zy.sort,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:xy.sortLead}),(0,x.jsx)(`select`,{className:K.menuSelect,"aria-label":xy.sortName,value:p,onChange:e=>m(e.target.value),children:cv.map(e=>(0,x.jsx)(`option`,{value:e,children:Sy[e]},e))}),(0,x.jsx)(`svg`,{className:K.menuMark,width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3.5 6L8 10.5L12.5 6`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})]})]}),S.length===0?(0,x.jsxs)(`div`,{className:Zy.empty,"data-picker-empty":!0,children:[(0,x.jsx)(`p`,{className:Zy.emptyWords,"data-text":`body`,children:Dy(d.trim())}),(0,x.jsx)(`button`,{type:`button`,className:K.key,onClick:ce,children:xy.clear})]}):(0,x.jsx)(`div`,{ref:re,role:`listbox`,"aria-multiselectable":`true`,"aria-label":xy.listName,className:Zy.list,onKeyDown:se,onFocus:()=>N(!0),onBlur:e=>{e.relatedTarget instanceof Node&&e.currentTarget.contains(e.relatedTarget)||N(!1)},children:(0,x.jsx)(`div`,{ref:P,className:Zy.rows,style:fe,"data-windowed":I.windowed,children:L.flatMap(e=>[e===de?(0,x.jsx)(`div`,{"aria-hidden":`true`,"data-lines-gap":!0,style:{height:I.gap}},`gap`):null,z(e)])})}),(0,x.jsx)(`p`,{className:Zy.said,role:`status`,children:h}),(0,x.jsxs)(`div`,{className:Zy.foot,"data-picker-foot":!0,children:[(0,x.jsx)(`button`,{type:`button`,className:K.key,"aria-disabled":C||w||S.length===0?!0:void 0,onClick:()=>{C||w||S.length===0||k(pv(t,S,n))},children:xy.selectShown}),(0,x.jsx)(`button`,{type:`button`,className:K.key,onClick:()=>k(new Set),children:xy.clear}),(0,x.jsx)(`button`,{type:`button`,className:`${K.key} ${Zy.done}`,onClick:E,children:xy.done})]})]})}),me=o?.closest(`[role="dialog"]`)??(typeof document>`u`?null:document.body);return me?(0,Ay.createPortal)(pe,me):pe}var nb=e=>e.kind===`actor`?`actor:${e.actor.label}`:`department:${e.name}`,rb=e=>e.kind===`department`||!e.actor.unreadable&&e.actor.counts.tools>0;function ib(){let e=jy(`(min-width: 1440px)`),t=jy(`(min-width: 900px)`);return e?50:t?30:1/0}function ab(){return(0,x.jsx)(`svg`,{className:K.chevron,width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M6 3.5L10.5 8L6 12.5`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})}function ob({head:e,open:t,onToggle:n,onShowInEventLog:r}){let i=(0,b.useId)(),a=ib();if(e.kind===`department`)return(0,x.jsx)(`h3`,{className:K.foldHeading,"data-fold-head":e.name,children:(0,x.jsxs)(`button`,{type:`button`,className:`${K.foldHead} ${K.foldHeadDept}`,"aria-expanded":t,"aria-label":vy(e.name,e.counts),onClick:n,children:[(0,x.jsx)(ab,{}),(0,x.jsx)(`span`,{className:K.foldName,"data-fold-name":!0,"data-text":`heading`,children:e.name}),(0,x.jsx)(`span`,{className:K.foldCount,"data-fold-count":!0,children:py(e.counts)})]})});let{actor:o}=e,s=!o.unreadable&&o.counts.tools>=50,c=(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:K.foldTile,children:(0,x.jsx)(Ry,{index:o.index,colour:Pe(o.index)})}),(0,x.jsxs)(`span`,{className:K.foldName,"data-fold-name":!0,translate:`no`,"data-text":`heading`,children:[(0,x.jsx)(`span`,{className:K.foldActor,children:o.name}),o.archetype?` · ${o.archetype}`:``]}),o.unreadable?(0,x.jsx)(`span`,{className:K.foldCount,"data-fold-error":!0,children:hy(o.label)}):(0,x.jsx)(`span`,{className:K.foldCount,"data-fold-count":!0,children:o.counts.tools===0?my:py(o.counts)}),s&&(0,x.jsx)(`span`,{id:i,className:K.foldNote,"data-fold-note":!0,children:gy(50)}),!o.unreadable&&(0,x.jsx)(`span`,{className:K.foldStrip,children:(0,x.jsx)(Vy,{cells:o.strip,max:a})})]}),l=_y({label:o.label,name:o.name,archetype:o.archetype,tools:o.counts.tools,didNotPass:o.counts.didNotPass,unreadable:o.unreadable});return rb(e)?(0,x.jsx)(`h3`,{className:K.foldHeading,"data-fold-head":o.label,children:(0,x.jsxs)(`button`,{type:`button`,className:K.foldHead,"aria-expanded":t,"aria-label":l,"aria-describedby":s?i:void 0,onClick:n,children:[(0,x.jsx)(ab,{}),c]})}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`h3`,{className:K.foldHeading,"data-fold-head":o.label,children:(0,x.jsxs)(`span`,{className:`${K.foldHead} ${K.foldStill}`,children:[(0,x.jsx)(`span`,{className:K.chevronRoom,"aria-hidden":`true`}),c]})}),o.unreadable&&r&&(0,x.jsx)(`div`,{className:K.foldWay,children:(0,x.jsx)(`button`,{type:`button`,className:K.key,onClick:r,children:Hv.showInEventLog})})]})}var sb={glyph:`_glyph_bhdp0_1`,passed:`_passed_bhdp0_8`,rejected:`_rejected_bhdp0_12`,refused:`_refused_bhdp0_13`,failed:`_failed_bhdp0_14`,notJudged:`_notJudged_bhdp0_18`,didNotPass:`_didNotPass_bhdp0_22`};function cb(e,t,n){let r={fill:`none`,stroke:`currentColor`,strokeWidth:t,strokeLinecap:`round`,strokeLinejoin:`round`},i=(0,x.jsx)(`circle`,{cx:`10`,cy:`10`,r:`8.25`,...r});switch(e){case`passed`:return(0,x.jsx)(`path`,{fill:`currentColor`,fillRule:`evenodd`,d:`M1 10a9 9 0 1 0 18 0a9 9 0 1 0 -18 0Z M4.75 11.05L8.63 14.93L15.28 7.82L13.52 6.18L8.57 11.47L6.45 9.35Z`});case`rejected`:return(0,x.jsxs)(x.Fragment,{children:[i,(0,x.jsx)(`path`,{d:`M6.9 6.9L13.1 13.1M13.1 6.9L6.9 13.1`,...r})]});case`refused`:return(0,x.jsxs)(x.Fragment,{children:[i,(0,x.jsx)(`path`,{d:`M4.2 15.8L15.8 4.2`,...r})]});case`failed`:return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`path`,{d:`M10 2.2L18.2 16.8H1.8Z`,...r}),(0,x.jsx)(`path`,{d:`M10 7.4V12.2`,...r})]});case`notJudged`:return(0,x.jsxs)(x.Fragment,{children:[i,(0,x.jsx)(`path`,{d:`M7.7 7.9a2.4 2.4 0 1 1 3.5 2.1c-.8.4-1.2.9-1.2 1.7v.4`,...r}),(0,x.jsx)(`circle`,{cx:`10`,cy:`14.5`,r:`1.1`,fill:`currentColor`})]});case`didNotPass`:return(0,x.jsx)(`circle`,{cx:`10`,cy:`10`,r:`8.25`,...r,strokeLinecap:`butt`,strokeDasharray:n})}}function lb({kind:e,size:t}){let n=t===10?3:1.75,r=t===10?`5 4`:`2.6 2.1`;return(0,x.jsx)(`svg`,{className:`${sb.glyph} ${sb[e]}`,"data-glyph":e,width:t,height:t,viewBox:`0 0 20 20`,"aria-hidden":`true`,focusable:`false`,children:cb(e,n,r)})}var ub={cell:`_cell_1xygk_1`,trace:`_trace_1xygk_22`,station:`_station_1xygk_35`,stationKey:`_stationKey_1xygk_58`,mark:`_mark_1xygk_83`,name:`_name_1xygk_91`,result:`_result_1xygk_119`,evidence:`_evidence_1xygk_120`,fork:`_fork_1xygk_144`,forkLink:`_forkLink_1xygk_167`,forkWords:`_forkWords_1xygk_200`,chevron:`_chevron_1xygk_205`,row:`_row_1xygk_267`,spur:`_spur_1xygk_275`,rowStation:`_rowStation_1xygk_279`,segment:`_segment_1xygk_290`},db=e=>e===`reached`||e===`stopped`,fb=e=>e===void 0?void 0:db(e)?`solid`:`dashed`;function pb({model:e,station:t,size:n}){let r=e.stations[t];if(r===`stopped`){let r=e.stop;return(0,x.jsx)(lb,{kind:r&&r.station===t?r.glyph:`didNotPass`,size:n})}return(0,x.jsx)(`span`,{className:ub.cell,"data-cell":r})}function mb({mark:e,onAttempt:t,href:n}){let r=k_(e.outcome);return(0,x.jsx)(`div`,{className:ub.fork,"data-fork":e.attempt,children:(0,x.jsxs)(`a`,{className:ub.forkLink,href:n,"data-fork-attempt":e.attempt,onClick:n=>{n.defaultPrevented||n.button!==0||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey||(n.preventDefault(),t?.(e.attempt))},children:[(0,x.jsx)(lb,{kind:r,size:20}),(0,x.jsx)(`span`,{className:ub.forkWords,children:qv(e.attempt,bv[r])}),(0,x.jsx)(`svg`,{className:ub.chevron,width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M6 3.5L10.5 8L6 12.5`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})]})})}function hb(e){return e===`notReached`?gv.notReached:e===`unknown`?gv.unknown:null}function gb({model:e,size:t,colour:n,open:r,onToggle:i,stationResult:a,renderEvidence:o,onAttempt:s,attemptHref:c}){let l=(0,b.useId)(),u={"--line":n};return t===`row`?(0,x.jsx)(`span`,{className:ub.row,style:u,"aria-hidden":`true`,"data-forge-line":`row`,children:O_.map((t,n)=>{let r=e.spurs.filter(e=>e.station===t);return(0,x.jsxs)(b.Fragment,{children:[n>0&&(0,x.jsx)(`span`,{className:ub.segment,"data-rail":fb(e.stations[t])}),(0,x.jsxs)(`span`,{className:ub.rowStation,"data-station":t,"data-state":e.stations[t],children:[(0,x.jsx)(pb,{model:e,station:t,size:10}),r.length>0&&(0,x.jsx)(`span`,{className:ub.spur,"data-spurs":r.length,children:r.map(e=>(0,x.jsx)(lb,{kind:k_(e.outcome),size:10},e.attempt))})]})]},t)})}):(0,x.jsx)(`ol`,{className:ub.trace,style:u,role:`list`,"aria-label":yv,"data-forge-line":`trace`,children:O_.map((t,n)=>{let u=e.stations[t],d=o?.(t),f=d!=null&&d!==!1,p=db(u)&&f,m=p&&!!r?.has(t),h=a?.(t)??hb(u),g=`${l}-${t}-result`,_=`${l}-${t}-evidence`,v=`${l}-${t}-name`,y=u===`notReached`||u===`unknown`,b=[...e.spurs.filter(e=>e.station===t),...e.branch&&e.branch.station===t?[e.branch]:[]];return(0,x.jsxs)(`li`,{className:ub.station,"data-station":t,"data-state":u,"data-open":m||void 0,"data-rail":fb(e.stations[O_[n+1]]),children:[(0,x.jsxs)(`button`,{type:`button`,className:ub.stationKey,"aria-label":vv(t,u),"aria-expanded":p?m:void 0,"aria-controls":p?_:void 0,"aria-disabled":!p||void 0,"aria-describedby":!p&&h!=null?g:void 0,tabIndex:p?void 0:-1,onClick:p?()=>i?.(t):void 0,children:[(0,x.jsx)(`span`,{className:ub.mark,"aria-hidden":`true`,children:(0,x.jsx)(pb,{model:e,station:t,size:20})}),(0,x.jsx)(`span`,{id:v,className:ub.name,"data-text":`heading`,children:hv[t]})]}),!m&&h!=null&&(0,x.jsx)(`div`,{id:g,className:ub.result,"data-quiet":y||void 0,"data-text":y?void 0:`body`,children:h}),p&&(0,x.jsx)(`div`,{id:_,className:ub.evidence,role:`region`,"aria-labelledby":v,hidden:!m,children:m?d:null}),b.map(e=>(0,x.jsx)(mb,{mark:e,onAttempt:s,href:c?c(e.attempt):`#`},e.attempt))]},t)})})}function _b(e){let t=e.split(`_`);return t.map((e,n)=>(0,x.jsxs)(b.Fragment,{children:[n<t.length-1?`${e}_`:e,n<t.length-1&&(0,x.jsx)(`wbr`,{})]},n))}function vb({entry:e,actorCount:t,onOpen:n,line:r,setSize:i,posInSet:a}){let o=(0,b.useId)(),s=xv(e.actorIndex),c=k_(e.outcome),l=bv[c],u=e.attempts.length,d=e.description!==``&&e.description!==e.name,f=e.sameNameActors.map(xv),p={"--actor":Pe(e.actorIndex)};return(0,x.jsxs)(`li`,{className:K.item,style:p,"data-tool-row":e.n,"data-tool-name":e.name,"data-actor":s,"data-outcome":e.outcome,"data-line":r,"aria-setsize":i,"aria-posinset":a,children:[(0,x.jsx)(`span`,{className:K.sideMark,"data-side-mark":!0,"aria-hidden":`true`}),(0,x.jsxs)(`button`,{type:`button`,className:K.row,"aria-label":ly({name:e.name,outcome:l,actorLabel:s,actorName:e.actorName,forges:u}),"aria-describedby":d?`${o}-does ${o}-meta`:`${o}-meta`,onClick:e=>n(e.currentTarget),children:[(0,x.jsxs)(`span`,{className:K.top,children:[(0,x.jsxs)(`span`,{className:K.name,"data-row-name":!0,"data-text":`heading`,children:[(0,x.jsxs)(`span`,{children:[`[`,e.n,`]`]}),` `,(0,x.jsx)(`span`,{translate:`no`,children:_b(e.name)})]}),(0,x.jsxs)(`span`,{className:K.outcome,"data-row-outcome":!0,children:[(0,x.jsx)(lb,{kind:c,size:20}),(0,x.jsx)(`span`,{children:l})]})]}),(0,x.jsx)(`span`,{className:K.lineCell,children:(0,x.jsx)(gb,{model:N_(e,NaN),size:`row`,colour:P_(e.actorIndex,t)})}),d&&(0,x.jsx)(`span`,{id:`${o}-does`,className:K.does,"data-row-does":!0,"data-text":`body`,children:e.description}),(0,x.jsxs)(`span`,{id:`${o}-meta`,className:K.metaCell,children:[(0,x.jsxs)(`span`,{className:K.meta,"data-row-meta":!0,children:[(0,x.jsx)(`span`,{className:K.actor,"data-row-actor":!0,children:`${s} ${e.actorName}`}),` · ${sy({department:e.firstForgedDepartment,turn:e.firstForgedTurn,uses:e.outcome===`passed`?F_(e):null,reforges:Math.max(0,u-1)})}`]}),f.length>0&&(0,x.jsx)(`span`,{className:K.same,"data-row-same":!0,children:cy(f)})]})]})]})}function yb(e,t,n,r=null){let i=n.trim().toLowerCase(),a=r===null?null:new Set(r);return t===`all`&&i===``&&a===null?e:e.filter(e=>(a===null||a.has(e.actorIndex))&&(t===`all`||e.outcome===t)&&(i===``||e.name.toLowerCase().includes(i)))}function bb(e){let t={tools:0,forges:0,reforges:0,passed:0,didNotPass:0};for(let n of e)t.tools+=n.counts.tools,t.forges+=n.counts.forges,t.reforges+=n.counts.reforges,t.passed+=n.counts.passed,t.didNotPass+=n.counts.didNotPass;return t}var xb=e=>e.firstForgedDepartment||gv.unknown;function Sb(e,t){let n=new Map;for(let r of e){let e=t(r),i=n.get(e);i?i.push(r):n.set(e,[r])}return[...n]}function Cb(e){let t={tools:0,forges:0,reforges:0,passed:0,didNotPass:0};for(let n of e){let e=n.attempts.filter(e=>e.approved).length;t.tools+=1,t.forges+=n.attempts.length,t.reforges+=Math.max(0,n.attempts.length-1),t.passed+=e,t.didNotPass+=n.attempts.length-e}return t}function wb(e,t,n){return t===`none`?[{head:null,rows:e}]:t===`department`?Sb(e,xb).map(([e,t])=>({head:{kind:`department`,name:e,counts:Cb(t)},rows:t})):n.map(t=>{let n=e.filter(e=>e.actorIndex===t.index);return{head:{kind:`actor`,actor:t},rows:Sb(n,xb).flatMap(([,e])=>e)}})}var Tb={head:64,dept:40,row:112},Eb=e=>`${e.actorIndex}:${e.name}`,Db=e=>e.kind===`head`?null:e.dept;function Ob(e,t,n,r){let i=[];if(e===`none`)return t.forEach((e,t)=>{i.push({kind:`row`,key:Eb(e),estimate:Tb.row,focusable:!0,fold:-1,dept:null,entry:e,pos:t+1})}),{lines:i,rowCount:t.length};let a=0;return n.forEach((e,t)=>{let n=e.head;if(n===null)return;let o=nb(n),s=rb(n)&&e.rows.length>0&&r(o),c=rb(n)||n.kind===`actor`&&n.actor.unreadable;i.push({kind:`head`,key:o,estimate:Tb.head,focusable:c,fold:t});let l=n.kind===`actor`?Sb(e.rows,xb):[[null,e.rows]];for(let[e,n]of l){s&&e!==null&&i.push({kind:`dept`,key:`${o}|dept:${e}`,estimate:Tb.dept,focusable:!1,headKey:o,fold:t,dept:e});for(let r of n)a+=1,s&&i.push({kind:`row`,key:`${o}|${Eb(r)}`,estimate:Tb.row,focusable:!0,headKey:o,fold:t,dept:e,entry:r,pos:a})}}),{lines:i,rowCount:a}}var kb=8,Ab=new Set,jb=[];function Mb({value:e,onChoose:t}){let[n,r]=(0,b.useState)(!1),i=(0,b.useId)(),a=(0,b.useRef)(null),o=(0,b.useRef)(null),s=(0,b.useRef)([]);(0,b.useEffect)(()=>{n&&s.current[nv.indexOf(e)]?.focus()},[n,e]),(0,b.useEffect)(()=>{if(!n)return;let e=e=>{a.current?.contains(e.target)||r(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[n]);let c=()=>{r(!1),o.current?.focus()},l=e=>{t(e),c()},u=e=>s.current[(e+nv.length)%nv.length]?.focus();return(0,x.jsxs)(`div`,{ref:a,className:K.groupMenu,children:[(0,x.jsxs)(`button`,{ref:o,type:`button`,className:`${K.key} ${K.menuKey}`,"aria-haspopup":`menu`,"aria-expanded":n,"aria-controls":n?i:void 0,onClick:()=>r(e=>!e),onKeyDown:e=>{(e.key===`ArrowDown`||e.key===`ArrowUp`)&&(e.preventDefault(),r(!0))},children:[(0,x.jsx)(`span`,{children:dy(e)}),(0,x.jsx)(`svg`,{className:K.menuKeyMark,width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3.5 6L8 10.5L12.5 6`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})]}),n&&(0,x.jsx)(`div`,{id:i,role:`menu`,"aria-label":uy.name,className:K.groupList,onKeyDown:e=>{let t=s.current.findIndex(e=>e===document.activeElement);switch(e.key){case`ArrowDown`:e.preventDefault(),u(t+1);break;case`ArrowUp`:e.preventDefault(),u(t-1);break;case`Home`:e.preventDefault(),u(0);break;case`End`:e.preventDefault(),u(nv.length-1);break;case`Enter`:case` `:e.preventDefault(),t>=0&&l(nv[t]);break;case`Escape`:e.preventDefault(),c();break;case`Tab`:c()}},children:nv.map((t,n)=>(0,x.jsxs)(`div`,{ref:e=>{s.current[n]=e},role:`menuitemradio`,"aria-checked":t===e,tabIndex:-1,className:K.groupItem,onClick:()=>l(t),children:[(0,x.jsx)(`svg`,{className:K.groupCheck,width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3 8.5L6.5 12L13 4.5`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})}),(0,x.jsx)(`span`,{children:uy[t]})]},t))})]})}function Nb({inPage:e=!1}){let t=D_(),{show:n,find:r,group:i,actors:a,set:o}=sv(),{openTrace:s,showActorLog:c}=ev(),l=(0,b.useId)(),u=(0,b.useId)(),d=(0,b.useRef)(null),f=(0,b.useRef)(null),p=(0,b.useRef)(null),[m,h]=(0,b.useState)(!1),g=t.actors.length,_=(0,b.useMemo)(()=>mv(a,g),[a,g]),v=(0,b.useMemo)(()=>_===null?t.actors:_.map(e=>t.actors[e]),[_,t.actors]),y=(0,b.useMemo)(()=>new Set(a.filter(e=>e<g)),[a,g]),S=(0,b.useMemo)(()=>yb(t.list,`all`,``,_),[t.list,_]),C=(0,b.useMemo)(()=>yb(S,n,r),[S,n,r]),w=i??rv(g),T=n!==`all`||r.trim()!==``,E=(0,b.useMemo)(()=>{let e=S.filter(e=>e.outcome===`passed`).length;return[{id:`all`,count:S.length},{id:`passed`,count:e},{id:`did_not_pass`,count:S.length-e}].filter(e=>e.id===`all`||e.count>0||e.id===n)},[S,n]),D=(0,b.useMemo)(()=>{let e=wb(C,w,v);return T?e.filter(e=>e.head===null||e.rows.length>0||e.head.kind===`actor`&&e.head.actor.unreadable):e},[C,w,v,T]),O=_===null?ey(t.counts,g):Ty(_.length,g,bb(v)),k=(0,b.useCallback)(e=>{o({actors:[...e].sort((e,t)=>e-t)})},[o]),A=(0,b.useCallback)(()=>h(!1),[]),[j,ee]=(0,b.useState)({group:w,all:null,toggled:Ab}),te=(0,b.useMemo)(()=>j.group===w?j:{group:w,all:null,toggled:Ab},[j,w]),M=g<=kb,N=(0,b.useCallback)(e=>(te.all??M)!==te.toggled.has(e),[te,M]),ne=D.filter(e=>e.head!==null&&rb(e.head)&&e.rows.length>0),P=ne.length>0&&ne.every(e=>N(nb(e.head))),re=w===`none`||ne.length===0,ie=e=>{B_({name:`forge_group_toggle`,scope:`one`}),ee(t=>{let n=t.group===w?t:{group:w,all:null,toggled:Ab},r=new Set(n.toggled);return r.has(e)?r.delete(e):r.add(e),{...n,toggled:r}})},F=()=>{B_({name:`forge_group_toggle`,scope:`all`}),ee({group:w,all:!P,toggled:Ab})},I=e=>{e!==w&&B_({name:`forge_toolbox_group`,group:e}),o({group:e===rv(g)?null:e})},ae=e=>{e!==n&&B_({name:`forge_toolbox_filter`,show:e}),o({show:e})},oe=(0,b.useCallback)((e,t)=>{s({actorIndex:e.actorIndex,toolName:e.name},t,`toolbox`)},[s]),{lines:se,rowCount:ce}=(0,b.useMemo)(()=>Ob(w,C,D,N),[w,C,D,N]),[le,L]=(0,b.useState)(null),ue=Xy(se,le),de=qy(se,le,ue.keep);ue.scrollTo.current=de.scrollToLine;let fe=()=>{o({find:``}),f.current?.focus()},R=()=>{ae(`all`);let e=d.current?.querySelectorAll(`input[type="radio"][value="all"], select`);Array.from(e??[]).find(e=>e.offsetParent!==null)?.focus()},z=e=>`${ty[e.id]} ${Jv(e.count)}`,pe=e=>{let t=se[e];return t.kind===`row`?(0,x.jsx)(vb,{entry:t.entry,actorCount:g,onOpen:e=>oe(t.entry,e),line:e,setSize:ce,posInSet:t.pos},Eb(t.entry)):null},me=[],he=de.kept!==void 0&&de.kept<de.first;de.kept!==void 0&&he&&me.push(de.kept);for(let e=de.first;e<=de.last;e+=1)me.push(e);de.kept!==void 0&&!he&&me.push(de.kept);let ge=de.kept===void 0||!de.gap?-1:he?de.first:de.kept,_e=(e,t)=>{if(e!==ge)return null;let n={height:de.gap};return t?(0,x.jsx)(`li`,{role:`presentation`,"aria-hidden":`true`,"data-lines-gap":!0,style:n},`gap`):(0,x.jsx)(`div`,{"aria-hidden":`true`,"data-lines-gap":!0,style:n},`gap`)},B=e=>e.flatMap(e=>[_e(e,!0),pe(e)]),ve=de.windowed?{paddingTop:de.padTop,paddingBottom:de.padBottom}:void 0,ye=[];for(let e of me){let t=ye[ye.length-1];t&&t.fold===se[e].fold?t.at.push(e):ye.push({fold:se[e].fold,at:[e]})}let be=e=>{let t=[];for(let n of e){let e=Db(se[n])??``,r=t[t.length-1];r&&r.dept===e?r.at.push(n):t.push({dept:e,at:[n]})}return t};return(0,x.jsxs)(`div`,{className:K.list,"data-toolbox-list":e?`page`:`dialog`,children:[(0,x.jsx)(`p`,{className:K.count,"data-toolbox-count":!0,children:O}),t.list.length===0?(0,x.jsxs)(`div`,{className:K.empty,"data-toolbox-empty":`no-tools`,children:[(0,x.jsx)(Vy,{cells:jb}),(0,x.jsx)(`p`,{className:K.emptyWords,"data-text":`body`,children:ry.noTools})]}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:K.keyRows,children:[(0,x.jsxs)(`div`,{className:K.lead,"data-toolbox-lead":!0,children:[(0,x.jsx)(Mb,{value:w,onChoose:I}),(0,x.jsxs)(`div`,{className:K.actorsMenu,children:[(0,x.jsx)(`button`,{ref:p,type:`button`,className:K.key,"aria-haspopup":`dialog`,"aria-expanded":m,onClick:()=>h(e=>!e),children:Cy(_===null?null:_.length,g)}),m&&(0,x.jsx)(tb,{actors:t.actors,tools:t.list.length,chosen:y,onChange:k,onClose:A,opener:p.current})]})]}),(0,x.jsxs)(`div`,{ref:d,className:K.keys,"data-toolbox-keys":!0,children:[(0,x.jsx)(`div`,{className:K.segments,role:`radiogroup`,"aria-label":ty.name,children:E.map(e=>(0,x.jsxs)(`label`,{className:K.segment,"data-show":e.id,children:[(0,x.jsx)(`input`,{type:`radio`,name:u,value:e.id,checked:n===e.id,onChange:()=>ae(e.id)}),(0,x.jsx)(`span`,{children:z(e)})]},e.id))}),(0,x.jsxs)(`label`,{className:K.menu,"data-toolbox-menu":!0,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:ty.menuLead}),(0,x.jsx)(`select`,{className:K.menuSelect,"aria-label":ty.name,value:n,onChange:e=>ae(e.target.value),children:E.map(e=>(0,x.jsx)(`option`,{value:e.id,children:z(e)},e.id))}),(0,x.jsx)(`svg`,{className:K.menuMark,width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3.5 6L8 10.5L12.5 6`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})]}),(0,x.jsxs)(`div`,{className:K.find,children:[(0,x.jsx)(`label`,{className:K.findLabel,htmlFor:l,children:ny.label}),(0,x.jsxs)(`span`,{className:K.field,children:[(0,x.jsx)(`input`,{id:l,ref:f,className:K.input,type:`search`,placeholder:ny.placeholder,value:r,onChange:e=>o({find:e.target.value}),spellCheck:!1,autoComplete:`off`}),r!==``&&(0,x.jsx)(`button`,{type:`button`,className:K.clear,"aria-label":ny.clearName,title:ny.clearName,onClick:fe,children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3 3L13 13M13 3L3 13`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`})})})]})]})]})]}),C.length===0&&T?(0,x.jsx)(`div`,{className:K.empty,"data-toolbox-empty":r.trim()===``?`no-rows`:`no-match`,children:r.trim()===``?(0,x.jsxs)(x.Fragment,{children:[n===`did_not_pass`&&_===null&&(0,x.jsx)(`p`,{className:K.emptyWords,"data-text":`body`,children:ry.everyToolPassed}),(0,x.jsx)(`button`,{type:`button`,className:K.key,onClick:R,children:ty.all})]}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`p`,{className:K.emptyWords,"data-text":`body`,children:iy(r.trim())}),(0,x.jsx)(`button`,{type:`button`,className:K.key,onClick:fe,children:ny.clear})]})}):(0,x.jsxs)(`div`,{className:K.rows,children:[(0,x.jsxs)(`div`,{className:K.head,children:[(0,x.jsx)(`button`,{type:`button`,className:`${K.key} ${K.openAll}`,"aria-disabled":re?!0:void 0,tabIndex:re?-1:void 0,onClick:re?void 0:F,children:P?fy.close:fy.open}),(0,x.jsx)(`span`,{className:K.stations,"data-toolbox-stations":!0,"aria-hidden":`true`,children:O_.map(e=>(0,x.jsx)(`span`,{children:hv[e]},e))})]}),w===`none`?(0,x.jsx)(`ol`,{ref:L,className:K.items,"data-toolbox-rows":!0,"data-line-count":se.length,"data-windowed":de.windowed,style:ve,children:B(me)}):(0,x.jsx)(`div`,{ref:L,role:`list`,className:K.groups,"data-toolbox-rows":!0,"data-line-count":se.length,"data-windowed":de.windowed,style:ve,children:ye.map(({fold:e,at:t})=>{let n=D[e],r=n?.head??null;if(r===null)return null;let i=nb(r),a=rb(r)&&n.rows.length>0&&N(i),o=t.find(e=>se[e].kind===`head`),s=t.filter(e=>se[e].kind!==`head`);return(0,x.jsxs)(`div`,{role:`listitem`,"aria-setsize":D.length,"aria-posinset":e+1,className:K.fold,"data-fold":r.kind===`actor`?r.actor.label:r.name,children:[o!==void 0&&_e(o,!1),o!==void 0&&(0,x.jsx)(`div`,{className:K.foldTop,"data-line":o,children:(0,x.jsx)(ob,{head:r,open:a,onToggle:()=>ie(i),onShowInEventLog:r.kind===`actor`&&r.actor.unreadable?()=>c(r.actor.index):void 0})}),r.kind===`actor`?be(s).map(({dept:e,at:t})=>{let n=t.find(e=>se[e].kind===`dept`),r=t.filter(e=>se[e].kind===`row`);return(0,x.jsxs)(`div`,{className:K.department,children:[n!==void 0&&_e(n,!1),n!==void 0&&(0,x.jsx)(`h4`,{className:K.deptLine,"data-dept-line":!0,"data-line":n,children:e}),r.length>0&&(0,x.jsx)(`ol`,{className:K.items,children:B(r)})]},e)}):s.length>0&&(0,x.jsx)(`ol`,{className:K.items,children:B(s)})]},i)})})]})]})]})}var Pb={dialog:`_dialog_x8cpw_1`,"sheet-up":`_sheet-up_x8cpw_1`,header:`_header_x8cpw_36`,headerEnd:`_headerEnd_x8cpw_48`,title:`_title_x8cpw_55`,exportInHeader:`_exportInHeader_x8cpw_73`,exportStatus:`_exportStatus_x8cpw_77`,footStatus:`_footStatus_x8cpw_95`,body:`_body_x8cpw_106`,foot:`_foot_x8cpw_95`,exportAtFoot:`_exportAtFoot_x8cpw_114`};function Fb(e){return e.map(e=>({n:e.n,name:e.name,description:e.description,mode:e.mode,firstForgedTurn:e.firstForgedTurn,firstForgedDepartment:e.firstForgedDepartment,departments:[...e.departments],reuseCount:e.reuseCount,approved:e.approved,confidence:e.confidence,inputSchema:e.inputSchema,outputSchema:e.outputSchema,sampleOutput:e.sampleOutput,inputFields:e.inputFields,outputFields:e.outputFields,actor:xv(e.actorIndex),actorName:e.actorName}))}function Ib(e){let t=new Blob([JSON.stringify(Fb(e),null,2)],{type:`application/json`}),n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=oy,r.click(),URL.revokeObjectURL(n)}var Lb=500;function Rb({covered:e,onClose:t}){let n=D_(),{show:r,find:i,actors:a}=sv(),o=Pt(!0),s=(0,b.useRef)(null);(0,b.useEffect)(()=>{s.current?.focus()},[]);let c=(0,b.useRef)(e);c.current=e,(0,b.useEffect)(()=>{let e=e=>{e.key!==`Escape`||e.defaultPrevented||c.current||(e.preventDefault(),t())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[t]);let[l,u]=(0,b.useState)({state:`idle`}),d=()=>{B_({name:`forge_record_export`,what:`toolbox`});let e=yb(n.list,r,i,mv(a,n.actors.length)),t=()=>{try{Ib(e),u({state:`idle`})}catch{u({state:`failed`})}};e.length<=Lb?t():(u({state:`exporting`,tools:e.length}),requestAnimationFrame(()=>{window.setTimeout(t,0)}))},f=l.state===`exporting`?yy(l.tools):l.state===`failed`?by:``;return(0,x.jsx)(`div`,{className:Oy.backdrop,onMouseDown:e=>{e.target===e.currentTarget&&t()},children:(0,x.jsxs)(`div`,{ref:o,role:`dialog`,"aria-modal":`true`,"aria-label":Zv(n.list.length),tabIndex:-1,className:Pb.dialog,inert:e,children:[(0,x.jsxs)(`div`,{className:Pb.header,"data-toolbox-header":!0,children:[(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Oy.iconKey}`,onClick:()=>t(),"aria-label":$v,title:$v,children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3 3L13 13M13 3L3 13`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`})})}),(0,x.jsx)(`h2`,{ref:s,className:Pb.title,tabIndex:-1,"data-toolbox-title":!0,"data-text":`heading`,children:Xv}),(0,x.jsxs)(`span`,{className:Pb.headerEnd,children:[(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Pb.exportInHeader}`,onClick:d,children:ay}),(0,x.jsx)(ky,{})]}),(0,x.jsx)(`span`,{className:Pb.exportStatus,role:`status`,"data-export-status":!0,children:f})]}),(0,x.jsx)(`div`,{className:Pb.body,children:(0,x.jsx)(Nb,{})}),(0,x.jsxs)(`div`,{className:Pb.foot,children:[(0,x.jsx)(`p`,{className:Pb.footStatus,role:`status`,"data-export-status":!0,children:f}),(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Pb.exportAtFoot}`,onClick:d,children:ay})]})]})})}var zb=`paracosm:forgeOpenStations`,Bb=20,Vb=e=>typeof e==`string`&&O_.includes(e);function Hb(e){let t=new Map,n;try{n=e.getItem(zb)}catch{return t}if(!n)return t;let r;try{r=JSON.parse(n)}catch{return t}if(!r||typeof r!=`object`||Array.isArray(r))return t;for(let[e,n]of Object.entries(r))Array.isArray(n)&&t.set(e,O_.filter(e=>n.some(t=>Vb(t)&&t===e)));return t}function Ub(e,t){return Hb(e).get(t)??[]}function Wb(e,t,n){let r=Hb(e);r.delete(t),r.set(t,O_.filter(e=>n.includes(e)));let i=[...r.keys()];for(let e of i.slice(0,Math.max(0,i.length-Bb)))r.delete(e);try{e.setItem(zb,JSON.stringify(Object.fromEntries(r)))}catch{}}function Gb(e,t,n){let r=new Set([e.deciding]);for(let e of t)n(e)&&r.add(e);return r}function Kb(e){return t=>t===`request`||e&&(t===`judge`||t===`added`)}function qb(e,t){let n=null;try{n=new URL(e).searchParams.get(`replay`)}catch{}return n||t||`live`}var Jb={open:`_open_o8eqn_1`,part:`_part_o8eqn_11`,heading:`_heading_o8eqn_18`,body:`_body_o8eqn_26`,meta:`_meta_o8eqn_34`,quiet:`_quiet_o8eqn_42`,code:`_code_o8eqn_49`,actor:`_actor_o8eqn_62`,rule:`_rule_o8eqn_68`,actorText:`_actorText_o8eqn_74`,link:`_link_o8eqn_81`,fieldsBar:`_fieldsBar_o8eqn_105`,switch:`_switch_o8eqn_110`,switchTrack:`_switchTrack_o8eqn_139`,caption:`_caption_o8eqn_167`,fields:`_fields_o8eqn_105`,confidence:`_confidence_o8eqn_247`,meter:`_meter_o8eqn_258`,meterFill:`_meterFill_o8eqn_267`,uses:`_uses_o8eqn_275`,use:`_use_o8eqn_275`,recordKeys:`_recordKeys_o8eqn_295`,recordSaid:`_recordSaid_o8eqn_307`,record:`_record_o8eqn_295`};function Yb(e,t){let n=t.trim(),r=e=>String(e??``).trim()===n,i=[];for(let t of e){let e=t.data??{},n=t.type===`forge_attempt`&&r(e.name),a=t.type===`specialist_done`&&Array.isArray(e.forgedTools)&&e.forgedTools.some(e=>!!e&&typeof e==`object`&&r(e.name));if(!n&&!a)continue;let o={...e};delete o._filteredTools,i.push(o)}return i}function Xb(e){try{return JSON.stringify(e,null,2)}catch{return null}}var Zb=5e3;function Qb({entry:e,frames:t,onShowInEventLog:n}){let r=(0,b.useId)(),i=(0,b.useMemo)(()=>Xb(t),[t]),[a,o]=(0,b.useState)(null),s=(0,b.useRef)(null),c=(0,b.useRef)(0);(0,b.useEffect)(()=>()=>{s.current!==null&&window.clearTimeout(s.current)},[]);let l=e=>{s.current!==null&&window.clearTimeout(s.current),s.current=null,o(e),e===`copied`&&(s.current=window.setTimeout(()=>o(null),Zb))},u=()=>{if(i===null)return;B_({name:`forge_record_export`,what:`record_copy`});let e=++c.current;Dt(i).then(()=>{e===c.current&&l(`copied`)},()=>{e===c.current&&l(`copyFailed`)})},d=()=>{if(i!==null){B_({name:`forge_record_export`,what:`record_download`});try{let t=URL.createObjectURL(new Blob([i],{type:`application/json`})),n=document.createElement(`a`);n.href=t,n.download=Uv(e.name),document.body.append(n),n.click(),n.remove(),window.setTimeout(()=>URL.revokeObjectURL(t),1e3),l(null)}catch{l(`downloadFailed`)}}},f={copied:Hv.copied,copyFailed:Hv.copyFailed,downloadFailed:Hv.downloadFailed};return(0,x.jsxs)(`section`,{className:Jb.open,"data-record-panel":!0,"aria-labelledby":r,children:[(0,x.jsx)(`h3`,{id:r,className:Jb.heading,"data-text":`heading`,children:Hv.rawRecord}),i===null?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`p`,{className:Jb.body,"data-text":`body`,children:Hv.unreadable}),(0,x.jsx)(`div`,{className:Jb.recordKeys,children:(0,x.jsx)(`button`,{type:`button`,className:Jb.switch,onClick:n,children:Hv.showInEventLog})})]}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:Jb.recordKeys,children:[(0,x.jsx)(`button`,{type:`button`,className:Jb.switch,onClick:u,children:Hv.copy}),(0,x.jsx)(`button`,{type:`button`,className:Jb.switch,onClick:d,children:Hv.download}),(0,x.jsx)(`button`,{type:`button`,className:Jb.switch,onClick:n,children:Hv.showInEventLog}),(0,x.jsx)(`p`,{className:Jb.recordSaid,role:`status`,children:a?f[a]:null})]}),(0,x.jsx)(`pre`,{className:Jb.record,"data-raw-record":!0,translate:`no`,tabIndex:0,"aria-label":Hv.rawRecord,children:i})]})]})}function $b({entry:e}){let t=F_(e);return(0,x.jsxs)(`div`,{className:Jb.open,children:[(0,x.jsx)(`p`,{className:Jb.body,"data-text":`body`,children:Nv(t)}),e.history.length>0&&(0,x.jsx)(`ol`,{className:Jb.uses,children:e.history.map((e,t)=>{let n=t===0||e.isReforge;return(0,x.jsxs)(`li`,{className:Jb.use,"data-history-row":n?`forge`:`use`,children:[(0,x.jsx)(`p`,{className:Jb.meta,children:Vv(e.turn,e.department,e.eventTitle)}),e.output?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`p`,{className:Jb.meta,children:Bv.output}),(0,x.jsx)(`pre`,{className:Jb.code,translate:`no`,children:e.output})]}):null,n&&(0,x.jsx)(`p`,{className:Jb.quiet,children:Bv.testNotRecorded})]},`${e.turn}-${e.eventIndex}-${e.department}-${t}`)})}),t===0&&(0,x.jsx)(`p`,{className:Jb.quiet,children:Bv.notUsed})]})}function ex({confidence:e}){let t=Math.min(1,Math.max(0,Number(e.toFixed(2))));return(0,x.jsxs)(`div`,{className:Jb.open,children:[(0,x.jsx)(`h3`,{className:Jb.heading,"data-text":`heading`,children:Rv.heading}),(0,x.jsx)(`p`,{className:Jb.meta,children:Rv.notice}),(0,x.jsxs)(`div`,{className:Jb.confidence,children:[(0,x.jsx)(`p`,{className:Jb.body,"data-text":`body`,children:zv(e)}),(0,x.jsx)(`div`,{role:`meter`,className:Jb.meter,"aria-label":Rv.meterName,"aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":t,children:(0,x.jsx)(`span`,{className:Jb.meterFill,style:{width:`${t*100}%`},"data-meter-fill":!0})})]}),(0,x.jsx)(`p`,{className:Jb.quiet,children:Rv.wordsNotRecorded})]})}function tx({station:e}){return(0,x.jsx)(x.Fragment,{children:jv[e]})}function nx({reason:e}){let t=(0,b.useId)();return(0,x.jsxs)(`section`,{className:Oy.reason,"aria-labelledby":t,children:[(0,x.jsx)(`h3`,{id:t,className:Oy.reasonHeading,"data-text":`heading`,children:Av.heading}),e?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`pre`,{className:Oy.reasonText,translate:`no`,children:e}),(0,x.jsx)(`p`,{className:Oy.reasonNote,children:Av.limit})]}):(0,x.jsx)(`p`,{className:Oy.reasonNote,children:Av.none})]})}var rx=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function ix(e){if(!rx(e))return``;let{type:t}=e;return typeof t==`string`?t:Array.isArray(t)?t.filter(e=>typeof e==`string`).join(` | `):``}function ax(e,t){if(rx(e)&&rx(e.properties)){let t=Array.isArray(e.required)?e.required:[];return Object.entries(e.properties).map(([e,n])=>({name:e,type:ix(n),required:t.includes(e),description:rx(n)&&typeof n.description==`string`?n.description:``}))}return t.map(e=>({name:e,type:null,required:null,description:``}))}function ox(e,t){if(t.length===0||!rx(e)||!rx(e.properties))return e;let n=Object.keys(e.properties);return n.length===t.length&&t.every(e=>n.includes(e))?e:void 0}function sx(e,t,n){return[`sim-event-${e}-${t}-${n}`,`turn-row-${t}-h`].find(e=>document.getElementById(e)!==null)??null}function cx({caption:e,rows:t,none:n}){let r=(0,b.useId)(),[i,a,o,s]=Lv.columns;return t.length===0?(0,x.jsxs)(`div`,{className:Jb.part,children:[(0,x.jsx)(`p`,{className:Jb.caption,"data-text":`heading`,children:e}),(0,x.jsx)(`p`,{className:Jb.quiet,children:n})]}):(0,x.jsxs)(`table`,{className:Jb.fields,role:`table`,"aria-labelledby":r,children:[(0,x.jsx)(`caption`,{id:r,className:Jb.caption,"data-text":`heading`,children:e}),(0,x.jsx)(`thead`,{role:`rowgroup`,children:(0,x.jsx)(`tr`,{role:`row`,children:Lv.columns.map(e=>(0,x.jsx)(`th`,{role:`columnheader`,scope:`col`,children:e},e))})}),(0,x.jsx)(`tbody`,{role:`rowgroup`,children:t.map(e=>(0,x.jsxs)(`tr`,{role:`row`,children:[(0,x.jsx)(`td`,{role:`cell`,"data-label":i,"data-code":``,translate:`no`,children:e.name}),e.type===null?(0,x.jsx)(`td`,{role:`cell`,"data-label":a,"data-quiet":``,children:Lv.notRecorded}):(0,x.jsx)(`td`,{role:`cell`,"data-label":a,"data-code":``,translate:`no`,children:e.type}),(0,x.jsx)(`td`,{role:`cell`,"data-label":o,children:e.required===null?``:e.required?Lv.yes:Lv.no}),(0,x.jsx)(`td`,{role:`cell`,"data-label":s,children:e.description})]},e.name))})]})}function lx({entry:e,attempt:t,actor:n,onGoToEvent:r}){let[i,a]=(0,b.useState)(!1),o=(0,b.useId)(),s=t??e.history[0]??null,c=s?.turn??e.firstForgedTurn,l=s?.eventIndex??0,u=s?.department||e.firstForgedDepartment,d=s?.eventTitle??``,f=t?.description||e.description,[p,m]=(0,b.useState)(null);(0,b.useEffect)(()=>{m(sx(e.actorIndex,c,l))},[e.actorIndex,c,l]);let h=e=>{let t=p?document.getElementById(p):null;t&&(e.preventDefault(),r(t))},g=t&&t.inputFields.length>0?t.inputFields:e.inputFields,_=t&&t.outputFields.length>0?t.outputFields:e.outputFields,v=ox(e.inputSchema,t?t.inputFields:[]),y=ox(e.outputSchema,t?t.outputFields:[]),S=v!=null||y!=null;return(0,x.jsxs)(`div`,{className:Jb.open,children:[(0,x.jsxs)(`div`,{className:Jb.actor,style:{"--actor":n.colour},"data-actor-line":!0,children:[(0,x.jsx)(`span`,{className:Jb.rule,"aria-hidden":`true`,"data-actor-rule":!0}),(0,x.jsxs)(`div`,{className:Jb.actorText,children:[(0,x.jsx)(`p`,{className:Jb.meta,children:Fv({label:n.label,name:n.name,archetype:n.archetype,department:u,turn:c,eventTitle:d})}),p&&d&&(0,x.jsx)(`a`,{className:Jb.link,href:`#${p}`,onClick:h,children:Iv(d)})]})]}),(0,x.jsxs)(`div`,{className:Jb.part,children:[(0,x.jsx)(`h3`,{id:o,className:Jb.heading,"data-text":`heading`,children:Lv.whatItDoes}),(0,x.jsx)(`p`,{className:Jb.body,"data-text":`body`,children:f})]}),(0,x.jsxs)(`div`,{className:Jb.part,children:[S&&(0,x.jsx)(`div`,{className:Jb.fieldsBar,children:(0,x.jsxs)(`button`,{type:`button`,role:`switch`,"aria-checked":i,className:Jb.switch,onClick:()=>a(e=>!e),children:[(0,x.jsx)(`span`,{className:Jb.switchTrack,"aria-hidden":`true`}),Lv.rawJson]})}),i&&S?(0,x.jsx)(`pre`,{className:Jb.code,translate:`no`,"data-raw-json":!0,children:JSON.stringify({input:v??null,output:y??null},null,2)}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(cx,{caption:Lv.inputFields,rows:ax(v,g),none:Lv.noInputFields}),(0,x.jsx)(cx,{caption:Lv.outputFields,rows:ax(y,_),none:Lv.noOutputFields})]})]})]})}var ux=5e3;function dx(){let[e,t]=(0,b.useState)(()=>typeof navigator>`u`||navigator.onLine!==!1);return(0,b.useEffect)(()=>{let e=()=>t(navigator.onLine!==!1);return window.addEventListener(`online`,e),window.addEventListener(`offline`,e),()=>{window.removeEventListener(`online`,e),window.removeEventListener(`offline`,e)}},[]),e}function fx(){try{return window.localStorage}catch{return null}}function px({entry:e,attempt:t,open:n,actorCount:r,runKey:i,sessionId:a=null,events:o,onClose:s,onGoToEvent:c,onShowInEventLog:l,onShown:u}){let d=D_(),f=Pt(!0),p=(0,b.useRef)(null),m=(0,b.useRef)(null),h=(0,b.useId)();(0,b.useEffect)(()=>{[p.current,m.current].find(e=>e!==null&&e.offsetParent!==null)?.focus()},[]),(0,b.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.preventDefault(),s())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[s]);let[g,_]=(0,b.useState)(t),v=e.attempts.length,y=M_(e,g??NaN),S=y>0?e.attempts[y-1]:null,C=S?S.approved?`passed`:`did_not_pass`:e.outcome,w=C===`passed`,T=S?S.errorReason:e.errorReason??null,E=S?.confidence??e.confidence,D=N_(e,y),O=(0,b.useMemo)(()=>Kb(w),[w]),k=O_.filter(e=>(D.stations[e]===`reached`||D.stations[e]===`stopped`)&&O(e)),A=(0,b.useMemo)(()=>qb(window.location.href,i),[i]),[j,ee]=(0,b.useState)(()=>{let e=fx(),t=e?Ub(e,A):[];return Gb(D,[...t,...n??[]],O)}),te=(0,b.useRef)(!1);(0,b.useEffect)(()=>{if(!te.current){te.current=!0;for(let e of O_)e!==D.deciding&&j.has(e)&&B_({name:`forge_station_open`,station:e,via:`kept`})}},[D.deciding,j]);let M=e=>{ee(e);let t=fx();t&&Wb(t,A,[...e])},N=e=>{let t=new Set(j);t.has(e)?t.delete(e):(t.add(e),B_({name:`forge_station_open`,station:e,via:`press`})),M(t)},ne=k.every(e=>j.has(e)),P=()=>{if(!ne)for(let e of k)j.has(e)||B_({name:`forge_station_open`,station:e,via:`open_all`});M(new Set(ne?k.filter(e=>e===D.deciding):k))},re=(0,b.useRef)(null),ie=(t,n)=>{let r=M_(e,t);if(r===0||r===y)return;let i=e.attempts[r-1].approved;ee(Gb(N_(e,r),[...j],Kb(i))),re.current=n?y:null,_(r)},F=(0,b.useRef)(y);(0,b.useEffect)(()=>{F.current!==y&&(F.current=y,g===void 0&&ee(e=>Gb(D,[...e],O)))},[y,g,D,O]),(0,b.useEffect)(()=>{let e=re.current;re.current=null,e!==null&&(f.current?.querySelector(`[data-fork-attempt="${e}"]`)??[p.current,m.current].find(e=>e!==null&&e.offsetParent!==null))?.focus()},[y,f]),(0,b.useEffect)(()=>{u?.({attempt:y,open:O_.filter(e=>j.has(e))})},[u,y,j]);let{shared:I,share:ae,clear:oe}=on(),se=dx(),ce=(0,b.useId)();(0,b.useEffect)(()=>{if(I?.state!==`copied`)return;let e=window.setTimeout(oe,ux);return()=>window.clearTimeout(e)},[I,oe]);let le=()=>{a&&(B_({name:`forge_link_copy`}),ae(Z_(window.location.origin,a,Q_(window.location.href),{actorIndex:e.actorIndex,toolName:e.name,...y>0?{attempt:y}:{},open:O_.filter(e=>j.has(e))},d)))},L=I?.state===`refused`||I?.state===`unanswered`,[ue,de]=(0,b.useState)(!1),fe=(0,b.useMemo)(()=>ue?Yb(o,e.name):[],[ue,o,e.name]),R=()=>{B_({name:`forge_log_jump`}),l()},z=t=>{switch(t){case`request`:return S?.description||e.description;case`code`:return w?(0,x.jsx)(tx,{station:`code`}):null;case`tests`:return w?(0,x.jsx)(tx,{station:`tests`}):null;case`judge`:return w?Mv(E):null;case`added`:return w?Nv(F_(e)):null}},pe=d.actors[e.actorIndex];return(0,x.jsx)(`div`,{className:Oy.backdrop,onMouseDown:e=>{e.target===e.currentTarget&&s()},children:(0,x.jsxs)(`div`,{ref:f,role:`dialog`,"aria-modal":`true`,"aria-label":Cv(e.name,e.n),tabIndex:-1,className:Oy.dialog,children:[(0,x.jsxs)(`div`,{className:Oy.header,"data-forge-header":!0,children:[(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Oy.iconKey}`,onClick:()=>s(),"aria-label":Tv,title:Tv,children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M3 3L13 13M13 3L3 13`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`})})}),(0,x.jsx)(Ry,{index:e.actorIndex,colour:Pe(e.actorIndex)}),(0,x.jsx)(`span`,{className:Oy.number,children:wv(e.n)}),(0,x.jsx)(`h2`,{ref:p,className:`${Oy.name} ${Oy.nameInRow}`,tabIndex:-1,translate:`no`,"data-text":`heading`,children:e.name}),(0,x.jsxs)(`span`,{className:Oy.headerEnd,children:[a&&(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Oy.iconKey}`,onClick:le,"aria-label":Ev.key,"aria-describedby":ce,title:Ev.key,children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M6.5 9.5L9.5 6.5M7 4.5L8.5 3a2.5 2.5 0 0 1 3.5 3.5L10.5 8M9 11.5L7.5 13A2.5 2.5 0 0 1 4 9.5L5.5 8`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.75`,strokeLinecap:`round`,strokeLinejoin:`round`})})}),(0,x.jsx)(ky,{})]})]}),a&&(0,x.jsxs)(`div`,{id:ce,className:Oy.linkNote,role:`status`,"aria-live":`polite`,"data-link-note":!0,children:[!se&&(0,x.jsx)(`p`,{className:Oy.linkSaid,children:Ev.offline}),I?.state===`copied`&&(0,x.jsx)(`p`,{className:Oy.linkSaid,children:Ev.copied}),L&&I&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`p`,{className:Oy.linkSaid,children:Ev.failed}),(0,x.jsx)(`p`,{className:Oy.linkText,"data-tool-link":!0,translate:`no`,children:I.url})]})]}),(0,x.jsxs)(`div`,{className:Oy.head,"data-forge-head":!0,children:[v>1&&(0,x.jsxs)(`div`,{className:Oy.attempts,role:`group`,"aria-label":Kv(y,v),children:[(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Oy.iconKey}`,"aria-label":Wv.previous,title:Wv.previous,"aria-disabled":y<=1||void 0,onClick:()=>{y>1&&ie(y-1,!1)},children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M10 3.5L5.5 8L10 12.5`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})}),(0,x.jsx)(`span`,{className:Oy.attemptLine,"data-attempt-line":!0,"aria-hidden":`true`,children:y===v?Gv(y,v):Kv(y,v)}),(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Oy.iconKey}`,"aria-label":Wv.next,title:Wv.next,"aria-disabled":y>=v||void 0,onClick:()=>{y<v&&ie(y+1,!1)},children:(0,x.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,x.jsx)(`path`,{d:`M6 3.5L10.5 8L6 12.5`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})})})]}),(0,x.jsx)(`p`,{className:Oy.label,children:Ov}),(0,x.jsx)(`h2`,{ref:m,className:`${Oy.name} ${Oy.nameInHead}`,tabIndex:-1,translate:`no`,"data-text":`heading`,children:e.name}),(0,x.jsxs)(`p`,{className:Oy.outcome,"data-forge-outcome":!0,"data-text":`heading`,children:[(0,x.jsx)(lb,{kind:k_(C),size:20}),(0,x.jsx)(`span`,{children:kv[C]})]}),!w&&(0,x.jsx)(nx,{reason:T})]}),(0,x.jsxs)(`div`,{className:Oy.line,children:[k.length>1&&(0,x.jsx)(`div`,{className:Oy.lineHead,children:(0,x.jsx)(`button`,{type:`button`,className:Oy.key,"aria-label":ne?Pv.closeName:Pv.openName,onClick:P,children:ne?Pv.close:Pv.open})}),(0,x.jsx)(gb,{model:D,size:`trace`,colour:P_(e.actorIndex,r),open:j,onToggle:N,stationResult:z,renderEvidence:t=>{if(!O(t))return null;switch(t){case`request`:return(0,x.jsx)(lx,{entry:e,attempt:S,actor:{label:pe?.label??xv(e.actorIndex),name:e.actorName,archetype:pe?.archetype??``,colour:Pe(e.actorIndex)},onGoToEvent:c});case`judge`:return(0,x.jsx)(ex,{confidence:E});case`added`:return(0,x.jsx)($b,{entry:e});default:return null}},onAttempt:e=>ie(e,!0)})]}),(0,x.jsxs)(`div`,{className:Oy.recordFoot,children:[(0,x.jsx)(`button`,{type:`button`,className:`${Oy.key} ${Oy.recordKey}`,"aria-expanded":ue,"aria-controls":h,onClick:()=>de(e=>!e),children:Hv.key}),(0,x.jsx)(`div`,{id:h,className:Oy.recordBody,hidden:!ue,children:ue&&(0,x.jsx)(Qb,{entry:e,frames:fe,onShowInEventLog:R})})]})]})})}var mx={trace:null,toolbox:!1},hx=[];function gx(e){let{show:t,find:n,group:r,actors:i}=q_(e,{getEntryByNumber:()=>void 0,actors:[]},!1).state.toolbox;return{show:tv.includes(t)?t:`all`,find:n??``,group:nv.includes(r)?r:null,actors:[...new Set((i??[]).map(e=>e-1))].sort((e,t)=>e-t)}}var _x=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),vx=(e,t)=>e.show===t.show&&e.find===t.find&&e.group===t.group&&_x(e.actors,t.actors);function yx({state:e,runKey:t,sessionId:n,showToolLog:r,children:i}){let a=D_(),[o,s]=(0,b.useState)(mx),c=(0,b.useRef)(null),l=(0,b.useRef)(null),u=(0,b.useRef)(!1),d=(0,b.useRef)(!1),f=(0,b.useRef)(0),p=(0,b.useRef)(null),m=(0,b.useRef)(null),h=(0,b.useRef)(a);h.current=a;let g=(0,b.useRef)(e.isComplete);g.current=e.isComplete;let _=(0,b.useRef)(o);_.current=o;let v=(0,b.useRef)(null),[y,S]=(0,b.useState)(null),[C,w]=(0,b.useState)(()=>typeof window>`u`?iv:gx(window.location.href)),T=(0,b.useRef)(C),E=(0,b.useCallback)(()=>{let e=window.location.href,t=Y_(e,{...u.current&&d.current?{open:!0}:{},...T.current});if(t!==e)try{window.history.replaceState(window.history.state,``,t)}catch{}},[]),D=(0,b.useCallback)(e=>{let t=T.current,n={...t,...e};vx(n,t)||(T.current=n,w(n),E())},[E]),O=(0,b.useCallback)(()=>{d.current||=(v.current=window.location.href,window.history.pushState({forgeView:!0},``),!0)},[]),k=(0,b.useCallback)((e,t,n)=>{h.current.getEntryFor(e.actorIndex,e.toolName)&&(n&&B_({name:`forge_trace_open`,from:n}),u.current?l.current=t??null:c.current=t??null,O(),S(null),s(t=>({trace:e,toolbox:t.toolbox})))},[O]),A=(0,b.useCallback)((e,t)=>{u.current||(t&&B_({name:`forge_toolbox_open`,from:t}),c.current=e??null,u.current=!0,O(),E(),s(e=>({trace:e.trace,toolbox:!0})))},[O,E]),j=(0,b.useCallback)((e,t)=>{if(e instanceof HTMLElement&&(c.current=e,p.current=e),l.current=null,u.current=!1,s(mx),d.current){d.current=!1;let e=v.current;v.current=null,e!==null&&e!==window.location.href&&window.history.replaceState(window.history.state,``,e),f.current+=1,m.current=t??null,window.history.back()}else t?.()},[]),ee=(0,b.useCallback)(()=>{if(!u.current){j();return}S(null),s({trace:null,toolbox:!0});let e=window.location.href,t=X_(e,U_);t!==e&&window.history.replaceState(window.history.state,``,t)},[j]),te=(0,b.useCallback)(()=>j(),[j]);(0,b.useEffect)(()=>{let e=()=>{if(f.current>0){--f.current,E();let e=m.current;m.current=null,e?.();let t=p.current;p.current=null,t?.isConnected&&requestAnimationFrame(()=>{t.scrollIntoView({block:`nearest`}),document.activeElement!==t&&t.focus({preventScroll:!0})})}else if(d.current)_.current.trace&&u.current?(S(null),s({trace:null,toolbox:!0}),d.current=!1,O(),E()):(d.current=!1,v.current=null,l.current=null,u.current=!1,s(mx),E());else{if(window.history.state?.forgeView!==!0)return;let{state:e}=q_(window.location.href,h.current,g.current);if(!e.trace&&!e.toolbox.open)return;d.current=!0,v.current=Y_(X_(window.location.href,U_),{open:!1,...T.current}),u.current=e.toolbox.open,S(null),s({trace:e.trace??null,toolbox:e.toolbox.open})}};return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},[O,E]);let M=o.trace,N=M?a.getEntryFor(M.actorIndex,M.toolName):void 0,ne=N?e.actors[e.actorIds[N.actorIndex]]?.events??hx:hx,P=(0,b.useCallback)(()=>{if(!N)return;let{name:e,actorName:t}=N;j(null,()=>r?.(e,t))},[N,j,r]),re=(0,b.useCallback)(t=>{let n=e.actorIds[t];n&&j(null,()=>r?.(``,n))},[e.actorIds,j,r]);(0,b.useEffect)(()=>{M&&!N&&ee()},[M,N,ee]),(0,b.useEffect)(()=>{if(!M||!N||!d.current)return;let e=window.location.href,t=J_(e,{trace:{actorIndex:N.actorIndex,toolName:N.name,...y&&y.attempt>0?{attempt:y.attempt}:{},...y?{open:y.open}:{}},toolbox:q_(e,a,!1).state.toolbox},a);t!==e&&window.history.replaceState(window.history.state,``,t)},[M,N,y,a]);let ie=e.isComplete,F=(0,b.useRef)(null);(0,b.useEffect)(()=>{if(!ie)return;let e=`${t??``}|${n??``}`;if(F.current===e)return;F.current=e;let r=window.location.href,{state:i,dangling:o}=q_(r,a,!0);o.length>0&&window.history.replaceState(window.history.state,``,X_(r,o));let s=gx(window.location.href),c={...s,actors:s.actors.filter(e=>e<a.actors.length)};if(vx(c,T.current)||(T.current=c,w(c)),_.current.trace||_.current.toolbox)return;let l=Y_(X_(window.location.href,U_),{open:!1,...c});l!==window.location.href&&window.history.replaceState(window.history.state,``,l),i.toolbox.open&&A(null),i.trace&&k(i.trace,null,`link`)},[ie,t,n,a,k,A]);let I=M!==null,ae=(0,b.useRef)(!1);(0,b.useEffect)(()=>{if(I){ae.current=!0;return}if(!ae.current||(ae.current=!1,!o.toolbox))return;let e=l.current;l.current=null,e?.isConnected?e.focus():document.querySelector(`[data-toolbox-title]`)?.focus()},[I,o.toolbox]);let oe=M!==null||o.toolbox,se=(0,b.useRef)(!1);(0,b.useEffect)(()=>{if(oe){se.current=!0;return}if(!se.current)return;se.current=!1;let e=c.current;c.current=null,e?.isConnected&&e.focus()},[oe]);let ce=(0,b.useMemo)(()=>({openTrace:k,openToolbox:A,close:j,showActorLog:re,current:o}),[k,A,j,re,o]),le=(0,b.useMemo)(()=>({...C,set:D}),[C,D]);return(0,x.jsx)($_.Provider,{value:ce,children:(0,x.jsxs)(ov.Provider,{value:le,children:[i,o.toolbox&&(0,x.jsx)(Rb,{covered:M!==null,onClose:te}),M&&N&&(0,x.jsx)(px,{entry:N,attempt:M.attempt,open:M.open,actorCount:e.actorIds.length,runKey:t,sessionId:ie?n:null,events:ne,onShown:S,onClose:ee,onGoToEvent:j,onShowInEventLog:P},`${N.actorIndex}:${N.name}`)]})})}var bx=420,xx=260;function Sx({content:e,children:t,dot:n,block:r,disabled:i=!1}){let[a,o]=(0,b.useState)(!1),[s,c]=(0,b.useState)({x:0,y:0}),l=(0,b.useRef)(null),u=(0,b.useRef)(void 0);b.useEffect(()=>{if(!a)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),o(!1))};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[a]);let d=(0,b.useCallback)(e=>{clearTimeout(u.current);let t=e.currentTarget.getBoundingClientRect(),n=Math.min(bx,window.innerWidth-20),r=t.left,i=t.top-xx-6;i<10&&(i=t.bottom+6),r+n>window.innerWidth-10&&(r=window.innerWidth-n-10),r<10&&(r=10),i+xx>window.innerHeight-10&&(i=window.innerHeight-xx-10),i<10&&(i=10),c({x:r,y:i}),o(!0)},[]),f=(0,b.useCallback)(()=>{u.current=setTimeout(()=>o(!1),100)},[]),p=a&&!i?(0,x.jsx)(`div`,{id:`paracosm-tooltip`,role:`tooltip`,onMouseEnter:()=>{clearTimeout(u.current),o(!0)},onMouseLeave:f,style:{position:`fixed`,left:s.x,top:s.y,zIndex:99999,background:`var(--bg-card)`,border:`2px solid var(--amber)`,borderRadius:`8px`,padding:`14px 18px`,fontSize:`var(--font-sm)`,color:`var(--text-1)`,lineHeight:1.6,width:`${bx}px`,maxWidth:`90vw`,maxHeight:`80vh`,overflowY:`auto`,boxShadow:`0 8px 40px rgba(0,0,0,.4)`,pointerEvents:`auto`,whiteSpace:`normal`,wordBreak:`break-word`,animation:`fadeUp 0.15s ease both`},children:e}):null;return(0,x.jsxs)(`span`,{ref:l,onMouseEnter:d,onMouseLeave:f,style:{position:`relative`,display:r?`block`:`inline-flex`,alignItems:r?void 0:`center`,width:r?`100%`:void 0,minWidth:r?0:void 0,cursor:`pointer`},tabIndex:0,"aria-describedby":a?`paracosm-tooltip`:void 0,onFocus:d,onBlur:f,children:[t,n&&(0,x.jsx)(`span`,{style:{width:`6px`,height:`6px`,borderRadius:`50%`,background:`var(--amber)`,opacity:a?.8:0,marginLeft:`3px`,transition:`opacity 0.15s`,flexShrink:0,display:`inline-block`,verticalAlign:`middle`},"aria-hidden":`true`}),p&&typeof document<`u`?(0,Ay.createPortal)(p,document.body):null]})}var Cx={root:`_root_a1e21_1`,triggerButton:`_triggerButton_a1e21_6`,triggerCaret:`_triggerCaret_a1e21_29`,menuPopover:`_menuPopover_a1e21_34`,menuButton:`_menuButton_a1e21_49`,loadFileButton:`_loadFileButton_a1e21_49`,runSavedButton:`_runSavedButton_a1e21_49`,runNewButton:`_runNewButton_a1e21_49`,menuButtonInnerLeft:`_menuButtonInnerLeft_a1e21_68`,menuButtonIcon:`_menuButtonIcon_a1e21_74`,runNewBadge:`_runNewBadge_a1e21_94`,disabled:`_disabled_a1e21_116`,runSavedBadge:`_runSavedBadge_a1e21_128`,savedCardsWrap:`_savedCardsWrap_a1e21_145`,savedStatus:`_savedStatus_a1e21_149`,savedError:`_savedError_a1e21_149`,loadFileBadge:`_loadFileBadge_a1e21_170`,sessionCard:`_sessionCard_a1e21_181`,sessionCardTitle:`_sessionCardTitle_a1e21_203`,sessionCardLine2:`_sessionCardLine2_a1e21_212`,sessionCardLine3:`_sessionCardLine3_a1e21_218`,tooltipHeading:`_tooltipHeading_a1e21_224`,historyRow:`_historyRow_a1e21_234`,historyRowLabel:`_historyRowLabel_a1e21_259`,historyRowBadge:`_historyRowBadge_a1e21_265`,historyList:`_historyList_a1e21_276`,historyCardWrap:`_historyCardWrap_a1e21_285`,historyCard:`_historyCard_a1e21_285`,historyCardTitle:`_historyCardTitle_a1e21_310`,historyCardLine2:`_historyCardLine2_a1e21_318`,historyCardLine3:`_historyCardLine3_a1e21_324`,historyDelete:`_historyDelete_a1e21_329`,historyClearAll:`_historyClearAll_a1e21_353`},wx=Cx;function Tx(e){let t=Math.max(0,Math.floor((Date.now()-e)/1e3));if(t<60)return`${t}s ago`;let n=Math.floor(t/60);if(n<60)return`${n}m ago`;let r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function Ex(e){if(!e||e<=0)return`·`;let t=Math.round(e/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function Dx(e){return e==null?`·`:e<.005?`<$0.01`:`$${e.toFixed(2)}`}function Ox({s:e,onPick:t}){let n=Rn(e),r=n?`${n}${e.scenarioName?` · ${e.scenarioName}`:``}`:e.scenarioName||`Simulation Run`,i=e.title||e.scenarioName||r,a=[n,e.title&&e.scenarioName?e.scenarioName:``,e.turnCount==null?``:`${e.turnCount} turn${e.turnCount===1?``:`s`}`].filter(Boolean).join(` · `),o=`${new Date(e.createdAt).toLocaleString()} (${Tx(e.createdAt)}) · ${Ex(e.durationMs)} · ${Dx(e.totalCostUSD)}`;return(0,x.jsxs)(`button`,{type:`button`,onClick:t,className:Cx.sessionCard,children:[(0,x.jsx)(`div`,{className:Cx.sessionCardTitle,children:i}),a&&(0,x.jsx)(`div`,{className:Cx.sessionCardLine2,children:a}),(0,x.jsx)(`div`,{className:Cx.sessionCardLine3,children:o})]})}function kx({onRun:e,onLoadFromFile:t,history:n=[],onRestoreHistory:r,onClearHistory:i,liveStateHasEvents:a=!1}){let[o,s]=(0,b.useState)(!1),[c,l]=(0,b.useState)(!1),[u,d]=(0,b.useState)(!0),f=(0,b.useRef)(null),{sessions:p,status:m,refresh:h}=Oe(),g=p.length>0,_=eA();(0,b.useEffect)(()=>{o&&h()},[o,h]);let v=(0,b.useCallback)(()=>{s(!1),l(!1)},[]);(0,b.useEffect)(()=>{if(!o)return;let e=e=>{f.current&&!f.current.contains(e.target)&&v()},t=e=>{e.key===`Escape`&&v()};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[o,v]);let y=()=>{_&&(v(),e?.())},S=e=>{window.location.assign(kg(window.location.href,e))},C=()=>{v(),t?.()},w=Og(m,p);return(0,x.jsxs)(`div`,{ref:f,className:Cx.root,children:[(0,x.jsx)(Sx,{disabled:o,content:(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:Cx.tooltipHeading,children:`Run`}),(0,x.jsx)(`div`,{children:`Launches a fresh simulation, replays a cached one, or loads a saved JSON from disk. Click to open the menu.`})]}),children:(0,x.jsxs)(`button`,{type:`button`,onClick:()=>s(e=>!e),"aria-haspopup":`menu`,"aria-expanded":o,className:Cx.triggerButton,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`▶`}),`RUN`,(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Cx.triggerCaret,children:`▾`})]})}),o&&(0,x.jsxs)(`div`,{role:`menu`,"aria-label":`Run actions`,className:Cx.menuPopover,children:[(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:y,disabled:!_,className:Cx.runNewButton,children:[(0,x.jsxs)(`span`,{className:Cx.menuButtonInnerLeft,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Cx.menuButtonIcon,children:`▶`}),(0,x.jsx)(`span`,{children:_?`Run New Simulation`:`Loading scenario…`})]}),(0,x.jsx)(`span`,{className:Cx.runNewBadge,children:`spends credits`})]}),(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>g&&l(e=>!e),disabled:!g,className:[Cx.runSavedButton,g?``:Cx.disabled].filter(Boolean).join(` `),children:[(0,x.jsxs)(`span`,{className:Cx.menuButtonInnerLeft,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Cx.menuButtonIcon,children:`↻`}),(0,x.jsx)(`span`,{children:`Run Saved Simulation`})]}),(0,x.jsx)(`span`,{className:[Cx.runSavedBadge,g?``:Cx.disabled].filter(Boolean).join(` `),children:g?`${p.length} cached · ${c?`hide`:`pick`}`:`no cache yet`})]}),c&&g&&(0,x.jsxs)(`div`,{className:Cx.savedCardsWrap,children:[w===`cards`&&p.map(e=>(0,x.jsx)(Ox,{s:e,onPick:()=>S(e.id)},e.id)),w===`loading`&&(0,x.jsx)(`div`,{className:Cx.savedStatus,children:`Loading cached runs…`}),w===`error`&&(0,x.jsx)(`div`,{className:Cx.savedError,children:`Could not reach /sessions. Try again in a moment.`}),w===`unavailable`&&(0,x.jsx)(`div`,{className:Cx.savedStatus,children:`Session cache is disabled on this server.`})]}),n.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,className:wx.historyRow,onClick:()=>d(e=>!e),"aria-expanded":u,children:[(0,x.jsxs)(`span`,{className:wx.historyRowLabel,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`🕘`}),(0,x.jsx)(`span`,{children:`Local history`})]}),(0,x.jsxs)(`span`,{className:wx.historyRowBadge,children:[n.length,` recent · `,u?`hide`:`show`]})]}),u&&(0,x.jsxs)(`div`,{className:wx.historyList,children:[n.map(e=>{let t=Date.parse(e.createdAt)||e.id,n=(e.summary.actorNames??[]).join(` vs `)||e.scenarioShortName,i=e.summary.turnCount?`${e.summary.turnCount} turn${e.summary.turnCount===1?``:`s`}`:``,o=[n,n===e.scenarioShortName?``:e.scenarioShortName,i].filter(Boolean).join(` · `),s=`${Tx(t)} · ${e.summary.eventCount} ev · ${Dx(e.summary.totalCostUSD)}`;return(0,x.jsx)(`div`,{className:wx.historyCardWrap,children:(0,x.jsxs)(`button`,{type:`button`,className:wx.historyCard,onClick:()=>{(!a||window.confirm(`Replace current simulation with this history entry?`))&&(r?.(e),v())},children:[(0,x.jsx)(`div`,{className:wx.historyCardTitle,children:n}),(0,x.jsx)(`div`,{className:wx.historyCardLine2,children:o}),(0,x.jsx)(`div`,{className:wx.historyCardLine3,children:s})]})},e.id)}),i&&(0,x.jsx)(`button`,{type:`button`,className:wx.historyClearAll,title:`Wipe everything in this browser: saved-runs ring, event cache, current sim state. It also lets go of this browser's run on the server, stopping it if it is running. Run history, saved sessions and output files are kept: Delete server data in the ⋯ menu deletes those, where admin writes are on and an admin token is saved.`,onClick:()=>{window.confirm(`Clear all local browser state?
114
114
 
115
115
  • Saved-runs ring (this dropdown)
116
116
  • Event cache (Sim / Constellation / Log)
@@ -121,11 +121,11 @@ It also lets go of this browser's run on the server, and stops it if it is runni
121
121
  Run history, saved sessions, and on-disk artifact files are kept (Delete server data in the ⋯ menu deletes those, where it shows).
122
122
 
123
123
  Cannot be undone.`)&&i()},children:`Clear local data`})]})]}),t&&(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:C,className:Cx.loadFileButton,children:[(0,x.jsxs)(`span`,{className:Cx.menuButtonInnerLeft,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Cx.menuButtonIcon,children:`📁`}),(0,x.jsx)(`span`,{children:`Load from file…`})]}),(0,x.jsx)(`span`,{className:Cx.loadFileBadge,children:`json export`})]})]})]})}var Ax={bar:`_bar_16636_1`,logoLink:`_logoLink_16636_7`,logoSpan:`_logoSpan_16636_14`,logoImg:`_logoImg_16636_21`,logoGlow:`_logoGlow_16636_25`,brand:`_brand_16636_33`,brandAccent:`_brandAccent_16636_42`,agentosTag:`_agentosTag_16636_46`,divider:`_divider_16636_55`,scenarioName:`_scenarioName_16636_60`,center:`_center_16636_67`,meta:`_meta_16636_71`,tokenInline:`_tokenInline_16636_78`,tokenLabel:`_tokenLabel_16636_83`,tokenValue:`_tokenValue_16636_87`,progressTrack:`_progressTrack_16636_91`,progressFill:`_progressFill_16636_95`,tooltipTitle:`_tooltipTitle_16636_100`,fallbackBlock:`_fallbackBlock_16636_107`,fallbackRow:`_fallbackRow_16636_113`,fallbackRowMeta:`_fallbackRowMeta_16636_122`,fallbackPill:`_fallbackPill_16636_126`,tagline:`_tagline_16636_140`,github:`_github_16636_146`,githubIcon:`_githubIcon_16636_169`,tourBtn:`_tourBtn_16636_173`,launchingChip:`_launchingChip_16636_186`,toolBtn:`_toolBtn_16636_199`,overflowAnchor:`_overflowAnchor_16636_211`,overflowTrigger:`_overflowTrigger_16636_215`,overflowMenu:`_overflowMenu_16636_224`,overflowItem:`_overflowItem_16636_241`,overflowItemDanger:`_overflowItemDanger_16636_255`,statusPill:`_statusPill_16636_275`,statusText:`_statusText_16636_286`,themeBtn:`_themeBtn_16636_290`};function jx({size:e=20}){let{resolved:t}=C(),n=t===`light`?`rgba(122,82,0,.12)`:`rgba(232,180,74,.15)`;return(0,x.jsxs)(`span`,{className:Ax.logoSpan,style:{"--logo-size":`${e}px`,"--logo-glow":n},children:[(0,x.jsx)(`img`,{src:`/favicon.svg`,width:e,height:e,alt:`Paracosm`,className:Ax.logoImg}),(0,x.jsx)(`span`,{className:`pc-logo-glow ${Ax.logoGlow}`})]})}function Mx({scenario:e,sse:t,gameState:n,onSave:r,onLoad:i,onClear:a,onWipeServer:o,onRunActionsOpen:s,onRun:c,onTour:l,onCopy:u,onShareViz:d,launching:f=!1,history:p,onRestoreHistory:m,onClearHistory:h}){let{resolved:g,setTheme:_}=C(),v=Object.values(n.actors).some(e=>e.events.length>0),[y,S]=(0,b.useState)(!1),w=(0,b.useRef)(null),T=Pt(y);(0,b.useEffect)(()=>{y&&s?.()},[y,s]),(0,b.useEffect)(()=>{if(!y)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),S(!1))},t=e=>{let t=w.current;t&&(t.contains(e.target)||S(!1))};return document.addEventListener(`keydown`,e),document.addEventListener(`mousedown`,t),()=>{document.removeEventListener(`keydown`,e),document.removeEventListener(`mousedown`,t)}},[y]);let E=t.isAborted?`var(--amber)`:t.isComplete?`var(--green)`:t.status===`connected`?`var(--color-success)`:`var(--text-3)`,D=t.isAborted?`Interrupted`:t.isComplete?`Complete`:t.status===`connected`?`Live`:t.status===`error`?`Reconnecting`:`Connecting`,O=e=>{switch(e){case`client_disconnected`:return`browser tab closed before the sim finished`;case`quota_exhausted`:return`provider credits exhausted`;case`user_aborted`:return`cancelled by the user`;case`provider_error`:return`provider returned an unrecoverable error`;case`another_run_started`:return`you started another run`;case`server_restarted`:return`the server restarted before the run finished`;case`unknown`:return`reason not recorded by the server`;default:return e}},k=t.isAborted?(()=>{if(t.providerError)return`Run interrupted: ${t.providerError.message}. Click Clear to reset.`;let e=t.abortReason;return e?`${`Run interrupted: ${O(e.reason)}`}${typeof e.completedTurns==`number`?` after ${e.completedTurns} turn${e.completedTurns===1?``:`s`}`:``}. Click Clear to reset.`:`Run was interrupted before finishing all turns. Click Clear to reset.`})():t.isComplete?`Run finished all turns. Verdict is broadcast in Reports.`:t.status===`connected`?`Connected to the simulation server. Press RUN to start.`:t.status===`error`?`Reconnecting to the simulation server.`:`Connecting to the simulation server.`,A=n.maxTurns>0?`${Math.round(n.turn/n.maxTurns*100)}%`:`0%`;return(0,x.jsxs)(`header`,{className:`topbar flex items-center justify-between px-4 gap-3 shrink-0 ${Ax.bar}`,role:`banner`,children:[(0,x.jsxs)(`div`,{className:`flex items-center gap-2 shrink-0`,children:[(0,x.jsxs)(`a`,{href:`/`,className:`${Ax.logoLink} ${Ax.brand}`,"aria-label":`Paracosm home`,children:[(0,x.jsx)(jx,{size:20}),(0,x.jsxs)(`span`,{children:[`PARA`,(0,x.jsx)(`span`,{className:Ax.brandAccent,children:`COSM`})]})]}),(0,x.jsx)(`a`,{href:`https://agentos.sh/en`,target:`_blank`,rel:`noopener`,className:`topbar-agentos ${Ax.agentosTag}`,"aria-label":`AgentOS Runtime (opens in new tab)`,title:`AgentOS Runtime`,children:`AGENTOS`}),(0,x.jsx)(`span`,{className:`topbar-agentos ${Ax.divider}`,"aria-hidden":`true`,children:`|`}),(0,x.jsx)(`span`,{className:`topbar-scenario ${Ax.scenarioName}`,children:e.labels.name})]}),(0,x.jsxs)(`div`,{className:`flex items-center gap-3 flex-1 justify-center ${Ax.center}`,children:[n.turn>0&&(0,x.jsxs)(`div`,{className:`topbar-meta flex items-center gap-2 shrink-0 ${Ax.meta}`,children:[(0,x.jsx)(Sx,{content:(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:Ax.tooltipTitle,children:[`Turn `,n.turn,` / `,n.maxTurns]}),(0,x.jsxs)(`div`,{children:[`One decision cycle per turn. Departments analyze the situation, the commander picks a policy, the kernel advances in-sim time, colonists age. At turn`,` `,n.maxTurns,` `,`the run finishes`,n.actorIds.length===2?` and the verdict judge compares the two commanders.`:`; cohort runs (3+ commanders) skip the verdict and surface group-median deltas instead.`]})]}),children:(0,x.jsxs)(`span`,{className:Ax.tokenInline,children:[(0,x.jsx)(`span`,{className:Ax.tokenLabel,children:`T`}),(0,x.jsx)(`strong`,{className:Ax.tokenValue,children:n.turn}),(0,x.jsxs)(`span`,{className:Ax.tokenLabel,children:[`/`,n.maxTurns]})]})}),(0,x.jsx)(Sx,{content:(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:Ax.tooltipTitle,children:[`In-sim time `,n.time]}),(0,x.jsxs)(`div`,{children:[`The time the colony thinks it's living in. Advances by the scenario's `,(0,x.jsx)(`code`,{children:`timePerTurn`}),` (usually 5-10) each decision cycle. Drives aging, childbirth, retirement, and long-arc narrative. Real wall-clock time doesn't matter — only the in-sim time.`]})]}),children:(0,x.jsxs)(`span`,{className:Ax.tokenInline,children:[(0,x.jsx)(`span`,{className:Ax.tokenLabel,children:`Y`}),(0,x.jsx)(`strong`,{className:Ax.tokenValue,children:n.time})]})}),(0,x.jsx)(Sx,{content:(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:Ax.tooltipTitle,children:[`Random seed `,n.seed]}),(0,x.jsx)(`div`,{children:`All kernel-side randomness (colonist generation, mood drift, crisis selection) derives from this seed. Same seed + same leaders + same scenario produces identical rosters and identical kernel outcomes — so Leader A and Leader B start from the same colony and diverge only by their personalities, not by luck.`})]}),children:(0,x.jsxs)(`span`,{className:Ax.tokenInline,children:[(0,x.jsx)(`span`,{className:Ax.tokenLabel,children:`S`}),(0,x.jsx)(`strong`,{className:Ax.tokenValue,children:n.seed})]})}),(0,x.jsx)(`div`,{className:`topbar-progress w-20 h-1.5 rounded-full overflow-hidden ${Ax.progressTrack}`,role:`progressbar`,"aria-valuenow":n.turn,"aria-valuemin":0,"aria-valuemax":n.maxTurns,"aria-label":`Simulation progress, turn ${n.turn} of ${n.maxTurns}`,children:(0,x.jsx)(`div`,{className:`h-full rounded-full transition-all ${Ax.progressFill}`,style:{"--progress-pct":A}})}),t.validationFallbacks.length>0&&(()=>{let e=t.validationFallbacks.filter(e=>!e.salvaged),n=t.validationFallbacks.filter(e=>e.salvaged),r=e.reduce((e,t)=>e+t.count,0),i=n.reduce((e,t)=>e+t.count,0),a=r+i,o=`${r} validation fallback${r===1?``:`s`}`,s=`${i} ${i===1?`reply`:`replies`} kept without the keys the run does not hold`,c=[r>0?o:``,i>0?s:``].filter(Boolean).join(`, `),l=e=>(0,x.jsx)(`div`,{className:Ax.fallbackBlock,children:e.map(e=>(0,x.jsxs)(`div`,{className:Ax.fallbackRow,children:[(0,x.jsx)(`span`,{children:e.schemaName}),(0,x.jsxs)(`span`,{className:Ax.fallbackRowMeta,children:[e.count,`× `,e.lastSite?`(last: ${e.lastSite})`:``]})]},e.schemaName))});return(0,x.jsx)(Sx,{content:(0,x.jsxs)(`div`,{children:[r>0&&(0,x.jsxs)(`div`,{style:{marginBottom:i>0?8:0},children:[(0,x.jsxs)(`div`,{className:Ax.tooltipTitle,children:[`⚠ `,o]}),(0,x.jsx)(`div`,{style:{marginBottom:8},children:`An LLM call returned a JSON payload that failed zod schema validation. After retries were exhausted the orchestrator continued with an empty skeleton so the sim wouldn't abort mid-turn. Numbers here let you spot which schema is misbehaving.`}),l(e)]}),i>0&&(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:Ax.tooltipTitle,children:[`⚠ `,s]}),(0,x.jsx)(`div`,{style:{marginBottom:8},children:`A reply failed schema validation only on effect keys the run does not hold. After retries the run kept the model's own reply with those keys dropped; nothing was replaced with a skeleton.`}),l(n)]})]}),children:(0,x.jsxs)(`span`,{"aria-label":c,className:Ax.fallbackPill,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`⚠`}),a]})})})()]}),(0,x.jsx)(`div`,{className:`topbar-center hidden md:block truncate ${Ax.tagline}`,children:n.turn===0?`Same input. Different decisions. Emergent divergence.`:``})]}),(0,x.jsxs)(`div`,{className:`flex items-center gap-2 shrink-0`,children:[(0,x.jsxs)(`a`,{href:`https://github.com/framerslab/paracosm`,target:`_blank`,rel:`noopener noreferrer`,className:`topbar-github ${Ax.github}`,title:`Star Paracosm on GitHub`,"aria-label":`Open Paracosm on GitHub`,children:[(0,x.jsx)(`svg`,{width:`13`,height:`13`,viewBox:`0 0 16 16`,fill:`currentColor`,"aria-hidden":`true`,className:Ax.githubIcon,children:(0,x.jsx)(`path`,{d:`M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.01 8.01 0 0016 8c0-4.42-3.58-8-8-8z`})}),(0,x.jsx)(`span`,{className:`topbar-github-label`,children:`GITHUB`})]}),l&&(0,x.jsxs)(`button`,{onClick:l,className:`topbar-tour ${Ax.tourBtn}`,title:`Interactive guided tour with sample data`,"aria-label":`Start guided tour`,children:[(0,x.jsx)(`span`,{className:`topbar-tour-label`,children:`HOW IT WORKS`}),(0,x.jsx)(`span`,{className:`topbar-tour-icon`,"aria-hidden":`true`,style:{display:`none`},children:`?`})]}),c&&!n.isRunning&&!f&&(0,x.jsx)(kx,{onRun:c,onLoadFromFile:i,history:p,onRestoreHistory:m,onClearHistory:h,liveStateHasEvents:t.events.length>0}),f&&!n.isRunning&&(0,x.jsx)(`span`,{className:Ax.launchingChip,role:`status`,"aria-live":`polite`,children:`LAUNCHING…`}),(v&&(r||u||d)||a)&&(0,x.jsxs)(`div`,{ref:w,className:Ax.overflowAnchor,children:[(0,x.jsx)(`button`,{type:`button`,onClick:()=>S(e=>!e),"aria-haspopup":`menu`,"aria-expanded":y,"aria-label":y?`Close run actions`:`Open run actions menu`,title:`Save · Share · Copy · Wipe`,className:`${Ax.toolBtn} ${Ax.overflowTrigger}`,children:`⋯`}),y&&(0,x.jsxs)(`div`,{ref:T,role:`menu`,tabIndex:-1,className:Ax.overflowMenu,children:[v&&r&&(0,x.jsx)(`button`,{role:`menuitem`,type:`button`,onClick:()=>{S(!1),r()},className:Ax.overflowItem,title:`Export simulation data as .json`,children:`Save`}),v&&d&&(0,x.jsx)(`button`,{role:`menuitem`,type:`button`,onClick:()=>{S(!1),d()},className:Ax.overflowItem,title:`Copy a deep link that opens this run on the visualization tab`,children:`Share viz link`}),v&&u&&(0,x.jsx)(`button`,{role:`menuitem`,type:`button`,onClick:()=>{S(!1),u()},className:Ax.overflowItem,title:`Copy simulation summary to clipboard`,children:`Copy`}),a&&(0,x.jsx)(`button`,{role:`menuitem`,type:`button`,onClick:()=>{S(!1),a()},className:Ax.overflowItemDanger,title:`Clear in-browser simulation buffer + cached events, and let go of this browser's run on the server, stopping it if it is running. Run history, saved sessions and output files are kept.`,children:`Clear local data`}),o&&(0,x.jsx)(`button`,{role:`menuitem`,type:`button`,onClick:()=>{S(!1),o()},className:Ax.overflowItemDanger,title:`Delete the server's stored runs, saved sessions and run output files, for every visitor. Pages showing a finished run this server holds, this one included, empty their view of it.`,children:`Delete server data`})]})]}),(0,x.jsx)(`span`,{className:Ax.divider,"aria-hidden":`true`,children:`|`}),(0,x.jsxs)(`span`,{className:Ax.statusPill,style:{"--status-color":E},role:`status`,"aria-live":`polite`,"aria-label":`${D}. ${k}`,title:k,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:t.status===`connected`&&!t.isComplete?`●`:`○`}),(0,x.jsx)(`span`,{className:`topbar-status-text ${Ax.statusText}`,children:D})]}),(0,x.jsx)(`button`,{onClick:()=>_(g===`dark`?`light`:`dark`),className:`px-2 py-0.5 rounded cursor-pointer transition-colors ${Ax.themeBtn}`,title:`Switch to ${g===`dark`?`light`:`dark`} mode`,"aria-label":`Switch to ${g===`dark`?`light`:`dark`} mode`,children:g===`dark`?`☀`:`☽`})]})]})}var Nx={root:`_root_zo4p2_1`,tab:`_tab_zo4p2_10`,withDivider:`_withDivider_zo4p2_41`,active:`_active_zo4p2_45`,inactive:`_inactive_zo4p2_55`,icon:`_icon_zo4p2_60`,label:`_label_zo4p2_65`};function Px({id:e,size:t=16}){let n=t,r={width:n,height:n,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`};switch(e){case`quickstart`:return(0,x.jsx)(`svg`,{...r,children:(0,x.jsx)(`polygon`,{points:`13 2 3 14 12 14 11 22 21 10 12 10 13 2`})});case`sim`:return(0,x.jsx)(`svg`,{...r,children:(0,x.jsx)(`path`,{d:`M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83`})});case`viz`:return(0,x.jsxs)(`svg`,{...r,children:[(0,x.jsx)(`circle`,{cx:`8`,cy:`8`,r:`3`}),(0,x.jsx)(`circle`,{cx:`16`,cy:`16`,r:`3`}),(0,x.jsx)(`circle`,{cx:`18`,cy:`8`,r:`2`}),(0,x.jsx)(`circle`,{cx:`6`,cy:`16`,r:`2`}),(0,x.jsx)(`line`,{x1:`10.5`,y1:`9.5`,x2:`14`,y2:`14`})]});case`settings`:return(0,x.jsxs)(`svg`,{...r,children:[(0,x.jsx)(`circle`,{cx:`12`,cy:`12`,r:`3`}),(0,x.jsx)(`path`,{d:`M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z`})]});case`reports`:return(0,x.jsxs)(`svg`,{...r,children:[(0,x.jsx)(`path`,{d:`M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z`}),(0,x.jsx)(`polyline`,{points:`14 2 14 8 20 8`}),(0,x.jsx)(`line`,{x1:`16`,y1:`13`,x2:`8`,y2:`13`}),(0,x.jsx)(`line`,{x1:`16`,y1:`17`,x2:`8`,y2:`17`})]});case`library`:return(0,x.jsx)(`svg`,{...r,children:(0,x.jsx)(`path`,{d:`M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2zM22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z`})});case`studio`:return(0,x.jsxs)(`svg`,{...r,children:[(0,x.jsx)(`polyline`,{points:`4 7 4 4 20 4 20 7`}),(0,x.jsx)(`line`,{x1:`9`,y1:`20`,x2:`15`,y2:`20`}),(0,x.jsx)(`line`,{x1:`12`,y1:`4`,x2:`12`,y2:`20`})]});case`chat`:return(0,x.jsx)(`svg`,{...r,children:(0,x.jsx)(`path`,{d:`M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z`})});case`about`:return(0,x.jsxs)(`svg`,{...r,children:[(0,x.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,x.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12`,y2:`12`}),(0,x.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12.01`,y2:`8`})]})}}var Fx=[{id:`quickstart`,label:`QUICKSTART`},{id:`studio`,label:`STUDIO`},{id:`sim`,label:`SIM`},{id:`viz`,label:`VIZ`},{id:`chat`,label:`CHAT`},{id:`reports`,label:`REPORTS`},{id:`library`,label:`LIBRARY`},{id:`settings`,label:`SETTINGS`},{id:`about`,label:`ABOUT`}];function Ix({active:e,onTabChange:t,scenario:n}){let r=Fx.filter(e=>e.id!==`chat`||n.policies.characterChat),i=(0,b.useRef)([]);function a(e,t){let n=null;e.key===`ArrowRight`?n=(t+1)%r.length:e.key===`ArrowLeft`?n=(t-1+r.length)%r.length:e.key===`Home`?n=0:e.key===`End`&&(n=r.length-1),n!==null&&(e.preventDefault(),i.current[n]?.focus())}return(0,x.jsx)(`nav`,{className:`tab-bar ${Nx.root}`,role:`tablist`,"aria-label":`Dashboard navigation`,children:r.map((n,o)=>{let s=e===n.id;return(0,x.jsxs)(`button`,{ref:e=>{i.current[o]=e},onClick:()=>t(n.id),onKeyDown:e=>a(e,o),role:`tab`,type:`button`,"aria-selected":s,"aria-label":n.label,"aria-controls":`tabpanel-${n.id}`,id:`tab-${n.id}`,title:n.label,tabIndex:s?0:-1,className:[Nx.tab,o<r.length-1?Nx.withDivider:``,s?Nx.active:Nx.inactive].filter(Boolean).join(` `),children:[(0,x.jsx)(`span`,{className:Nx.icon,"aria-hidden":`true`,children:(0,x.jsx)(Px,{id:n.id,size:18})}),(0,x.jsx)(`span`,{className:Nx.label,"aria-hidden":`true`,children:n.label})]},n.id)})})}var Lx=new Set([`platform.openai.com`,`console.anthropic.com`]);function Rx(e){if(typeof e!=`string`||!e)return null;let t;try{t=new URL(e)}catch{return null}return t.protocol!==`https:`&&t.protocol!==`http:`||t.username||t.password||t.port||!Lx.has(t.hostname)?null:t.toString()}var zx={banner:`_banner_21dmw_1`,icon:`_icon_21dmw_17`,body:`_body_21dmw_30`,heading:`_heading_21dmw_35`,message:`_message_21dmw_40`,messageActor:`_messageActor_21dmw_46`,actionLink:`_actionLink_21dmw_50`,dismissBtn:`_dismissBtn_21dmw_61`,actionText:`_actionText_21dmw_72`};function Bx({providerError:e,onDismiss:t}){let n=(e.kind===`quota`||e.kind===`auth`?`critical`:`warning`)==`critical`?{bg:`rgba(196, 74, 30, 0.14)`,border:`var(--red, #c44a1e)`,text:`var(--red, #c44a1e)`,actionBg:`var(--red, #c44a1e)`,actionText:`var(--bg-primary, #14110e)`}:{bg:`rgba(232, 180, 74, 0.14)`,border:`var(--amber, #e8b44a)`,text:`var(--amber, #e8b44a)`,actionBg:`var(--amber, #e8b44a)`,actionText:`var(--bg-primary, #14110e)`},r=e.kind===`quota`?`${Vx(e.provider)} credits exhausted`:e.kind===`auth`?`${Vx(e.provider)} API key invalid`:e.kind===`rate_limit`?`${Vx(e.provider)} rate-limited`:e.kind===`network`?`Network error contacting ${Vx(e.provider)}`:`Provider error`,i=Rx(e.actionUrl),a={"--banner-bg":n.bg,"--banner-border":n.border,"--banner-text":n.text,"--action-bg":n.actionBg,"--action-text":n.actionText};return(0,x.jsxs)(`div`,{role:`alert`,"aria-live":`assertive`,className:zx.banner,style:a,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:zx.icon,children:`!`}),(0,x.jsxs)(`div`,{className:zx.body,children:[(0,x.jsx)(`div`,{className:zx.heading,children:r}),(0,x.jsxs)(`div`,{className:zx.message,children:[e.message,e.leader?(0,x.jsxs)(`span`,{className:zx.messageActor,children:[` (hit by `,e.leader,`)`]}):null]})]}),i?(0,x.jsx)(`a`,{href:i,target:`_blank`,rel:`noreferrer noopener`,className:zx.actionLink,children:e.kind===`quota`?`Add credits →`:`Fix key →`}):typeof e.actionUrl==`string`&&e.actionUrl?(0,x.jsx)(`span`,{className:zx.actionText,children:e.actionUrl}):null,t?(0,x.jsx)(`button`,{onClick:t,"aria-label":`Dismiss banner`,className:zx.dismissBtn,children:`Dismiss`}):null]})}function Vx(e){return e===`openai`?`OpenAI`:e===`anthropic`?`Anthropic`:e===`openrouter`?`OpenRouter`:e===`gemini`?`Gemini`:`Provider`}var q={root:`_root_rnpr5_1`,headerRow:`_headerRow_rnpr5_10`,title:`_title_rnpr5_18`,subTitle:`_subTitle_rnpr5_30`,runMeta:`_runMeta_rnpr5_38`,cardsRow:`_cardsRow_rnpr5_48`,card:`_card_rnpr5_48`,cardHeader:`_cardHeader_rnpr5_69`,cardLabel:`_cardLabel_rnpr5_78`,cardName:`_cardName_rnpr5_86`,cardId:`_cardId_rnpr5_93`,kvList:`_kvList_rnpr5_99`,kv:`_kv_rnpr5_99`,description:`_description_rnpr5_124`,signalList:`_signalList_rnpr5_132`,signal:`_signal_rnpr5_132`,signalLabel:`_signalLabel_rnpr5_150`,signalValue:`_signalValue_rnpr5_153`,section:`_section_rnpr5_158`,sectionTitle:`_sectionTitle_rnpr5_168`,metricsGrid:`_metricsGrid_rnpr5_177`,metric:`_metric_rnpr5_177`,metricLabel:`_metricLabel_rnpr5_193`,metricValue:`_metricValue_rnpr5_201`,metricDelta:`_metricDelta_rnpr5_211`,metricDeltaUp:`_metricDeltaUp_rnpr5_217`,metricDeltaDown:`_metricDeltaDown_rnpr5_221`,chartWrap:`_chartWrap_rnpr5_225`,chart:`_chart_rnpr5_225`,chartLegend:`_chartLegend_rnpr5_240`,legendItem:`_legendItem_rnpr5_249`,legendSwatch:`_legendSwatch_rnpr5_255`,summaryRow:`_summaryRow_rnpr5_261`,summaryCell:`_summaryCell_rnpr5_267`,summaryLabel:`_summaryLabel_rnpr5_277`,summaryValue:`_summaryValue_rnpr5_286`,fingerprintList:`_fingerprintList_rnpr5_296`,fingerprintChip:`_fingerprintChip_rnpr5_302`,dismissBar:`_dismissBar_rnpr5_319`,dismissButton:`_dismissButton_rnpr5_325`,legendSwatchInline:`_legendSwatchInline_rnpr5_343`,playbackControls:`_playbackControls_rnpr5_347`,playbackPlayBtn:`_playbackPlayBtn_rnpr5_354`,playbackResetBtn:`_playbackResetBtn_rnpr5_368`,playbackSlider:`_playbackSlider_rnpr5_381`,playbackList:`_playbackList_rnpr5_387`,playbackHint:`_playbackHint_rnpr5_402`,playbackEvent:`_playbackEvent_rnpr5_408`,playbackTurn:`_playbackTurn_rnpr5_416`,playbackType:`_playbackType_rnpr5_421`,playbackBody:`_playbackBody_rnpr5_428`},Hx={hba1c:`HbA1c`,fastingGlucose:`Fasting Glucose`,weight:`Weight (lb)`,bmi:`BMI`,exerciseAdherence:`Exercise Adherence`,sleepHours:`Sleep (hrs/night)`,qualityOfLife:`Quality of Life`,mortalityRisk:`10-yr Mortality Risk`,cardioFitness:`Cardio Fitness`,sideEffectBurden:`Side-effect Load`,patientMotivation:`Motivation`,familySupport:`Family Support`,population:`Population`,morale:`Morale`,alignmentBench:`AlignmentBench`,specGamingRate:`Spec Gaming Rate`,capabilityIndex:`Capability Index`,releaseReadiness:`Release Readiness`,redTeamCoverage:`Red-team Coverage`,runwayMonths:`Runway`,burnRate:`Burn`,marketShare:`Market Share`,revenueArr:`Revenue ARR`},Ux=[`hba1c`,`weight`,`exerciseAdherence`],Wx={hba1c:`#ef6f5d`,weight:`#ffd970`,exerciseAdherence:`#34d399`,bmi:`#a78bfa`,qualityOfLife:`#7cb6ff`,mortalityRisk:`#ef6f5d`,alignmentBench:`#7cb6ff`,specGamingRate:`#ef6f5d`,releaseReadiness:`#ffd970`,morale:`#ffd970`,runwayMonths:`#5fd49a`,marketShare:`#7cb6ff`},Gx=new Set([`hba1c`,`fastingGlucose`,`weight`,`bmi`,`exerciseAdherence`,`sleepHours`,`qualityOfLife`,`mortalityRisk`,`cardioFitness`,`sideEffectBurden`]);function Kx(e){return Number.isNaN(e)?`—`:Math.abs(e)>=1e6?`${(e/1e6).toFixed(2)}M`:Math.abs(e)>=1e3?`${(e/1e3).toFixed(1)}k`:Number.isInteger(e)?String(e):Math.abs(e)<1?e.toFixed(3):e.toFixed(2)}function qx(e,t){let n=t-e;return Math.abs(n)<1e-6?{text:`·`,direction:`flat`}:{text:`${n>0?`+`:``}${Kx(n)}`,direction:n>0?`up`:`down`}}function Jx(e){return e==null?`—`:typeof e==`number`?Kx(e):typeof e==`boolean`?e?`true`:`false`:typeof e==`string`?e:JSON.stringify(e)}var Yx={run_started:`Run started`,turn_started:`Turn started`,event_start:`Crisis event`,specialist_start:`Specialist analyzing`,specialist_done:`Specialist done`,forge_attempt:`Forge attempt`,forge_approved:`Tool forged`,forge_rejected:`Forge rejected`,decision_pending:`Decision pending`,decision_made:`Decision made`,outcome:`Outcome`,bulletin:`Bulletin`,turn_done:`Turn complete`,agent_reactions:`Agent reactions`,promotion:`Promotion`,systems_snapshot:`Snapshot`,complete:`Complete`};function Xx(e){let t=e.data??{};return typeof t.title==`string`?t.title:typeof t.summary==`string`?t.summary:typeof t.name==`string`?t.name:typeof t.description==`string`?t.description:typeof t.outcome==`string`?t.outcome:typeof t.toolName==`string`?t.toolName:typeof t.department==`string`?t.department:``}function Zx({artifact:e,state:t,onDismiss:n}){let{subject:r,intervention:i,finalState:a,trajectory:o,cost:s,fingerprint:c,metadata:l}=e,u=(0,b.useMemo)(()=>{let e=o;return e?.timepoints&&e.timepoints.length>0?e.timepoints[0]?.worldSnapshot?.metrics??{}:e?.sampleTimepoint?.worldSnapshot?.metrics??{}},[o]),d=a?.metrics??{},f=r?.profile?Object.entries(r.profile).slice(0,6):[],p=(0,b.useMemo)(()=>{let e=o?.timepoints??[];return e.length===0?null:{points:e,series:Ux.map(t=>{let n=e.map(e=>e.worldSnapshot?.metrics?.[t]??null),r=n.filter(e=>typeof e==`number`);return r.length<1?null:{metric:t,values:n,min:Math.min(...r),max:Math.max(...r)}}).filter(e=>e!==null)}},[o]),m=(0,b.useMemo)(()=>{let e=new Set;return Object.keys(d).forEach(t=>e.add(t)),Object.keys(u).forEach(t=>e.add(t)),(Array.from(e).some(e=>Gx.has(e))?Array.from(e).filter(e=>Gx.has(e)):Array.from(e)).slice(0,12)},[d,u]),h=c?Object.entries(c).slice(0,6):[];return(0,x.jsxs)(`div`,{className:q.root,children:[(0,x.jsxs)(`div`,{className:q.headerRow,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`h2`,{className:q.title,children:`Digital Twin · Intervention Result`}),(0,x.jsxs)(`span`,{className:q.subTitle,children:[l?.scenario?.name??`scenario`,` · seed `,l?.seed??`?`,` · `,o?.timepoints?.length??0,` turns`]})]}),(0,x.jsxs)(`div`,{className:q.runMeta,children:[l?.runId&&(0,x.jsxs)(`span`,{children:[`run: `,l.runId.slice(0,28)]}),s?.totalUSD!=null&&(0,x.jsxs)(`span`,{children:[`$`,s.totalUSD.toFixed(3)]}),s?.llmCalls!=null&&(0,x.jsxs)(`span`,{children:[s.llmCalls,` LLM calls`]})]})]}),(0,x.jsxs)(`div`,{className:q.cardsRow,children:[(0,x.jsxs)(`div`,{className:q.card,children:[(0,x.jsxs)(`div`,{className:q.cardHeader,children:[(0,x.jsx)(`span`,{className:q.cardLabel,children:`Subject`}),(0,x.jsx)(`span`,{className:q.cardId,children:r?.id})]}),(0,x.jsx)(`div`,{className:q.cardName,children:r?.name}),f.length>0&&(0,x.jsx)(`div`,{className:q.kvList,children:f.map(([e,t])=>(0,x.jsxs)(`div`,{className:q.kv,children:[(0,x.jsx)(`span`,{children:e}),(0,x.jsx)(`span`,{children:Jx(t)})]},e))}),r?.signals&&r.signals.length>0&&(0,x.jsx)(`div`,{className:q.signalList,children:r.signals.slice(0,4).map((e,t)=>(0,x.jsxs)(`div`,{className:q.signal,children:[(0,x.jsx)(`span`,{className:q.signalLabel,children:e.label}),(0,x.jsxs)(`span`,{className:q.signalValue,children:[typeof e.value==`number`?Kx(e.value):String(e.value),e.unit?` ${e.unit}`:``]})]},t))})]}),(0,x.jsxs)(`div`,{className:q.card,children:[(0,x.jsxs)(`div`,{className:q.cardHeader,children:[(0,x.jsx)(`span`,{className:q.cardLabel,children:`Intervention`}),(0,x.jsx)(`span`,{className:q.cardId,children:i?.id})]}),(0,x.jsx)(`div`,{className:q.cardName,children:i?.name}),i?.description&&(0,x.jsx)(`p`,{className:q.description,children:i.description}),(0,x.jsxs)(`div`,{className:q.kvList,children:[i?.duration&&(0,x.jsxs)(`div`,{className:q.kv,children:[(0,x.jsx)(`span`,{children:`Duration`}),(0,x.jsxs)(`span`,{children:[i.duration.value,` `,i.duration.unit]})]}),i?.adherenceProfile&&(0,x.jsxs)(`div`,{className:q.kv,children:[(0,x.jsx)(`span`,{children:`Adherence`}),(0,x.jsxs)(`span`,{children:[(i.adherenceProfile.expected*100).toFixed(0),`%`]})]})]})]})]}),m.length>0&&(0,x.jsxs)(`div`,{className:q.section,children:[(0,x.jsx)(`h3`,{className:q.sectionTitle,children:`Final state · delta vs initial`}),(0,x.jsx)(`div`,{className:q.metricsGrid,children:m.map(e=>{let t=u[e],n=d[e];if(typeof n!=`number`)return null;let r=typeof t==`number`?qx(t,n):null;return(0,x.jsxs)(`div`,{className:q.metric,children:[(0,x.jsx)(`span`,{className:q.metricLabel,children:Hx[e]??e}),(0,x.jsx)(`span`,{className:q.metricValue,children:Kx(n)}),r&&(0,x.jsx)(`span`,{className:`${q.metricDelta} ${r.direction===`up`?q.metricDeltaUp:r.direction===`down`?q.metricDeltaDown:``}`,children:r.text})]},e)})})]}),p&&p.series.length>0&&(0,x.jsxs)(`div`,{className:q.section,children:[(0,x.jsx)(`h3`,{className:q.sectionTitle,children:`Trajectory`}),(0,x.jsxs)(`div`,{className:q.chartWrap,children:[(0,x.jsxs)(`svg`,{className:q.chart,viewBox:`0 0 600 200`,preserveAspectRatio:`none`,children:[p.series.map(e=>{let t=Math.max(1e-4,e.max-e.min),n=p.points.length>1?580/(p.points.length-1):0,r=``;return e.values.forEach((i,a)=>{if(typeof i!=`number`)return;let o=10+a*n,s=180-(i-e.min)/t*160;r+=(r?` L`:`M`)+` ${o.toFixed(1)} ${s.toFixed(1)}`}),(0,x.jsxs)(`g`,{children:[(0,x.jsx)(`path`,{d:r,stroke:Wx[e.metric]??`#ffd970`,strokeWidth:1.5,fill:`none`}),e.values.map((r,i)=>{if(typeof r!=`number`)return null;let a=10+i*n,o=180-(r-e.min)/t*160;return(0,x.jsx)(`circle`,{cx:a,cy:o,r:2.5,fill:Wx[e.metric]??`#ffd970`},`${e.metric}-${i}`)})]},e.metric)}),p.points.map((e,t)=>{let n=10+t*(p.points.length>1?580/(p.points.length-1):0);return(0,x.jsx)(`text`,{x:n,y:196,fontSize:9,textAnchor:`middle`,fill:`#888`,children:e.label??`t${e.time??t}`},`label-${t}`)})]}),(0,x.jsx)(`div`,{className:q.chartLegend,children:p.series.map(e=>(0,x.jsxs)(`span`,{className:q.legendItem,children:[(0,x.jsx)(`span`,{className:`${q.legendSwatch} ${q.legendSwatchInline}`,style:{"--swatch-color":Wx[e.metric]}}),Hx[e.metric]??e.metric]},e.metric))})]})]}),h.length>0&&(0,x.jsxs)(`div`,{className:q.section,children:[(0,x.jsx)(`h3`,{className:q.sectionTitle,children:`Fingerprint`}),(0,x.jsx)(`div`,{className:q.fingerprintList,children:h.map(([e,t])=>(0,x.jsxs)(`span`,{className:q.fingerprintChip,children:[e,(0,x.jsx)(`b`,{children:String(t)})]},e))})]}),(0,x.jsx)(Qx,{state:t}),n&&(0,x.jsx)(`div`,{className:q.dismissBar,children:(0,x.jsx)(`button`,{onClick:n,className:q.dismissButton,children:`Clear · run another`})})]})}function Qx({state:e}){let t=(0,b.useMemo)(()=>{if(!e)return[];let t=e.actorIds[0];return t?e.actors[t]?.events??[]:[]},[e]),n=t.length,[r,i]=(0,b.useState)(0),[a,o]=(0,b.useState)(!1),s=(0,b.useRef)(!1);if((0,b.useEffect)(()=>{!s.current&&n>0&&(s.current=!0,i(n))},[n]),(0,b.useEffect)(()=>{if(!a)return;if(r>=n){o(!1);return}let e=window.setTimeout(()=>i(e=>e+1),600);return()=>window.clearTimeout(e)},[a,r,n]),n===0)return null;let c=t.slice(0,r);return(0,x.jsxs)(`div`,{className:q.section,children:[(0,x.jsxs)(`h3`,{className:q.sectionTitle,children:[`Playback · `,r,` / `,n,` events`]}),(0,x.jsxs)(`div`,{className:q.playbackControls,children:[(0,x.jsx)(`button`,{onClick:()=>o(!a),className:q.playbackPlayBtn,children:a?`Pause`:r>=n?`Replay`:`Play`}),(0,x.jsx)(`button`,{onClick:()=>{i(0),o(!1)},className:q.playbackResetBtn,children:`Reset`}),(0,x.jsx)(`input`,{type:`range`,min:0,max:n,value:r,onChange:e=>{i(Number(e.target.value)),o(!1)},className:q.playbackSlider})]}),(0,x.jsx)(`div`,{className:q.playbackList,children:c.length===0?(0,x.jsx)(`div`,{className:q.playbackHint,children:`Drag the slider or press Play to step through the run.`}):c.map(e=>(0,x.jsxs)(`div`,{className:q.playbackEvent,children:[(0,x.jsx)(`span`,{className:q.playbackTurn,children:e.turn==null?``:`T${e.turn}`}),(0,x.jsx)(`span`,{className:q.playbackType,children:Yx[e.type]??e.type}),(0,x.jsx)(`span`,{className:q.playbackBody,children:Xx(e)})]},e.id))})]})}var $x={root:`_root_w82tn_1`,headerRow:`_headerRow_w82tn_10`,title:`_title_w82tn_18`,spinner:`_spinner_w82tn_33`,"dt-spin":`_dt-spin_w82tn_1`,timer:`_timer_w82tn_42`,cardsRow:`_cardsRow_w82tn_50`,card:`_card_w82tn_50`,cardHeader:`_cardHeader_w82tn_71`,cardLabel:`_cardLabel_w82tn_80`,cardId:`_cardId_w82tn_89`,cardName:`_cardName_w82tn_95`,kvList:`_kvList_w82tn_102`,kv:`_kv_w82tn_102`,description:`_description_w82tn_127`,statsBar:`_statsBar_w82tn_135`,stat:`_stat_w82tn_135`,statLabel:`_statLabel_w82tn_151`,statValue:`_statValue_w82tn_159`,progressBar:`_progressBar_w82tn_169`,progressFill:`_progressFill_w82tn_177`,eventLog:`_eventLog_w82tn_183`,eventLogHeader:`_eventLogHeader_w82tn_195`,eventLogTitle:`_eventLogTitle_w82tn_203`,eventLogScroll:`_eventLogScroll_w82tn_211`,eventRow:`_eventRow_w82tn_228`,eventTurn:`_eventTurn_w82tn_240`,eventType:`_eventType_w82tn_246`,eventBody:`_eventBody_w82tn_257`,eventEmpty:`_eventEmpty_w82tn_264`},eS={run_started:`Run started`,turn_started:`Turn started`,event_start:`Crisis event`,specialist_start:`Specialist analyzing`,specialist_done:`Specialist done`,forge_attempt:`Forge attempt`,forge_approved:`Tool forged`,forge_rejected:`Forge rejected`,decision_pending:`Decision pending`,decision_made:`Decision made`,outcome:`Outcome`,bulletin:`Bulletin`,turn_done:`Turn complete`,agent_reactions:`Agent reactions`,promotion:`Promotion`,systems_snapshot:`Snapshot`,complete:`Complete`};function tS(e){return Number.isNaN(e)?`—`:Math.abs(e)>=1e6?`${(e/1e6).toFixed(2)}M`:Math.abs(e)>=1e3?`${(e/1e3).toFixed(1)}k`:Number.isInteger(e)?String(e):Math.abs(e)<1?e.toFixed(3):e.toFixed(2)}function nS(e){let t=e.data??{};return typeof t.title==`string`?t.title:typeof t.summary==`string`?t.summary:typeof t.name==`string`?t.name:typeof t.description==`string`?t.description:typeof t.outcome==`string`?t.outcome:typeof t.toolName==`string`?t.toolName:typeof t.department==`string`?t.department:``}function rS({state:e,subject:t,intervention:n}){let[r,i]=(0,b.useState)(0),a=(0,b.useRef)(Date.now()),o=(0,b.useRef)(null),s=(0,b.useRef)(!0);(0,b.useEffect)(()=>{let e=window.setInterval(()=>{i(Math.round((Date.now()-a.current)/1e3))},500);return()=>window.clearInterval(e)},[]);let c=e.actorIds[0],l=c?e.actors[c]:null,u=l?.events??[],d=e.turn,f=e.maxTurns||1,p=Math.min(100,Math.max(0,d/f*100)),m=e.cost?.totalCostUSD??0,h=e.cost?.llmCalls??0,g=l?.tools??0,_=l?.citations??0;(0,b.useEffect)(()=>{if(!s.current)return;let e=o.current;e&&(e.scrollTop=e.scrollHeight)},[u.length]);let v=()=>{let e=o.current;e&&(s.current=e.scrollHeight-e.scrollTop-e.clientHeight<40)},y=t.profile?Object.entries(t.profile).slice(0,4):[];return(0,x.jsxs)(`div`,{className:$x.root,children:[(0,x.jsxs)(`div`,{className:$x.headerRow,children:[(0,x.jsxs)(`h2`,{className:$x.title,children:[(0,x.jsx)(`span`,{className:$x.spinner,"aria-hidden":`true`}),`Digital Twin · Running`]}),(0,x.jsxs)(`span`,{className:$x.timer,children:[r,`s elapsed · streaming live · `,f,` `,f===1?`turn`:`turns`,` × LLM decisions`]})]}),(0,x.jsxs)(`div`,{className:$x.cardsRow,children:[(0,x.jsxs)(`div`,{className:$x.card,children:[(0,x.jsxs)(`div`,{className:$x.cardHeader,children:[(0,x.jsx)(`span`,{className:$x.cardLabel,children:`Subject`}),(0,x.jsx)(`span`,{className:$x.cardId,children:t.id})]}),(0,x.jsx)(`div`,{className:$x.cardName,children:t.name}),y.length>0&&(0,x.jsx)(`div`,{className:$x.kvList,children:y.map(([e,t])=>(0,x.jsxs)(`div`,{className:$x.kv,children:[(0,x.jsx)(`span`,{children:e}),(0,x.jsx)(`span`,{children:typeof t==`number`?tS(t):String(t)})]},e))})]}),(0,x.jsxs)(`div`,{className:$x.card,children:[(0,x.jsxs)(`div`,{className:$x.cardHeader,children:[(0,x.jsx)(`span`,{className:$x.cardLabel,children:`Intervention`}),(0,x.jsx)(`span`,{className:$x.cardId,children:n.id})]}),(0,x.jsx)(`div`,{className:$x.cardName,children:n.name}),(0,x.jsx)(`p`,{className:$x.description,children:n.description}),n.duration&&(0,x.jsx)(`div`,{className:$x.kvList,children:(0,x.jsxs)(`div`,{className:$x.kv,children:[(0,x.jsx)(`span`,{children:`Duration`}),(0,x.jsxs)(`span`,{children:[n.duration.value,` `,n.duration.unit]})]})})]})]}),(0,x.jsxs)(`div`,{className:$x.statsBar,children:[(0,x.jsxs)(`div`,{className:$x.stat,children:[(0,x.jsx)(`span`,{className:$x.statLabel,children:`Turn`}),(0,x.jsxs)(`span`,{className:$x.statValue,children:[d,` / `,f]}),(0,x.jsx)(`div`,{className:$x.progressBar,children:(0,x.jsx)(`div`,{className:$x.progressFill,style:{width:`${p}%`}})})]}),(0,x.jsxs)(`div`,{className:$x.stat,children:[(0,x.jsx)(`span`,{className:$x.statLabel,children:`LLM Calls`}),(0,x.jsx)(`span`,{className:$x.statValue,children:h})]}),(0,x.jsxs)(`div`,{className:$x.stat,children:[(0,x.jsx)(`span`,{className:$x.statLabel,children:`Cost`}),(0,x.jsxs)(`span`,{className:$x.statValue,children:[`$`,m.toFixed(4)]})]}),(0,x.jsxs)(`div`,{className:$x.stat,children:[(0,x.jsx)(`span`,{className:$x.statLabel,children:`Tools forged`}),(0,x.jsx)(`span`,{className:$x.statValue,children:g})]}),(0,x.jsxs)(`div`,{className:$x.stat,children:[(0,x.jsx)(`span`,{className:$x.statLabel,children:`Citations`}),(0,x.jsx)(`span`,{className:$x.statValue,children:_})]})]}),(0,x.jsxs)(`div`,{className:$x.eventLog,children:[(0,x.jsxs)(`div`,{className:$x.eventLogHeader,children:[(0,x.jsx)(`span`,{className:$x.eventLogTitle,children:`Live event log · streaming from /events`}),(0,x.jsxs)(`span`,{className:$x.timer,children:[u.length,` events`]})]}),(0,x.jsx)(`div`,{ref:o,onScroll:v,className:$x.eventLogScroll,children:u.length===0?(0,x.jsx)(`div`,{className:$x.eventEmpty,children:`Waiting for the first server event…`}):u.map(e=>(0,x.jsxs)(`div`,{className:$x.eventRow,children:[(0,x.jsx)(`span`,{className:$x.eventTurn,children:e.turn==null?``:`T${e.turn}`}),(0,x.jsx)(`span`,{className:$x.eventType,children:eS[e.type]??e.type}),(0,x.jsx)(`span`,{className:$x.eventBody,children:nS(e)})]},e.id))})]})]})}var iS=`▁▂▃▄▅▆▇█`;function aS({data:e,label:t,suffix:n=``,color:r}){if(!e.length)return(0,x.jsx)(`span`,{style:{color:`var(--text-3)`,fontFamily:`var(--mono)`,fontSize:`var(--font-2xs)`},children:`—`});let i=Math.max(...e)||1,a=e.map(e=>iS[Math.min(7,Math.floor(e/i*7.99))]).join(``),o=e[e.length-1];return(0,x.jsxs)(`span`,{style:{fontFamily:`var(--mono)`,fontSize:`var(--font-2xs)`,whiteSpace:`nowrap`},children:[t&&(0,x.jsxs)(`span`,{style:{color:`var(--text-3)`,fontSize:`var(--font-3xs)`,textTransform:`uppercase`,letterSpacing:`0.3px`,fontWeight:600},children:[t,` `]}),(0,x.jsx)(`span`,{style:{color:r||`var(--amber)`,letterSpacing:`-0.5px`},children:a}),` `,(0,x.jsxs)(`span`,{style:{color:r||`var(--text-1)`},children:[o,n]})]})}var oS={root:`_root_17urj_1`,headerRow:`_headerRow_17urj_8`,archetypeChip:`_archetypeChip_17urj_15`,slot:`_slot_17urj_32`,verdictChip:`_verdictChip_17urj_50`,winner:`_winner_17urj_59`,tie:`_tie_17urj_64`,second:`_second_17urj_69`,name:`_name_17urj_75`,unitTag:`_unitTag_17urj_82`,traits:`_traits_17urj_91`,traitsSep:`_traitsSep_17urj_95`,traitsLine:`_traitsLine_17urj_100`,subRow:`_subRow_17urj_109`,quote:`_quote_17urj_116`,awaiting:`_awaiting_17urj_126`,sparklines:`_sparklines_17urj_134`,tooltipHeading:`_tooltipHeading_17urj_141`,tooltipInstructions:`_tooltipInstructions_17urj_150`,tooltipTraitBlock:`_tooltipTraitBlock_17urj_157`,tooltipTraitRow:`_tooltipTraitRow_17urj_164`,tooltipTraitLabel:`_tooltipTraitLabel_17urj_169`,tooltipTraitValue:`_tooltipTraitValue_17urj_173`,compact:`_compact_17urj_177`,compactBand:`_compactBand_17urj_192`,compactSlot:`_compactSlot_17urj_205`,compactName:`_compactName_17urj_224`,compactSep:`_compactSep_17urj_234`,compactStat:`_compactStat_17urj_239`,compactArchetype:`_compactArchetype_17urj_246`,compactMood:`_compactMood_17urj_259`,compactCrisis:`_compactCrisis_17urj_260`,compactDeciding:`_compactDeciding_17urj_261`,"pulse-deciding":`_pulse-deciding_17urj_1`,chipDeciding:`_chipDeciding_17urj_308`,chip:`_chip_17urj_308`,dynamicRow:`_dynamicRow_17urj_329`,chipLabel:`_chipLabel_17urj_354`,chipValue:`_chipValue_17urj_360`,chipCrisis:`_chipCrisis_17urj_365`,chipStatus:`_chipStatus_17urj_384`,mood_low:`_mood_low_17urj_388`,mood_tense:`_mood_tense_17urj_398`,mood_ok:`_mood_ok_17urj_408`,mood_high:`_mood_high_17urj_412`};function sS(e){return e<25?{label:`low`,icon:`▼`,tone:`low`}:e<50?{label:`tense`,icon:`▽`,tone:`tense`}:e<75?{label:`steady`,icon:`△`,tone:`ok`}:{label:`rising`,icon:`▲`,tone:`high`}}function cS(e,t){if(!e)return[];let n=[];for(let[r,i]of Object.entries(e)){if(!r||i===!1||i===``||i==null)continue;let e=typeof i==`boolean`?`on`:String(i);if(n.push({key:r,label:lS(r),value:e}),n.length>=t)break}return n}function lS(e){if(!e)return e;let t=e.replace(/[_-]+/g,` `).replace(/([a-z])([A-Z])/g,`$1 $2`).trim().toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}function uS(e,t){let n=Math.round(t*4);return`${e} ${`█`.repeat(n)+`░`.repeat(4-n)} ${t.toFixed(2)}`}function dS({actorIndex:e,leader:t,popHistory:n,moraleHistory:r,verdictPlacement:i,compact:a=!1,event:o,statuses:s,pendingDecision:c,nameFallback:l}){let u=Pe(e),d=`color-mix(in srgb, ${u} 12%, transparent)`,f=`color-mix(in srgb, ${u} 55%, transparent)`,p=`Leader ${String.fromCharCode(65+e)}`,m=t?.name||l||p,h=(()=>{let t=e,n=``;do n=String.fromCharCode(65+t%26)+n,t=Math.floor(t/26)-1;while(t>=0);return n})();if(a){let e=n.length>0?n[n.length-1]:null,i=r.length>0?r[r.length-1]:null,a=i===null?null:sS(i),s=t?.archetype?.replace(/^The\s+/i,``).toUpperCase()||``;return(0,x.jsxs)(`div`,{className:oS.compact,style:{"--actor-color":u,"--actor-bg":d,"--actor-border":f},"aria-label":`${m} compact summary`,children:[(0,x.jsx)(`span`,{className:oS.compactBand,"aria-hidden":`true`}),(0,x.jsx)(`span`,{className:oS.compactSlot,"aria-hidden":`true`,title:`Slot ${h}`,children:h}),(0,x.jsx)(`span`,{className:oS.compactName,children:m}),s&&(0,x.jsx)(`span`,{className:oS.compactArchetype,title:t?.archetype,children:s}),e!==null&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:oS.compactSep,children:`·`}),(0,x.jsxs)(`span`,{className:oS.compactStat,children:[`POP `,Math.round(e)]})]}),i!==null&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:oS.compactSep,children:`·`}),(0,x.jsxs)(`span`,{className:oS.compactStat,children:[`MORALE `,Math.round(i),`%`]})]}),a&&(0,x.jsxs)(`span`,{className:`${oS.compactMood} ${oS[`mood_${a.tone}`]??``}`.trim(),title:`Mood: ${a.label}`,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:a.icon}),(0,x.jsx)(`span`,{children:a.label})]}),o?.title&&(0,x.jsxs)(`span`,{className:oS.compactCrisis,title:o.description??o.title,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`⚠`}),(0,x.jsx)(`span`,{children:o.title.length>24?`${o.title.slice(0,24)}…`:o.title})]}),c&&(0,x.jsx)(`span`,{className:oS.compactDeciding,title:c,children:`DECIDING…`})]})}let g=t?.archetype||``,_=t?.unit||``,v=t?.hexaco||{},y=Object.values(v).some(e=>e>0),b=[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`],S=y?[`O`,`C`,`E`,`A`,`Em`,`HH`].map((e,t)=>uS(e,v[b[t]]??0)).join(` `):``,C=i?`${oS.verdictChip} ${oS[i]??``}`.trim():``;return(0,x.jsxs)(`div`,{className:oS.root,style:{"--actor-color":u,"--actor-bg":d,"--actor-border":f},children:[(0,x.jsxs)(`div`,{className:oS.headerRow,children:[(0,x.jsx)(`span`,{className:oS.slot,"aria-hidden":`true`,title:`Slot ${h}`,children:h}),g&&(0,x.jsx)(`span`,{className:oS.archetypeChip,children:g.toUpperCase().replace(/^THE\s+/i,``)}),i&&(0,x.jsx)(`span`,{title:i===`winner`?`Verdict: this leader won`:i===`tie`?`Verdict: tie`:`Verdict: runner-up`,className:C,children:i===`winner`?`★ WINNER`:i===`tie`?`= TIE`:`2ND`}),(0,x.jsx)(Sx,{dot:!0,content:(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`b`,{className:oS.tooltipHeading,children:[g?`${g}: `:``,m]}),_&&(0,x.jsxs)(`div`,{children:[`Unit: `,_]}),t?.instructions&&(0,x.jsx)(`div`,{className:oS.tooltipInstructions,children:t.instructions}),y&&(0,x.jsx)(`div`,{className:oS.tooltipTraitBlock,children:b.map(e=>(0,x.jsxs)(`div`,{className:oS.tooltipTraitRow,children:[(0,x.jsx)(`span`,{className:oS.tooltipTraitLabel,children:e.charAt(0).toUpperCase()+e.slice(1).replace(/([A-Z])/g,` $1`)}),(0,x.jsx)(`span`,{className:oS.tooltipTraitValue,children:(v[e]??0).toFixed(2)})]},e))})]}),children:(0,x.jsx)(`span`,{className:oS.name,children:m})}),_&&(0,x.jsx)(`span`,{className:oS.unitTag,children:_}),S&&(0,x.jsxs)(`span`,{className:`leader-traits ${oS.traits}`,children:[(0,x.jsx)(`span`,{className:oS.traitsSep,children:`|`}),(0,x.jsx)(`span`,{className:oS.traitsLine,children:S})]})]}),(0,x.jsxs)(`div`,{className:oS.subRow,children:[(0,x.jsx)(`span`,{className:oS.quote,children:(()=>{if(t?.quote)return`"${t.quote}"`;if(t?.instructions){let e=t.instructions.replace(/^You are [^.]+\.\s*/i,``).replace(/^"[^"]+"\.\s*/i,``).replace(/Your HEXACO profile drives your leadership.*$/i,``).trim();if(e)return`"${e.slice(0,80)}${e.length>80?`...`:``}"`}return n.length===0&&r.length===0?(0,x.jsx)(`span`,{className:oS.awaiting,children:`Awaiting first turn…`}):``})()}),(0,x.jsxs)(`span`,{className:`leader-sparklines ${oS.sparklines}`,children:[(0,x.jsx)(aS,{data:n,label:`POP`,color:u}),` `,(0,x.jsx)(aS,{data:r,label:`MORALE`,suffix:`%`,color:`var(--amber)`})]})]}),(0,x.jsx)(fS,{moraleHistory:r,event:o,statuses:s,pendingDecision:c})]})}function fS({moraleHistory:e,event:t,statuses:n,pendingDecision:r}){let i=e.length>0?e[e.length-1]:null,a=i===null?null:sS(i),o=cS(n,2);return a||t?.title||r||o.length>0?(0,x.jsxs)(`div`,{className:oS.dynamicRow,role:`status`,"aria-live":`polite`,"aria-atomic":`false`,"aria-relevant":`additions text`,children:[a&&(0,x.jsxs)(`span`,{className:`${oS.chip} ${oS[`mood_${a.tone}`]??``}`.trim(),title:`Mood derived from current morale (${Math.round(i)}%)`,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:a.icon}),(0,x.jsx)(`span`,{className:oS.chipLabel,children:`Mood`}),(0,x.jsx)(`span`,{className:oS.chipValue,children:a.label})]}),t?.title&&(0,x.jsxs)(`span`,{className:`${oS.chip} ${oS.chipCrisis}`,title:t.description??t.title,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`⚠`}),(0,x.jsx)(`span`,{className:oS.chipLabel,children:lS(t.category)||`Event`}),(0,x.jsx)(`span`,{className:oS.chipValue,children:t.title.length>32?`${t.title.slice(0,32)}…`:t.title})]}),r&&(0,x.jsxs)(`span`,{className:`${oS.chip} ${oS.chipDeciding}`,title:r,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`⏳`}),(0,x.jsx)(`span`,{className:oS.chipLabel,children:`Deciding`})]}),o.map(({key:e,label:t,value:n})=>(0,x.jsxs)(`span`,{className:`${oS.chip} ${oS.chipStatus}`,title:`${t}: ${n}`,children:[(0,x.jsx)(`span`,{className:oS.chipLabel,children:t}),(0,x.jsx)(`span`,{className:oS.chipValue,children:n})]},e))]}):null}function pS(e){if(!e)return``;let t=Object.entries(e);return t.length===0?``:t.map(([e,t])=>`${e}: ${typeof t==`boolean`?t?`yes`:`no`:String(t)}`).join(`
124
- `)}function mS(e,t){if(t.format!==`percent`)return e;let n=t.max??t.initial;return n===void 0||n<=1?e*100:e}function hS(e,t){if(t.format===`percent`)return`${Math.round(mS(e,t))}%`;if(t.format===`number`){let t=Math.round(e*10)/10;return Number.isInteger(t)?String(t):t.toFixed(1)}return String(e)}var gS={bar:`_bar_1gubl_1`,crisis:`_crisis_1gubl_18`,pill:`_pill_1gubl_29`,label:`_label_1gubl_39`,value:`_value_1gubl_52`,valueB:`_valueB_1gubl_52`,valueA:`_valueA_1gubl_52`,delta:`_delta_1gubl_65`,deltaNeutral:`_deltaNeutral_1gubl_65`,deltaNegative:`_deltaNegative_1gubl_65`,deltaPositive:`_deltaPositive_1gubl_65`,sep:`_sep_1gubl_81`,causesChip:`_causesChip_1gubl_86`};function _S(e){return e===`foodMonthsReserve`?`mo`:``}var vS={population:`POP`,morale:`MORALE`,foodMonthsReserve:`FOOD`,powerKw:`POWER`,infrastructureModules:`MODULES`,scienceOutput:`SCIENCE`,hullIntegrity:`HULL`,oxygenReserveHours:`O2`},yS={population:`P`,morale:`M`,foodMonthsReserve:`F`,powerKw:`W`,infrastructureModules:`I`,scienceOutput:`S`,hullIntegrity:`H`,oxygenReserveHours:`O₂`};function bS(e,t){if(t==null)return``;let n=Math.round((e-t)*100)/100;return n===0?``:n>0?`+${n}`:`${n}`}function xS(e,t){return e?t===`neutral`?gS.deltaNeutral:t===`lossIsRed`?e.startsWith(`-`)?gS.deltaPositive:gS.deltaNegative:e.startsWith(`+`)?gS.deltaPositive:gS.deltaNegative:``}function SS(e){if(!e)return``;let t=Object.entries(e).filter(([,e])=>e>0).sort((e,t)=>t[1]-e[1]);if(t.length===0)return``;let n=t.slice(0,3).map(([e,t])=>`${t} ${e.replace(`radiation cancer`,`radiation`).replace(`natural causes`,`age`).replace(`age-related complications`,`age`).replace(`fatal fracture`,`fracture`).replace(`accident: `,``).replace(`accident`,`accident`)}`),r=t.length-n.length;return r>0?`${n.join(` · `)} +${r}`:n.join(` · `)}function CS({actors:e,crisisText:t,toolRegistry:n}){let r=Xk(),i=e[0],a=e[1],o=i?.state,s=a?.state,c=o?.metrics??null,l=s?.metrics??null,u=o?.prevMetrics??null,d=s?.prevMetrics??null,f=o?.deaths??0,p=s?.deaths??0,m=o?.deathCauses,h=s?.deathCauses,g=o?.tools??0,_=s?.tools??0,v=o?.citations??0,y=s?.citations??0,S=i?.id??``,C=a?.id??``,w=o?.statuses,T=s?.statuses,E=o?.environment,D=s?.environment,{reuseA:O,reuseB:k}=(0,b.useMemo)(()=>{let e=0,t=0;for(let r of n?.list??[])for(let n=1;n<r.history.length;n++){let i=r.history[n];i.rejected||(i.actorName===S?e++:i.actorName===C&&t++)}return{reuseA:e,reuseB:t}},[n,S,C]),A=(0,b.useRef)({toolsA:g,toolsB:_,reuseA:O,reuseB:k,citationsA:v,citationsB:y,deathsA:f,deathsB:p}),j=A.current,ee=bS(g,j.toolsA),te=bS(_,j.toolsB),M=bS(O,j.reuseA),N=bS(k,j.reuseB),ne=bS(v,j.citationsA),P=bS(y,j.citationsB),re=bS(f,j.deathsA),ie=bS(p,j.deathsB);if((0,b.useEffect)(()=>{A.current={toolsA:g,toolsB:_,reuseA:O,reuseB:k,citationsA:v,citationsB:y,deathsA:f,deathsB:p}},[g,_,O,k,v,y,f,p]),!c&&!l)return null;let F=r.ui.headerMetrics.filter(e=>e.id!==`population`&&e.id!==`morale`).slice(0,4),I=Pe(0),ae=Pe(1);return(0,x.jsxs)(`div`,{className:`stats-bar ${gS.bar}`,role:`region`,"aria-label":`Leader statistics`,tabIndex:0,style:{"--actor-color-a":I,"--actor-color-b":ae},children:[t&&(0,x.jsx)(`span`,{className:gS.crisis,children:t}),F.map(e=>{let t=c?.[e.id]??0,n=l?.[e.id]??0,r=t=>t==null?void 0:mS(t,e),i=bS(mS(t,e),r(u?.[e.id])),a=bS(mS(n,e),r(d?.[e.id])),o=hS(t,e),s=hS(n,e),f=_S(e.id),p=vS[e.id]||e.id.replace(/([A-Z])/g,` $1`).trim().toUpperCase(),m=yS[e.id]||p.charAt(0);return(0,x.jsxs)(`span`,{className:gS.pill,children:[(0,x.jsxs)(`span`,{className:gS.label,title:p,children:[(0,x.jsx)(`span`,{className:`pill-label-full`,children:p}),(0,x.jsx)(`span`,{className:`pill-label-short`,children:m})]}),(0,x.jsxs)(`span`,{className:gS.valueA,children:[o,f]}),i&&(0,x.jsx)(`span`,{className:xS(i,`gain`),children:i}),(0,x.jsx)(`span`,{className:gS.sep,children:`vs`}),(0,x.jsxs)(`span`,{className:gS.valueB,children:[s,f]}),a&&(0,x.jsx)(`span`,{className:xS(a,`gain`),children:a})]},e.id)}),(0,x.jsxs)(`span`,{className:gS.pill,children:[(0,x.jsxs)(`span`,{className:gS.label,title:`Deaths`,children:[(0,x.jsx)(`span`,{className:`pill-label-full`,children:`DEATHS`}),(0,x.jsx)(`span`,{className:`pill-label-short`,children:`†`})]}),(0,x.jsx)(`span`,{className:gS.valueA,title:m&&Object.keys(m).length>0?`Leader A deaths by cause: ${Object.entries(m).map(([e,t])=>`${t} ${e}`).join(`, `)}`:void 0,children:f}),re&&(0,x.jsx)(`span`,{className:xS(re,`lossIsRed`),children:re}),(0,x.jsx)(`span`,{className:gS.sep,children:`vs`}),(0,x.jsx)(`span`,{className:gS.valueB,title:h&&Object.keys(h).length>0?`Leader B deaths by cause: ${Object.entries(h).map(([e,t])=>`${t} ${e}`).join(`, `)}`:void 0,children:p}),ie&&(0,x.jsx)(`span`,{className:xS(ie,`lossIsRed`),children:ie}),(()=>{let e=SS(m),t=SS(h);return!e&&!t?null:(0,x.jsxs)(`span`,{className:gS.causesChip,children:[`(`,e||`0`,` / `,t||`0`,`)`]})})()]}),(0,x.jsxs)(`span`,{className:gS.pill,children:[(0,x.jsxs)(`span`,{className:gS.label,title:`Tools forged`,children:[(0,x.jsx)(`span`,{className:`pill-label-full`,children:`TOOLS`}),(0,x.jsx)(`span`,{className:`pill-label-short`,children:`T`})]}),(0,x.jsx)(`span`,{className:gS.valueA,children:g}),ee&&(0,x.jsx)(`span`,{className:gS.deltaPositive,children:ee}),(0,x.jsx)(`span`,{className:gS.sep,children:`/`}),(0,x.jsx)(`span`,{className:gS.valueB,children:_}),te&&(0,x.jsx)(`span`,{className:gS.deltaPositive,children:te})]}),n&&n.list.length>0&&(0,x.jsxs)(`span`,{className:gS.pill,title:`Forged-tool reuse count per leader. Reuses amortize forge cost across multiple events.`,children:[(0,x.jsxs)(`span`,{className:gS.label,title:`Reuse count`,children:[(0,x.jsx)(`span`,{className:`pill-label-full`,children:`REUSE`}),(0,x.jsx)(`span`,{className:`pill-label-short`,children:`R`})]}),(0,x.jsx)(`span`,{className:gS.valueA,children:O}),M&&(0,x.jsx)(`span`,{className:gS.deltaPositive,children:M}),(0,x.jsx)(`span`,{className:gS.sep,children:`/`}),(0,x.jsx)(`span`,{className:gS.valueB,children:k}),N&&(0,x.jsx)(`span`,{className:gS.deltaPositive,children:N})]}),(0,x.jsxs)(`span`,{className:gS.pill,children:[(0,x.jsxs)(`span`,{className:gS.label,title:`Citations`,children:[(0,x.jsx)(`span`,{className:`pill-label-full`,children:`CITES`}),(0,x.jsx)(`span`,{className:`pill-label-short`,children:`C`})]}),(0,x.jsx)(`span`,{className:gS.valueA,children:v}),ne&&(0,x.jsx)(`span`,{className:xS(ne,`neutral`),children:ne}),(0,x.jsx)(`span`,{className:gS.sep,children:`/`}),(0,x.jsx)(`span`,{className:gS.valueB,children:y}),P&&(0,x.jsx)(`span`,{className:xS(P,`neutral`),children:P})]}),(w||T)&&(0,x.jsxs)(`span`,{className:gS.pill,title:`Categorical scenario-declared statuses (world.statuses).\n\nLeader A:\n${pS(w)||`(none)`}\n\nLeader B:\n${pS(T)||`(none)`}`,children:[(0,x.jsxs)(`span`,{className:gS.label,children:[(0,x.jsx)(`span`,{className:`pill-label-full`,children:`STATUSES`}),(0,x.jsx)(`span`,{className:`pill-label-short`,children:`§`})]}),(0,x.jsx)(`span`,{className:gS.valueA,children:w?Object.keys(w).length:0}),(0,x.jsx)(`span`,{className:gS.sep,children:`/`}),(0,x.jsx)(`span`,{className:gS.valueB,children:T?Object.keys(T).length:0})]}),(E||D)&&(0,x.jsxs)(`span`,{className:gS.pill,title:`Environment bag (world.environment), external conditions.\n\nLeader A:\n${pS(E)||`(none)`}\n\nLeader B:\n${pS(D)||`(none)`}`,children:[(0,x.jsxs)(`span`,{className:gS.label,children:[(0,x.jsx)(`span`,{className:`pill-label-full`,children:`ENV`}),(0,x.jsx)(`span`,{className:`pill-label-short`,children:`E`})]}),(0,x.jsx)(`span`,{className:gS.valueA,children:E?Object.keys(E).length:0}),(0,x.jsx)(`span`,{className:gS.sep,children:`/`}),(0,x.jsx)(`span`,{className:gS.valueB,children:D?Object.keys(D).length:0})]})]})}var wS={timelineRow:`_timelineRow_iwf5k_1`,sideWrap:`_sideWrap_iwf5k_36`,sideHeader:`_sideHeader_iwf5k_55`,sideHeaderIdx:`_sideHeaderIdx_iwf5k_66`,sideHeaderName:`_sideHeaderName_iwf5k_75`,sideHeaderArchetype:`_sideHeaderArchetype_iwf5k_86`,side:`_side_iwf5k_36`,outcomeBadge:`_outcomeBadge_iwf5k_109`,tooltipHeader:`_tooltipHeader_iwf5k_120`,tooltipTurn:`_tooltipTurn_iwf5k_127`,tooltipTime:`_tooltipTime_iwf5k_132`,tooltipCategory:`_tooltipCategory_iwf5k_138`,tooltipEmergent:`_tooltipEmergent_iwf5k_147`,tooltipTitle:`_tooltipTitle_iwf5k_154`,tooltipSummary:`_tooltipSummary_iwf5k_161`,tooltipDecision:`_tooltipDecision_iwf5k_168`,tooltipDecisionLabel:`_tooltipDecisionLabel_iwf5k_177`,tooltipOutcome:`_tooltipOutcome_iwf5k_185`,entry:`_entry_iwf5k_193`,current:`_current_iwf5k_205`,glow:`_glow_iwf5k_1`,entryHead:`_entryHead_iwf5k_209`,entryTurn:`_entryTurn_iwf5k_217`,entryTitle:`_entryTitle_iwf5k_225`,entryCategory:`_entryCategory_iwf5k_235`,entryEmergent:`_entryEmergent_iwf5k_245`,entrySummary:`_entrySummary_iwf5k_253`,entrySubEvents:`_entrySubEvents_iwf5k_265`,entrySubEventRow:`_entrySubEventRow_iwf5k_272`,entrySubIdx:`_entrySubIdx_iwf5k_277`,entryDecision:`_entryDecision_iwf5k_284`};function TS(e,t){let n=[],r=e;for(let e of r.events){if(e.type===`turn_start`&&e.data.title&&e.data.title!==`Director generating...`&&n.push({turn:e.data.turn,time:e.data.time,title:e.data.title,summary:e.data.turnSummary||e.data.crisis||``,category:e.data.category||``,emergent:e.data.emergent||!1}),e.type===`event_start`){let t=e.data.turn,r=n.find(e=>e.turn===t);r&&(r.subEvents||=[],r.subEvents.push({index:Number(e.data.eventIndex??0),title:String(e.data.title||``),category:String(e.data.category||``)}))}if(e.type===`outcome`){let t=n.find(t=>t.turn===e.data.turn);t&&(t.outcome=e.data.outcome,t.decision=e.data._decision||``)}}return n.length&&(n[n.length-1].current=!t),n}function ES(e){if(!e)return{label:``,color:`var(--text-3)`};let t=e.includes(`success`);return{label:e.includes(`risky`)?t?`RISKY WIN`:`RISKY LOSS`:t?`SAFE WIN`:`SAFE LOSS`,color:t?`var(--green)`:`var(--rust)`}}function DS(e){if(!e)return null;let{color:t}=ES(e),n=e.includes(`success`),r=e.includes(`risky`)?n?`RS`:`RF`:n?`CS`:`CF`;return(0,x.jsx)(`span`,{className:wS.outcomeBadge,style:{"--status-color":t,"--status-bg":`transparent`},children:r})}function OS({t:e,sideColor:t}){let{label:n,color:r}=ES(e.outcome),i={"--side-color":t};return(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:wS.tooltipHeader,children:[(0,x.jsxs)(`b`,{className:wS.tooltipTurn,style:i,children:[`Turn `,e.turn]}),(0,x.jsxs)(`span`,{className:wS.tooltipTime,children:[`Y`,e.time]}),e.category&&(0,x.jsx)(`span`,{className:wS.tooltipCategory,children:e.category}),e.emergent&&(0,x.jsx)(`span`,{className:wS.tooltipEmergent,children:`EMERGENT`})]}),(0,x.jsx)(`div`,{className:wS.tooltipTitle,children:e.title}),e.summary&&(0,x.jsx)(`div`,{className:wS.tooltipSummary,children:e.summary}),e.decision&&(0,x.jsxs)(`div`,{className:wS.tooltipDecision,children:[(0,x.jsx)(`span`,{className:wS.tooltipDecisionLabel,style:i,children:`Decision: `}),e.decision]}),e.outcome&&(0,x.jsx)(`div`,{className:wS.tooltipOutcome,style:{"--outcome-color":r},children:n})]})}function kS({turns:e,actorIndex:t}){let n=Pe(t),r={"--side-color":n},i=(0,b.useRef)(null),a=(0,b.useRef)(!0);return(0,b.useEffect)(()=>{if(!a.current)return;let e=i.current;e&&e.scrollTo({top:e.scrollHeight,behavior:`smooth`})},[e.length]),(0,x.jsx)(`div`,{ref:i,onScroll:()=>{let e=i.current;e&&(a.current=e.scrollHeight-e.scrollTop-e.clientHeight<40)},className:wS.side,children:e.map(e=>(0,x.jsx)(Sx,{dot:!0,content:(0,x.jsx)(OS,{t:e,sideColor:n}),children:(0,x.jsxs)(`div`,{className:[wS.entry,e.current?wS.current:``].filter(Boolean).join(` `),style:r,children:[(0,x.jsxs)(`div`,{className:wS.entryHead,children:[(0,x.jsxs)(`span`,{className:wS.entryTurn,style:r,children:[`T`,e.turn,` `,e.time]}),(0,x.jsx)(`span`,{className:wS.entryTitle,children:e.title}),e.category&&(0,x.jsx)(`span`,{className:wS.entryCategory,children:e.category}),e.emergent&&(0,x.jsx)(`span`,{className:wS.entryEmergent,children:`EMERGENT`}),DS(e.outcome)]}),e.summary&&(0,x.jsx)(`div`,{className:wS.entrySummary,children:e.summary}),e.subEvents&&e.subEvents.length>1&&(0,x.jsx)(`div`,{className:wS.entrySubEvents,children:e.subEvents.map((e,t)=>(0,x.jsxs)(`div`,{className:wS.entrySubEventRow,children:[(0,x.jsxs)(`span`,{className:wS.entrySubIdx,children:[e.index+1,`.`]}),(0,x.jsx)(`span`,{children:e.title})]},t))}),e.decision&&!e.subEvents?.length&&(0,x.jsx)(`div`,{className:wS.entryDecision,children:e.decision})]})},e.turn))})}function AS({state:e}){let t=e.actorIds.map((t,n)=>{let r=e.actors[t];return{id:t,idx:n,turns:r?TS(r,e.isComplete):[],name:r?.leader?.name??t,archetype:r?.leader?.archetype}});return t.every(e=>e.turns.length===0)?null:(0,x.jsx)(`div`,{className:`timeline-row ${wS.timelineRow}`,role:`region`,"aria-label":`Turn timeline`,children:t.map(e=>{let t=Pe(e.idx);return(0,x.jsxs)(`div`,{className:wS.sideWrap,style:{"--side-color":t},children:[(0,x.jsxs)(`header`,{className:wS.sideHeader,children:[(0,x.jsxs)(`span`,{className:wS.sideHeaderIdx,children:[`A`,e.idx+1]}),(0,x.jsx)(`span`,{className:wS.sideHeaderName,title:e.name,children:e.name}),e.archetype&&(0,x.jsx)(`span`,{className:wS.sideHeaderArchetype,title:e.archetype,children:e.archetype})]}),(0,x.jsx)(kS,{turns:e.turns,actorIndex:e.idx})]},e.id)})})}var jS={risky_success:{bg:`rgba(232,180,74,.12)`,color:`var(--vis)`,border:`var(--amber-dim)`,label:`RISKY WIN`},risky_failure:{bg:`rgba(224,101,48,.12)`,color:`var(--rust)`,border:`var(--rust-dim)`,label:`RISKY LOSS`},conservative_success:{bg:`rgba(106,173,72,.12)`,color:`var(--green)`,border:`rgba(106,173,72,.25)`,label:`SAFE WIN`},conservative_failure:{bg:`rgba(224,101,48,.08)`,color:`var(--rust)`,border:`var(--rust-dim)`,label:`SAFE LOSS`}};function MS({outcome:e}){let t=jS[e]||{bg:`var(--bg-card)`,color:`var(--text-3)`,border:`var(--border)`,label:e.replace(/_/g,` `).toUpperCase()};return(0,x.jsx)(`span`,{style:{padding:`3px 10px`,borderRadius:`4px`,fontSize:`var(--font-xs)`,fontWeight:800,fontFamily:`var(--mono)`,display:`inline-block`,whiteSpace:`nowrap`,background:t.bg,color:t.color,border:`1px solid ${t.border}`},children:t.label})}var NS={row:`_row_1v4rw_1`,inline:`_inline_1v4rw_11`,label:`_label_1v4rw_17`,pill:`_pill_1v4rw_27`,popoverWrap:`_popoverWrap_1v4rw_41`,popoverHeader:`_popoverHeader_1v4rw_45`,popoverText:`_popoverText_1v4rw_54`,popoverUrlRow:`_popoverUrlRow_1v4rw_61`,popoverUrl:`_popoverUrl_1v4rw_61`,popoverDoi:`_popoverDoi_1v4rw_72`,popoverProvenance:`_popoverProvenance_1v4rw_78`,popoverHint:`_popoverHint_1v4rw_87`};function PS({citations:e,label:t=`sources`,inline:n=!1}){let r=h_();if(!e||e.length===0)return null;let i=new Set,a=[];for(let t of e){let e=(t.url||``).trim(),n=(t.text||``).trim();if(!e&&!n||!e&&n===`Seed document`)continue;let o=e||n,s=r.getNumber(o);if(s===0||i.has(s))continue;i.add(s);let c=r.getEntry(o);a.push({n:s,entry:c??{text:n||e,url:e,doi:t.doi}})}return a.length===0?null:(0,x.jsxs)(`div`,{className:[NS.row,n?NS.inline:``].filter(Boolean).join(` `),children:[t&&(0,x.jsx)(`span`,{className:NS.label,children:t}),a.map(({n:e,entry:t})=>(0,x.jsx)(FS,{n:e,entry:t},e))]})}function FS({n:e,entry:t}){let n=t.url||``,r=t.text||n||`Source [${e}]`,i=t.doi,a=t.departments?[...t.departments]:[],o=t.actorNames?[...t.actorNames]:[],s=(0,x.jsxs)(`div`,{className:NS.popoverWrap,children:[(0,x.jsxs)(`div`,{className:NS.popoverHeader,children:[`REFERENCE [`,e,`]`]}),(0,x.jsx)(`div`,{className:NS.popoverText,children:r}),n&&(0,x.jsx)(`div`,{className:NS.popoverUrlRow,children:(0,x.jsx)(`a`,{href:n,target:`_blank`,rel:`noopener noreferrer`,className:NS.popoverUrl,children:n})}),i&&(0,x.jsxs)(`div`,{className:NS.popoverDoi,children:[`DOI:`,i]}),(a.length>0||o.length>0)&&(0,x.jsxs)(`div`,{className:NS.popoverProvenance,children:[a.length>0&&(0,x.jsxs)(x.Fragment,{children:[`cited by `,a.join(`, `),` · `]}),o.length>0&&(0,x.jsxs)(x.Fragment,{children:[`leader `,o.join(` · `)]})]}),(0,x.jsx)(`div`,{className:NS.popoverHint,children:`Click to open source · or scroll to References below`})]});return(0,x.jsx)(Sx,{content:s,children:(0,x.jsxs)(`a`,{href:n||`#cite-${e}`,target:n?`_blank`:void 0,rel:n?`noopener noreferrer`:void 0,onClick:t=>{let r=document.getElementById(`cite-${e}`);r&&(n||t.preventDefault(),r.scrollIntoView({behavior:`smooth`,block:`center`}),r.style.transition=`background 0.4s`,r.style.background=`rgba(232,180,74,0.18)`,setTimeout(()=>{r.style.background=``},1200))},className:NS.pill,children:[`[`,e,`]`]})})}var J={eventStartRow:`_eventStartRow_1d0sd_1`,notFirst:`_notFirst_1d0sd_9`,eventNumber:`_eventNumber_1d0sd_14`,eventStartTitle:`_eventStartTitle_1d0sd_21`,eventCategoryPill:`_eventCategoryPill_1d0sd_26`,promotionTooltipTitle:`_promotionTooltipTitle_1d0sd_35`,promotionTooltipRow:`_promotionTooltipRow_1d0sd_42`,promotionTooltipKey:`_promotionTooltipKey_1d0sd_46`,promotionTooltipValue:`_promotionTooltipValue_1d0sd_50`,promotionTooltipReason:`_promotionTooltipReason_1d0sd_55`,promotionRow:`_promotionRow_1d0sd_60`,promotionArrow:`_promotionArrow_1d0sd_70`,promotionRole:`_promotionRole_1d0sd_75`,promotionReason:`_promotionReason_1d0sd_81`,forgeBtn:`_forgeBtn_1d0sd_90`,forgeSlide:`_forgeSlide_1d0sd_1`,forgeRow:`_forgeRow_1d0sd_110`,forgeBadge:`_forgeBadge_1d0sd_117`,forgeDept:`_forgeDept_1d0sd_130`,forgeDescription:`_forgeDescription_1d0sd_136`,forgeName:`_forgeName_1d0sd_141`,forgeVerdictPass:`_forgeVerdictPass_1d0sd_147`,forgeVerdictFail:`_forgeVerdictFail_1d0sd_159`,forgeFieldsRow:`_forgeFieldsRow_1d0sd_171`,fieldsLabelIn:`_fieldsLabelIn_1d0sd_181`,fieldsLabelOut:`_fieldsLabelOut_1d0sd_185`,forgeError:`_forgeError_1d0sd_189`,specWrap:`_specWrap_1d0sd_196`,specCard:`_specCard_1d0sd_200`,specHeader:`_specHeader_1d0sd_209`,specHeaderDept:`_specHeaderDept_1d0sd_217`,specToolCount:`_specToolCount_1d0sd_225`,severityBadge:`_severityBadge_1d0sd_231`,specSummary:`_specSummary_1d0sd_241`,specSummaryEmpty:`_specSummaryEmpty_1d0sd_248`,specRisks:`_specRisks_1d0sd_256`,specRisksLabel:`_specRisksLabel_1d0sd_260`,specRiskRow:`_specRiskRow_1d0sd_269`,specRiskSeverity:`_specRiskSeverity_1d0sd_278`,specRecs:`_specRecs_1d0sd_287`,specRecsLabel:`_specRecsLabel_1d0sd_291`,specRecRow:`_specRecRow_1d0sd_300`,toolDetail:`_toolDetail_1d0sd_309`,newTool:`_newTool_1d0sd_320`,forgeGlow:`_forgeGlow_1d0sd_1`,reused:`_reused_1d0sd_324`,toolSummary:`_toolSummary_1d0sd_328`,toolSummaryMain:`_toolSummaryMain_1d0sd_336`,toolSummaryHead:`_toolSummaryHead_1d0sd_341`,toolNewBadge:`_toolNewBadge_1d0sd_348`,toolReusedBadge:`_toolReusedBadge_1d0sd_361`,toolFirstForged:`_toolFirstForged_1d0sd_374`,toolSchemaBadge:`_toolSchemaBadge_1d0sd_380`,toolDescription:`_toolDescription_1d0sd_390`,toolNameLine:`_toolNameLine_1d0sd_397`,toolPassPill:`_toolPassPill_1d0sd_405`,toolFailPill:`_toolFailPill_1d0sd_418`,toolInspectBtn:`_toolInspectBtn_1d0sd_431`,toolBody:`_toolBody_1d0sd_449`,toolMetaRow:`_toolMetaRow_1d0sd_454`,toolMetaLabel:`_toolMetaLabel_1d0sd_459`,toolRawSummary:`_toolRawSummary_1d0sd_466`,toolRawPre:`_toolRawPre_1d0sd_474`,toolEmpty:`_toolEmpty_1d0sd_489`,outcomeCard:`_outcomeCard_1d0sd_494`,decisionPulse:`_decisionPulse_1d0sd_1`,outcomeHead:`_outcomeHead_1d0sd_505`,outcomeLabel:`_outcomeLabel_1d0sd_512`,outcomeMeta:`_outcomeMeta_1d0sd_520`,outcomeText:`_outcomeText_1d0sd_527`,outcomeDeltas:`_outcomeDeltas_1d0sd_533`,outcomeDeltaSpan:`_outcomeDeltaSpan_1d0sd_540`,outcomeBar:`_outcomeBar_1d0sd_544`,outcomeBarDeparts:`_outcomeBarDeparts_1d0sd_552`,outcomeReasoningSummary:`_outcomeReasoningSummary_1d0sd_556`,outcomeReasoningBody:`_outcomeReasoningBody_1d0sd_563`,outcomeReasoningPre:`_outcomeReasoningPre_1d0sd_570`,outcomeRationale:`_outcomeRationale_1d0sd_582`,outcomePolicyLine:`_outcomePolicyLine_1d0sd_587`,driftRow:`_driftRow_1d0sd_591`,driftLabel:`_driftLabel_1d0sd_599`,driftName:`_driftName_1d0sd_607`,reactionsCard:`_reactionsCard_1d0sd_611`,reactionsHead:`_reactionsHead_1d0sd_620`,reactionsLabel:`_reactionsLabel_1d0sd_627`,reactionsBar:`_reactionsBar_1d0sd_636`,reactionsBarSegment:`_reactionsBarSegment_1d0sd_645`,reactionsLegend:`_reactionsLegend_1d0sd_650`,reactionsLegendItem:`_reactionsLegendItem_1d0sd_657`,reactionsLegendSwatch:`_reactionsLegendSwatch_1d0sd_663`,reactionsQuotesSummary:`_reactionsQuotesSummary_1d0sd_671`,reactionsQuotesList:`_reactionsQuotesList_1d0sd_679`,reactionTooltipName:`_reactionTooltipName_1d0sd_686`,reactionTooltipMeta:`_reactionTooltipMeta_1d0sd_692`,reactionTooltipHexaco:`_reactionTooltipHexaco_1d0sd_697`,reactionTooltipHealth:`_reactionTooltipHealth_1d0sd_704`,reactionTooltipQuote:`_reactionTooltipQuote_1d0sd_709`,reactionTooltipMoodLine:`_reactionTooltipMoodLine_1d0sd_717`,reactionTooltipBeliefs:`_reactionTooltipBeliefs_1d0sd_724`,reactionRow:`_reactionRow_1d0sd_730`,notLast:`_notLast_1d0sd_739`,reactionRowName:`_reactionRowName_1d0sd_743`,reactionRowQuote:`_reactionRowQuote_1d0sd_750`,reactionRowMoodPill:`_reactionRowMoodPill_1d0sd_761`,bulletinWrap:`_bulletinWrap_1d0sd_773`,bulletinTooltipName:`_bulletinTooltipName_1d0sd_777`,bulletinTooltipRole:`_bulletinTooltipRole_1d0sd_781`,bulletinTooltipBody:`_bulletinTooltipBody_1d0sd_786`,bulletinTooltipMood:`_bulletinTooltipMood_1d0sd_792`,bulletinRow:`_bulletinRow_1d0sd_798`,bulletinName:`_bulletinName_1d0sd_807`,bulletinPost:`_bulletinPost_1d0sd_813`,bulletinLikes:`_bulletinLikes_1d0sd_822`,turnDone:`_turnDone_1d0sd_828`,fallbackBox:`_fallbackBox_1d0sd_841`,fallbackTitle:`_fallbackTitle_1d0sd_853`,fallbackSite:`_fallbackSite_1d0sd_859`,fallbackPreviewWrap:`_fallbackPreviewWrap_1d0sd_864`,fallbackPreviewSummary:`_fallbackPreviewSummary_1d0sd_868`,fallbackPreviewPre:`_fallbackPreviewPre_1d0sd_874`,schemaBlock:`_schemaBlock_1d0sd_885`,schemaFieldsLabel:`_schemaFieldsLabel_1d0sd_889`,schemaFieldsList:`_schemaFieldsList_1d0sd_897`,schemaTitle:`_schemaTitle_1d0sd_902`,schemaTable:`_schemaTable_1d0sd_911`,schemaRow:`_schemaRow_1d0sd_919`,schemaKeyCell:`_schemaKeyCell_1d0sd_923`,schemaRequired:`_schemaRequired_1d0sd_931`,schemaTypeCell:`_schemaTypeCell_1d0sd_936`,schemaDescCell:`_schemaDescCell_1d0sd_943`,forgeDetails:`_forgeDetails_1d0sd_951`,forgeSummary:`_forgeSummary_1d0sd_963`,forgeInspectAbs:`_forgeInspectAbs_1d0sd_980`,forgeBody:`_forgeBody_1d0sd_998`,specDetails:`_specDetails_1d0sd_1003`,specSummaryRow:`_specSummaryRow_1d0sd_1012`,specBody:`_specBody_1d0sd_1029`,reactionsDetails:`_reactionsDetails_1d0sd_1035`,reactionsSummary:`_reactionsSummary_1d0sd_1043`,reactionsTopMood:`_reactionsTopMood_1d0sd_1060`,reactionsBody:`_reactionsBody_1d0sd_1068`,bulletinDetails:`_bulletinDetails_1d0sd_1073`,bulletinSummary:`_bulletinSummary_1d0sd_1077`,bulletinSummaryLabel:`_bulletinSummaryLabel_1d0sd_1095`,bulletinSummaryNames:`_bulletinSummaryNames_1d0sd_1105`,bulletinBody:`_bulletinBody_1d0sd_1115`,fallbackDetails:`_fallbackDetails_1d0sd_1119`,fallbackSummary:`_fallbackSummary_1d0sd_1130`},IS={positive:`var(--green)`,negative:`var(--rust)`,anxious:`var(--amber)`,defiant:`var(--rust)`,hopeful:`var(--green)`,resigned:`var(--text-3)`,neutral:`var(--text-2)`},LS={positive:`#6aad48`,negative:`#e06530`,anxious:`#e8b44a`,defiant:`#e06530`,hopeful:`#6aad48`,resigned:`#a89878`,neutral:`#a89878`};function RS({event:e,actorIndex:t,actorSlot:n}){let r=Xk(),i=ev(),a=n??t,o=Pe(t),s={"--side-color":o},c=e.data;switch(e.type){case`turn_start`:return null;case`event_start`:{let e=Number(c.eventIndex??0),t=Number(c.totalEvents??1),n=String(c.title||``),r=String(c.category||``);return t<=1?null:(0,x.jsxs)(`div`,{id:`sim-event-${a}-${Number(c.turn??0)}-${e}`,tabIndex:-1,className:[J.eventStartRow,e>0?J.notFirst:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`span`,{className:J.eventNumber,children:[`EVENT `,e+1,`/`,t]}),(0,x.jsx)(`span`,{className:J.eventStartTitle,children:n}),r&&(0,x.jsx)(`span`,{className:J.eventCategoryPill,children:r})]})}case`promotion`:{let e=String(c.reason||``),t=String(c.name||``),n=String(c.role||``);return(0,x.jsx)(Sx,{content:(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`b`,{className:J.promotionTooltipTitle,style:s,children:[`Promotion: `,n]}),t&&(0,x.jsxs)(`div`,{className:J.promotionTooltipRow,children:[(0,x.jsx)(`span`,{className:J.promotionTooltipKey,children:`Agent:`}),` `,(0,x.jsx)(`span`,{className:J.promotionTooltipValue,children:t})]}),e&&(0,x.jsx)(`div`,{className:J.promotionTooltipReason,children:e})]}),children:(0,x.jsxs)(`div`,{className:J.promotionRow,children:[(0,x.jsx)(`span`,{className:J.promotionArrow,children:`→`}),(0,x.jsx)(`span`,{className:J.promotionRole,style:s,children:n}),(0,x.jsx)(`span`,{className:J.promotionReason,children:e})]})})}case`specialist_start`:case`decision_pending`:return null;case`forge_attempt`:{let e=String(c.department||``),t=String(c.name||`unnamed`),n=String(c.description||t),r=String(c.mode||`sandbox`),s=c.approved!==!1,l=typeof c.confidence==`number`?c.confidence:.85,u=c.errorReason?String(c.errorReason):``,d=s?o:`var(--rust)`,f=Array.isArray(c.inputFields)?c.inputFields:[],p=Array.isArray(c.outputFields)?c.outputFields:[],m={"--accent":d,"--bg-tint":s?`color-mix(in srgb, ${o} 7%, transparent)`:`rgba(224,101,48,0.04)`,"--border-tint":s?`color-mix(in srgb, ${o} 25%, transparent)`:`rgba(224,101,48,0.2)`,"--shadow-tint":s?`0 0 0 1px color-mix(in srgb, ${o} 10%, transparent)`:`var(--card-shadow)`,"--badge-color":s?`var(--bg-deep)`:`#fff`,"--badge-bg":d,"--badge-shadow":s?`0 0 8px rgba(232,180,74,0.4)`:`none`};return(0,x.jsx)(x.Fragment,{children:(0,x.jsxs)(`details`,{className:J.forgeDetails,style:m,children:[(0,x.jsx)(`summary`,{className:J.forgeSummary,children:(0,x.jsxs)(`span`,{className:J.forgeRow,children:[(0,x.jsx)(`span`,{className:J.forgeBadge,children:s?`✦ FORGED TOOL`:`↻ FORGE RETRY`}),(0,x.jsx)(`span`,{className:J.forgeDept,children:e}),(0,x.jsx)(`span`,{className:J.forgeDescription,children:n}),(0,x.jsxs)(`span`,{className:J.forgeName,children:[t,` (`,r,`)`]}),(0,x.jsx)(`span`,{className:s?J.forgeVerdictPass:J.forgeVerdictFail,children:s?`PASS ${l.toFixed(2)}`:`RETRY`})]})}),(0,x.jsx)(`button`,{type:`button`,onClick:e=>i.openTrace({actorIndex:a,toolName:t},e.currentTarget,`inspect`),"aria-label":`Inspect forged tool ${t}`,className:J.forgeInspectAbs,children:`INSPECT`}),(0,x.jsxs)(`div`,{className:J.forgeBody,children:[(f.length>0||p.length>0)&&(0,x.jsxs)(`div`,{className:J.forgeFieldsRow,children:[f.length>0&&(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`span`,{className:J.fieldsLabelIn,children:`in:`}),` `,f.join(`, `)]}),p.length>0&&(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`span`,{className:J.fieldsLabelOut,children:`out:`}),` `,p.join(`, `)]})]}),!s&&u&&(0,x.jsx)(`div`,{className:J.forgeError,children:u})]})]})})}case`specialist_done`:{let e=String(c.department||``),t=c._filteredTools||[],n=t.filter(e=>e?.isNew!==!0),s=Array.isArray(c.risks)?c.risks:[],l=Array.isArray(c.recommendedActions)?c.recommendedActions.map(String):[],u=s.some(e=>e.severity===`critical`)?`critical`:s.some(e=>e.severity===`high`)?`high`:``,d=String(c.summary||``),f=Number(c.citations)||0;if(!d&&s.length===0&&l.length===0&&t.length===0&&f===0)return null;let p={"--card-bg":u===`critical`?`rgba(224,101,48,.08)`:u===`high`?`rgba(232,180,74,.06)`:`var(--bg-card)`,"--card-border":u===`critical`?`rgba(224,101,48,.25)`:u===`high`?`rgba(232,180,74,.2)`:`var(--border)`,"--card-accent":u===`critical`?`var(--rust)`:u===`high`?`var(--amber)`:`var(--teal)`},m=u?{"--sev-color":u===`critical`?`var(--rust)`:`var(--amber)`,"--sev-bg":u===`critical`?`rgba(224,101,48,.15)`:`rgba(232,180,74,.1)`}:void 0;return(0,x.jsx)(x.Fragment,{children:(0,x.jsxs)(`div`,{className:J.specWrap,children:[(0,x.jsxs)(`details`,{className:J.specDetails,style:p,children:[(0,x.jsxs)(`summary`,{className:J.specSummaryRow,children:[(0,x.jsxs)(`span`,{className:J.specHeaderDept,children:[r.ui.departmentIcons[e]||``,` `,e]}),t.length>0&&(0,x.jsxs)(`span`,{className:J.specToolCount,children:[`+`,t.length,` tool`,t.length===1?``:`s`,n.length<t.length&&` (${n.length} reused)`]}),u&&(0,x.jsxs)(`span`,{className:J.severityBadge,style:m,children:[u.toUpperCase(),` RISK`]}),(0,x.jsx)(PS,{citations:c.citationList||[],inline:!0,label:``})]}),(0,x.jsxs)(`div`,{className:J.specBody,children:[d?(0,x.jsx)(`div`,{className:J.specSummary,children:d}):s.length===0&&l.length===0&&(f>0||t.length>0)?(0,x.jsxs)(`div`,{className:J.specSummaryEmpty,children:[`Department analysis complete — no narrative summary returned, but`,f>0&&` ${f} source${f===1?``:`s`} surveyed`,f>0&&t.length>0&&` and `,t.length>0&&` ${t.length} tool${t.length===1?``:`s`} forged`,`.`]}):null,s.length>0&&(0,x.jsxs)(`div`,{className:J.specRisks,children:[(0,x.jsx)(`div`,{className:J.specRisksLabel,children:`RISKS`}),s.slice(0,3).map((e,t)=>(0,x.jsxs)(`div`,{className:J.specRiskRow,children:[(0,x.jsx)(`span`,{className:J.specRiskSeverity,style:{"--risk-color":e.severity===`critical`||e.severity===`high`?`var(--rust)`:`var(--amber)`},children:String(e.severity||`med`).toUpperCase()}),(0,x.jsx)(`span`,{children:String(e.description||``)})]},t))]}),l.length>0&&(0,x.jsxs)(`div`,{className:J.specRecs,children:[(0,x.jsx)(`div`,{className:J.specRecsLabel,children:`RECOMMENDATIONS`}),l.slice(0,3).map((e,t)=>(0,x.jsx)(`div`,{className:J.specRecRow,children:e},t))]})]})]}),n.map((e,t)=>{let n=e.approved!==!1,r=e.isNew===!0,s=n?r?o:`var(--green)`:`var(--rust)`,c=n?r?`color-mix(in srgb, ${o} 10%, transparent)`:`rgba(106,173,72,.06)`:`rgba(224,101,48,.04)`,l=n?r?`color-mix(in srgb, ${o} 40%, transparent)`:`rgba(106,173,72,.2)`:`rgba(224,101,48,.15)`,u=r?`0 0 0 1px color-mix(in srgb, ${o} 15%, transparent), var(--card-shadow)`:`var(--card-shadow)`,d=e.inputSchema,f=e.outputSchema,p=!!d||!!f,m={"--tool-bg":c,"--tool-border":l,"--tool-accent":s,"--tool-shadow":u,"--side-color":o},h=[J.toolDetail,r?J.newTool:J.reused].join(` `);return(0,x.jsxs)(`details`,{className:h,style:m,children:[(0,x.jsxs)(`summary`,{className:J.toolSummary,children:[(0,x.jsxs)(`div`,{className:J.toolSummaryMain,children:[(0,x.jsxs)(`div`,{className:J.toolSummaryHead,children:[r?(0,x.jsx)(`span`,{className:J.toolNewBadge,children:`FORGED TOOL`}):(0,x.jsx)(`span`,{className:J.toolReusedBadge,children:`REUSED`}),!r&&e.firstForgedTurn!=null&&(0,x.jsxs)(`span`,{className:J.toolFirstForged,children:[`first forged T`,e.firstForgedTurn,e.firstForgedDepartment&&e.firstForgedDepartment!==e.department?` · ${e.firstForgedDepartment}`:``]}),p&&(0,x.jsx)(`span`,{className:J.toolSchemaBadge,children:`SCHEMA`})]}),(0,x.jsx)(`span`,{className:J.toolDescription,children:String(e.description||e.name||``)}),(0,x.jsxs)(`span`,{className:J.toolNameLine,children:[e.name,` `,e.mode?`(${e.mode})`:``]})]}),(0,x.jsx)(`span`,{className:n?J.toolPassPill:J.toolFailPill,children:n?`PASS ${(typeof e.confidence==`number`?e.confidence:.85).toFixed(2)}`:`RETRY`})]}),(0,x.jsx)(`button`,{type:`button`,onClick:t=>{t.preventDefault(),t.stopPropagation(),i.openTrace({actorIndex:a,toolName:String(e.name||``)},t.currentTarget,`inspect`)},"aria-label":`Inspect tool ${e.name||``}`,className:J.toolInspectBtn,children:`INSPECT`}),(0,x.jsxs)(`div`,{className:J.toolBody,children:[e.crisis&&(0,x.jsxs)(`div`,{className:J.toolMetaRow,children:[(0,x.jsx)(`span`,{className:J.toolMetaLabel,children:`CRISIS: `}),String(e.crisis)]}),e.department&&(0,x.jsxs)(`div`,{className:J.toolMetaRow,children:[(0,x.jsx)(`span`,{className:J.toolMetaLabel,children:`DEPT: `}),String(e.department)]}),(d||Array.isArray(e.inputFields)&&e.inputFields.length>0)&&(0,x.jsx)(BS,{label:`INPUT`,color:`var(--teal)`,schema:d,fields:e.inputFields}),(f||Array.isArray(e.outputFields)&&e.outputFields.length>0)&&(0,x.jsx)(BS,{label:`OUTPUT`,color:`var(--green)`,schema:f,fields:e.outputFields}),e.output&&(0,x.jsxs)(`details`,{children:[(0,x.jsx)(`summary`,{className:J.toolRawSummary,style:{"--side-color":o},children:`Raw Output`}),(0,x.jsx)(`pre`,{className:J.toolRawPre,children:typeof e.output==`object`?JSON.stringify(e.output,null,2):String(e.output)})]}),!e.output&&!d&&!f&&(!e.inputFields||e.inputFields.length===0)&&(0,x.jsx)(`div`,{className:J.toolEmpty,children:`Tool forged but no output captured. The tool will be available for subsequent turns.`})]})]},t)})]})})}case`outcome`:{let e=String(c.outcome||``),n=String(c._decision||``),r=String(c._rationale||``),i=String(c._reasoning||``),a=c._policies||[],s=c._barCheck,l={...c.systemDeltas,...c.politicsDeltas},u=String(c.turn||``),d=Number(c._toolCount??0),f=Number(c._citeCount??0),p={"--side-color":o,"--outcome-bg":t===0?`rgba(232,180,74,.06)`:`rgba(76,168,168,.06)`,"--outcome-border":t===0?`var(--amber-dim)`:`var(--teal-dim)`};return(0,x.jsxs)(`div`,{className:J.outcomeCard,style:p,children:[(0,x.jsxs)(`div`,{className:J.outcomeHead,children:[(0,x.jsxs)(`span`,{children:[(0,x.jsxs)(`span`,{className:J.outcomeLabel,children:[`DECISION #`,u]}),(0,x.jsxs)(`span`,{className:J.outcomeMeta,children:[d,` tools · `,f,` citations`]})]}),(0,x.jsx)(MS,{outcome:e})]}),(0,x.jsx)(`div`,{className:J.outcomeText,children:n}),s&&(0,x.jsx)(`div`,{className:s.departs?`${J.outcomeBar} ${J.outcomeBarDeparts}`:J.outcomeBar,children:zS(s)}),Object.keys(l).length>0&&(0,x.jsx)(`div`,{className:J.outcomeDeltas,children:Object.entries(l).map(([e,t])=>(0,x.jsxs)(`span`,{className:J.outcomeDeltaSpan,children:[e,` `,t>0?`+`:``,typeof t==`number`?Number.isInteger(t)?t:t.toFixed(2):t,` · `]},e))}),(r||i||a.length>0)&&(0,x.jsxs)(`details`,{children:[(0,x.jsx)(`summary`,{className:J.outcomeReasoningSummary,children:`Full reasoning & policies`}),(0,x.jsxs)(`div`,{className:J.outcomeReasoningBody,children:[i&&(0,x.jsx)(`div`,{className:J.outcomeReasoningPre,children:i}),n&&(0,x.jsx)(`div`,{children:n}),r&&(0,x.jsx)(`div`,{className:J.outcomeRationale,children:r}),a.map((e,t)=>(0,x.jsxs)(`div`,{className:J.outcomePolicyLine,children:[`→ `,e]},t))]})]})]})}case`personality_drift`:{let e=Object.values(c.agents||{});return e.length?(0,x.jsxs)(`div`,{className:J.driftRow,children:[(0,x.jsx)(`span`,{className:J.driftLabel,children:`DRIFT `}),e.slice(0,3).map((t,n)=>(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`span`,{className:J.driftName,style:s,children:t.name?.split(` `)[0]}),` `,`O`,t.hexaco?.O??`?`,` C`,t.hexaco?.C??`?`,n<Math.min(e.length,3)-1?` · `:``]},n))]}):null}case`agent_reactions`:{let e=c.reactions||[],t=c.totalReactions||e.length;if(!e.length)return null;let n={};for(let t of e)n[t.mood]=(n[t.mood]||0)+1;let r=Object.entries(n).sort((e,t)=>t[1]-e[1]).map(([t,n])=>({mood:t,count:n,pct:Math.round(n/e.length*100),bg:LS[t]||`#a89878`}));return(0,x.jsxs)(`details`,{className:J.reactionsDetails,children:[(0,x.jsxs)(`summary`,{className:J.reactionsSummary,children:[(0,x.jsxs)(`span`,{className:J.reactionsLabel,style:s,children:[t,` VOICES`]}),(0,x.jsx)(`div`,{className:J.reactionsBar,children:r.map(e=>(0,x.jsx)(`div`,{className:J.reactionsBarSegment,style:{"--seg-flex":String(e.pct),"--seg-bg":e.bg},title:`${e.pct}% ${e.mood}`},e.mood))}),(0,x.jsx)(`span`,{className:J.reactionsTopMood,children:r[0]?`${r[0].pct}% ${r[0].mood}`:``})]}),(0,x.jsxs)(`div`,{className:J.reactionsBody,children:[(0,x.jsx)(`div`,{className:J.reactionsLegend,children:r.slice(0,3).map(e=>(0,x.jsxs)(`span`,{className:J.reactionsLegendItem,children:[(0,x.jsx)(`span`,{className:J.reactionsLegendSwatch,style:{"--swatch-bg":e.bg}}),e.pct,`% `,e.mood]},e.mood))}),(0,x.jsxs)(`details`,{children:[(0,x.jsxs)(`summary`,{className:J.reactionsQuotesSummary,style:s,children:[`quotes (`,e.length,`)`]}),(0,x.jsx)(`div`,{className:J.reactionsQuotesList,children:e.slice(0,4).map((t,n)=>(0,x.jsx)(Sx,{dot:!0,content:(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`b`,{className:J.reactionTooltipName,style:s,children:t.name}),(0,x.jsxs)(`div`,{className:J.reactionTooltipMeta,children:[t.role,` in `,t.department,` `,t.age?`· Age ${t.age}`:``]}),(0,x.jsxs)(`div`,{className:J.reactionTooltipHexaco,children:[`O:`,t.hexaco?.O,` C:`,t.hexaco?.C,` E:`,t.hexaco?.E,` A:`,t.hexaco?.A,` Em:`,t.hexaco?.Em,` HH:`,t.hexaco?.HH]}),(0,x.jsxs)(`div`,{className:J.reactionTooltipHealth,children:[`Bone: `,t.boneDensity,`% · Radiation: `,t.radiation,`mSv · Psych: `,t.psychScore]}),(0,x.jsxs)(`div`,{className:J.reactionTooltipQuote,children:[`“`,t.quote,`”`]}),(0,x.jsxs)(`div`,{className:J.reactionTooltipMoodLine,style:{"--mood-color":IS[t.mood]||`var(--text-3)`},children:[String(t.mood||``).toUpperCase(),` · intensity `,t.intensity?.toFixed?.(2)||`?`]}),t.memory?.beliefs?.length>0&&(0,x.jsxs)(`div`,{className:J.reactionTooltipBeliefs,children:[`Beliefs: `,t.memory.beliefs.slice(0,2).join(`; `)]})]}),children:(0,x.jsxs)(`div`,{className:[J.reactionRow,n<Math.min(e.length,4)-1?J.notLast:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`span`,{className:J.reactionRowName,style:s,children:t.name}),(0,x.jsxs)(`span`,{className:J.reactionRowQuote,children:[`“`,String(t.quote||``),`”`]}),(0,x.jsx)(`span`,{className:J.reactionRowMoodPill,style:{"--mood-color":IS[t.mood]||`var(--text-3)`},children:String(t.mood||``).toUpperCase()})]})},n))})]})]})]})}case`bulletin`:{let e=c.posts||[];return e.length?(0,x.jsxs)(`details`,{className:J.bulletinDetails,children:[(0,x.jsxs)(`summary`,{className:J.bulletinSummary,children:[(0,x.jsxs)(`span`,{className:J.bulletinSummaryLabel,children:[e.length,` POSTS`]}),(0,x.jsxs)(`span`,{className:J.bulletinSummaryNames,children:[e.slice(0,2).map(e=>String(e.name??``).split(` `)[0]).filter(Boolean).join(` · `),e.length>2?` +${e.length-2}`:``]})]}),(0,x.jsx)(`div`,{className:J.bulletinBody,children:e.slice(0,3).map((e,t)=>(0,x.jsx)(Sx,{dot:!0,content:(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`b`,{className:J.bulletinTooltipName,style:s,children:e.name}),` `,(0,x.jsxs)(`span`,{className:J.bulletinTooltipRole,children:[e.role,` `,e.department]}),(0,x.jsx)(`div`,{className:J.bulletinTooltipBody,children:e.post}),(0,x.jsxs)(`div`,{className:J.bulletinTooltipMood,style:{"--mood-color":IS[e.mood]||`var(--text-3)`},children:[String(e.mood||``).toUpperCase(),` · `,e.likes||0,` likes · `,e.replies||0,` replies`]})]}),children:(0,x.jsxs)(`div`,{className:J.bulletinRow,children:[(0,x.jsx)(`span`,{className:J.bulletinName,style:s,children:e.name}),(0,x.jsx)(`span`,{className:J.bulletinPost,children:String(e.post||``)}),(0,x.jsxs)(`span`,{className:J.bulletinLikes,children:[`♥`,e.likes||0]})]})},t))})]}):null}case`turn_done`:return null;case`validation_fallback`:{let e=String(c.schemaName||`<unknown>`),t=String(c.site||``),n=String(c.rawTextPreview||``),r=c.salvaged===!0,i=Array.isArray(c.droppedKeys)?c.droppedKeys.map(e=>String(e)):[];return(0,x.jsxs)(`details`,{className:J.fallbackDetails,style:s,children:[(0,x.jsxs)(`summary`,{className:J.fallbackSummary,children:[(0,x.jsxs)(`span`,{className:J.fallbackTitle,children:[`⚠ `,r?`SCHEMA SALVAGE`:`SCHEMA FALLBACK`,` — `,e]}),(0,x.jsxs)(`span`,{className:J.fallbackSite,children:[`site: `,t||`n/a`]}),r&&(0,x.jsxs)(`span`,{className:J.fallbackSite,children:[`kept without: `,i.length>0?i.join(`, `):`n/a`]})]}),n&&(0,x.jsxs)(`details`,{className:J.fallbackPreviewWrap,children:[(0,x.jsx)(`summary`,{className:J.fallbackPreviewSummary,children:`Raw output preview`}),(0,x.jsx)(`pre`,{className:J.fallbackPreviewPre,children:n})]})]})}default:return null}}function zS(e){let t=e.clearsBar?`clears it`:`is under it`,n=e.choseBold?`the bold option was taken`:`the bold option was refused`;if(!e.departs)return`Bar ${e.bar}: the bold option's chance ${e.boldChance} ${t}, so ${n}`;let r=e.departureFact?`, for: ${e.departureFact}`:`, with no fact named for it`;return`Bar ${e.bar}: the bold option's chance ${e.boldChance} ${t}, yet ${n}${r}`}function BS({label:e,color:t,schema:n,fields:r}){let i=n&&typeof n==`object`&&n.properties||null,a=n&&typeof n==`object`&&Array.isArray(n.required)?n.required:[];if(!i)return!r||r.length===0?null:(0,x.jsxs)(`div`,{className:J.schemaBlock,children:[(0,x.jsxs)(`span`,{className:J.schemaFieldsLabel,style:{"--field-color":t},children:[e,` FIELDS:`,` `]}),(0,x.jsx)(`span`,{className:J.schemaFieldsList,children:r.join(`, `)})]});let o=Object.entries(i).slice(0,12);return(0,x.jsxs)(`div`,{className:J.schemaBlock,children:[(0,x.jsxs)(`div`,{className:J.schemaTitle,style:{"--field-color":t},children:[e,` SCHEMA`]}),(0,x.jsx)(`table`,{className:J.schemaTable,children:(0,x.jsx)(`tbody`,{children:o.map(([e,n])=>{let r=String(n?.type??`any`),i=typeof n?.description==`string`?n.description:``,o=a.includes(e);return(0,x.jsxs)(`tr`,{className:J.schemaRow,children:[(0,x.jsxs)(`td`,{className:J.schemaKeyCell,children:[e,o&&(0,x.jsx)(`span`,{className:J.schemaRequired,children:`*`})]}),(0,x.jsx)(`td`,{className:J.schemaTypeCell,style:{"--field-color":t},children:r}),(0,x.jsx)(`td`,{className:J.schemaDescCell,children:i})]},e)})})})]})}var VS={badge:`_badge_1lgt8_1`,same:`_same_1lgt8_15`,differentOutcome:`_differentOutcome_1lgt8_21`,differentEvent:`_differentEvent_1lgt8_27`,pending:`_pending_1lgt8_33`,oneSided:`_oneSided_1lgt8_40`},HS={same:`✓ SAME`,"different-outcome":`⚠ DIFFERENT OUTCOME`,"different-event":`⚠ DIFFERENT EVENT`,pending:`… running`,"one-sided":`· · · waiting`},US={same:`Same event, same outcome`,"different-outcome":`Same event, different outcome`,"different-event":`Different events`,pending:`Turn is still running`,"one-sided":`Only one leader has reached this turn`},WS={same:VS.same,"different-outcome":VS.differentOutcome,"different-event":VS.differentEvent,pending:VS.pending,"one-sided":VS.oneSided};function GS({classification:e}){return(0,x.jsx)(`span`,{className:`${VS.badge} ${WS[e]}`,"aria-label":US[e],children:HS[e]})}var KS={row:`_row_rngwb_1`,differentOutcome:`_differentOutcome_rngwb_9`,differentEvent:`_differentEvent_rngwb_13`,header:`_header_rngwb_17`,headerTurn:`_headerTurn_rngwb_30`,headerTitle:`_headerTitle_rngwb_36`,headerTitleSplit:`_headerTitleSplit_rngwb_45`,headerTitleA:`_headerTitleA_rngwb_52`,headerTitleB:`_headerTitleB_rngwb_61`,cells:`_cells_rngwb_70`,cell:`_cell_rngwb_70`,cellBand:`_cellBand_rngwb_82`,cellEmpty:`_cellEmpty_rngwb_92`,cellPending:`_cellPending_rngwb_99`,cellPendingSpinner:`_cellPendingSpinner_rngwb_110`},qS=new Set([`turn_start`,`specialist_start`,`decision_pending`]);function JS(e){let t=new Set,n=!1;for(let r of e)if(r.type===`specialist_start`){let e=r.data?.department;typeof e==`string`&&e.length>0&&t.add(e)}else r.type===`decision_pending`&&(n=!0);let r=[];return t.size>0&&r.push(`${[...t].join(`, `)} analyzing`),n&&r.push(`awaiting decision`),r.length>0?r.join(` · `)+`…`:`Working on this turn…`}function YS({entry:e,eventsA:t,eventsB:n,runTerminal:r,runAborted:i}){let a=`${KS.row} ${e.classification===`different-outcome`?KS.differentOutcome:e.classification===`different-event`?KS.differentEvent:``}`,o=e.titleA===e.titleB&&e.titleA!==``;return(0,x.jsxs)(`section`,{id:`turn-row-${e.turn}`,className:a,"aria-labelledby":`turn-row-${e.turn}-h`,children:[(0,x.jsxs)(`h3`,{id:`turn-row-${e.turn}-h`,className:KS.header,tabIndex:-1,children:[(0,x.jsxs)(`span`,{className:KS.headerTurn,children:[`T`,e.turn]}),(0,x.jsx)(GS,{classification:e.classification}),o?(0,x.jsx)(`span`,{className:KS.headerTitle,children:e.titleA}):(0,x.jsxs)(`span`,{className:KS.headerTitleSplit,children:[(0,x.jsx)(`span`,{className:KS.headerTitleA,children:e.titleA||`—`}),(0,x.jsx)(`span`,{className:KS.headerTitleB,children:e.titleB||`—`})]})]}),(0,x.jsx)(`div`,{className:KS.cells,children:[t,n].map((t,n)=>{let a=t.filter(e=>!qS.has(e.type)),o=t.length>0&&a.length===0,s=t.length===0&&e.classification===`one-sided`&&!r;return(0,x.jsxs)(`div`,{className:KS.cell,style:{"--cell-color":Pe(n)},"aria-label":`Leader ${n===0?`A`:`B`} events for this turn`,children:[(0,x.jsx)(`span`,{className:KS.cellBand,"aria-hidden":`true`}),t.length===0?s?(0,x.jsxs)(`div`,{className:KS.cellPending,"aria-live":`polite`,title:`Parallel runs can drift turn-to-turn — events arrive whenever this side's LLM calls finish.`,children:[(0,x.jsx)(`span`,{className:`spinner ${KS.cellPendingSpinner}`,"aria-hidden":`true`}),`Catching up to turn `,e.turn,`…`]}):r?(0,x.jsx)(`div`,{className:KS.cellEmpty,title:i?`Run was interrupted before this side reached this turn.`:`No event recorded for this side on this turn.`,children:i?`Stopped before T${e.turn}`:`No event for T${e.turn}`}):(0,x.jsx)(`div`,{className:KS.cellEmpty,children:`(no events yet)`}):o?r?(0,x.jsx)(`div`,{className:KS.cellEmpty,title:i?`Run was interrupted while this turn was still processing.`:`No outcome recorded for this side on this turn.`,children:i?`Stopped during T${e.turn}`:`T${e.turn} ended without an outcome`}):(0,x.jsxs)(`div`,{className:KS.cellPending,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${KS.cellPendingSpinner}`}),JS(t)]}):a.map(e=>(0,x.jsx)(RS,{event:e,actorIndex:n},e.id))]},n)})})]})}function XS(e,t,n){let r=e.filter(e=>e.turn===n),i=t.filter(e=>e.turn===n);if(r.length===0&&i.length===0)return null;let a=[...r].reverse().find(e=>e.type===`event_start`),o=[...i].reverse().find(e=>e.type===`event_start`),s=String(a?.data?.title??``),c=String(o?.data?.title??``),l=String(r.find(e=>e.type===`outcome`)?.data?.outcome??``),u=String(i.find(e=>e.type===`outcome`)?.data?.outcome??``);return r.length===0||i.length===0?{turn:n,classification:`one-sided`,titleA:s,titleB:c,outcomeA:l,outcomeB:u}:!l||!u?{turn:n,classification:`pending`,titleA:s,titleB:c,outcomeA:l,outcomeB:u}:s===c?l===u?{turn:n,classification:`same`,titleA:s,titleB:c,outcomeA:l,outcomeB:u}:{turn:n,classification:`different-outcome`,titleA:s,titleB:c,outcomeA:l,outcomeB:u}:{turn:n,classification:`different-event`,titleA:s,titleB:c,outcomeA:l,outcomeB:u}}function ZS(e,t){let n=new Set;for(let t of e)typeof t.turn==`number`&&n.add(t.turn);for(let e of t)typeof e.turn==`number`&&n.add(e.turn);let r=[...n].sort((e,t)=>e-t),i=new Map;for(let n of r){let r=XS(e,t,n);r&&i.set(n,r)}return i}var QS={grid:`_grid_lwobn_1`,scroll:`_scroll_lwobn_10`,empty:`_empty_lwobn_16`};function $S({state:e}){let t=e.actorIds[0],n=e.actorIds[1],r=t?e.actors[t]:null,i=n?e.actors[n]:null,a=r?.events??[],o=i?.events??[],s=(0,b.useMemo)(()=>ZS(a,o),[a,o]),c=(0,b.useMemo)(()=>[...s.keys()],[s]),l=(0,b.useMemo)(()=>eC(a),[a]),u=(0,b.useMemo)(()=>eC(o),[o]),d=(0,b.useRef)(null),f=(0,b.useRef)(!0);return(0,b.useEffect)(()=>{if(!f.current)return;let e=d.current;e&&e.scrollTo({top:e.scrollHeight,behavior:`smooth`})},[a.length,o.length]),(0,x.jsx)(`div`,{className:`sim-columns ${QS.grid}`,children:(0,x.jsx)(`div`,{ref:d,onScroll:()=>{let e=d.current;e&&(f.current=e.scrollHeight-e.scrollTop-e.clientHeight<60)},className:QS.scroll,children:c.length===0?(0,x.jsx)(`div`,{className:QS.empty,children:`No turns yet — events will appear as the run progresses.`}):c.map(t=>{let n=s.get(t);return(0,x.jsx)(YS,{entry:n,eventsA:l.get(t)??[],eventsB:u.get(t)??[],runTerminal:e.isComplete||e.isAborted,runAborted:e.isAborted},t)})})})}function eC(e){let t=new Map;for(let n of e){if(typeof n.turn!=`number`)continue;let e=t.get(n.turn)??[];e.push(n),t.set(n.turn,e)}return t}var tC={row:`_row_1fazu_1`,header:`_header_1fazu_9`,headerTurn:`_headerTurn_1fazu_22`,headerTitle:`_headerTitle_1fazu_28`,headerTitleSplit:`_headerTitleSplit_1fazu_37`,headerTitlePerActor:`_headerTitlePerActor_1fazu_45`,cells:`_cells_1fazu_53`,cell:`_cell_1fazu_53`,cellBand:`_cellBand_1fazu_69`,cellEmpty:`_cellEmpty_1fazu_79`,cellPending:`_cellPending_1fazu_87`,cellPendingSpinner:`_cellPendingSpinner_1fazu_97`},nC=new Set([`turn_start`,`specialist_start`,`decision_pending`]);function rC(e){let t=new Set,n=!1;for(let r of e)if(r.type===`specialist_start`){let e=r.data?.department;typeof e==`string`&&e.length>0&&t.add(e)}else r.type===`decision_pending`&&(n=!0);let r=[];return t.size>0&&r.push(`${[...t].join(`, `)} analyzing`),n&&r.push(`awaiting decision`),r.length>0?r.join(` · `)+`…`:`Working on this turn…`}function iC(e){for(let t of e)if(t.type===`event`||t.type===`turn_done`){let e=t.data?.title;if(typeof e==`string`&&e.length>0)return e}return``}function aC({turn:e,actorIds:t,eventsByActor:n,runTerminal:r,runAborted:i}){let a=n.map(iC),o=a.filter(e=>e.length>0),s=o.length>0&&o.every(e=>e===o[0])?o[0]:``;return(0,x.jsxs)(`section`,{id:`turn-row-${e}`,className:tC.row,"aria-labelledby":`turn-row-${e}-h`,children:[(0,x.jsxs)(`h3`,{id:`turn-row-${e}-h`,className:tC.header,tabIndex:-1,children:[(0,x.jsxs)(`span`,{className:tC.headerTurn,children:[`T`,e]}),s?(0,x.jsx)(`span`,{className:tC.headerTitle,children:s}):(0,x.jsx)(`span`,{className:tC.headerTitleSplit,children:a.map((e,n)=>(0,x.jsx)(`span`,{className:tC.headerTitlePerActor,style:{"--cell-color":Pe(n)},children:e||`—`},t[n]))})]}),(0,x.jsx)(`div`,{className:tC.cells,children:t.map((t,a)=>{let o=n[a]??[],s=o.filter(e=>!nC.has(e.type)),c=o.length>0&&s.length===0;return(0,x.jsxs)(`div`,{className:tC.cell,style:{"--cell-color":Pe(a)},"aria-label":`Events for actor ${a+1} on turn ${e}`,children:[(0,x.jsx)(`span`,{className:tC.cellBand,"aria-hidden":`true`}),o.length===0?r?(0,x.jsx)(`div`,{className:tC.cellEmpty,title:i?`Run was interrupted before this actor reached this turn.`:`No event recorded for this actor on this turn.`,children:i?`Stopped before T${e}`:`No event for T${e}`}):(0,x.jsxs)(`div`,{className:tC.cellPending,"aria-live":`polite`,title:`Parallel runs can drift turn-to-turn — events arrive whenever this actor's LLM calls finish.`,children:[(0,x.jsx)(`span`,{className:`spinner ${tC.cellPendingSpinner}`,"aria-hidden":`true`}),`Catching up to turn `,e,`…`]}):c?r?(0,x.jsx)(`div`,{className:tC.cellEmpty,title:i?`Run was interrupted while this turn was still processing.`:`No outcome recorded for this actor on this turn.`,children:i?`Stopped during T${e}`:`T${e} ended without an outcome`}):(0,x.jsxs)(`div`,{className:tC.cellPending,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${tC.cellPendingSpinner}`}),rC(o)]}):s.map(e=>(0,x.jsx)(RS,{event:e,actorIndex:a%2,actorSlot:a},e.id))]},t)})})]})}var oC={grid:`_grid_1773u_1`,scrollX:`_scrollX_1773u_10`,stickyHeader:`_stickyHeader_1773u_20`,headerCell:`_headerCell_1773u_32`,scrollY:`_scrollY_1773u_37`,empty:`_empty_1773u_45`},sC=360;function cC({state:e}){let t=e.actorIds,n=(0,b.useMemo)(()=>t.map(t=>lC(e.actors[t]?.events??[])),[t,e.actors]),r=(0,b.useMemo)(()=>{let e=new Set;for(let t of n)for(let n of t.keys())e.add(n);return[...e].sort((e,t)=>e-t)},[n]),i=(0,b.useRef)(null),a=(0,b.useRef)(!0),o=()=>{let e=i.current;e&&(a.current=e.scrollHeight-e.scrollTop-e.clientHeight<60)},s=(0,b.useMemo)(()=>t.map(t=>e.actors[t]?.events.length??0).join(`,`),[t,e.actors]);(0,b.useEffect)(()=>{if(!a.current)return;let e=i.current;e&&e.scrollTo({top:e.scrollHeight,behavior:`smooth`})},[s]);let c={"--cell-min-width":`${sC}px`,"--cell-count":String(t.length)};return(0,x.jsx)(`div`,{className:oC.grid,style:c,children:(0,x.jsxs)(`div`,{className:oC.scrollX,children:[(0,x.jsx)(`header`,{className:oC.stickyHeader,children:t.map((t,n)=>{let r=e.actors[t];return(0,x.jsx)(`div`,{className:oC.headerCell,children:(0,x.jsx)(dS,{compact:!0,actorIndex:n,leader:r?.leader??null,nameFallback:t,popHistory:r?.popHistory??[],moraleHistory:r?.moraleHistory??[],event:r?.event,pendingDecision:r?.pendingDecision})},t)})}),(0,x.jsx)(`div`,{ref:i,onScroll:o,className:oC.scrollY,children:r.length===0?(0,x.jsx)(`div`,{className:oC.empty,children:`No turns yet — events will appear as the run progresses.`}):r.map(r=>(0,x.jsx)(aC,{turn:r,actorIds:t,eventsByActor:n.map(e=>e.get(r)??[]),runTerminal:e.isComplete||e.isAborted,runAborted:e.isAborted},r))})]})})}function lC(e){let t=new Map;for(let n of e){if(typeof n.turn!=`number`)continue;let e=t.get(n.turn)??[];e.push(n),t.set(n.turn,e)}return t}var uC={list:`_list_pe3ki_1`,item:`_item_pe3ki_10`,itemNumber:`_itemNumber_pe3ki_22`,itemLink:`_itemLink_pe3ki_29`,itemText:`_itemText_pe3ki_35`,itemMeta:`_itemMeta_pe3ki_39`,title:`_title_pe3ki_46`,wrap:`_wrap_pe3ki_56`,summary:`_summary_pe3ki_62`,filterBar:`_filterBar_pe3ki_73`,filterField:`_filterField_pe3ki_91`,filterLabel:`_filterLabel_pe3ki_105`,filterSelect:`_filterSelect_pe3ki_115`,filterStats:`_filterStats_pe3ki_142`,empty:`_empty_pe3ki_150`};function dC(e){let t=[...e.departments].join(`, `),n=[...e.actorNames].join(` · `);return(0,x.jsxs)(`li`,{id:`cite-${e.n}`,className:uC.item,children:[(0,x.jsxs)(`span`,{className:uC.itemNumber,children:[`[`,e.n,`]`]}),(0,x.jsxs)(`span`,{children:[e.url?(0,x.jsx)(`a`,{href:e.url,target:`_blank`,rel:`noopener noreferrer`,className:uC.itemLink,children:e.text}):(0,x.jsx)(`span`,{className:uC.itemText,children:e.text}),(0,x.jsxs)(`div`,{className:uC.itemMeta,children:[e.doi&&(0,x.jsxs)(x.Fragment,{children:[`DOI:`,e.doi,` · `]}),t&&(0,x.jsxs)(x.Fragment,{children:[`cited by `,t,` · `]}),(0,x.jsxs)(`span`,{title:`Which leader's run referenced this source`,children:[`leader `,n]})]})]})]},e.n)}function fC(e,t,n){return!t&&!n?e:e.filter(e=>!(t&&!e.actorNames.has(t)||n&&!e.departments.has(n)))}function pC(e){let t=new Set,n=new Set;for(let r of e){for(let e of r.actorNames)t.add(e);for(let e of r.departments)n.add(e)}return{actors:[...t].sort((e,t)=>e.localeCompare(t)),departments:[...n].sort((e,t)=>e.localeCompare(t))}}function mC({actors:e,departments:t,actorFilter:n,departmentFilter:r,onActorChange:i,onDepartmentChange:a,total:o,shown:s}){return e.length<2&&t.length<2?null:(0,x.jsxs)(`div`,{className:uC.filterBar,role:`region`,"aria-label":`Filter references`,children:[e.length>1&&(0,x.jsxs)(`div`,{className:uC.filterField,children:[(0,x.jsx)(`label`,{className:uC.filterLabel,htmlFor:`references-actor-filter`,children:`Leader`}),(0,x.jsxs)(`select`,{id:`references-actor-filter`,className:uC.filterSelect,value:n??``,onChange:e=>i(e.target.value||null),children:[(0,x.jsx)(`option`,{value:``,children:`All leaders`}),e.map(e=>(0,x.jsx)(`option`,{value:e,children:e},e))]})]}),t.length>1&&(0,x.jsxs)(`div`,{className:uC.filterField,children:[(0,x.jsx)(`label`,{className:uC.filterLabel,htmlFor:`references-department-filter`,children:`Department`}),(0,x.jsxs)(`select`,{id:`references-department-filter`,className:uC.filterSelect,value:r??``,onChange:e=>a(e.target.value||null),children:[(0,x.jsx)(`option`,{value:``,children:`All departments`}),t.map(e=>(0,x.jsx)(`option`,{value:e,children:e},e))]})]}),(0,x.jsxs)(`span`,{className:uC.filterStats,children:[`Showing `,s,` of `,o]})]})}function hC({registry:e,title:t=`References`,collapsible:n=!1,defaultOpen:r=!1,onToggle:i}){let[a,o]=(0,b.useState)(null),[s,c]=(0,b.useState)(null),{actors:l,departments:u}=(0,b.useMemo)(()=>pC(e.list),[e.list]),d=(0,b.useMemo)(()=>fC(e.list,a,s),[e.list,a,s]);if((0,b.useEffect)(()=>{if(typeof window>`u`)return;let t=()=>{let t=window.location.hash.match(/^#cite-(\d+)$/);if(!t)return;let n=Number(t[1]);Number.isFinite(n)&&(d.some(e=>e.n===n)||e.list.some(e=>e.n===n)&&(o(null),c(null)))};return t(),window.addEventListener(`hashchange`,t),()=>window.removeEventListener(`hashchange`,t)},[d,e.list]),e.list.length===0)return null;let f=(0,x.jsx)(mC,{actors:l,departments:u,actorFilter:a,departmentFilter:s,onActorChange:o,onDepartmentChange:c,total:e.list.length,shown:d.length}),p=d.length>0?(0,x.jsx)(`ol`,{className:uC.list,children:d.map(dC)}):(0,x.jsx)(`div`,{className:uC.empty,children:`No references match the current filters.`});return n?(0,x.jsxs)(`details`,{open:r,onToggle:i?e=>i(e.currentTarget.open):void 0,className:uC.wrap,children:[(0,x.jsxs)(`summary`,{className:uC.summary,children:[t,` · `,e.list.length]}),f,p]}):(0,x.jsxs)(`div`,{className:uC.wrap,children:[(0,x.jsxs)(`h3`,{className:uC.title,children:[t,` · `,e.list.length]}),f,p]})}function gC({registry:e}){return e.list.length===0?null:(0,x.jsx)(`ol`,{className:uC.list,children:e.list.map(dC)})}var _C={scroller:`_scroller_thxdg_1`,row:`_row_thxdg_8`,arrow:`_arrow_thxdg_40`},vC=.8;function yC({label:e,children:t,className:n,rowClassName:r,role:i,ariaLabel:a}){let o=(0,b.useRef)(null),s=(0,b.useRef)(null),c=(0,b.useRef)(null),l=(0,b.useRef)(null),[u,d]=(0,b.useState)({scrolls:!1,previous:!1,next:!1}),f=(0,b.useCallback)(()=>{let e=o.current,t=e?.parentElement;if(!e||!t)return;let n=getComputedStyle(e),r=t.clientWidth-parseFloat(n.marginLeft)-parseFloat(n.marginRight),i=e.scrollWidth>r+1,a=e.scrollWidth-e.clientWidth,u=i&&e.scrollLeft>1,f=i&&e.scrollLeft<a-1,p=document.activeElement;p===c.current&&!c.current?.disabled&&!f&&u?l.current=`previous`:p===s.current&&!s.current?.disabled&&!u&&f&&(l.current=`next`),d(e=>e.scrolls===i&&e.previous===u&&e.next===f?e:{scrolls:i,previous:u,next:f})},[]);(0,b.useEffect)(()=>{let e=o.current;if(!e)return;f();let t=new ResizeObserver(f),n=()=>{t.disconnect(),t.observe(e),e.parentElement&&t.observe(e.parentElement);for(let n of Array.from(e.children))t.observe(n)};n();let r=new MutationObserver(()=>{n(),f()});return r.observe(e,{childList:!0,subtree:!0,characterData:!0}),e.addEventListener(`scroll`,f,{passive:!0}),()=>{t.disconnect(),r.disconnect(),e.removeEventListener(`scroll`,f)}},[f]),(0,b.useEffect)(()=>{let e=l.current;if(!e)return;l.current=null;let t=document.activeElement;t&&t!==document.body&&t!==s.current&&t!==c.current||(e===`previous`?c:s).current?.disabled===!0&&(e===`previous`?s:c).current?.focus()},[u]);let p=e=>{let t=o.current;if(!t)return;let n=t.scrollWidth-t.clientWidth,r=Math.max(0,Math.min(n,t.scrollLeft+e*t.clientWidth*vC)),i=typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches;t.scrollTo({left:r,behavior:i?`auto`:`smooth`})},{scrolls:m}=u;return(0,x.jsxs)(`div`,{className:[_C.scroller,n].filter(Boolean).join(` `),children:[m&&(0,x.jsx)(`button`,{ref:s,type:`button`,className:_C.arrow,"aria-label":`Show previous ${e}`,title:`Show previous ${e}`,disabled:!u.previous,onClick:()=>p(-1),children:(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`‹`})}),(0,x.jsx)(`div`,{ref:o,role:i,"aria-label":a,className:[_C.row,r].filter(Boolean).join(` `),"data-fade-start":u.previous?`true`:`false`,"data-fade-end":u.next?`true`:`false`,children:t}),m&&(0,x.jsx)(`button`,{ref:c,type:`button`,className:_C.arrow,"aria-label":`Show next ${e}`,title:`Show next ${e}`,disabled:!u.next,onClick:()=>p(1),children:(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`›`})})]})}var bC={bar:`_bar_u6y4c_1`,label:`_label_u6y4c_13`,keys:`_keys_u6y4c_22`,keysRow:`_keysRow_u6y4c_26`,hint:`_hint_u6y4c_31`,cta:`_cta_u6y4c_71`,ctaCount:`_ctaCount_u6y4c_94`,exportBtn:`_exportBtn_u6y4c_103`,modalBackdrop:`_modalBackdrop_u6y4c_116`,modalDialog:`_modalDialog_u6y4c_127`,modalHeader:`_modalHeader_u6y4c_143`,modalTitle:`_modalTitle_u6y4c_152`,modalClose:`_modalClose_u6y4c_164`,modalBody:`_modalBody_u6y4c_174`};function xC({citationRegistry:e,toolRegistry:t,layoutToggle:n}){let[r,i]=(0,b.useState)(null),a=(0,b.useCallback)(()=>i(null),[]),{openToolbox:o}=ev();(0,b.useEffect)(()=>{if(!r)return;let e=e=>{e.key===`Escape`&&a()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[r,a]);let s=e.list.length,c=t.list.length;return s===0&&c===0&&!n?null:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{role:`region`,"aria-label":`Simulation evidence`,className:bC.bar,children:[(0,x.jsxs)(yC,{label:`evidence keys`,className:bC.keys,rowClassName:bC.keysRow,children:[(0,x.jsx)(`span`,{className:bC.label,children:`Evidence`}),s>0&&(0,x.jsx)(CC,{label:`References`,count:s,onClick:()=>i(`refs`),ariaLabel:`Open References list (${s} sources)`}),c>0&&(0,x.jsx)(CC,{label:`Forged Toolbox`,count:c,onClick:e=>o(e.currentTarget,`sim`),ariaLabel:`Open Forged Toolbox (${c} tools)`}),n]}),(0,x.jsx)(`span`,{className:bC.hint,children:`Click any inline [N] pill to jump to its source.`})]}),r===`refs`&&(0,x.jsx)(wC,{title:`References · ${s}`,onClose:a,extraActions:(0,x.jsx)(SC,{label:`EXPORT JSON`,filename:`paracosm-references.json`,data:e.list.map(e=>({n:e.n,text:e.text,url:e.url,doi:e.doi,departments:[...e.departments],actorNames:[...e.actorNames]}))}),children:(0,x.jsx)(gC,{registry:e})})]})}function SC({label:e,filename:t,data:n}){return(0,x.jsx)(`button`,{onClick:()=>{let e=new Blob([JSON.stringify(n,null,2)],{type:`application/json`}),r=document.createElement(`a`);r.href=URL.createObjectURL(e),r.download=t,r.click(),URL.revokeObjectURL(r.href)},className:bC.exportBtn,children:e})}function CC({label:e,count:t,onClick:n,ariaLabel:r}){return(0,x.jsxs)(`button`,{onClick:n,"aria-label":r,className:bC.cta,children:[(0,x.jsx)(`span`,{children:e.toUpperCase()}),(0,x.jsx)(`span`,{className:bC.ctaCount,children:t})]})}function wC({title:e,onClose:t,children:n,extraActions:r}){return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":e,onClick:t,className:bC.modalBackdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:bC.modalDialog,children:[(0,x.jsxs)(`div`,{className:bC.modalHeader,children:[(0,x.jsx)(`h2`,{className:bC.modalTitle,children:e}),r,(0,x.jsx)(`button`,{onClick:t,"aria-label":`Close`,className:bC.modalClose,children:`×`})]}),(0,x.jsx)(`div`,{className:bC.modalBody,children:n})]})})}var TC={panel:`_panel_nvkty_1`,label:`_label_nvkty_13`,copy:`_copy_nvkty_23`,button:`_button_nvkty_30`};function EC({enabled:e=!0}){let[t,n]=(0,b.useState)(!1),r=Xk(),i=Qk(),a=nA(),o=(0,b.useCallback)(async()=>{if(!t&&i){n(!0);try{let e=dg(window.localStorage);if(!e||!fg(e,r.id)){alert(`No previous launch config found for ${r.labels.name}. Run once from Settings first.`);return}let t=vg(e,_g(window.localStorage)),n=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...t,captureSnapshots:!0})}),i=await n.json().catch(()=>({}));if(n.status===429){alert(i.error||`Rate limit hit. Add an API key in Settings to bypass.`);return}if(!n.ok){alert(i.error||`Re-run failed: server responded with HTTP ${n.status}.`);return}if(i.redirect){k(window,i.visitorId),a(),pg(window.localStorage,t);let e=Array.isArray(t.actors)?t.actors:null;e&&e.length>0&&mg(window.localStorage,e,typeof t.scenarioId==`string`?t.scenarioId:void 0),window.location.href=fh(window.location.href,i.redirect)}else alert(`Re-run failed: server did not return a redirect. Check the server logs.`)}catch(e){alert(`Re-run failed: ${e}`)}finally{n(!1)}}},[t,i,r.id,r.labels.name,a]);return e?(0,x.jsxs)(`div`,{className:TC.panel,children:[(0,x.jsx)(`span`,{className:TC.label,children:`Re-run`}),(0,x.jsx)(`span`,{className:TC.copy,children:`Spin up a new run with the same leaders + scenario, seed bumped by one.`}),(0,x.jsx)(`button`,{type:`button`,className:TC.button,onClick:o,disabled:t||!i,children:t?`Launching…`:i?`Run again with seed+1 ›`:`Loading scenario…`})]}):null}var DC={card:`_card_1bn52_1`,empty:`_empty_1bn52_14`,headerRow:`_headerRow_1bn52_18`,kicker:`_kicker_1bn52_26`,lead:`_lead_1bn52_40`,leadMuted:`_leadMuted_1bn52_50`,leadCount:`_leadCount_1bn52_54`,refreshBtn:`_refreshBtn_1bn52_58`,grid:`_grid_1bn52_72`,tile:`_tile_1bn52_78`,tileTitle:`_tileTitle_1bn52_99`,tileMeta:`_tileMeta_1bn52_106`,tileCost:`_tileCost_1bn52_112`,tileCta:`_tileCta_1bn52_118`,moreNote:`_moreNote_1bn52_127`};function OC({hideWhenUnavailable:e=!0}={}){let{sessions:t,status:n,refresh:r}=Oe(),i=(0,b.useRef)(null),a=(0,b.useMemo)(()=>t.slice(0,3),[t]);if(n===`loading`||n===`unavailable`&&e)return null;let o=e=>{let t=new URL(window.location.href);t.searchParams.set(`replay`,e),t.searchParams.set(`tab`,`sim`),t.hash=``,window.location.assign(t.toString())},s=e=>new Date(e).toLocaleString(void 0,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`}),c=t.length===0,l=[DC.card,c?DC.empty:``].filter(Boolean).join(` `),u=[DC.kicker,c?DC.empty:``].filter(Boolean).join(` `),d=[DC.lead,c?DC.empty:``].filter(Boolean).join(` `);return(0,x.jsxs)(`div`,{ref:i,className:l,children:[(0,x.jsxs)(`div`,{className:DC.headerRow,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:u,children:[`▶ `,c?`Replay from cache`:`Watch a prior run`]}),c?(0,x.jsxs)(`div`,{className:d,children:[`No saved runs yet.`,` `,(0,x.jsxs)(`span`,{className:DC.leadMuted,children:[`Once any simulation completes it`,`'`,`s auto-cached here, so you can replay the full turn-by-turn playback — every decision, tool forge, and divergence — without re-spending credits.`]})]}):(0,x.jsxs)(`div`,{className:d,children:[`Don`,`'`,`t want to spend credits?`,` `,(0,x.jsxs)(`span`,{className:DC.leadMuted,children:[`Replay any of `,(0,x.jsx)(`strong`,{className:DC.leadCount,children:t.length}),` `,`cached simulation`,t.length===1?``:`s`,` turn-by-turn, complete with every decision, tool forge, and divergence.`]})]})]}),(0,x.jsx)(`button`,{type:`button`,onClick:r,"aria-label":`Refresh prior runs list`,title:`Refresh list`,className:DC.refreshBtn,children:`↻ Refresh`})]}),!c&&(0,x.jsx)(`div`,{className:DC.grid,children:a.map(e=>(0,x.jsxs)(`button`,{type:`button`,onClick:()=>o(e.id),"aria-label":`Replay ${e.title||e.scenarioName||e.scenarioId||e.id}`,className:DC.tile,children:[(0,x.jsx)(`span`,{className:DC.tileTitle,children:e.title||e.scenarioName||e.scenarioId||`Simulation`}),(0,x.jsxs)(`span`,{className:DC.tileMeta,children:[e.title&&e.scenarioName?`${e.scenarioName} · `:``,typeof e.turnCount==`number`?`${e.turnCount} turns · `:``,Rn(e)?`${Rn(e)} · `:``,s(e.createdAt)]}),typeof e.totalCostUSD==`number`&&e.totalCostUSD>0&&(0,x.jsxs)(`span`,{className:DC.tileCost,children:[`$`,e.totalCostUSD.toFixed(2)]}),(0,x.jsx)(`span`,{className:DC.tileCta,children:`Replay →`})]},e.id))}),!c&&t.length>3&&(0,x.jsxs)(`div`,{className:DC.moreNote,children:[`+ `,t.length-3,` more — use the `,(0,x.jsx)(`strong`,{children:`LOAD`}),` button in the top bar to browse the full list.`]})]})}var kC={padding:`4px 10px`,fontSize:`var(--font-xs)`,fontFamily:`var(--mono)`,fontWeight:600,background:`transparent`,color:`var(--text-3)`,border:`1px solid var(--border)`,cursor:`pointer`,textTransform:`uppercase`,letterSpacing:`0.04em`},AC={...kC,color:`var(--amber)`,background:`var(--bg-card)`,borderColor:`var(--amber)`};function jC({layout:e,actorCount:t,onChange:n}){return(0,x.jsxs)(`div`,{role:`group`,"aria-label":`Sim layout`,style:{display:`inline-flex`,gap:0},children:[(0,x.jsx)(`button`,{type:`button`,"data-layout":`side-by-side`,"aria-pressed":e===`side-by-side`,onClick:()=>n(`side-by-side`),style:{...e===`side-by-side`?AC:kC,borderRadius:`3px 0 0 3px`},title:`Side-by-side: per-actor columns with horizontal scroll for 3+`,children:`Side-by-side`}),(0,x.jsx)(`button`,{type:`button`,"data-layout":`constellation`,"aria-pressed":e===`constellation`,onClick:()=>n(`constellation`),style:{...e===`constellation`?AC:kC,borderRadius:`0 3px 3px 0`,borderLeft:`none`},title:`Constellation: radial cohort layout`,children:`Constellation`})]})}var MC={wrap:`_wrap_1k1fu_1`,svg:`_svg_1k1fu_11`,empty:`_empty_1k1fu_17`,edge:`_edge_1k1fu_25`,node:`_node_1k1fu_29`,label:`_label_1k1fu_42`,statLine:`_statLine_1k1fu_55`,statBadge:`_statBadge_1k1fu_62`,outcomeGlyph:`_outcomeGlyph_1k1fu_69`,outcomeSuccess:`_outcomeSuccess_1k1fu_76`,outcomeFailure:`_outcomeFailure_1k1fu_80`,outcomePending:`_outcomePending_1k1fu_84`,statBadgeMortality:`_statBadgeMortality_1k1fu_88`,edgeLabel:`_edgeLabel_1k1fu_93`,centerChip:`_centerChip_1k1fu_100`,centerChipTurn:`_centerChipTurn_1k1fu_104`,centerChipScenario:`_centerChipScenario_1k1fu_112`},NC=[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`];function PC(e){if(e.length<2)return{pairs:[],hasSpread:!1,hasAnyData:!1};let t=e.some(e=>Object.keys(e.hexaco??{}).length>0),n=[];for(let t=0;t<e.length;t+=1)for(let r=t+1;r<e.length;r+=1){let i=e[t],a=e[r],o=0;for(let e of NC){let t=(typeof i.hexaco?.[e]==`number`?i.hexaco[e]:.5)-(typeof a.hexaco?.[e]==`number`?a.hexaco[e]:.5);o+=t*t}n.push({a:i.name,b:a.name,distance:Math.sqrt(o),normalized:0})}let r=n.reduce((e,t)=>Math.max(e,t.distance),0);for(let e of n)e.normalized=r>0?e.distance/r:0;return{pairs:n,hasSpread:r>0,hasAnyData:t}}function FC(e,t){let n=e.actors[t];if(!n)return{pop:null,morale:null,decisions:0,tools:0,deaths:0,latestOutcome:`pending`};let r=`pending`;for(let e=n.events.length-1;e>=0;e--){let t=n.events[e];if(t.type!==`outcome`)continue;let i=String(t.data?.outcome??``);i.includes(`success`)?r=`success`:i.includes(`failure`)&&(r=`failure`);break}return{pop:n.popHistory.length>0?n.popHistory[n.popHistory.length-1]:null,morale:n.moraleHistory.length>0?n.moraleHistory[n.moraleHistory.length-1]:null,decisions:n.decisions??0,tools:n.tools??0,deaths:n.deaths??0,latestOutcome:r}}var IC=`Unknown`;function LC(e){return e?e.trim():``}function RC(e){let t=new Map;return e.actorIds.forEach((n,r)=>{let i=e.actors[n],a=LC(i?.leader?.archetype),o=a||`__unknown__`,s=a||IC,c=t.get(o);c?c.ids.push(n):t.set(o,{archetype:a,label:s,ids:[n],firstIndex:r})}),[...t.values()].sort((e,t)=>e.firstIndex-t.firstIndex)}var zC={legend:`_legend_1h9pr_1`,heading:`_heading_1h9pr_14`,pills:`_pills_1h9pr_24`,pill:`_pill_1h9pr_24`,pillFocused:`_pillFocused_1h9pr_56`,pillDimmed:`_pillDimmed_1h9pr_62`,pillCount:`_pillCount_1h9pr_66`,pillLabel:`_pillLabel_1h9pr_76`};function BC({cohorts:e,focusedArchetype:t,onFocusChange:n}){let r=e.reduce((e,t)=>e+t.ids.length,0);if(e.length<2||r<3)return null;let i=e=>{n&&n(t===e?null:e)};return(0,x.jsxs)(`div`,{className:zC.legend,role:`group`,"aria-label":`Cohort summary: ${e.length} archetypes across ${r} actors`,children:[(0,x.jsx)(`span`,{className:zC.heading,children:`COHORTS`}),(0,x.jsx)(`div`,{className:zC.pills,children:e.map(e=>{let r=t===e.archetype&&e.archetype!==``,a=t&&t!==e.archetype,o=`${zC.pill} ${r?zC.pillFocused:``} ${a?zC.pillDimmed:``}`;return(0,x.jsxs)(`button`,{type:`button`,className:o,onClick:()=>i(e.archetype),disabled:!n,"aria-pressed":r,"aria-label":`${e.label} cohort, ${e.ids.length} actor${e.ids.length===1?``:`s`}`,children:[(0,x.jsx)(`span`,{className:zC.pillCount,children:e.ids.length}),(0,x.jsx)(`span`,{className:zC.pillLabel,children:e.label})]},e.archetype||`__unknown__`)})})]})}var VC=18,HC=80,UC=9;function WC(e){if(e===0)return[];let t=Math.min(460,Math.max(120,60+12*e)),n=t+HC,r=[];for(let i=0;i<e;i+=1){let a=i/Math.max(1,e)*2*Math.PI-Math.PI/2;r.push({cx:n+t*Math.cos(a),cy:n+t*Math.sin(a),angle:a})}return r}function GC(e){return e===0?0:(Math.min(460,Math.max(120,60+12*e))+HC)*2}function KC({state:e,onActorClick:t}){let n=e.actorIds,r=b.useMemo(()=>WC(n.length),[n.length]),i=b.useMemo(()=>n.map(t=>({name:t,hexaco:e.actors[t]?.leader?.hexaco??{}})),[n,e.actors]),a=i.map(e=>`${e.name}:${Object.values(e.hexaco).join(`,`)}`).join(`|`),o=b.useMemo(()=>PC(i),[a]),s=b.useMemo(()=>{let e=new Map;for(let t of o.pairs)e.set(`${t.a}|${t.b}`,t.normalized),e.set(`${t.b}|${t.a}`,t.normalized);return e},[o]),c=Xk(),l=b.useMemo(()=>n.map(t=>FC(e,t)),[n,e]),u=(0,b.useMemo)(()=>RC(e),[e]),[d,f]=(0,b.useState)(null),p=(0,b.useMemo)(()=>{let e=new Map;for(let t of u)for(let n of t.ids)e.set(n,t.archetype);return e},[u]),m=e=>d===null||p.get(e)===d;if(n.length===0)return(0,x.jsx)(`div`,{className:MC.empty,children:`Constellation will appear when actors are launched.`});let h=GC(n.length);return(0,x.jsxs)(`div`,{className:MC.wrap,children:[(0,x.jsx)(BC,{cohorts:u,focusedArchetype:d,onFocusChange:f}),(0,x.jsxs)(`svg`,{className:MC.svg,viewBox:`0 0 ${h} ${h}`,width:h,height:h,role:`img`,"aria-label":`Constellation of ${n.length} actors`,children:[n.map((e,t)=>n.slice(t+1).map(i=>{let a=r[t],c=r[n.indexOf(i)];if(!a||!c)return null;let l=s.get(`${e}|${i}`)??0,u=m(e)&&m(i),f=d===null||u?1:.12,p=Math.max(.06,Math.min(.95,1-l))*f,h=o.hasSpread&&n.length<UC&&(d===null||u),g=(a.cx+c.cx)/2,_=(a.cy+c.cy)/2;return(0,x.jsxs)(b.Fragment,{children:[(0,x.jsx)(`line`,{"data-edge":`${e}|${i}`,className:MC.edge,x1:a.cx,y1:a.cy,x2:c.cx,y2:c.cy,strokeOpacity:p,strokeWidth:1.5}),h&&(0,x.jsx)(`text`,{className:MC.edgeLabel,x:g,y:_,textAnchor:`middle`,dominantBaseline:`middle`,"aria-hidden":`true`,children:l.toFixed(2)})]},`${e}|${i}`)})),n.map((n,i)=>{let a=r[i];if(!a)return null;let o=Pe(i),s=e.actors[n]?.leader?.archetype??``,c=a.cx+Math.cos(a.angle)*32,u=a.cy+Math.sin(a.angle)*32,f=a.angle>-Math.PI/2&&a.angle<Math.PI/2?`start`:`end`,p=d!==null&&!m(n)?.25:1;return(0,x.jsxs)(`g`,{opacity:p,children:[(0,x.jsx)(`circle`,{"data-actor":n,className:MC.node,cx:a.cx,cy:a.cy,r:VC,fill:o,onClick:()=>t(n),onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),t(n))},tabIndex:0,role:`button`,"aria-label":`Open report for ${n}`,children:(0,x.jsx)(`title`,{children:`${n}${s?` · ${s}`:``}`})}),(0,x.jsx)(`text`,{className:MC.label,x:c,y:u,textAnchor:f,dominantBaseline:`middle`,children:n}),(()=>{let e=l[i];if(!e)return null;let t=e.pop!==null&&e.morale!==null?`POP ${Math.round(e.pop)} · MORALE ${Math.round(e.morale)}%`:``,n=e.latestOutcome===`success`?`✓`:e.latestOutcome===`failure`?`⚠`:`…`,r=e.latestOutcome===`success`?MC.outcomeSuccess:e.latestOutcome===`failure`?MC.outcomeFailure:MC.outcomePending,a=e.deaths>=5;return(0,x.jsxs)(x.Fragment,{children:[t&&(0,x.jsx)(`text`,{className:MC.statLine,x:c,y:u+14,textAnchor:f,dominantBaseline:`middle`,children:t}),(0,x.jsxs)(`text`,{className:MC.statBadge,x:c,y:u+28,textAnchor:f,dominantBaseline:`middle`,children:[`D${e.decisions} · F${e.tools} `,(0,x.jsx)(`tspan`,{className:`${MC.outcomeGlyph} ${r}`,children:n}),a&&(0,x.jsx)(`tspan`,{className:MC.statBadgeMortality,children:` · ${e.deaths}†`})]})]})})()]},n)}),(()=>{let t=h/2,r=h/2,i=c.labels.actorNounPlural??`actors`;return(0,x.jsxs)(`g`,{className:MC.centerChip,role:`presentation`,children:[(0,x.jsxs)(`text`,{className:MC.centerChipTurn,x:t,y:r-6,textAnchor:`middle`,dominantBaseline:`middle`,children:[`T`,e.turn,`/`,e.maxTurns]}),(0,x.jsxs)(`text`,{className:MC.centerChipScenario,x:t,y:r+10,textAnchor:`middle`,dominantBaseline:`middle`,children:[c.labels.shortName,` · `,n.length,` `,i]})]})})()]})]})}function qC(e){return e.length>0?e[e.length-1]:0}function JC(e,t){return{id:e,name:t.leader?.name??e,archetype:t.leader?.archetype??``,population:qC(t.popHistory),morale:qC(t.moraleHistory),deaths:t.deaths,tools:t.toolNames?.size??t.tools??0,turn:t.popHistory.length,pending:!!t.pendingDecision}}function YC(e){return e.actorIds.map(t=>{let n=e.actors[t];return n?JC(t,n):null}).filter(e=>e!==null)}function XC(e){switch(e){case`name`:case`archetype`:return`asc`;case`deaths`:return`asc`;case`population`:case`morale`:case`tools`:case`turn`:return`desc`}}function ZC(e,t,n,r){let i=r===`asc`?1:-1,a;switch(n){case`name`:a=e.name.localeCompare(t.name);break;case`archetype`:a=e.archetype.localeCompare(t.archetype);break;case`population`:a=e.population-t.population;break;case`morale`:a=e.morale-t.morale;break;case`deaths`:a=e.deaths-t.deaths;break;case`tools`:a=e.tools-t.tools;break;case`turn`:a=e.turn-t.turn}return a===0?e.name.localeCompare(t.name):a*i}function QC(e,t,n){return[...e].sort((e,r)=>ZC(e,r,t,n))}var $C={wrap:`_wrap_1yfha_1`,scroll:`_scroll_1yfha_9`,table:`_table_1yfha_13`,th:`_th_1yfha_21`,numeric:`_numeric_1yfha_32`,activeSort:`_activeSort_1yfha_36`,sortButton:`_sortButton_1yfha_40`,sortGlyph:`_sortGlyph_1yfha_70`,row:`_row_1yfha_75`,rowClickable:`_rowClickable_1yfha_83`,colorCell:`_colorCell_1yfha_95`,colorDot:`_colorDot_1yfha_100`,nameCell:`_nameCell_1yfha_108`,actorName:`_actorName_1yfha_116`,pendingPill:`_pendingPill_1yfha_121`,archetypeCell:`_archetypeCell_1yfha_136`,numCell:`_numCell_1yfha_142`,moraleWrap:`_moraleWrap_1yfha_150`,moraleBar:`_moraleBar_1yfha_158`,moraleFill:`_moraleFill_1yfha_168`,moraleText:`_moraleText_1yfha_176`,empty:`_empty_1yfha_183`},ew=[{key:`name`,label:`Actor`,numeric:!1},{key:`archetype`,label:`Archetype`,numeric:!1},{key:`turn`,label:`Turn`,numeric:!0},{key:`population`,label:`Pop`,numeric:!0},{key:`morale`,label:`Morale`,numeric:!0},{key:`deaths`,label:`Deaths`,numeric:!0},{key:`tools`,label:`Tools`,numeric:!0}];function tw(e,t){return e?t===`asc`?`ascending`:`descending`:`none`}function nw({state:e,onActorClick:t}){let[n,r]=(0,b.useState)(`morale`),[i,a]=(0,b.useState)(`desc`),o=(0,b.useCallback)(e=>{r(t=>t===e?(a(e=>e===`asc`?`desc`:`asc`),t):(a(XC(e)),e))},[]),s=(0,b.useMemo)(()=>YC(e),[e]),c=(0,b.useMemo)(()=>QC(s,n,i),[s,n,i]),l=e=>n=>{t&&(n.key===`Enter`||n.key===` `)&&(n.preventDefault(),t(e))};return c.length===0?(0,x.jsx)(`div`,{className:$C.empty,role:`status`,children:`No actor data yet — events will populate this table as the run progresses.`}):(0,x.jsx)(`div`,{className:$C.wrap,"aria-label":`Actor roster (${c.length} actors)`,children:(0,x.jsx)(`div`,{className:$C.scroll,children:(0,x.jsxs)(`table`,{className:$C.table,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{children:[(0,x.jsx)(`th`,{"aria-hidden":`true`,className:$C.colorCell}),ew.map(e=>{let t=e.key===n;return(0,x.jsx)(`th`,{"aria-sort":tw(t,i),className:`${$C.th} ${e.numeric?$C.numeric:``} ${t?$C.activeSort:``}`,children:(0,x.jsxs)(`button`,{type:`button`,className:$C.sortButton,onClick:()=>o(e.key),"aria-label":`Sort by ${e.label}${t?` (${i===`asc`?`ascending`:`descending`} active)`:``}`,children:[(0,x.jsx)(`span`,{children:e.label}),(0,x.jsx)(`span`,{className:$C.sortGlyph,"aria-hidden":`true`,children:t?i===`asc`?`▲`:`▼`:`·`})]})},e.key)})]})}),(0,x.jsx)(`tbody`,{children:c.map(n=>{let r=e.actorIds.indexOf(n.id),i=r>=0?Pe(r):`var(--text-3)`;return(0,x.jsxs)(`tr`,{className:`${$C.row} ${t?$C.rowClickable:``}`,tabIndex:t?0:-1,onClick:t?()=>t(n.id):void 0,onKeyDown:t?l(n.id):void 0,"aria-label":`${n.name}, ${n.archetype}, turn ${n.turn}, population ${n.population}, morale ${n.morale}%, ${n.deaths} deaths, ${n.tools} tools`,children:[(0,x.jsx)(`td`,{className:$C.colorCell,"aria-hidden":`true`,children:(0,x.jsx)(`span`,{className:$C.colorDot,style:{background:i}})}),(0,x.jsxs)(`td`,{className:$C.nameCell,children:[(0,x.jsx)(`span`,{className:$C.actorName,children:n.name}),n.pending&&(0,x.jsx)(`span`,{className:$C.pendingPill,title:`Waiting on commander decision`,children:`pending`})]}),(0,x.jsx)(`td`,{className:$C.archetypeCell,children:n.archetype}),(0,x.jsxs)(`td`,{className:$C.numCell,children:[`T`,n.turn]}),(0,x.jsx)(`td`,{className:$C.numCell,children:n.population}),(0,x.jsx)(`td`,{className:$C.numCell,children:(0,x.jsxs)(`span`,{className:$C.moraleWrap,children:[(0,x.jsx)(`span`,{className:$C.moraleBar,"aria-hidden":`true`,children:(0,x.jsx)(`span`,{className:$C.moraleFill,style:{width:`${Math.min(100,Math.max(0,n.morale))}%`,background:i}})}),(0,x.jsxs)(`span`,{className:$C.moraleText,children:[n.morale,`%`]})]})}),(0,x.jsx)(`td`,{className:$C.numCell,children:n.deaths}),(0,x.jsx)(`td`,{className:$C.numCell,children:n.tools})]},n.id)})})]})})})}function rw(e,t){if(e.length===0)return 0;if(e.length===1)return e[0];let n=Math.max(0,Math.min(1,t))*(e.length-1),r=Math.floor(n),i=Math.ceil(n);if(r===i)return e[r];let a=n-r;return e[r]*(1-a)+e[i]*a}function iw(e,t){let n=e.actorIds.map(t=>e.actors[t]).filter(e=>!!e).map(e=>t(e));if(n.length===0)return[];let r=n.reduce((e,t)=>Math.max(e,t.length),0),i=[];for(let e=0;e<r;e++){let t=[];for(let r of n)r.length>e&&t.push(r[e]);if(t.length===0)continue;let r=[...t].sort((e,t)=>e-t);i.push({turn:e+1,n:r.length,min:r[0],q1:rw(r,.25),median:rw(r,.5),q3:rw(r,.75),max:r[r.length-1]})}return i}var aw=e=>e.popHistory,ow=e=>e.moraleHistory;function sw(e,t,n){let r=n-t,i=e=>r<=0?.5:(e-t)/r;return{turn:e.turn,n:e.n,min:i(e.min),q1:i(e.q1),median:i(e.median),q3:i(e.q3),max:i(e.max)}}function cw(e){if(e.length===0)return{lo:0,hi:1};let t=1/0,n=-1/0;for(let r of e)r.min<t&&(t=r.min),r.max>n&&(n=r.max);return!isFinite(t)||!isFinite(n)?{lo:0,hi:1}:t===n?{lo:t-1,hi:n+1}:{lo:t,hi:n}}var lw={panel:`_panel_1ox36_1`,heading:`_heading_1ox36_9`,headingLabel:`_headingLabel_1ox36_17`,headingHint:`_headingHint_1ox36_26`,charts:`_charts_1ox36_33`,chartWrap:`_chartWrap_1ox36_39`,chartHeader:`_chartHeader_1ox36_45`,chartTitle:`_chartTitle_1ox36_53`,chartLatest:`_chartLatest_1ox36_60`,chart:`_chart_1ox36_33`,envelope:`_envelope_1ox36_76`,iqr:`_iqr_1ox36_82`,median:`_median_1ox36_88`,empty:`_empty_1ox36_96`},uw=[{id:`morale`,label:`Morale`,unitSuffix:`%`,pick:ow,fixedRange:{lo:0,hi:100}},{id:`population`,label:`Population`,unitSuffix:``,pick:aw}],dw=360,fw=90,pw=8,mw=6;function hw({bands:e,fixedRange:t,unitSuffix:n}){if(e.length===0)return(0,x.jsx)(`div`,{className:lw.empty,role:`status`,children:`No turns recorded yet.`});let r=t??cw(e),i=e.map(e=>sw(e,r.lo,r.hi)),a=t=>e.length===1?180:pw+t/(e.length-1)*344,o=e=>mw+(1-e)*78,s=`${i.map((e,t)=>`${t===0?`M`:`L`} ${a(t)} ${o(e.max)}`).join(` `)} ${[...i].reverse().map(e=>{let t=i.indexOf(e);return`L ${a(t)} ${o(e.min)}`}).join(` `)} Z`,c=`${i.map((e,t)=>`${t===0?`M`:`L`} ${a(t)} ${o(e.q3)}`).join(` `)} ${[...i].reverse().map(e=>{let t=i.indexOf(e);return`L ${a(t)} ${o(e.q1)}`}).join(` `)} Z`,l=i.map((e,t)=>`${t===0?`M`:`L`} ${a(t)} ${o(e.median)}`).join(` `),u=e[e.length-1];return(0,x.jsxs)(`svg`,{className:lw.chart,viewBox:`0 0 ${dw} ${fw}`,width:dw,height:fw,role:`img`,"aria-label":`Quantile distribution across turns. Latest turn ${u.turn}: median ${u.median.toFixed(0)}${n}, range ${u.min.toFixed(0)}-${u.max.toFixed(0)}${n} across ${u.n} actor${u.n===1?``:`s`}.`,children:[(0,x.jsx)(`path`,{className:lw.envelope,d:s}),(0,x.jsx)(`path`,{className:lw.iqr,d:c}),(0,x.jsx)(`path`,{className:lw.median,d:l})]})}function gw({state:e}){let t=(0,b.useMemo)(()=>uw.map(t=>({def:t,bands:iw(e,t.pick)})),[e]);return t.some(e=>e.bands.length>0)?(0,x.jsxs)(`div`,{className:lw.panel,"aria-label":`Distribution across actors`,children:[(0,x.jsxs)(`div`,{className:lw.heading,children:[(0,x.jsx)(`span`,{className:lw.headingLabel,children:`DISTRIBUTION`}),(0,x.jsx)(`span`,{className:lw.headingHint,children:`median · IQR · min-max envelope`})]}),(0,x.jsx)(`div`,{className:lw.charts,children:t.map(({def:e,bands:t})=>{let n=t[t.length-1];return(0,x.jsxs)(`div`,{className:lw.chartWrap,children:[(0,x.jsxs)(`div`,{className:lw.chartHeader,children:[(0,x.jsx)(`span`,{className:lw.chartTitle,children:e.label}),n&&(0,x.jsxs)(`span`,{className:lw.chartLatest,children:[`T`,n.turn,` · median `,Math.round(n.median),e.unitSuffix,` · `,n.min.toFixed(0),`-`,n.max.toFixed(0),e.unitSuffix,` · n=`,n.n]})]}),(0,x.jsx)(hw,{bands:t,fixedRange:e.fixedRange,unitSuffix:e.unitSuffix})]},e.id)})})]}):null}var _w={overlay:`_overlay_prjqp_1`,modal:`_modal_prjqp_11`,dockOverlay:`_dockOverlay_prjqp_22`,dock:`_dock_prjqp_22`,head:`_head_prjqp_60`,actorName:`_actorName_prjqp_68`,closeBtn:`_closeBtn_prjqp_73`,body:`_body_prjqp_83`,section:`_section_prjqp_88`,sectionTitle:`_sectionTitle_prjqp_92`,list:`_list_prjqp_100`,decisionItem:`_decisionItem_prjqp_106`,decisionTitle:`_decisionTitle_prjqp_111`,decisionRationale:`_decisionRationale_prjqp_115`,empty:`_empty_prjqp_120`,turnArticle:`_turnArticle_prjqp_124`,turnHeader:`_turnHeader_prjqp_129`,turnList:`_turnList_prjqp_134`,turnEvent:`_turnEvent_prjqp_140`,turnEventType:`_turnEventType_prjqp_145`};function vw(e){let t=e.data??{};return t.title??t.choice??t.summary??e.type}function yw({actorName:e,actorIndex:t,state:n,onClose:r,mode:i=`modal`}){let a=Pt(i===`modal`&&e!==null);if(b.useEffect(()=>{if(e===null)return;let t=e=>{e.key===`Escape`&&(e.preventDefault(),r())};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e,r]),e===null)return null;let o=n.actors[e];if(!o)return null;let s=o.events??[],c=s.filter(e=>e.type===`decision_made`),l=new Map;for(let e of s){let t=e.turn??0,n=l.get(t)??[];n.push(e),l.set(t,n)}let u=[...l.keys()].sort((e,t)=>e-t),d=i===`dock`,f=d?_w.dockOverlay:_w.overlay,p=d?_w.dock:_w.modal,m=d?void 0:r,h=d?void 0:e=>e.stopPropagation();return(0,x.jsx)(`div`,{className:f,role:`presentation`,onClick:m,children:(0,x.jsxs)(`div`,{ref:a,className:p,role:`dialog`,"aria-modal":!d||void 0,"aria-label":`Report for ${e}`,tabIndex:-1,onClick:h,children:[(0,x.jsxs)(`header`,{className:_w.head,children:[(0,x.jsx)(`div`,{className:_w.actorName,children:e}),(0,x.jsx)(`button`,{type:`button`,"aria-label":`Close drill-in`,className:_w.closeBtn,onClick:r,children:`×`})]}),(0,x.jsxs)(`div`,{className:_w.body,children:[(0,x.jsx)(dS,{actorIndex:t,leader:o.leader,popHistory:o.popHistory,moraleHistory:o.moraleHistory}),c.length>0&&(0,x.jsxs)(`section`,{className:_w.section,children:[(0,x.jsxs)(`h3`,{className:_w.sectionTitle,children:[`Decisions (`,c.length,`)`]}),(0,x.jsx)(`ul`,{className:_w.list,children:c.map(e=>{let t=e.data?.choice??e.data?.title??`<choice>`,n=e.data?.rationale??``;return(0,x.jsxs)(`li`,{className:_w.decisionItem,children:[(0,x.jsxs)(`div`,{className:_w.decisionTitle,children:[`T`,e.turn??`?`,`: `,t]}),n&&(0,x.jsx)(`div`,{className:_w.decisionRationale,children:n})]},e.id)})})]}),(0,x.jsxs)(`section`,{className:_w.section,children:[(0,x.jsxs)(`h3`,{className:_w.sectionTitle,children:[`Timeline (`,s.length,` events)`]}),u.length===0&&(0,x.jsx)(`p`,{className:_w.empty,children:`No events captured yet.`}),u.map(e=>(0,x.jsxs)(`article`,{className:_w.turnArticle,children:[(0,x.jsxs)(`header`,{className:_w.turnHeader,children:[`Turn `,e]}),(0,x.jsx)(`ul`,{className:_w.turnList,children:(l.get(e)??[]).map(e=>(0,x.jsxs)(`li`,{className:_w.turnEvent,children:[(0,x.jsx)(`span`,{className:_w.turnEventType,children:e.type}),` `,vw(e)]},e.id))})]},e))]})]})]})})}var bw={root:`_root_1s21i_1`,scrollableBody:`_scrollableBody_1s21i_8`,leadersRow:`_leadersRow_1s21i_16`,introBar:`_introBar_1s21i_22`,introBody:`_introBody_1s21i_33`,introHeading:`_introHeading_1s21i_40`,introExpandButton:`_introExpandButton_1s21i_44`,introDismissButton:`_introDismissButton_1s21i_56`,progressBar:`_progressBar_1s21i_75`,progressLabel:`_progressLabel_1s21i_86`,progressTrack:`_progressTrack_1s21i_93`,progressFill:`_progressFill_1s21i_101`,progressPercent:`_progressPercent_1s21i_107`,centerState:`_centerState_1s21i_111`,centerStateHeading:`_centerStateHeading_1s21i_122`,centerStateHeadingLarger:`_centerStateHeadingLarger_1s21i_134`,centerStateHeadingAmber:`_centerStateHeadingAmber_1s21i_146`,centerStateCopy:`_centerStateCopy_1s21i_154`,centerStateCopyWide:`_centerStateCopyWide_1s21i_154`,centerStateSpinnerSmall:`_centerStateSpinnerSmall_1s21i_166`,centerStateSpinnerLarge:`_centerStateSpinnerLarge_1s21i_173`,emptyStateActions:`_emptyStateActions_1s21i_180`,buttonRun:`_buttonRun_1s21i_187`,buttonLoad:`_buttonLoad_1s21i_210`,buttonSettings:`_buttonSettings_1s21i_226`,tourHint:`_tourHint_1s21i_241`,tourLink:`_tourLink_1s21i_247`,tourAside:`_tourAside_1s21i_260`,replayCtaWrap:`_replayCtaWrap_1s21i_265`,flashCard:`_flashCard_1s21i_272`,flashOn:`_flashOn_1s21i_275`};function xw({onDismiss:e}){let[t,n]=(0,b.useState)(!1);return(0,x.jsxs)(`div`,{role:`region`,"aria-label":`How to read the simulation`,className:bw.introBar,children:[(0,x.jsxs)(`div`,{className:bw.introBody,children:[(0,x.jsx)(`b`,{className:bw.introHeading,children:`How to read this:`}),` `,t?(0,x.jsx)(x.Fragment,{children:`Multiple commanders with different HEXACO profiles run the same seed side by side. Each turn, departments analyze in parallel and may forge a new computational tool in a QuickJS WebAssembly sandbox or reuse an existing one. Commanders decide. The settlement diverges. Click any tile in Viz to drill into a colonist; click any forge card to inspect the generated code.`}):(0,x.jsxs)(x.Fragment,{children:[`multiple commanders, one seed, divergent histories. HEXACO shapes every LLM call.`,` `,(0,x.jsx)(`button`,{onClick:()=>n(!0),className:bw.introExpandButton,children:`more`})]})]}),(0,x.jsx)(`button`,{onClick:e,className:bw.introDismissButton,"aria-label":`Dismiss introduction`,children:`Got it`})]})}function Sw({state:e,sseStatus:t,onRun:n,onTour:r,verdict:i,shownRun:a,launching:o,interventionArtifact:s,interventionRunning:c,interventionState:l=e,onInterventionDismiss:u,forceLayout:d}){let f=Xk(),p=Qk();if(s)return(0,x.jsx)(`div`,{className:bw.root,children:(0,x.jsx)(`div`,{className:bw.scrollableBody,children:(0,x.jsx)(Zx,{artifact:s,state:l,onDismiss:u})})});if(c)return(0,x.jsx)(`div`,{className:bw.root,children:(0,x.jsx)(`div`,{className:bw.scrollableBody,children:(0,x.jsx)(rS,{state:l,subject:c.subject,intervention:c.intervention})})});let m=h_(),h=D_(),[g,_]=(0,b.useState)(!1),v=o??g,[y,S]=(0,b.useState)(`side-by-side`),C=(0,b.useRef)(!1),w=(0,b.useCallback)(e=>{C.current=!0,S(e)},[]);(0,b.useEffect)(()=>{C.current||e.actorIds.length>50&&y!==`constellation`&&S(`constellation`)},[e.actorIds.length,y]);let T=d??y,[E,D]=(0,b.useState)(null),O=E?e.actorIds.indexOf(E):0,k=e.actorIds[0],A=e.actorIds[1],j=k?e.actors[k]:null,ee=A?e.actors[A]:null,te=Object.values(e.actors).some(e=>e.events.length>0),M=e.isRunning&&!te;(0,b.useEffect)(()=>{(te||e.isRunning)&&o===void 0&&_(!1)},[te,e.isRunning,o]);let N=(0,b.useCallback)(()=>{o===void 0&&_(!0),n?.()},[n,o]),ne=f.presets.find(e=>e.id==="default"),P=ne?.leaders??ne?.actors,re=(0,b.useMemo)(()=>typeof window>`u`?null:gg(window.localStorage),[]),ie=P?.[0]??re?.[0],F=P?.[1]??re?.[1],I=ie?.name?{name:ie.name,archetype:ie.archetype??``,unit:ie.unit??se(f,0),hexaco:ie.hexaco??{},instructions:ie.instructions??``,quote:``}:null,ae=F?.name?{name:F.name,archetype:F.archetype??``,unit:F.unit??se(f,1),hexaco:F.hexaco??{},instructions:F.instructions??``,quote:``}:null,[oe,ce]=(0,b.useState)(()=>typeof window>`u`||localStorage.getItem(`paracosm-intro-dismissed`)!==`1`),le=()=>{ce(!1),localStorage.setItem(`paracosm-intro-dismissed`,`1`)},L=j?.event,ue=L?`T${L.turn} \u2014 ${L.time}: ${L.title}`:``,de=(0,b.useMemo)(()=>{let e=i&&typeof i==`object`?i.winner:null;return t=>e===`tie`?`tie`:e===t?`winner`:e===`A`||e===`B`?`second`:null},[i]),fe=e.maxTurns>0?Math.min(100,Math.max(0,e.turn/e.maxTurns*100)):0,R=(0,b.useCallback)(()=>{let e=document.querySelector(`[data-paracosm-replay-cta="true"]`);e&&(e.scrollIntoView({behavior:`smooth`,block:`center`}),e.classList.add(bw.flashOn),window.setTimeout(()=>e.classList.remove(bw.flashOn),1200))},[]),z=(0,b.useCallback)(()=>{let e=new URL(window.location.href);e.searchParams.set(`tab`,`settings`),window.history.replaceState({},``,e.toString()),window.location.reload()},[]),pe=e.isRunning||e.isComplete||te||t===`connected`;return(0,x.jsxs)(`div`,{className:bw.root,children:[(0,x.jsxs)(`div`,{className:bw.scrollableBody,children:[e.isComplete&&i&&i.winner?(0,x.jsx)(jn,{verdict:i,shownRun:a}):null,T===`constellation`?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(KC,{state:e,onActorClick:e=>D(e)}),(0,x.jsx)(gw,{state:e}),(0,x.jsx)(nw,{state:e,onActorClick:e=>D(e)})]}):e.actorIds.length>=3?(0,x.jsx)(CS,{actors:e.actorIds.map(t=>({id:t,state:e.actors[t]})),crisisText:ue,toolRegistry:h}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`leaders-row ${bw.leadersRow}`,children:[(0,x.jsx)(dS,{actorIndex:0,leader:j?.leader||I,popHistory:j?.popHistory||[],moraleHistory:j?.moraleHistory||[],verdictPlacement:de(`A`),event:j?.event,statuses:j?.statuses,pendingDecision:j?.pendingDecision}),(0,x.jsx)(dS,{actorIndex:1,leader:ee?.leader||ae,popHistory:ee?.popHistory||[],moraleHistory:ee?.moraleHistory||[],verdictPlacement:de(`B`),event:ee?.event,statuses:ee?.statuses,pendingDecision:ee?.pendingDecision})]}),(0,x.jsx)(CS,{actors:e.actorIds.slice(0,2).map(t=>({id:t,state:e.actors[t]})),crisisText:ue,toolRegistry:h})]}),e.isRunning&&!e.isComplete&&e.maxTurns>0&&(0,x.jsxs)(`div`,{className:bw.progressBar,children:[(0,x.jsxs)(`span`,{className:bw.progressLabel,children:[`Turn `,Math.max(1,e.turn),` / `,e.maxTurns]}),(0,x.jsx)(`div`,{className:bw.progressTrack,children:(0,x.jsx)(`div`,{className:bw.progressFill,style:{width:`${fe}%`}})}),(0,x.jsxs)(`span`,{className:bw.progressPercent,children:[Math.round(fe),`%`]})]}),oe&&(j?.events.length??0)>0&&(0,x.jsx)(xw,{onDismiss:le}),M&&!te&&!e.isComplete&&e.turn===0&&(0,x.jsxs)(`div`,{className:bw.centerState,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${bw.centerStateSpinnerSmall}`,"aria-hidden":`true`}),(0,x.jsx)(`div`,{className:bw.centerStateHeading,children:`Simulation starting...`}),(0,x.jsx)(`div`,{className:bw.centerStateCopy,children:`The Event Director is reading simulation state and generating the first event. Departments will analyze and forge tools once it arrives.`})]}),v&&!te&&!e.isRunning&&(0,x.jsxs)(`div`,{className:bw.centerState,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${bw.centerStateSpinnerLarge}`,"aria-hidden":`true`}),(0,x.jsx)(`div`,{className:bw.centerStateHeadingAmber,children:`Launching Simulation...`}),(0,x.jsx)(`div`,{className:bw.centerStateCopy,children:`Initializing the Event Director, departments, and agent personalities. First events will appear shortly.`})]}),!te&&!e.isComplete&&!v&&t===`connecting`&&(0,x.jsxs)(`div`,{className:bw.centerState,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${bw.centerStateSpinnerSmall}`,"aria-hidden":`true`}),(0,x.jsx)(`div`,{className:bw.centerStateHeading,children:`Connecting...`}),(0,x.jsx)(`div`,{className:bw.centerStateCopy,children:`Loading simulation state from the server. If a simulation is running, events will appear shortly.`})]}),!e.isRunning&&!e.isComplete&&!te&&t===`connected`&&!v&&typeof window<`u`&&new URLSearchParams(window.location.search).has(`replay`)&&(0,x.jsxs)(`div`,{className:bw.centerState,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${bw.centerStateSpinnerSmall}`,"aria-hidden":`true`}),(0,x.jsx)(`div`,{className:bw.centerStateHeading,children:`Loading replay…`}),(0,x.jsx)(`div`,{className:bw.centerStateCopy,children:`Streaming the cached run back from the server. Turns and events will populate as they arrive.`})]}),!e.isRunning&&!e.isComplete&&!te&&t===`connected`&&!v&&!(typeof window<`u`&&new URLSearchParams(window.location.search).has(`replay`))&&(0,x.jsxs)(`div`,{className:bw.centerState,children:[(0,x.jsx)(`div`,{className:bw.centerStateHeadingLarger,children:`No simulation running`}),(0,x.jsx)(`div`,{className:bw.centerStateCopyWide,children:`Configure your commanders with different HEXACO personality profiles, choose a scenario, and launch from the Settings tab. Or load a previously saved simulation.`}),(0,x.jsxs)(`div`,{className:bw.emptyStateActions,children:[n&&(0,x.jsx)(`button`,{onClick:N,disabled:v||!p,className:bw.buttonRun,children:v?`Launching…`:p?`Run Simulation`:`Loading scenario…`}),(0,x.jsx)(`button`,{onClick:R,className:bw.buttonLoad,children:`Load Prior Run`}),(0,x.jsx)(`button`,{onClick:z,className:bw.buttonSettings,children:`Settings`})]}),r&&(0,x.jsxs)(`div`,{className:bw.tourHint,children:[`First time here?`,` `,(0,x.jsx)(`button`,{type:`button`,onClick:r,className:bw.tourLink,children:`Take the guided tour →`}),(0,x.jsx)(`span`,{className:bw.tourAside,children:`(canned demo, no LLM cost)`})]}),(0,x.jsx)(`div`,{"data-paracosm-replay-cta":`true`,className:`${bw.replayCtaWrap} ${bw.flashCard}`,children:(0,x.jsx)(OC,{})})]}),pe&&T===`side-by-side`&&e.actorIds.length===2&&(0,x.jsx)($S,{state:e}),pe&&T===`side-by-side`&&e.actorIds.length>=3&&(0,x.jsx)(cC,{state:e}),(0,x.jsx)(AS,{state:e})]}),(0,x.jsx)(xC,{citationRegistry:m,toolRegistry:h,layoutToggle:(0,x.jsx)(jC,{layout:T,actorCount:e.actorIds.length,onChange:w})}),(0,x.jsx)(EC,{enabled:e.isComplete&&!e.isRunning}),(0,x.jsx)(yw,{actorName:E,actorIndex:O>=0?O:0,state:e,onClose:()=>D(null),mode:e.actorIds.length>=5?`dock`:`modal`})]})}function Cw(e,t){return e===`O`?t>.7?`creative`:t<.3?`conventional`:``:e===`C`?t>.7?`disciplined`:t<.3?`flexible`:``:e===`E`?t>.7?`charismatic`:t<.3?`reserved`:``:e===`A`?t>.7?`cooperative`:t<.3?`competitive`:``:e===`Em`?t>.7?`empathetic`:t<.3?`calm`:``:e===`HH`?t>.7?`sincere`:t<.3?`strategic`:``:``}function ww({label:e,shortLabel:t,value:n,onChange:r,sideColor:i}){let a=Cw(t,n),o=i||`var(--amber)`,s={flex:1,accentColor:o,"--pc-range-fill":o,"--pc-range-pct":`${Math.round(n*100)}%`};return(0,x.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`6px`},children:[(0,x.jsx)(`label`,{style:{fontSize:`var(--font-sm)`,color:`var(--text-2)`,minWidth:`32px`,fontWeight:700},children:t}),(0,x.jsx)(`input`,{type:`range`,min:`0`,max:`1`,step:`0.05`,value:n,onChange:e=>r(parseFloat(e.target.value)),className:`pc-range`,style:s,"aria-label":e,"aria-valuetext":n.toFixed(2)}),(0,x.jsx)(`span`,{style:{fontSize:`var(--font-md)`,fontFamily:`var(--mono)`,minWidth:`36px`,textAlign:`right`,color:`var(--text-1)`,fontWeight:600},children:n.toFixed(2)}),(0,x.jsx)(`span`,{style:{fontSize:`var(--font-3xs)`,color:`var(--text-3)`,minWidth:`55px`,fontFamily:`var(--mono)`},children:a})]})}var Tw={notice:`_notice_9kjix_1`,badge:`_badge_9kjix_16`,body:`_body_9kjix_30`,headline:`_headline_9kjix_35`,copy:`_copy_9kjix_43`,links:`_links_9kjix_56`,link:`_link_9kjix_56`};function Ew(){return(0,x.jsxs)(`div`,{className:Tw.notice,role:`note`,"aria-label":`Pluggable trait models`,children:[(0,x.jsx)(`span`,{className:Tw.badge,"aria-hidden":`true`,children:`NEW`}),(0,x.jsxs)(`div`,{className:Tw.body,children:[(0,x.jsx)(`div`,{className:Tw.headline,children:`Leaders accept pluggable trait models.`}),(0,x.jsxs)(`p`,{className:Tw.copy,children:[`The dashboard form below configures HEXACO leaders today. The API also accepts `,(0,x.jsx)(`code`,{children:`ai-agent`}),` leaders (six axes for AI-system decision-makers: exploration, verification-rigor, deference, risk-tolerance, transparency, instruction-following). Slider generalization for non-HEXACO models is queued; in the meantime, supply a`,` `,(0,x.jsx)(`code`,{children:`traitProfile`}),` field via`,` `,(0,x.jsx)(`code`,{children:`runSimulation(leader, ...)`}),` directly.`]}),(0,x.jsxs)(`div`,{className:Tw.links,children:[(0,x.jsx)(`a`,{href:`https://github.com/framerslab/paracosm/blob/master/docs/COOKBOOK.md#pluggable-traits-ai-agent-end-to-end`,target:`_blank`,rel:`noopener`,className:Tw.link,children:`Captured ai-agent end-to-end run`}),(0,x.jsx)(`a`,{href:`https://github.com/framerslab/paracosm/blob/master/docs/COOKBOOK.md#pluggable-traits-ai-agent-end-to-end`,target:`_blank`,rel:`noopener`,className:Tw.link,children:`Trait-model cookbook`})]})]})]})}var Dw={root:`_root_5ydsz_1`,heading:`_heading_5ydsz_11`,fieldRow:`_fieldRow_5ydsz_23`,field:`_field_5ydsz_23`,label:`_label_5ydsz_33`,presetLabel:`_presetLabel_5ydsz_33`,input:`_input_5ydsz_44`,presetSelect:`_presetSelect_5ydsz_44`,textarea:`_textarea_5ydsz_44`,textareaBlock:`_textareaBlock_5ydsz_61`,presetRow:`_presetRow_5ydsz_72`,hexacoGrid:`_hexacoGrid_5ydsz_91`},Ow=[{key:`openness`,label:`Openness`,short:`O`},{key:`conscientiousness`,label:`Conscientiousness`,short:`C`},{key:`extraversion`,label:`Extraversion`,short:`E`},{key:`agreeableness`,label:`Agreeableness`,short:`A`},{key:`emotionality`,label:`Emotionality`,short:`Em`},{key:`honestyHumility`,label:`Honesty-Humility`,short:`HH`}],kw=[{id:`visionary`,label:`The Visionary (high O, low C)`,hexaco:{openness:.95,conscientiousness:.35,extraversion:.85,agreeableness:.55,emotionality:.3,honestyHumility:.65}},{id:`engineer`,label:`The Engineer (high C, low O)`,hexaco:{openness:.25,conscientiousness:.97,extraversion:.3,agreeableness:.6,emotionality:.7,honestyHumility:.9}},{id:`diplomat`,label:`The Diplomat (high A, high HH)`,hexaco:{openness:.6,conscientiousness:.55,extraversion:.7,agreeableness:.9,emotionality:.5,honestyHumility:.85}},{id:`maverick`,label:`The Maverick (high O, high E, low A)`,hexaco:{openness:.9,conscientiousness:.4,extraversion:.95,agreeableness:.25,emotionality:.2,honestyHumility:.4}},{id:`guardian`,label:`The Guardian (high C, high Em, high HH)`,hexaco:{openness:.3,conscientiousness:.85,extraversion:.4,agreeableness:.7,emotionality:.85,honestyHumility:.95}},{id:`strategist`,label:`The Strategist (balanced, low Em)`,hexaco:{openness:.65,conscientiousness:.75,extraversion:.5,agreeableness:.45,emotionality:.2,honestyHumility:.55}},{id:`balanced`,label:`Balanced (all 0.50)`,hexaco:{openness:.5,conscientiousness:.5,extraversion:.5,agreeableness:.5,emotionality:.5,honestyHumility:.5}}];function Aw({label:e,sideColor:t,data:n,onChange:r}){let i=(0,b.useId)(),a=`${i}-name`,o=`${i}-archetype`,s=`${i}-unit`,c=`${i}-instructions`,l=`${i}-preset`,u=(e,t)=>r({...n,[e]:t}),d=(e,t)=>r({...n,hexaco:{...n.hexaco,[e]:t}});return(0,x.jsxs)(`div`,{className:Dw.root,style:{"--side-color":t},children:[(0,x.jsx)(`h3`,{className:Dw.heading,children:e}),(0,x.jsxs)(`div`,{className:`responsive-stack ${Dw.fieldRow}`,children:[(0,x.jsxs)(`div`,{className:Dw.field,children:[(0,x.jsx)(`label`,{htmlFor:a,className:Dw.label,children:`Name`}),(0,x.jsx)(`input`,{id:a,value:n.name,onChange:e=>u(`name`,e.target.value),className:Dw.input})]}),(0,x.jsxs)(`div`,{className:Dw.field,children:[(0,x.jsx)(`label`,{htmlFor:o,className:Dw.label,children:`Archetype`}),(0,x.jsx)(`input`,{id:o,value:n.archetype,onChange:e=>u(`archetype`,e.target.value),className:Dw.input})]}),(0,x.jsxs)(`div`,{className:Dw.field,children:[(0,x.jsx)(`label`,{htmlFor:s,className:Dw.label,children:`Unit`}),(0,x.jsx)(`input`,{id:s,value:n.unit,onChange:e=>u(`unit`,e.target.value),className:Dw.input})]})]}),(0,x.jsxs)(`div`,{className:Dw.textareaBlock,children:[(0,x.jsx)(`label`,{htmlFor:c,className:Dw.label,children:`Instructions`}),(0,x.jsx)(`textarea`,{id:c,value:n.instructions,onChange:e=>u(`instructions`,e.target.value),rows:3,className:Dw.textarea})]}),(0,x.jsx)(Ew,{}),(0,x.jsxs)(`div`,{className:Dw.presetRow,children:[(0,x.jsx)(`label`,{htmlFor:l,className:Dw.presetLabel,children:`Personality`}),(0,x.jsxs)(`select`,{id:l,className:`pc-select ${Dw.presetSelect}`,onChange:e=>{let t=kw.find(t=>t.id===e.target.value);t&&r({...n,hexaco:{...t.hexaco}})},defaultValue:``,children:[(0,x.jsx)(`option`,{value:``,disabled:!0,children:`Apply preset...`}),kw.map(e=>(0,x.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),(0,x.jsx)(`div`,{className:`responsive-grid-3 ${Dw.hexacoGrid}`,children:Ow.map(e=>(0,x.jsx)(ww,{label:e.label,shortLabel:e.short,value:n.hexaco[e.key]??.5,onChange:t=>d(e.key,t),sideColor:t},e.key))})]})}function jw(e){let t={scenario:e.scenario,webSearch:e.webSearch},n=e.seedUrl.trim(),r=e.seedText.trim(),i=e.provider?.trim(),a=e.model?.trim(),o=Number.parseInt(e.maxSearches,10);return n?t.seedUrl=n:r&&(t.seedText=r),Number.isFinite(o)&&o>0&&(t.maxSearches=o),i&&(t.provider=i),a&&(t.model=a),t}async function Mw(e){if(e.ok)return null;try{let t=await e.json();if(typeof t.error==`string`&&t.error.length>0)return t.error}catch{}return`The compile was refused (HTTP ${e.status}).`}var Nw={display:`block`,fontFamily:`var(--mono)`,fontSize:11,fontWeight:700,letterSpacing:`0.08em`,textTransform:`uppercase`,color:`var(--text-3)`,marginBottom:4},Pw={fontFamily:`var(--mono)`,fontSize:13,fontWeight:800,letterSpacing:`0.08em`,textTransform:`uppercase`,color:`var(--text-2)`},Fw={width:`100%`,padding:`6px 10px`,background:`var(--bg-card)`,color:`var(--text-3)`,border:`1px solid var(--border)`,borderRadius:3,cursor:`pointer`,fontFamily:`var(--mono)`,fontSize:10,fontWeight:800,letterSpacing:`0.08em`,textTransform:`uppercase`},Iw={card:`_card_m5xbp_1`,header:`_header_m5xbp_10`,title:`_title_m5xbp_20`,lead:`_lead_m5xbp_28`,btnRow:`_btnRow_m5xbp_34`,btn:`_btn_m5xbp_34`,amber:`_amber_m5xbp_53`,fileInput:`_fileInput_m5xbp_58`,editorWrap:`_editorWrap_m5xbp_62`,editor:`_editor_m5xbp_62`,statusBar:`_statusBar_m5xbp_83`,seedDetails:`_seedDetails_m5xbp_93`,seedSummary:`_seedSummary_m5xbp_97`,seedBody:`_seedBody_m5xbp_105`,input:`_input_m5xbp_112`,textarea:`_textarea_m5xbp_123`,checkboxLabel:`_checkboxLabel_m5xbp_136`,fineprint:`_fineprint_m5xbp_144`,progressWrap:`_progressWrap_m5xbp_151`,progressRow:`_progressRow_m5xbp_157`,progressStatus:`_progressStatus_m5xbp_166`,result:`_result_m5xbp_170`,actions:`_actions_m5xbp_178`,actionBtn:`_actionBtn_m5xbp_186`,primary:`_primary_m5xbp_203`,spacer:`_spacer_m5xbp_214`,memCount:`_memCount_m5xbp_218`},Lw={id:`my-scenario`,version:`1.0.0`,engineArchetype:`closed_turn_based_settlement`,labels:{name:`My Scenario`,shortName:`custom`,populationNoun:`agents`,settlementNoun:`settlement`,currency:`credits`},theme:{primaryColor:`#6366f1`,accentColor:`#818cf8`},setup:{defaultTurns:8,defaultSeed:100,defaultStartTime:2040,defaultPopulation:50,configurableSections:[`actors`,`departments`,`models`]},departments:[{id:`operations`,label:`Operations`,role:`Operations Lead`,icon:``,defaultModel:`gpt-5.4-mini`,instructions:`You analyze operations.`},{id:`research`,label:`Research`,role:`Head of Research`,icon:``,defaultModel:`gpt-5.4-mini`,instructions:`You analyze research.`}],metrics:[{id:`population`,label:`Population`,source:`metrics.population`,format:`number`}],effects:{environmental:{morale:.08},resource:{morale:.05}},ui:{headerMetrics:[{id:`population`,format:`number`}],tooltipFields:[],reportSections:[`crisis`],departmentIcons:{},setupSections:[`actors`]},policies:{toolForging:{enabled:!0},liveSearch:{enabled:!1,mode:`off`},bulletin:{enabled:!0},characterChat:{enabled:!0},sandbox:{timeoutMs:1e4,memoryMB:128}},presets:[]},Rw=`paracosm:editorCompileResult`;function zw(){try{let e=window.sessionStorage.getItem(Rw);if(!e)return null;let t=JSON.parse(e);return typeof t.message==`string`?{success:t.success===!0,message:t.message}:null}catch{return null}}function Bw({onAdminWrite:e}){let[t,n]=(0,b.useState)({adminWrite:!1,memoryScenarios:[]}),[r,i]=(0,b.useState)(``),[a,o]=(0,b.useState)(``),[s,c]=(0,b.useState)(``),[l,u]=(0,b.useState)(``),[d,f]=(0,b.useState)(!0),[p,m]=(0,b.useState)(`5`),[h,g]=(0,b.useState)(``),[_,v]=(0,b.useState)(``),[y,S]=(0,b.useState)(!1),[C,w]=(0,b.useState)(!1),[T,O]=(0,b.useState)([]),[k,A]=(0,b.useState)(()=>zw()),j=(0,b.useRef)(null),ee=(0,b.useRef)(null);(0,b.useEffect)(()=>{fetch(`/admin-config`).then(e=>e.json()).then(t=>{n(t),e?.(t.adminWrite===!0)}).catch(()=>{});try{window.sessionStorage.removeItem(Rw)}catch{}},[]);let M=(0,b.useCallback)(()=>{fetch(`/scenario`).then(e=>e.ok?e.json():null).then(e=>{e?.id&&i(JSON.stringify(e,null,2))}).catch(()=>{})},[]);(0,b.useEffect)(()=>(M(),D(window,M)),[M]),(0,b.useEffect)(()=>{if(!r.trim())o(``);else try{JSON.parse(r),o(``)}catch(e){o(String(e).replace(`SyntaxError: `,``))}},[r]);let N=()=>i(JSON.stringify(Lw,null,2)),ne=(0,b.useCallback)(async()=>{try{let e=await(await fetch(`/scenario`)).json();i(JSON.stringify(e,null,2)),A({success:!0,message:`Loaded active scenario: ${e.labels?.name||e.id}`})}catch(e){A({success:!1,message:`Failed to load: ${e}`})}},[]),P=()=>j.current?.click(),re=e=>{let t=e.target.files?.[0];if(!t)return;let n=new FileReader;n.onload=()=>{let e=n.result;i(e);try{JSON.parse(e),A({success:!0,message:`Imported ${t.name} (${(t.size/1024).toFixed(1)}KB)`})}catch{A({success:!1,message:`Imported ${t.name} but JSON is invalid`})}},n.readAsText(t),e.target.value=``},ie=()=>{if(r.trim())try{let e=JSON.parse(r),t=e.id||`scenario`,n=new Blob([JSON.stringify(e,null,2)],{type:`application/json`}),i=URL.createObjectURL(n),a=document.createElement(`a`);a.href=i,a.download=`${t}.json`,a.click(),URL.revokeObjectURL(i),A({success:!0,message:`Exported ${t}.json`})}catch{A({success:!1,message:`Fix JSON errors before exporting`})}},F=(0,b.useCallback)(async()=>{if(r.trim()&&!a){w(!0);try{let e=JSON.parse(r),t=await(await fetch(`/scenario/store`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scenario:e,saveToDisk:!1})})).json();t.stored?(E(window),A({success:!0,message:t.switchable?`Stored "${t.id}" in memory and added it to the scenario selector.`:`Stored "${t.id}" as draft JSON in memory. Compile it to make it runnable and switchable.`}),n(e=>({...e,memoryScenarios:[...new Set([...e.memoryScenarios,t.id])]}))):A({success:!1,message:t.error||`Store failed`})}catch(e){A({success:!1,message:String(e)})}w(!1)}},[r,a]),I=(0,b.useCallback)(async()=>{if(r.trim()&&!a&&t.adminWrite)try{let e=JSON.parse(r),t=B(),n=xe(t);if(n){A({success:!1,message:n});return}let i=await fetch(`/scenario/store`,{method:`POST`,headers:{"Content-Type":`application/json`,...t?{[fe]:t}:{}},body:JSON.stringify({scenario:e,saveToDisk:!0})}),a=await i.json();a.savedToDisk?(E(window),A({success:!0,message:a.switchable?`Saved "${a.id}" to disk at scenarios/${a.id}.json and loaded it into the live scenario catalog.`:`Saved "${a.id}" draft JSON to disk at scenarios/${a.id}.json. Compile it to make it runnable after restart.`})):i.status===401?(be(t),A({success:!1,message:`Disk write refused: the admin token is missing or wrong. ${R}`})):A({success:!1,message:a.error||`Disk write refused (HTTP ${i.status})`})}catch(e){A({success:!1,message:String(e)})}},[r,a,t.adminWrite]),ae=(0,b.useCallback)(async()=>{if(!r.trim()||a)return;let e;try{e=JSON.parse(r)}catch{A({success:!1,message:`Fix JSON errors before compiling`});return}S(!0),O([]),A(null);try{let t=jw({scenario:e,seedText:s,seedUrl:l,webSearch:d,maxSearches:p,provider:h,model:_}),n=await fetch(`/compile`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)}),r=await Mw(n);if(r!==null){A({success:!1,message:r}),S(!1);return}let i=n.body?.getReader();if(!i)throw Error(`No response stream`);let a=new TextDecoder,o=``;for(;;){let{done:e,value:t}=await i.read();if(e)break;o+=a.decode(t,{stream:!0});let n=o.split(`
124
+ `)}function mS(e,t){if(t.format!==`percent`)return e;let n=t.max??t.initial;return n===void 0||n<=1?e*100:e}function hS(e,t){if(t.format===`percent`)return`${Math.round(mS(e,t))}%`;if(t.format===`number`){let t=Math.round(e*10)/10;return Number.isInteger(t)?String(t):t.toFixed(1)}return String(e)}var gS={bar:`_bar_1gubl_1`,crisis:`_crisis_1gubl_18`,pill:`_pill_1gubl_29`,label:`_label_1gubl_39`,value:`_value_1gubl_52`,valueB:`_valueB_1gubl_52`,valueA:`_valueA_1gubl_52`,delta:`_delta_1gubl_65`,deltaNeutral:`_deltaNeutral_1gubl_65`,deltaNegative:`_deltaNegative_1gubl_65`,deltaPositive:`_deltaPositive_1gubl_65`,sep:`_sep_1gubl_81`,causesChip:`_causesChip_1gubl_86`};function _S(e){return e===`foodMonthsReserve`?`mo`:``}var vS={population:`POP`,morale:`MORALE`,foodMonthsReserve:`FOOD`,powerKw:`POWER`,infrastructureModules:`MODULES`,scienceOutput:`SCIENCE`,hullIntegrity:`HULL`,oxygenReserveHours:`O2`},yS={population:`P`,morale:`M`,foodMonthsReserve:`F`,powerKw:`W`,infrastructureModules:`I`,scienceOutput:`S`,hullIntegrity:`H`,oxygenReserveHours:`O₂`};function bS(e,t){if(t==null)return``;let n=Math.round((e-t)*100)/100;return n===0?``:n>0?`+${n}`:`${n}`}function xS(e,t){return e?t===`neutral`?gS.deltaNeutral:t===`lossIsRed`?e.startsWith(`-`)?gS.deltaPositive:gS.deltaNegative:e.startsWith(`+`)?gS.deltaPositive:gS.deltaNegative:``}function SS(e){if(!e)return``;let t=Object.entries(e).filter(([,e])=>e>0).sort((e,t)=>t[1]-e[1]);if(t.length===0)return``;let n=t.slice(0,3).map(([e,t])=>`${t} ${e.replace(`radiation cancer`,`radiation`).replace(`natural causes`,`age`).replace(`age-related complications`,`age`).replace(`fatal fracture`,`fracture`).replace(`accident: `,``).replace(`accident`,`accident`)}`),r=t.length-n.length;return r>0?`${n.join(` · `)} +${r}`:n.join(` · `)}function CS({actors:e,crisisText:t,toolRegistry:n}){let r=Qk(),i=e[0],a=e[1],o=i?.state,s=a?.state,c=o?.metrics??null,l=s?.metrics??null,u=o?.prevMetrics??null,d=s?.prevMetrics??null,f=o?.deaths??0,p=s?.deaths??0,m=o?.deathCauses,h=s?.deathCauses,g=o?.tools??0,_=s?.tools??0,v=o?.citations??0,y=s?.citations??0,S=i?.id??``,C=a?.id??``,w=o?.statuses,T=s?.statuses,E=o?.environment,D=s?.environment,{reuseA:O,reuseB:k}=(0,b.useMemo)(()=>{let e=0,t=0;for(let r of n?.list??[])for(let n=1;n<r.history.length;n++){let i=r.history[n];i.rejected||(i.actorName===S?e++:i.actorName===C&&t++)}return{reuseA:e,reuseB:t}},[n,S,C]),A=(0,b.useRef)({toolsA:g,toolsB:_,reuseA:O,reuseB:k,citationsA:v,citationsB:y,deathsA:f,deathsB:p}),j=A.current,ee=bS(g,j.toolsA),te=bS(_,j.toolsB),M=bS(O,j.reuseA),N=bS(k,j.reuseB),ne=bS(v,j.citationsA),P=bS(y,j.citationsB),re=bS(f,j.deathsA),ie=bS(p,j.deathsB);if((0,b.useEffect)(()=>{A.current={toolsA:g,toolsB:_,reuseA:O,reuseB:k,citationsA:v,citationsB:y,deathsA:f,deathsB:p}},[g,_,O,k,v,y,f,p]),!c&&!l)return null;let F=r.ui.headerMetrics.filter(e=>e.id!==`population`&&e.id!==`morale`).slice(0,4),I=Pe(0),ae=Pe(1);return(0,x.jsxs)(`div`,{className:`stats-bar ${gS.bar}`,role:`region`,"aria-label":`Leader statistics`,tabIndex:0,style:{"--actor-color-a":I,"--actor-color-b":ae},children:[t&&(0,x.jsx)(`span`,{className:gS.crisis,children:t}),F.map(e=>{let t=c?.[e.id]??0,n=l?.[e.id]??0,r=t=>t==null?void 0:mS(t,e),i=bS(mS(t,e),r(u?.[e.id])),a=bS(mS(n,e),r(d?.[e.id])),o=hS(t,e),s=hS(n,e),f=_S(e.id),p=vS[e.id]||e.id.replace(/([A-Z])/g,` $1`).trim().toUpperCase(),m=yS[e.id]||p.charAt(0);return(0,x.jsxs)(`span`,{className:gS.pill,children:[(0,x.jsxs)(`span`,{className:gS.label,title:p,children:[(0,x.jsx)(`span`,{className:`pill-label-full`,children:p}),(0,x.jsx)(`span`,{className:`pill-label-short`,children:m})]}),(0,x.jsxs)(`span`,{className:gS.valueA,children:[o,f]}),i&&(0,x.jsx)(`span`,{className:xS(i,`gain`),children:i}),(0,x.jsx)(`span`,{className:gS.sep,children:`vs`}),(0,x.jsxs)(`span`,{className:gS.valueB,children:[s,f]}),a&&(0,x.jsx)(`span`,{className:xS(a,`gain`),children:a})]},e.id)}),(0,x.jsxs)(`span`,{className:gS.pill,children:[(0,x.jsxs)(`span`,{className:gS.label,title:`Deaths`,children:[(0,x.jsx)(`span`,{className:`pill-label-full`,children:`DEATHS`}),(0,x.jsx)(`span`,{className:`pill-label-short`,children:`†`})]}),(0,x.jsx)(`span`,{className:gS.valueA,title:m&&Object.keys(m).length>0?`Leader A deaths by cause: ${Object.entries(m).map(([e,t])=>`${t} ${e}`).join(`, `)}`:void 0,children:f}),re&&(0,x.jsx)(`span`,{className:xS(re,`lossIsRed`),children:re}),(0,x.jsx)(`span`,{className:gS.sep,children:`vs`}),(0,x.jsx)(`span`,{className:gS.valueB,title:h&&Object.keys(h).length>0?`Leader B deaths by cause: ${Object.entries(h).map(([e,t])=>`${t} ${e}`).join(`, `)}`:void 0,children:p}),ie&&(0,x.jsx)(`span`,{className:xS(ie,`lossIsRed`),children:ie}),(()=>{let e=SS(m),t=SS(h);return!e&&!t?null:(0,x.jsxs)(`span`,{className:gS.causesChip,children:[`(`,e||`0`,` / `,t||`0`,`)`]})})()]}),(0,x.jsxs)(`span`,{className:gS.pill,children:[(0,x.jsxs)(`span`,{className:gS.label,title:`Tools forged`,children:[(0,x.jsx)(`span`,{className:`pill-label-full`,children:`TOOLS`}),(0,x.jsx)(`span`,{className:`pill-label-short`,children:`T`})]}),(0,x.jsx)(`span`,{className:gS.valueA,children:g}),ee&&(0,x.jsx)(`span`,{className:gS.deltaPositive,children:ee}),(0,x.jsx)(`span`,{className:gS.sep,children:`/`}),(0,x.jsx)(`span`,{className:gS.valueB,children:_}),te&&(0,x.jsx)(`span`,{className:gS.deltaPositive,children:te})]}),n&&n.list.length>0&&(0,x.jsxs)(`span`,{className:gS.pill,title:`Forged-tool reuse count per leader. Reuses amortize forge cost across multiple events.`,children:[(0,x.jsxs)(`span`,{className:gS.label,title:`Reuse count`,children:[(0,x.jsx)(`span`,{className:`pill-label-full`,children:`REUSE`}),(0,x.jsx)(`span`,{className:`pill-label-short`,children:`R`})]}),(0,x.jsx)(`span`,{className:gS.valueA,children:O}),M&&(0,x.jsx)(`span`,{className:gS.deltaPositive,children:M}),(0,x.jsx)(`span`,{className:gS.sep,children:`/`}),(0,x.jsx)(`span`,{className:gS.valueB,children:k}),N&&(0,x.jsx)(`span`,{className:gS.deltaPositive,children:N})]}),(0,x.jsxs)(`span`,{className:gS.pill,children:[(0,x.jsxs)(`span`,{className:gS.label,title:`Citations`,children:[(0,x.jsx)(`span`,{className:`pill-label-full`,children:`CITES`}),(0,x.jsx)(`span`,{className:`pill-label-short`,children:`C`})]}),(0,x.jsx)(`span`,{className:gS.valueA,children:v}),ne&&(0,x.jsx)(`span`,{className:xS(ne,`neutral`),children:ne}),(0,x.jsx)(`span`,{className:gS.sep,children:`/`}),(0,x.jsx)(`span`,{className:gS.valueB,children:y}),P&&(0,x.jsx)(`span`,{className:xS(P,`neutral`),children:P})]}),(w||T)&&(0,x.jsxs)(`span`,{className:gS.pill,title:`Categorical scenario-declared statuses (world.statuses).\n\nLeader A:\n${pS(w)||`(none)`}\n\nLeader B:\n${pS(T)||`(none)`}`,children:[(0,x.jsxs)(`span`,{className:gS.label,children:[(0,x.jsx)(`span`,{className:`pill-label-full`,children:`STATUSES`}),(0,x.jsx)(`span`,{className:`pill-label-short`,children:`§`})]}),(0,x.jsx)(`span`,{className:gS.valueA,children:w?Object.keys(w).length:0}),(0,x.jsx)(`span`,{className:gS.sep,children:`/`}),(0,x.jsx)(`span`,{className:gS.valueB,children:T?Object.keys(T).length:0})]}),(E||D)&&(0,x.jsxs)(`span`,{className:gS.pill,title:`Environment bag (world.environment), external conditions.\n\nLeader A:\n${pS(E)||`(none)`}\n\nLeader B:\n${pS(D)||`(none)`}`,children:[(0,x.jsxs)(`span`,{className:gS.label,children:[(0,x.jsx)(`span`,{className:`pill-label-full`,children:`ENV`}),(0,x.jsx)(`span`,{className:`pill-label-short`,children:`E`})]}),(0,x.jsx)(`span`,{className:gS.valueA,children:E?Object.keys(E).length:0}),(0,x.jsx)(`span`,{className:gS.sep,children:`/`}),(0,x.jsx)(`span`,{className:gS.valueB,children:D?Object.keys(D).length:0})]})]})}var wS={timelineRow:`_timelineRow_iwf5k_1`,sideWrap:`_sideWrap_iwf5k_36`,sideHeader:`_sideHeader_iwf5k_55`,sideHeaderIdx:`_sideHeaderIdx_iwf5k_66`,sideHeaderName:`_sideHeaderName_iwf5k_75`,sideHeaderArchetype:`_sideHeaderArchetype_iwf5k_86`,side:`_side_iwf5k_36`,outcomeBadge:`_outcomeBadge_iwf5k_109`,tooltipHeader:`_tooltipHeader_iwf5k_120`,tooltipTurn:`_tooltipTurn_iwf5k_127`,tooltipTime:`_tooltipTime_iwf5k_132`,tooltipCategory:`_tooltipCategory_iwf5k_138`,tooltipEmergent:`_tooltipEmergent_iwf5k_147`,tooltipTitle:`_tooltipTitle_iwf5k_154`,tooltipSummary:`_tooltipSummary_iwf5k_161`,tooltipDecision:`_tooltipDecision_iwf5k_168`,tooltipDecisionLabel:`_tooltipDecisionLabel_iwf5k_177`,tooltipOutcome:`_tooltipOutcome_iwf5k_185`,entry:`_entry_iwf5k_193`,current:`_current_iwf5k_205`,glow:`_glow_iwf5k_1`,entryHead:`_entryHead_iwf5k_209`,entryTurn:`_entryTurn_iwf5k_217`,entryTitle:`_entryTitle_iwf5k_225`,entryCategory:`_entryCategory_iwf5k_235`,entryEmergent:`_entryEmergent_iwf5k_245`,entrySummary:`_entrySummary_iwf5k_253`,entrySubEvents:`_entrySubEvents_iwf5k_265`,entrySubEventRow:`_entrySubEventRow_iwf5k_272`,entrySubIdx:`_entrySubIdx_iwf5k_277`,entryDecision:`_entryDecision_iwf5k_284`};function TS(e,t){let n=[],r=e;for(let e of r.events){if(e.type===`turn_start`&&e.data.title&&e.data.title!==`Director generating...`&&n.push({turn:e.data.turn,time:e.data.time,title:e.data.title,summary:e.data.turnSummary||e.data.crisis||``,category:e.data.category||``,emergent:e.data.emergent||!1}),e.type===`event_start`){let t=e.data.turn,r=n.find(e=>e.turn===t);r&&(r.subEvents||=[],r.subEvents.push({index:Number(e.data.eventIndex??0),title:String(e.data.title||``),category:String(e.data.category||``)}))}if(e.type===`outcome`){let t=n.find(t=>t.turn===e.data.turn);t&&(t.outcome=e.data.outcome,t.decision=e.data._decision||``)}}return n.length&&(n[n.length-1].current=!t),n}function ES(e){if(!e)return{label:``,color:`var(--text-3)`};let t=e.includes(`success`);return{label:e.includes(`risky`)?t?`RISKY WIN`:`RISKY LOSS`:t?`SAFE WIN`:`SAFE LOSS`,color:t?`var(--green)`:`var(--rust)`}}function DS(e){if(!e)return null;let{color:t}=ES(e),n=e.includes(`success`),r=e.includes(`risky`)?n?`RS`:`RF`:n?`CS`:`CF`;return(0,x.jsx)(`span`,{className:wS.outcomeBadge,style:{"--status-color":t,"--status-bg":`transparent`},children:r})}function OS({t:e,sideColor:t}){let{label:n,color:r}=ES(e.outcome),i={"--side-color":t};return(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:wS.tooltipHeader,children:[(0,x.jsxs)(`b`,{className:wS.tooltipTurn,style:i,children:[`Turn `,e.turn]}),(0,x.jsxs)(`span`,{className:wS.tooltipTime,children:[`Y`,e.time]}),e.category&&(0,x.jsx)(`span`,{className:wS.tooltipCategory,children:e.category}),e.emergent&&(0,x.jsx)(`span`,{className:wS.tooltipEmergent,children:`EMERGENT`})]}),(0,x.jsx)(`div`,{className:wS.tooltipTitle,children:e.title}),e.summary&&(0,x.jsx)(`div`,{className:wS.tooltipSummary,children:e.summary}),e.decision&&(0,x.jsxs)(`div`,{className:wS.tooltipDecision,children:[(0,x.jsx)(`span`,{className:wS.tooltipDecisionLabel,style:i,children:`Decision: `}),e.decision]}),e.outcome&&(0,x.jsx)(`div`,{className:wS.tooltipOutcome,style:{"--outcome-color":r},children:n})]})}function kS({turns:e,actorIndex:t}){let n=Pe(t),r={"--side-color":n},i=(0,b.useRef)(null),a=(0,b.useRef)(!0);return(0,b.useEffect)(()=>{if(!a.current)return;let e=i.current;e&&e.scrollTo({top:e.scrollHeight,behavior:`smooth`})},[e.length]),(0,x.jsx)(`div`,{ref:i,onScroll:()=>{let e=i.current;e&&(a.current=e.scrollHeight-e.scrollTop-e.clientHeight<40)},className:wS.side,children:e.map(e=>(0,x.jsx)(Sx,{dot:!0,content:(0,x.jsx)(OS,{t:e,sideColor:n}),children:(0,x.jsxs)(`div`,{className:[wS.entry,e.current?wS.current:``].filter(Boolean).join(` `),style:r,children:[(0,x.jsxs)(`div`,{className:wS.entryHead,children:[(0,x.jsxs)(`span`,{className:wS.entryTurn,style:r,children:[`T`,e.turn,` `,e.time]}),(0,x.jsx)(`span`,{className:wS.entryTitle,children:e.title}),e.category&&(0,x.jsx)(`span`,{className:wS.entryCategory,children:e.category}),e.emergent&&(0,x.jsx)(`span`,{className:wS.entryEmergent,children:`EMERGENT`}),DS(e.outcome)]}),e.summary&&(0,x.jsx)(`div`,{className:wS.entrySummary,children:e.summary}),e.subEvents&&e.subEvents.length>1&&(0,x.jsx)(`div`,{className:wS.entrySubEvents,children:e.subEvents.map((e,t)=>(0,x.jsxs)(`div`,{className:wS.entrySubEventRow,children:[(0,x.jsxs)(`span`,{className:wS.entrySubIdx,children:[e.index+1,`.`]}),(0,x.jsx)(`span`,{children:e.title})]},t))}),e.decision&&!e.subEvents?.length&&(0,x.jsx)(`div`,{className:wS.entryDecision,children:e.decision})]})},e.turn))})}function AS({state:e}){let t=e.actorIds.map((t,n)=>{let r=e.actors[t];return{id:t,idx:n,turns:r?TS(r,e.isComplete):[],name:r?.leader?.name??t,archetype:r?.leader?.archetype}});return t.every(e=>e.turns.length===0)?null:(0,x.jsx)(`div`,{className:`timeline-row ${wS.timelineRow}`,role:`region`,"aria-label":`Turn timeline`,children:t.map(e=>{let t=Pe(e.idx);return(0,x.jsxs)(`div`,{className:wS.sideWrap,style:{"--side-color":t},children:[(0,x.jsxs)(`header`,{className:wS.sideHeader,children:[(0,x.jsxs)(`span`,{className:wS.sideHeaderIdx,children:[`A`,e.idx+1]}),(0,x.jsx)(`span`,{className:wS.sideHeaderName,title:e.name,children:e.name}),e.archetype&&(0,x.jsx)(`span`,{className:wS.sideHeaderArchetype,title:e.archetype,children:e.archetype})]}),(0,x.jsx)(kS,{turns:e.turns,actorIndex:e.idx})]},e.id)})})}var jS={risky_success:{bg:`rgba(232,180,74,.12)`,color:`var(--vis)`,border:`var(--amber-dim)`,label:`RISKY WIN`},risky_failure:{bg:`rgba(224,101,48,.12)`,color:`var(--rust)`,border:`var(--rust-dim)`,label:`RISKY LOSS`},conservative_success:{bg:`rgba(106,173,72,.12)`,color:`var(--green)`,border:`rgba(106,173,72,.25)`,label:`SAFE WIN`},conservative_failure:{bg:`rgba(224,101,48,.08)`,color:`var(--rust)`,border:`var(--rust-dim)`,label:`SAFE LOSS`}};function MS({outcome:e}){let t=jS[e]||{bg:`var(--bg-card)`,color:`var(--text-3)`,border:`var(--border)`,label:e.replace(/_/g,` `).toUpperCase()};return(0,x.jsx)(`span`,{style:{padding:`3px 10px`,borderRadius:`4px`,fontSize:`var(--font-xs)`,fontWeight:800,fontFamily:`var(--mono)`,display:`inline-block`,whiteSpace:`nowrap`,background:t.bg,color:t.color,border:`1px solid ${t.border}`},children:t.label})}var NS={row:`_row_1v4rw_1`,inline:`_inline_1v4rw_11`,label:`_label_1v4rw_17`,pill:`_pill_1v4rw_27`,popoverWrap:`_popoverWrap_1v4rw_41`,popoverHeader:`_popoverHeader_1v4rw_45`,popoverText:`_popoverText_1v4rw_54`,popoverUrlRow:`_popoverUrlRow_1v4rw_61`,popoverUrl:`_popoverUrl_1v4rw_61`,popoverDoi:`_popoverDoi_1v4rw_72`,popoverProvenance:`_popoverProvenance_1v4rw_78`,popoverHint:`_popoverHint_1v4rw_87`};function PS({citations:e,label:t=`sources`,inline:n=!1}){let r=h_();if(!e||e.length===0)return null;let i=new Set,a=[];for(let t of e){let e=(t.url||``).trim(),n=(t.text||``).trim();if(!e&&!n||!e&&n===`Seed document`)continue;let o=e||n,s=r.getNumber(o);if(s===0||i.has(s))continue;i.add(s);let c=r.getEntry(o);a.push({n:s,entry:c??{text:n||e,url:e,doi:t.doi}})}return a.length===0?null:(0,x.jsxs)(`div`,{className:[NS.row,n?NS.inline:``].filter(Boolean).join(` `),children:[t&&(0,x.jsx)(`span`,{className:NS.label,children:t}),a.map(({n:e,entry:t})=>(0,x.jsx)(FS,{n:e,entry:t},e))]})}function FS({n:e,entry:t}){let n=t.url||``,r=t.text||n||`Source [${e}]`,i=t.doi,a=t.departments?[...t.departments]:[],o=t.actorNames?[...t.actorNames]:[],s=(0,x.jsxs)(`div`,{className:NS.popoverWrap,children:[(0,x.jsxs)(`div`,{className:NS.popoverHeader,children:[`REFERENCE [`,e,`]`]}),(0,x.jsx)(`div`,{className:NS.popoverText,children:r}),n&&(0,x.jsx)(`div`,{className:NS.popoverUrlRow,children:(0,x.jsx)(`a`,{href:n,target:`_blank`,rel:`noopener noreferrer`,className:NS.popoverUrl,children:n})}),i&&(0,x.jsxs)(`div`,{className:NS.popoverDoi,children:[`DOI:`,i]}),(a.length>0||o.length>0)&&(0,x.jsxs)(`div`,{className:NS.popoverProvenance,children:[a.length>0&&(0,x.jsxs)(x.Fragment,{children:[`cited by `,a.join(`, `),` · `]}),o.length>0&&(0,x.jsxs)(x.Fragment,{children:[`leader `,o.join(` · `)]})]}),(0,x.jsx)(`div`,{className:NS.popoverHint,children:`Click to open source · or scroll to References below`})]});return(0,x.jsx)(Sx,{content:s,children:(0,x.jsxs)(`a`,{href:n||`#cite-${e}`,target:n?`_blank`:void 0,rel:n?`noopener noreferrer`:void 0,onClick:t=>{let r=document.getElementById(`cite-${e}`);r&&(n||t.preventDefault(),r.scrollIntoView({behavior:`smooth`,block:`center`}),r.style.transition=`background 0.4s`,r.style.background=`rgba(232,180,74,0.18)`,setTimeout(()=>{r.style.background=``},1200))},className:NS.pill,children:[`[`,e,`]`]})})}var J={eventStartRow:`_eventStartRow_1d0sd_1`,notFirst:`_notFirst_1d0sd_9`,eventNumber:`_eventNumber_1d0sd_14`,eventStartTitle:`_eventStartTitle_1d0sd_21`,eventCategoryPill:`_eventCategoryPill_1d0sd_26`,promotionTooltipTitle:`_promotionTooltipTitle_1d0sd_35`,promotionTooltipRow:`_promotionTooltipRow_1d0sd_42`,promotionTooltipKey:`_promotionTooltipKey_1d0sd_46`,promotionTooltipValue:`_promotionTooltipValue_1d0sd_50`,promotionTooltipReason:`_promotionTooltipReason_1d0sd_55`,promotionRow:`_promotionRow_1d0sd_60`,promotionArrow:`_promotionArrow_1d0sd_70`,promotionRole:`_promotionRole_1d0sd_75`,promotionReason:`_promotionReason_1d0sd_81`,forgeBtn:`_forgeBtn_1d0sd_90`,forgeSlide:`_forgeSlide_1d0sd_1`,forgeRow:`_forgeRow_1d0sd_110`,forgeBadge:`_forgeBadge_1d0sd_117`,forgeDept:`_forgeDept_1d0sd_130`,forgeDescription:`_forgeDescription_1d0sd_136`,forgeName:`_forgeName_1d0sd_141`,forgeVerdictPass:`_forgeVerdictPass_1d0sd_147`,forgeVerdictFail:`_forgeVerdictFail_1d0sd_159`,forgeFieldsRow:`_forgeFieldsRow_1d0sd_171`,fieldsLabelIn:`_fieldsLabelIn_1d0sd_181`,fieldsLabelOut:`_fieldsLabelOut_1d0sd_185`,forgeError:`_forgeError_1d0sd_189`,specWrap:`_specWrap_1d0sd_196`,specCard:`_specCard_1d0sd_200`,specHeader:`_specHeader_1d0sd_209`,specHeaderDept:`_specHeaderDept_1d0sd_217`,specToolCount:`_specToolCount_1d0sd_225`,severityBadge:`_severityBadge_1d0sd_231`,specSummary:`_specSummary_1d0sd_241`,specSummaryEmpty:`_specSummaryEmpty_1d0sd_248`,specRisks:`_specRisks_1d0sd_256`,specRisksLabel:`_specRisksLabel_1d0sd_260`,specRiskRow:`_specRiskRow_1d0sd_269`,specRiskSeverity:`_specRiskSeverity_1d0sd_278`,specRecs:`_specRecs_1d0sd_287`,specRecsLabel:`_specRecsLabel_1d0sd_291`,specRecRow:`_specRecRow_1d0sd_300`,toolDetail:`_toolDetail_1d0sd_309`,newTool:`_newTool_1d0sd_320`,forgeGlow:`_forgeGlow_1d0sd_1`,reused:`_reused_1d0sd_324`,toolSummary:`_toolSummary_1d0sd_328`,toolSummaryMain:`_toolSummaryMain_1d0sd_336`,toolSummaryHead:`_toolSummaryHead_1d0sd_341`,toolNewBadge:`_toolNewBadge_1d0sd_348`,toolReusedBadge:`_toolReusedBadge_1d0sd_361`,toolFirstForged:`_toolFirstForged_1d0sd_374`,toolSchemaBadge:`_toolSchemaBadge_1d0sd_380`,toolDescription:`_toolDescription_1d0sd_390`,toolNameLine:`_toolNameLine_1d0sd_397`,toolPassPill:`_toolPassPill_1d0sd_405`,toolFailPill:`_toolFailPill_1d0sd_418`,toolInspectBtn:`_toolInspectBtn_1d0sd_431`,toolBody:`_toolBody_1d0sd_449`,toolMetaRow:`_toolMetaRow_1d0sd_454`,toolMetaLabel:`_toolMetaLabel_1d0sd_459`,toolRawSummary:`_toolRawSummary_1d0sd_466`,toolRawPre:`_toolRawPre_1d0sd_474`,toolEmpty:`_toolEmpty_1d0sd_489`,outcomeCard:`_outcomeCard_1d0sd_494`,decisionPulse:`_decisionPulse_1d0sd_1`,outcomeHead:`_outcomeHead_1d0sd_505`,outcomeLabel:`_outcomeLabel_1d0sd_512`,outcomeMeta:`_outcomeMeta_1d0sd_520`,outcomeText:`_outcomeText_1d0sd_527`,outcomeDeltas:`_outcomeDeltas_1d0sd_533`,outcomeDeltaSpan:`_outcomeDeltaSpan_1d0sd_540`,outcomeBar:`_outcomeBar_1d0sd_544`,outcomeBarDeparts:`_outcomeBarDeparts_1d0sd_552`,outcomeReasoningSummary:`_outcomeReasoningSummary_1d0sd_556`,outcomeReasoningBody:`_outcomeReasoningBody_1d0sd_563`,outcomeReasoningPre:`_outcomeReasoningPre_1d0sd_570`,outcomeRationale:`_outcomeRationale_1d0sd_582`,outcomePolicyLine:`_outcomePolicyLine_1d0sd_587`,driftRow:`_driftRow_1d0sd_591`,driftLabel:`_driftLabel_1d0sd_599`,driftName:`_driftName_1d0sd_607`,reactionsCard:`_reactionsCard_1d0sd_611`,reactionsHead:`_reactionsHead_1d0sd_620`,reactionsLabel:`_reactionsLabel_1d0sd_627`,reactionsBar:`_reactionsBar_1d0sd_636`,reactionsBarSegment:`_reactionsBarSegment_1d0sd_645`,reactionsLegend:`_reactionsLegend_1d0sd_650`,reactionsLegendItem:`_reactionsLegendItem_1d0sd_657`,reactionsLegendSwatch:`_reactionsLegendSwatch_1d0sd_663`,reactionsQuotesSummary:`_reactionsQuotesSummary_1d0sd_671`,reactionsQuotesList:`_reactionsQuotesList_1d0sd_679`,reactionTooltipName:`_reactionTooltipName_1d0sd_686`,reactionTooltipMeta:`_reactionTooltipMeta_1d0sd_692`,reactionTooltipHexaco:`_reactionTooltipHexaco_1d0sd_697`,reactionTooltipHealth:`_reactionTooltipHealth_1d0sd_704`,reactionTooltipQuote:`_reactionTooltipQuote_1d0sd_709`,reactionTooltipMoodLine:`_reactionTooltipMoodLine_1d0sd_717`,reactionTooltipBeliefs:`_reactionTooltipBeliefs_1d0sd_724`,reactionRow:`_reactionRow_1d0sd_730`,notLast:`_notLast_1d0sd_739`,reactionRowName:`_reactionRowName_1d0sd_743`,reactionRowQuote:`_reactionRowQuote_1d0sd_750`,reactionRowMoodPill:`_reactionRowMoodPill_1d0sd_761`,bulletinWrap:`_bulletinWrap_1d0sd_773`,bulletinTooltipName:`_bulletinTooltipName_1d0sd_777`,bulletinTooltipRole:`_bulletinTooltipRole_1d0sd_781`,bulletinTooltipBody:`_bulletinTooltipBody_1d0sd_786`,bulletinTooltipMood:`_bulletinTooltipMood_1d0sd_792`,bulletinRow:`_bulletinRow_1d0sd_798`,bulletinName:`_bulletinName_1d0sd_807`,bulletinPost:`_bulletinPost_1d0sd_813`,bulletinLikes:`_bulletinLikes_1d0sd_822`,turnDone:`_turnDone_1d0sd_828`,fallbackBox:`_fallbackBox_1d0sd_841`,fallbackTitle:`_fallbackTitle_1d0sd_853`,fallbackSite:`_fallbackSite_1d0sd_859`,fallbackPreviewWrap:`_fallbackPreviewWrap_1d0sd_864`,fallbackPreviewSummary:`_fallbackPreviewSummary_1d0sd_868`,fallbackPreviewPre:`_fallbackPreviewPre_1d0sd_874`,schemaBlock:`_schemaBlock_1d0sd_885`,schemaFieldsLabel:`_schemaFieldsLabel_1d0sd_889`,schemaFieldsList:`_schemaFieldsList_1d0sd_897`,schemaTitle:`_schemaTitle_1d0sd_902`,schemaTable:`_schemaTable_1d0sd_911`,schemaRow:`_schemaRow_1d0sd_919`,schemaKeyCell:`_schemaKeyCell_1d0sd_923`,schemaRequired:`_schemaRequired_1d0sd_931`,schemaTypeCell:`_schemaTypeCell_1d0sd_936`,schemaDescCell:`_schemaDescCell_1d0sd_943`,forgeDetails:`_forgeDetails_1d0sd_951`,forgeSummary:`_forgeSummary_1d0sd_963`,forgeInspectAbs:`_forgeInspectAbs_1d0sd_980`,forgeBody:`_forgeBody_1d0sd_998`,specDetails:`_specDetails_1d0sd_1003`,specSummaryRow:`_specSummaryRow_1d0sd_1012`,specBody:`_specBody_1d0sd_1029`,reactionsDetails:`_reactionsDetails_1d0sd_1035`,reactionsSummary:`_reactionsSummary_1d0sd_1043`,reactionsTopMood:`_reactionsTopMood_1d0sd_1060`,reactionsBody:`_reactionsBody_1d0sd_1068`,bulletinDetails:`_bulletinDetails_1d0sd_1073`,bulletinSummary:`_bulletinSummary_1d0sd_1077`,bulletinSummaryLabel:`_bulletinSummaryLabel_1d0sd_1095`,bulletinSummaryNames:`_bulletinSummaryNames_1d0sd_1105`,bulletinBody:`_bulletinBody_1d0sd_1115`,fallbackDetails:`_fallbackDetails_1d0sd_1119`,fallbackSummary:`_fallbackSummary_1d0sd_1130`},IS={positive:`var(--green)`,negative:`var(--rust)`,anxious:`var(--amber)`,defiant:`var(--rust)`,hopeful:`var(--green)`,resigned:`var(--text-3)`,neutral:`var(--text-2)`},LS={positive:`#6aad48`,negative:`#e06530`,anxious:`#e8b44a`,defiant:`#e06530`,hopeful:`#6aad48`,resigned:`#a89878`,neutral:`#a89878`};function RS({event:e,actorIndex:t,actorSlot:n}){let r=Qk(),i=ev(),a=n??t,o=Pe(t),s={"--side-color":o},c=e.data;switch(e.type){case`turn_start`:return null;case`event_start`:{let e=Number(c.eventIndex??0),t=Number(c.totalEvents??1),n=String(c.title||``),r=String(c.category||``);return t<=1?null:(0,x.jsxs)(`div`,{id:`sim-event-${a}-${Number(c.turn??0)}-${e}`,tabIndex:-1,className:[J.eventStartRow,e>0?J.notFirst:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`span`,{className:J.eventNumber,children:[`EVENT `,e+1,`/`,t]}),(0,x.jsx)(`span`,{className:J.eventStartTitle,children:n}),r&&(0,x.jsx)(`span`,{className:J.eventCategoryPill,children:r})]})}case`promotion`:{let e=String(c.reason||``),t=String(c.name||``),n=String(c.role||``);return(0,x.jsx)(Sx,{content:(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`b`,{className:J.promotionTooltipTitle,style:s,children:[`Promotion: `,n]}),t&&(0,x.jsxs)(`div`,{className:J.promotionTooltipRow,children:[(0,x.jsx)(`span`,{className:J.promotionTooltipKey,children:`Agent:`}),` `,(0,x.jsx)(`span`,{className:J.promotionTooltipValue,children:t})]}),e&&(0,x.jsx)(`div`,{className:J.promotionTooltipReason,children:e})]}),children:(0,x.jsxs)(`div`,{className:J.promotionRow,children:[(0,x.jsx)(`span`,{className:J.promotionArrow,children:`→`}),(0,x.jsx)(`span`,{className:J.promotionRole,style:s,children:n}),(0,x.jsx)(`span`,{className:J.promotionReason,children:e})]})})}case`specialist_start`:case`decision_pending`:return null;case`forge_attempt`:{let e=String(c.department||``),t=String(c.name||`unnamed`),n=String(c.description||t),r=String(c.mode||`sandbox`),s=c.approved!==!1,l=typeof c.confidence==`number`?c.confidence:.85,u=c.errorReason?String(c.errorReason):``,d=s?o:`var(--rust)`,f=Array.isArray(c.inputFields)?c.inputFields:[],p=Array.isArray(c.outputFields)?c.outputFields:[],m={"--accent":d,"--bg-tint":s?`color-mix(in srgb, ${o} 7%, transparent)`:`rgba(224,101,48,0.04)`,"--border-tint":s?`color-mix(in srgb, ${o} 25%, transparent)`:`rgba(224,101,48,0.2)`,"--shadow-tint":s?`0 0 0 1px color-mix(in srgb, ${o} 10%, transparent)`:`var(--card-shadow)`,"--badge-color":s?`var(--bg-deep)`:`#fff`,"--badge-bg":d,"--badge-shadow":s?`0 0 8px rgba(232,180,74,0.4)`:`none`};return(0,x.jsx)(x.Fragment,{children:(0,x.jsxs)(`details`,{className:J.forgeDetails,style:m,children:[(0,x.jsx)(`summary`,{className:J.forgeSummary,children:(0,x.jsxs)(`span`,{className:J.forgeRow,children:[(0,x.jsx)(`span`,{className:J.forgeBadge,children:s?`✦ FORGED TOOL`:`↻ FORGE RETRY`}),(0,x.jsx)(`span`,{className:J.forgeDept,children:e}),(0,x.jsx)(`span`,{className:J.forgeDescription,children:n}),(0,x.jsxs)(`span`,{className:J.forgeName,children:[t,` (`,r,`)`]}),(0,x.jsx)(`span`,{className:s?J.forgeVerdictPass:J.forgeVerdictFail,children:s?`PASS ${l.toFixed(2)}`:`RETRY`})]})}),(0,x.jsx)(`button`,{type:`button`,onClick:e=>i.openTrace({actorIndex:a,toolName:t},e.currentTarget,`inspect`),"aria-label":`Inspect forged tool ${t}`,className:J.forgeInspectAbs,children:`INSPECT`}),(0,x.jsxs)(`div`,{className:J.forgeBody,children:[(f.length>0||p.length>0)&&(0,x.jsxs)(`div`,{className:J.forgeFieldsRow,children:[f.length>0&&(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`span`,{className:J.fieldsLabelIn,children:`in:`}),` `,f.join(`, `)]}),p.length>0&&(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`span`,{className:J.fieldsLabelOut,children:`out:`}),` `,p.join(`, `)]})]}),!s&&u&&(0,x.jsx)(`div`,{className:J.forgeError,children:u})]})]})})}case`specialist_done`:{let e=String(c.department||``),t=c._filteredTools||[],n=t.filter(e=>e?.isNew!==!0),s=Array.isArray(c.risks)?c.risks:[],l=Array.isArray(c.recommendedActions)?c.recommendedActions.map(String):[],u=s.some(e=>e.severity===`critical`)?`critical`:s.some(e=>e.severity===`high`)?`high`:``,d=String(c.summary||``),f=Number(c.citations)||0;if(!d&&s.length===0&&l.length===0&&t.length===0&&f===0)return null;let p={"--card-bg":u===`critical`?`rgba(224,101,48,.08)`:u===`high`?`rgba(232,180,74,.06)`:`var(--bg-card)`,"--card-border":u===`critical`?`rgba(224,101,48,.25)`:u===`high`?`rgba(232,180,74,.2)`:`var(--border)`,"--card-accent":u===`critical`?`var(--rust)`:u===`high`?`var(--amber)`:`var(--teal)`},m=u?{"--sev-color":u===`critical`?`var(--rust)`:`var(--amber)`,"--sev-bg":u===`critical`?`rgba(224,101,48,.15)`:`rgba(232,180,74,.1)`}:void 0;return(0,x.jsx)(x.Fragment,{children:(0,x.jsxs)(`div`,{className:J.specWrap,children:[(0,x.jsxs)(`details`,{className:J.specDetails,style:p,children:[(0,x.jsxs)(`summary`,{className:J.specSummaryRow,children:[(0,x.jsxs)(`span`,{className:J.specHeaderDept,children:[r.ui.departmentIcons[e]||``,` `,e]}),t.length>0&&(0,x.jsxs)(`span`,{className:J.specToolCount,children:[`+`,t.length,` tool`,t.length===1?``:`s`,n.length<t.length&&` (${n.length} reused)`]}),u&&(0,x.jsxs)(`span`,{className:J.severityBadge,style:m,children:[u.toUpperCase(),` RISK`]}),(0,x.jsx)(PS,{citations:c.citationList||[],inline:!0,label:``})]}),(0,x.jsxs)(`div`,{className:J.specBody,children:[d?(0,x.jsx)(`div`,{className:J.specSummary,children:d}):s.length===0&&l.length===0&&(f>0||t.length>0)?(0,x.jsxs)(`div`,{className:J.specSummaryEmpty,children:[`Department analysis complete — no narrative summary returned, but`,f>0&&` ${f} source${f===1?``:`s`} surveyed`,f>0&&t.length>0&&` and `,t.length>0&&` ${t.length} tool${t.length===1?``:`s`} forged`,`.`]}):null,s.length>0&&(0,x.jsxs)(`div`,{className:J.specRisks,children:[(0,x.jsx)(`div`,{className:J.specRisksLabel,children:`RISKS`}),s.slice(0,3).map((e,t)=>(0,x.jsxs)(`div`,{className:J.specRiskRow,children:[(0,x.jsx)(`span`,{className:J.specRiskSeverity,style:{"--risk-color":e.severity===`critical`||e.severity===`high`?`var(--rust)`:`var(--amber)`},children:String(e.severity||`med`).toUpperCase()}),(0,x.jsx)(`span`,{children:String(e.description||``)})]},t))]}),l.length>0&&(0,x.jsxs)(`div`,{className:J.specRecs,children:[(0,x.jsx)(`div`,{className:J.specRecsLabel,children:`RECOMMENDATIONS`}),l.slice(0,3).map((e,t)=>(0,x.jsx)(`div`,{className:J.specRecRow,children:e},t))]})]})]}),n.map((e,t)=>{let n=e.approved!==!1,r=e.isNew===!0,s=n?r?o:`var(--green)`:`var(--rust)`,c=n?r?`color-mix(in srgb, ${o} 10%, transparent)`:`rgba(106,173,72,.06)`:`rgba(224,101,48,.04)`,l=n?r?`color-mix(in srgb, ${o} 40%, transparent)`:`rgba(106,173,72,.2)`:`rgba(224,101,48,.15)`,u=r?`0 0 0 1px color-mix(in srgb, ${o} 15%, transparent), var(--card-shadow)`:`var(--card-shadow)`,d=e.inputSchema,f=e.outputSchema,p=!!d||!!f,m={"--tool-bg":c,"--tool-border":l,"--tool-accent":s,"--tool-shadow":u,"--side-color":o},h=[J.toolDetail,r?J.newTool:J.reused].join(` `);return(0,x.jsxs)(`details`,{className:h,style:m,children:[(0,x.jsxs)(`summary`,{className:J.toolSummary,children:[(0,x.jsxs)(`div`,{className:J.toolSummaryMain,children:[(0,x.jsxs)(`div`,{className:J.toolSummaryHead,children:[r?(0,x.jsx)(`span`,{className:J.toolNewBadge,children:`FORGED TOOL`}):(0,x.jsx)(`span`,{className:J.toolReusedBadge,children:`REUSED`}),!r&&e.firstForgedTurn!=null&&(0,x.jsxs)(`span`,{className:J.toolFirstForged,children:[`first forged T`,e.firstForgedTurn,e.firstForgedDepartment&&e.firstForgedDepartment!==e.department?` · ${e.firstForgedDepartment}`:``]}),p&&(0,x.jsx)(`span`,{className:J.toolSchemaBadge,children:`SCHEMA`})]}),(0,x.jsx)(`span`,{className:J.toolDescription,children:String(e.description||e.name||``)}),(0,x.jsxs)(`span`,{className:J.toolNameLine,children:[e.name,` `,e.mode?`(${e.mode})`:``]})]}),(0,x.jsx)(`span`,{className:n?J.toolPassPill:J.toolFailPill,children:n?`PASS ${(typeof e.confidence==`number`?e.confidence:.85).toFixed(2)}`:`RETRY`})]}),(0,x.jsx)(`button`,{type:`button`,onClick:t=>{t.preventDefault(),t.stopPropagation(),i.openTrace({actorIndex:a,toolName:String(e.name||``)},t.currentTarget,`inspect`)},"aria-label":`Inspect tool ${e.name||``}`,className:J.toolInspectBtn,children:`INSPECT`}),(0,x.jsxs)(`div`,{className:J.toolBody,children:[e.crisis&&(0,x.jsxs)(`div`,{className:J.toolMetaRow,children:[(0,x.jsx)(`span`,{className:J.toolMetaLabel,children:`CRISIS: `}),String(e.crisis)]}),e.department&&(0,x.jsxs)(`div`,{className:J.toolMetaRow,children:[(0,x.jsx)(`span`,{className:J.toolMetaLabel,children:`DEPT: `}),String(e.department)]}),(d||Array.isArray(e.inputFields)&&e.inputFields.length>0)&&(0,x.jsx)(BS,{label:`INPUT`,color:`var(--teal)`,schema:d,fields:e.inputFields}),(f||Array.isArray(e.outputFields)&&e.outputFields.length>0)&&(0,x.jsx)(BS,{label:`OUTPUT`,color:`var(--green)`,schema:f,fields:e.outputFields}),e.output&&(0,x.jsxs)(`details`,{children:[(0,x.jsx)(`summary`,{className:J.toolRawSummary,style:{"--side-color":o},children:`Raw Output`}),(0,x.jsx)(`pre`,{className:J.toolRawPre,children:typeof e.output==`object`?JSON.stringify(e.output,null,2):String(e.output)})]}),!e.output&&!d&&!f&&(!e.inputFields||e.inputFields.length===0)&&(0,x.jsx)(`div`,{className:J.toolEmpty,children:`Tool forged but no output captured. The tool will be available for subsequent turns.`})]})]},t)})]})})}case`outcome`:{let e=String(c.outcome||``),n=String(c._decision||``),r=String(c._rationale||``),i=String(c._reasoning||``),a=c._policies||[],s=c._barCheck,l={...c.systemDeltas,...c.politicsDeltas},u=String(c.turn||``),d=Number(c._toolCount??0),f=Number(c._citeCount??0),p={"--side-color":o,"--outcome-bg":t===0?`rgba(232,180,74,.06)`:`rgba(76,168,168,.06)`,"--outcome-border":t===0?`var(--amber-dim)`:`var(--teal-dim)`};return(0,x.jsxs)(`div`,{className:J.outcomeCard,style:p,children:[(0,x.jsxs)(`div`,{className:J.outcomeHead,children:[(0,x.jsxs)(`span`,{children:[(0,x.jsxs)(`span`,{className:J.outcomeLabel,children:[`DECISION #`,u]}),(0,x.jsxs)(`span`,{className:J.outcomeMeta,children:[d,` tools · `,f,` citations`]})]}),(0,x.jsx)(MS,{outcome:e})]}),(0,x.jsx)(`div`,{className:J.outcomeText,children:n}),s&&(0,x.jsx)(`div`,{className:s.departs?`${J.outcomeBar} ${J.outcomeBarDeparts}`:J.outcomeBar,children:zS(s)}),Object.keys(l).length>0&&(0,x.jsx)(`div`,{className:J.outcomeDeltas,children:Object.entries(l).map(([e,t])=>(0,x.jsxs)(`span`,{className:J.outcomeDeltaSpan,children:[e,` `,t>0?`+`:``,typeof t==`number`?Number.isInteger(t)?t:t.toFixed(2):t,` · `]},e))}),(r||i||a.length>0)&&(0,x.jsxs)(`details`,{children:[(0,x.jsx)(`summary`,{className:J.outcomeReasoningSummary,children:`Full reasoning & policies`}),(0,x.jsxs)(`div`,{className:J.outcomeReasoningBody,children:[i&&(0,x.jsx)(`div`,{className:J.outcomeReasoningPre,children:i}),n&&(0,x.jsx)(`div`,{children:n}),r&&(0,x.jsx)(`div`,{className:J.outcomeRationale,children:r}),a.map((e,t)=>(0,x.jsxs)(`div`,{className:J.outcomePolicyLine,children:[`→ `,e]},t))]})]})]})}case`personality_drift`:{let e=Object.values(c.agents||{});return e.length?(0,x.jsxs)(`div`,{className:J.driftRow,children:[(0,x.jsx)(`span`,{className:J.driftLabel,children:`DRIFT `}),e.slice(0,3).map((t,n)=>(0,x.jsxs)(`span`,{children:[(0,x.jsx)(`span`,{className:J.driftName,style:s,children:t.name?.split(` `)[0]}),` `,`O`,t.hexaco?.O??`?`,` C`,t.hexaco?.C??`?`,n<Math.min(e.length,3)-1?` · `:``]},n))]}):null}case`agent_reactions`:{let e=c.reactions||[],t=c.totalReactions||e.length;if(!e.length)return null;let n={};for(let t of e)n[t.mood]=(n[t.mood]||0)+1;let r=Object.entries(n).sort((e,t)=>t[1]-e[1]).map(([t,n])=>({mood:t,count:n,pct:Math.round(n/e.length*100),bg:LS[t]||`#a89878`}));return(0,x.jsxs)(`details`,{className:J.reactionsDetails,children:[(0,x.jsxs)(`summary`,{className:J.reactionsSummary,children:[(0,x.jsxs)(`span`,{className:J.reactionsLabel,style:s,children:[t,` VOICES`]}),(0,x.jsx)(`div`,{className:J.reactionsBar,children:r.map(e=>(0,x.jsx)(`div`,{className:J.reactionsBarSegment,style:{"--seg-flex":String(e.pct),"--seg-bg":e.bg},title:`${e.pct}% ${e.mood}`},e.mood))}),(0,x.jsx)(`span`,{className:J.reactionsTopMood,children:r[0]?`${r[0].pct}% ${r[0].mood}`:``})]}),(0,x.jsxs)(`div`,{className:J.reactionsBody,children:[(0,x.jsx)(`div`,{className:J.reactionsLegend,children:r.slice(0,3).map(e=>(0,x.jsxs)(`span`,{className:J.reactionsLegendItem,children:[(0,x.jsx)(`span`,{className:J.reactionsLegendSwatch,style:{"--swatch-bg":e.bg}}),e.pct,`% `,e.mood]},e.mood))}),(0,x.jsxs)(`details`,{children:[(0,x.jsxs)(`summary`,{className:J.reactionsQuotesSummary,style:s,children:[`quotes (`,e.length,`)`]}),(0,x.jsx)(`div`,{className:J.reactionsQuotesList,children:e.slice(0,4).map((t,n)=>(0,x.jsx)(Sx,{dot:!0,content:(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`b`,{className:J.reactionTooltipName,style:s,children:t.name}),(0,x.jsxs)(`div`,{className:J.reactionTooltipMeta,children:[t.role,` in `,t.department,` `,t.age?`· Age ${t.age}`:``]}),(0,x.jsxs)(`div`,{className:J.reactionTooltipHexaco,children:[`O:`,t.hexaco?.O,` C:`,t.hexaco?.C,` E:`,t.hexaco?.E,` A:`,t.hexaco?.A,` Em:`,t.hexaco?.Em,` HH:`,t.hexaco?.HH]}),(0,x.jsxs)(`div`,{className:J.reactionTooltipHealth,children:[`Bone: `,t.boneDensity,`% · Radiation: `,t.radiation,`mSv · Psych: `,t.psychScore]}),(0,x.jsxs)(`div`,{className:J.reactionTooltipQuote,children:[`“`,t.quote,`”`]}),(0,x.jsxs)(`div`,{className:J.reactionTooltipMoodLine,style:{"--mood-color":IS[t.mood]||`var(--text-3)`},children:[String(t.mood||``).toUpperCase(),` · intensity `,t.intensity?.toFixed?.(2)||`?`]}),t.memory?.beliefs?.length>0&&(0,x.jsxs)(`div`,{className:J.reactionTooltipBeliefs,children:[`Beliefs: `,t.memory.beliefs.slice(0,2).join(`; `)]})]}),children:(0,x.jsxs)(`div`,{className:[J.reactionRow,n<Math.min(e.length,4)-1?J.notLast:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`span`,{className:J.reactionRowName,style:s,children:t.name}),(0,x.jsxs)(`span`,{className:J.reactionRowQuote,children:[`“`,String(t.quote||``),`”`]}),(0,x.jsx)(`span`,{className:J.reactionRowMoodPill,style:{"--mood-color":IS[t.mood]||`var(--text-3)`},children:String(t.mood||``).toUpperCase()})]})},n))})]})]})]})}case`bulletin`:{let e=c.posts||[];return e.length?(0,x.jsxs)(`details`,{className:J.bulletinDetails,children:[(0,x.jsxs)(`summary`,{className:J.bulletinSummary,children:[(0,x.jsxs)(`span`,{className:J.bulletinSummaryLabel,children:[e.length,` POSTS`]}),(0,x.jsxs)(`span`,{className:J.bulletinSummaryNames,children:[e.slice(0,2).map(e=>String(e.name??``).split(` `)[0]).filter(Boolean).join(` · `),e.length>2?` +${e.length-2}`:``]})]}),(0,x.jsx)(`div`,{className:J.bulletinBody,children:e.slice(0,3).map((e,t)=>(0,x.jsx)(Sx,{dot:!0,content:(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`b`,{className:J.bulletinTooltipName,style:s,children:e.name}),` `,(0,x.jsxs)(`span`,{className:J.bulletinTooltipRole,children:[e.role,` `,e.department]}),(0,x.jsx)(`div`,{className:J.bulletinTooltipBody,children:e.post}),(0,x.jsxs)(`div`,{className:J.bulletinTooltipMood,style:{"--mood-color":IS[e.mood]||`var(--text-3)`},children:[String(e.mood||``).toUpperCase(),` · `,e.likes||0,` likes · `,e.replies||0,` replies`]})]}),children:(0,x.jsxs)(`div`,{className:J.bulletinRow,children:[(0,x.jsx)(`span`,{className:J.bulletinName,style:s,children:e.name}),(0,x.jsx)(`span`,{className:J.bulletinPost,children:String(e.post||``)}),(0,x.jsxs)(`span`,{className:J.bulletinLikes,children:[`♥`,e.likes||0]})]})},t))})]}):null}case`turn_done`:return null;case`validation_fallback`:{let e=String(c.schemaName||`<unknown>`),t=String(c.site||``),n=String(c.rawTextPreview||``),r=c.salvaged===!0,i=Array.isArray(c.droppedKeys)?c.droppedKeys.map(e=>String(e)):[];return(0,x.jsxs)(`details`,{className:J.fallbackDetails,style:s,children:[(0,x.jsxs)(`summary`,{className:J.fallbackSummary,children:[(0,x.jsxs)(`span`,{className:J.fallbackTitle,children:[`⚠ `,r?`SCHEMA SALVAGE`:`SCHEMA FALLBACK`,` — `,e]}),(0,x.jsxs)(`span`,{className:J.fallbackSite,children:[`site: `,t||`n/a`]}),r&&(0,x.jsxs)(`span`,{className:J.fallbackSite,children:[`kept without: `,i.length>0?i.join(`, `):`n/a`]})]}),n&&(0,x.jsxs)(`details`,{className:J.fallbackPreviewWrap,children:[(0,x.jsx)(`summary`,{className:J.fallbackPreviewSummary,children:`Raw output preview`}),(0,x.jsx)(`pre`,{className:J.fallbackPreviewPre,children:n})]})]})}default:return null}}function zS(e){let t=e.clearsBar?`clears it`:`is under it`,n=e.choseBold?`the bold option was taken`:`the bold option was refused`;if(!e.departs)return`Bar ${e.bar}: the bold option's chance ${e.boldChance} ${t}, so ${n}`;let r=e.departureFact?`, for: ${e.departureFact}`:`, with no fact named for it`;return`Bar ${e.bar}: the bold option's chance ${e.boldChance} ${t}, yet ${n}${r}`}function BS({label:e,color:t,schema:n,fields:r}){let i=n&&typeof n==`object`&&n.properties||null,a=n&&typeof n==`object`&&Array.isArray(n.required)?n.required:[];if(!i)return!r||r.length===0?null:(0,x.jsxs)(`div`,{className:J.schemaBlock,children:[(0,x.jsxs)(`span`,{className:J.schemaFieldsLabel,style:{"--field-color":t},children:[e,` FIELDS:`,` `]}),(0,x.jsx)(`span`,{className:J.schemaFieldsList,children:r.join(`, `)})]});let o=Object.entries(i).slice(0,12);return(0,x.jsxs)(`div`,{className:J.schemaBlock,children:[(0,x.jsxs)(`div`,{className:J.schemaTitle,style:{"--field-color":t},children:[e,` SCHEMA`]}),(0,x.jsx)(`table`,{className:J.schemaTable,children:(0,x.jsx)(`tbody`,{children:o.map(([e,n])=>{let r=String(n?.type??`any`),i=typeof n?.description==`string`?n.description:``,o=a.includes(e);return(0,x.jsxs)(`tr`,{className:J.schemaRow,children:[(0,x.jsxs)(`td`,{className:J.schemaKeyCell,children:[e,o&&(0,x.jsx)(`span`,{className:J.schemaRequired,children:`*`})]}),(0,x.jsx)(`td`,{className:J.schemaTypeCell,style:{"--field-color":t},children:r}),(0,x.jsx)(`td`,{className:J.schemaDescCell,children:i})]},e)})})})]})}var VS={badge:`_badge_1lgt8_1`,same:`_same_1lgt8_15`,differentOutcome:`_differentOutcome_1lgt8_21`,differentEvent:`_differentEvent_1lgt8_27`,pending:`_pending_1lgt8_33`,oneSided:`_oneSided_1lgt8_40`},HS={same:`✓ SAME`,"different-outcome":`⚠ DIFFERENT OUTCOME`,"different-event":`⚠ DIFFERENT EVENT`,pending:`… running`,"one-sided":`· · · waiting`},US={same:`Same event, same outcome`,"different-outcome":`Same event, different outcome`,"different-event":`Different events`,pending:`Turn is still running`,"one-sided":`Only one leader has reached this turn`},WS={same:VS.same,"different-outcome":VS.differentOutcome,"different-event":VS.differentEvent,pending:VS.pending,"one-sided":VS.oneSided};function GS({classification:e}){return(0,x.jsx)(`span`,{className:`${VS.badge} ${WS[e]}`,"aria-label":US[e],children:HS[e]})}var KS={row:`_row_rngwb_1`,differentOutcome:`_differentOutcome_rngwb_9`,differentEvent:`_differentEvent_rngwb_13`,header:`_header_rngwb_17`,headerTurn:`_headerTurn_rngwb_30`,headerTitle:`_headerTitle_rngwb_36`,headerTitleSplit:`_headerTitleSplit_rngwb_45`,headerTitleA:`_headerTitleA_rngwb_52`,headerTitleB:`_headerTitleB_rngwb_61`,cells:`_cells_rngwb_70`,cell:`_cell_rngwb_70`,cellBand:`_cellBand_rngwb_82`,cellEmpty:`_cellEmpty_rngwb_92`,cellPending:`_cellPending_rngwb_99`,cellPendingSpinner:`_cellPendingSpinner_rngwb_110`},qS=new Set([`turn_start`,`specialist_start`,`decision_pending`]);function JS(e){let t=new Set,n=!1;for(let r of e)if(r.type===`specialist_start`){let e=r.data?.department;typeof e==`string`&&e.length>0&&t.add(e)}else r.type===`decision_pending`&&(n=!0);let r=[];return t.size>0&&r.push(`${[...t].join(`, `)} analyzing`),n&&r.push(`awaiting decision`),r.length>0?r.join(` · `)+`…`:`Working on this turn…`}function YS({entry:e,eventsA:t,eventsB:n,runTerminal:r,runAborted:i}){let a=`${KS.row} ${e.classification===`different-outcome`?KS.differentOutcome:e.classification===`different-event`?KS.differentEvent:``}`,o=e.titleA===e.titleB&&e.titleA!==``;return(0,x.jsxs)(`section`,{id:`turn-row-${e.turn}`,className:a,"aria-labelledby":`turn-row-${e.turn}-h`,children:[(0,x.jsxs)(`h3`,{id:`turn-row-${e.turn}-h`,className:KS.header,tabIndex:-1,children:[(0,x.jsxs)(`span`,{className:KS.headerTurn,children:[`T`,e.turn]}),(0,x.jsx)(GS,{classification:e.classification}),o?(0,x.jsx)(`span`,{className:KS.headerTitle,children:e.titleA}):(0,x.jsxs)(`span`,{className:KS.headerTitleSplit,children:[(0,x.jsx)(`span`,{className:KS.headerTitleA,children:e.titleA||`—`}),(0,x.jsx)(`span`,{className:KS.headerTitleB,children:e.titleB||`—`})]})]}),(0,x.jsx)(`div`,{className:KS.cells,children:[t,n].map((t,n)=>{let a=t.filter(e=>!qS.has(e.type)),o=t.length>0&&a.length===0,s=t.length===0&&e.classification===`one-sided`&&!r;return(0,x.jsxs)(`div`,{className:KS.cell,style:{"--cell-color":Pe(n)},"aria-label":`Leader ${n===0?`A`:`B`} events for this turn`,children:[(0,x.jsx)(`span`,{className:KS.cellBand,"aria-hidden":`true`}),t.length===0?s?(0,x.jsxs)(`div`,{className:KS.cellPending,"aria-live":`polite`,title:`Parallel runs can drift turn-to-turn — events arrive whenever this side's LLM calls finish.`,children:[(0,x.jsx)(`span`,{className:`spinner ${KS.cellPendingSpinner}`,"aria-hidden":`true`}),`Catching up to turn `,e.turn,`…`]}):r?(0,x.jsx)(`div`,{className:KS.cellEmpty,title:i?`Run was interrupted before this side reached this turn.`:`No event recorded for this side on this turn.`,children:i?`Stopped before T${e.turn}`:`No event for T${e.turn}`}):(0,x.jsx)(`div`,{className:KS.cellEmpty,children:`(no events yet)`}):o?r?(0,x.jsx)(`div`,{className:KS.cellEmpty,title:i?`Run was interrupted while this turn was still processing.`:`No outcome recorded for this side on this turn.`,children:i?`Stopped during T${e.turn}`:`T${e.turn} ended without an outcome`}):(0,x.jsxs)(`div`,{className:KS.cellPending,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${KS.cellPendingSpinner}`}),JS(t)]}):a.map(e=>(0,x.jsx)(RS,{event:e,actorIndex:n},e.id))]},n)})})]})}function XS(e,t,n){let r=e.filter(e=>e.turn===n),i=t.filter(e=>e.turn===n);if(r.length===0&&i.length===0)return null;let a=[...r].reverse().find(e=>e.type===`event_start`),o=[...i].reverse().find(e=>e.type===`event_start`),s=String(a?.data?.title??``),c=String(o?.data?.title??``),l=String(r.find(e=>e.type===`outcome`)?.data?.outcome??``),u=String(i.find(e=>e.type===`outcome`)?.data?.outcome??``);return r.length===0||i.length===0?{turn:n,classification:`one-sided`,titleA:s,titleB:c,outcomeA:l,outcomeB:u}:!l||!u?{turn:n,classification:`pending`,titleA:s,titleB:c,outcomeA:l,outcomeB:u}:s===c?l===u?{turn:n,classification:`same`,titleA:s,titleB:c,outcomeA:l,outcomeB:u}:{turn:n,classification:`different-outcome`,titleA:s,titleB:c,outcomeA:l,outcomeB:u}:{turn:n,classification:`different-event`,titleA:s,titleB:c,outcomeA:l,outcomeB:u}}function ZS(e,t){let n=new Set;for(let t of e)typeof t.turn==`number`&&n.add(t.turn);for(let e of t)typeof e.turn==`number`&&n.add(e.turn);let r=[...n].sort((e,t)=>e-t),i=new Map;for(let n of r){let r=XS(e,t,n);r&&i.set(n,r)}return i}var QS={grid:`_grid_lwobn_1`,scroll:`_scroll_lwobn_10`,empty:`_empty_lwobn_16`};function $S({state:e}){let t=e.actorIds[0],n=e.actorIds[1],r=t?e.actors[t]:null,i=n?e.actors[n]:null,a=r?.events??[],o=i?.events??[],s=(0,b.useMemo)(()=>ZS(a,o),[a,o]),c=(0,b.useMemo)(()=>[...s.keys()],[s]),l=(0,b.useMemo)(()=>eC(a),[a]),u=(0,b.useMemo)(()=>eC(o),[o]),d=(0,b.useRef)(null),f=(0,b.useRef)(!0);return(0,b.useEffect)(()=>{if(!f.current)return;let e=d.current;e&&e.scrollTo({top:e.scrollHeight,behavior:`smooth`})},[a.length,o.length]),(0,x.jsx)(`div`,{className:`sim-columns ${QS.grid}`,children:(0,x.jsx)(`div`,{ref:d,onScroll:()=>{let e=d.current;e&&(f.current=e.scrollHeight-e.scrollTop-e.clientHeight<60)},className:QS.scroll,children:c.length===0?(0,x.jsx)(`div`,{className:QS.empty,children:`No turns yet — events will appear as the run progresses.`}):c.map(t=>{let n=s.get(t);return(0,x.jsx)(YS,{entry:n,eventsA:l.get(t)??[],eventsB:u.get(t)??[],runTerminal:e.isComplete||e.isAborted,runAborted:e.isAborted},t)})})})}function eC(e){let t=new Map;for(let n of e){if(typeof n.turn!=`number`)continue;let e=t.get(n.turn)??[];e.push(n),t.set(n.turn,e)}return t}var tC={row:`_row_1fazu_1`,header:`_header_1fazu_9`,headerTurn:`_headerTurn_1fazu_22`,headerTitle:`_headerTitle_1fazu_28`,headerTitleSplit:`_headerTitleSplit_1fazu_37`,headerTitlePerActor:`_headerTitlePerActor_1fazu_45`,cells:`_cells_1fazu_53`,cell:`_cell_1fazu_53`,cellBand:`_cellBand_1fazu_69`,cellEmpty:`_cellEmpty_1fazu_79`,cellPending:`_cellPending_1fazu_87`,cellPendingSpinner:`_cellPendingSpinner_1fazu_97`},nC=new Set([`turn_start`,`specialist_start`,`decision_pending`]);function rC(e){let t=new Set,n=!1;for(let r of e)if(r.type===`specialist_start`){let e=r.data?.department;typeof e==`string`&&e.length>0&&t.add(e)}else r.type===`decision_pending`&&(n=!0);let r=[];return t.size>0&&r.push(`${[...t].join(`, `)} analyzing`),n&&r.push(`awaiting decision`),r.length>0?r.join(` · `)+`…`:`Working on this turn…`}function iC(e){for(let t of e)if(t.type===`event`||t.type===`turn_done`){let e=t.data?.title;if(typeof e==`string`&&e.length>0)return e}return``}function aC({turn:e,actorIds:t,eventsByActor:n,runTerminal:r,runAborted:i}){let a=n.map(iC),o=a.filter(e=>e.length>0),s=o.length>0&&o.every(e=>e===o[0])?o[0]:``;return(0,x.jsxs)(`section`,{id:`turn-row-${e}`,className:tC.row,"aria-labelledby":`turn-row-${e}-h`,children:[(0,x.jsxs)(`h3`,{id:`turn-row-${e}-h`,className:tC.header,tabIndex:-1,children:[(0,x.jsxs)(`span`,{className:tC.headerTurn,children:[`T`,e]}),s?(0,x.jsx)(`span`,{className:tC.headerTitle,children:s}):(0,x.jsx)(`span`,{className:tC.headerTitleSplit,children:a.map((e,n)=>(0,x.jsx)(`span`,{className:tC.headerTitlePerActor,style:{"--cell-color":Pe(n)},children:e||`—`},t[n]))})]}),(0,x.jsx)(`div`,{className:tC.cells,children:t.map((t,a)=>{let o=n[a]??[],s=o.filter(e=>!nC.has(e.type)),c=o.length>0&&s.length===0;return(0,x.jsxs)(`div`,{className:tC.cell,style:{"--cell-color":Pe(a)},"aria-label":`Events for actor ${a+1} on turn ${e}`,children:[(0,x.jsx)(`span`,{className:tC.cellBand,"aria-hidden":`true`}),o.length===0?r?(0,x.jsx)(`div`,{className:tC.cellEmpty,title:i?`Run was interrupted before this actor reached this turn.`:`No event recorded for this actor on this turn.`,children:i?`Stopped before T${e}`:`No event for T${e}`}):(0,x.jsxs)(`div`,{className:tC.cellPending,"aria-live":`polite`,title:`Parallel runs can drift turn-to-turn — events arrive whenever this actor's LLM calls finish.`,children:[(0,x.jsx)(`span`,{className:`spinner ${tC.cellPendingSpinner}`,"aria-hidden":`true`}),`Catching up to turn `,e,`…`]}):c?r?(0,x.jsx)(`div`,{className:tC.cellEmpty,title:i?`Run was interrupted while this turn was still processing.`:`No outcome recorded for this actor on this turn.`,children:i?`Stopped during T${e}`:`T${e} ended without an outcome`}):(0,x.jsxs)(`div`,{className:tC.cellPending,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${tC.cellPendingSpinner}`}),rC(o)]}):s.map(e=>(0,x.jsx)(RS,{event:e,actorIndex:a%2,actorSlot:a},e.id))]},t)})})]})}var oC={grid:`_grid_1773u_1`,scrollX:`_scrollX_1773u_10`,stickyHeader:`_stickyHeader_1773u_20`,headerCell:`_headerCell_1773u_32`,scrollY:`_scrollY_1773u_37`,empty:`_empty_1773u_45`},sC=360;function cC({state:e}){let t=e.actorIds,n=(0,b.useMemo)(()=>t.map(t=>lC(e.actors[t]?.events??[])),[t,e.actors]),r=(0,b.useMemo)(()=>{let e=new Set;for(let t of n)for(let n of t.keys())e.add(n);return[...e].sort((e,t)=>e-t)},[n]),i=(0,b.useRef)(null),a=(0,b.useRef)(!0),o=()=>{let e=i.current;e&&(a.current=e.scrollHeight-e.scrollTop-e.clientHeight<60)},s=(0,b.useMemo)(()=>t.map(t=>e.actors[t]?.events.length??0).join(`,`),[t,e.actors]);(0,b.useEffect)(()=>{if(!a.current)return;let e=i.current;e&&e.scrollTo({top:e.scrollHeight,behavior:`smooth`})},[s]);let c={"--cell-min-width":`${sC}px`,"--cell-count":String(t.length)};return(0,x.jsx)(`div`,{className:oC.grid,style:c,children:(0,x.jsxs)(`div`,{className:oC.scrollX,children:[(0,x.jsx)(`header`,{className:oC.stickyHeader,children:t.map((t,n)=>{let r=e.actors[t];return(0,x.jsx)(`div`,{className:oC.headerCell,children:(0,x.jsx)(dS,{compact:!0,actorIndex:n,leader:r?.leader??null,nameFallback:t,popHistory:r?.popHistory??[],moraleHistory:r?.moraleHistory??[],event:r?.event,pendingDecision:r?.pendingDecision})},t)})}),(0,x.jsx)(`div`,{ref:i,onScroll:o,className:oC.scrollY,children:r.length===0?(0,x.jsx)(`div`,{className:oC.empty,children:`No turns yet — events will appear as the run progresses.`}):r.map(r=>(0,x.jsx)(aC,{turn:r,actorIds:t,eventsByActor:n.map(e=>e.get(r)??[]),runTerminal:e.isComplete||e.isAborted,runAborted:e.isAborted},r))})]})})}function lC(e){let t=new Map;for(let n of e){if(typeof n.turn!=`number`)continue;let e=t.get(n.turn)??[];e.push(n),t.set(n.turn,e)}return t}var uC={list:`_list_pe3ki_1`,item:`_item_pe3ki_10`,itemNumber:`_itemNumber_pe3ki_22`,itemLink:`_itemLink_pe3ki_29`,itemText:`_itemText_pe3ki_35`,itemMeta:`_itemMeta_pe3ki_39`,title:`_title_pe3ki_46`,wrap:`_wrap_pe3ki_56`,summary:`_summary_pe3ki_62`,filterBar:`_filterBar_pe3ki_73`,filterField:`_filterField_pe3ki_91`,filterLabel:`_filterLabel_pe3ki_105`,filterSelect:`_filterSelect_pe3ki_115`,filterStats:`_filterStats_pe3ki_142`,empty:`_empty_pe3ki_150`};function dC(e){let t=[...e.departments].join(`, `),n=[...e.actorNames].join(` · `);return(0,x.jsxs)(`li`,{id:`cite-${e.n}`,className:uC.item,children:[(0,x.jsxs)(`span`,{className:uC.itemNumber,children:[`[`,e.n,`]`]}),(0,x.jsxs)(`span`,{children:[e.url?(0,x.jsx)(`a`,{href:e.url,target:`_blank`,rel:`noopener noreferrer`,className:uC.itemLink,children:e.text}):(0,x.jsx)(`span`,{className:uC.itemText,children:e.text}),(0,x.jsxs)(`div`,{className:uC.itemMeta,children:[e.doi&&(0,x.jsxs)(x.Fragment,{children:[`DOI:`,e.doi,` · `]}),t&&(0,x.jsxs)(x.Fragment,{children:[`cited by `,t,` · `]}),(0,x.jsxs)(`span`,{title:`Which leader's run referenced this source`,children:[`leader `,n]})]})]})]},e.n)}function fC(e,t,n){return!t&&!n?e:e.filter(e=>!(t&&!e.actorNames.has(t)||n&&!e.departments.has(n)))}function pC(e){let t=new Set,n=new Set;for(let r of e){for(let e of r.actorNames)t.add(e);for(let e of r.departments)n.add(e)}return{actors:[...t].sort((e,t)=>e.localeCompare(t)),departments:[...n].sort((e,t)=>e.localeCompare(t))}}function mC({actors:e,departments:t,actorFilter:n,departmentFilter:r,onActorChange:i,onDepartmentChange:a,total:o,shown:s}){return e.length<2&&t.length<2?null:(0,x.jsxs)(`div`,{className:uC.filterBar,role:`region`,"aria-label":`Filter references`,children:[e.length>1&&(0,x.jsxs)(`div`,{className:uC.filterField,children:[(0,x.jsx)(`label`,{className:uC.filterLabel,htmlFor:`references-actor-filter`,children:`Leader`}),(0,x.jsxs)(`select`,{id:`references-actor-filter`,className:uC.filterSelect,value:n??``,onChange:e=>i(e.target.value||null),children:[(0,x.jsx)(`option`,{value:``,children:`All leaders`}),e.map(e=>(0,x.jsx)(`option`,{value:e,children:e},e))]})]}),t.length>1&&(0,x.jsxs)(`div`,{className:uC.filterField,children:[(0,x.jsx)(`label`,{className:uC.filterLabel,htmlFor:`references-department-filter`,children:`Department`}),(0,x.jsxs)(`select`,{id:`references-department-filter`,className:uC.filterSelect,value:r??``,onChange:e=>a(e.target.value||null),children:[(0,x.jsx)(`option`,{value:``,children:`All departments`}),t.map(e=>(0,x.jsx)(`option`,{value:e,children:e},e))]})]}),(0,x.jsxs)(`span`,{className:uC.filterStats,children:[`Showing `,s,` of `,o]})]})}function hC({registry:e,title:t=`References`,collapsible:n=!1,defaultOpen:r=!1,onToggle:i}){let[a,o]=(0,b.useState)(null),[s,c]=(0,b.useState)(null),{actors:l,departments:u}=(0,b.useMemo)(()=>pC(e.list),[e.list]),d=(0,b.useMemo)(()=>fC(e.list,a,s),[e.list,a,s]);if((0,b.useEffect)(()=>{if(typeof window>`u`)return;let t=()=>{let t=window.location.hash.match(/^#cite-(\d+)$/);if(!t)return;let n=Number(t[1]);Number.isFinite(n)&&(d.some(e=>e.n===n)||e.list.some(e=>e.n===n)&&(o(null),c(null)))};return t(),window.addEventListener(`hashchange`,t),()=>window.removeEventListener(`hashchange`,t)},[d,e.list]),e.list.length===0)return null;let f=(0,x.jsx)(mC,{actors:l,departments:u,actorFilter:a,departmentFilter:s,onActorChange:o,onDepartmentChange:c,total:e.list.length,shown:d.length}),p=d.length>0?(0,x.jsx)(`ol`,{className:uC.list,children:d.map(dC)}):(0,x.jsx)(`div`,{className:uC.empty,children:`No references match the current filters.`});return n?(0,x.jsxs)(`details`,{open:r,onToggle:i?e=>i(e.currentTarget.open):void 0,className:uC.wrap,children:[(0,x.jsxs)(`summary`,{className:uC.summary,children:[t,` · `,e.list.length]}),f,p]}):(0,x.jsxs)(`div`,{className:uC.wrap,children:[(0,x.jsxs)(`h3`,{className:uC.title,children:[t,` · `,e.list.length]}),f,p]})}function gC({registry:e}){return e.list.length===0?null:(0,x.jsx)(`ol`,{className:uC.list,children:e.list.map(dC)})}var _C={scroller:`_scroller_thxdg_1`,row:`_row_thxdg_8`,arrow:`_arrow_thxdg_40`},vC=.8;function yC({label:e,children:t,className:n,rowClassName:r,role:i,ariaLabel:a}){let o=(0,b.useRef)(null),s=(0,b.useRef)(null),c=(0,b.useRef)(null),l=(0,b.useRef)(null),[u,d]=(0,b.useState)({scrolls:!1,previous:!1,next:!1}),f=(0,b.useCallback)(()=>{let e=o.current,t=e?.parentElement;if(!e||!t)return;let n=getComputedStyle(e),r=getComputedStyle(t),i=t.clientWidth-parseFloat(r.paddingLeft)-parseFloat(r.paddingRight)-parseFloat(n.marginLeft)-parseFloat(n.marginRight),a=e.scrollWidth>i+1,u=e.scrollWidth-e.clientWidth,f=a&&e.scrollLeft>1,p=a&&e.scrollLeft<u-1,m=document.activeElement;m===c.current&&!c.current?.disabled&&!p&&f?l.current=`previous`:m===s.current&&!s.current?.disabled&&!f&&p&&(l.current=`next`),d(e=>e.scrolls===a&&e.previous===f&&e.next===p?e:{scrolls:a,previous:f,next:p})},[]);(0,b.useEffect)(()=>{let e=o.current;if(!e)return;f();let t=new ResizeObserver(f),n=()=>{t.disconnect(),t.observe(e),e.parentElement&&t.observe(e.parentElement);for(let n of Array.from(e.children))t.observe(n)};n();let r=new MutationObserver(()=>{n(),f()});return r.observe(e,{childList:!0,subtree:!0,characterData:!0}),e.addEventListener(`scroll`,f,{passive:!0}),()=>{t.disconnect(),r.disconnect(),e.removeEventListener(`scroll`,f)}},[f]),(0,b.useEffect)(()=>{let e=l.current;if(!e)return;l.current=null;let t=document.activeElement;t&&t!==document.body&&t!==s.current&&t!==c.current||(e===`previous`?c:s).current?.disabled===!0&&(e===`previous`?s:c).current?.focus()},[u]);let p=e=>{let t=o.current;if(!t)return;let n=t.scrollWidth-t.clientWidth,r=Math.max(0,Math.min(n,t.scrollLeft+e*t.clientWidth*vC)),i=typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches;t.scrollTo({left:r,behavior:i?`auto`:`smooth`})},{scrolls:m}=u;return(0,x.jsxs)(`div`,{className:[_C.scroller,n].filter(Boolean).join(` `),children:[m&&(0,x.jsx)(`button`,{ref:s,type:`button`,className:_C.arrow,"aria-label":`Show previous ${e}`,title:`Show previous ${e}`,disabled:!u.previous,onClick:()=>p(-1),children:(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`‹`})}),(0,x.jsx)(`div`,{ref:o,role:i,"aria-label":a,className:[_C.row,r].filter(Boolean).join(` `),"data-fade-start":u.previous?`true`:`false`,"data-fade-end":u.next?`true`:`false`,children:t}),m&&(0,x.jsx)(`button`,{ref:c,type:`button`,className:_C.arrow,"aria-label":`Show next ${e}`,title:`Show next ${e}`,disabled:!u.next,onClick:()=>p(1),children:(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`›`})})]})}var bC={bar:`_bar_u6y4c_1`,label:`_label_u6y4c_13`,keys:`_keys_u6y4c_22`,keysRow:`_keysRow_u6y4c_26`,hint:`_hint_u6y4c_31`,cta:`_cta_u6y4c_71`,ctaCount:`_ctaCount_u6y4c_94`,exportBtn:`_exportBtn_u6y4c_103`,modalBackdrop:`_modalBackdrop_u6y4c_116`,modalDialog:`_modalDialog_u6y4c_127`,modalHeader:`_modalHeader_u6y4c_143`,modalTitle:`_modalTitle_u6y4c_152`,modalClose:`_modalClose_u6y4c_164`,modalBody:`_modalBody_u6y4c_174`};function xC({citationRegistry:e,toolRegistry:t,layoutToggle:n}){let[r,i]=(0,b.useState)(null),a=(0,b.useCallback)(()=>i(null),[]),{openToolbox:o}=ev();(0,b.useEffect)(()=>{if(!r)return;let e=e=>{e.key===`Escape`&&a()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[r,a]);let s=e.list.length,c=t.list.length;return s===0&&c===0&&!n?null:(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{role:`region`,"aria-label":`Simulation evidence`,className:bC.bar,children:[(0,x.jsxs)(yC,{label:`evidence keys`,className:bC.keys,rowClassName:bC.keysRow,children:[(0,x.jsx)(`span`,{className:bC.label,children:`Evidence`}),s>0&&(0,x.jsx)(CC,{label:`References`,count:s,onClick:()=>i(`refs`),ariaLabel:`Open References list (${s} sources)`}),c>0&&(0,x.jsx)(CC,{label:`Forged Toolbox`,count:c,onClick:e=>o(e.currentTarget,`sim`),ariaLabel:`Open Forged Toolbox (${c} tools)`}),n]}),(0,x.jsx)(`span`,{className:bC.hint,children:`Click any inline [N] pill to jump to its source.`})]}),r===`refs`&&(0,x.jsx)(wC,{title:`References · ${s}`,onClose:a,extraActions:(0,x.jsx)(SC,{label:`EXPORT JSON`,filename:`paracosm-references.json`,data:e.list.map(e=>({n:e.n,text:e.text,url:e.url,doi:e.doi,departments:[...e.departments],actorNames:[...e.actorNames]}))}),children:(0,x.jsx)(gC,{registry:e})})]})}function SC({label:e,filename:t,data:n}){return(0,x.jsx)(`button`,{onClick:()=>{let e=new Blob([JSON.stringify(n,null,2)],{type:`application/json`}),r=document.createElement(`a`);r.href=URL.createObjectURL(e),r.download=t,r.click(),URL.revokeObjectURL(r.href)},className:bC.exportBtn,children:e})}function CC({label:e,count:t,onClick:n,ariaLabel:r}){return(0,x.jsxs)(`button`,{onClick:n,"aria-label":r,className:bC.cta,children:[(0,x.jsx)(`span`,{children:e.toUpperCase()}),(0,x.jsx)(`span`,{className:bC.ctaCount,children:t})]})}function wC({title:e,onClose:t,children:n,extraActions:r}){return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":e,onClick:t,className:bC.modalBackdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:bC.modalDialog,children:[(0,x.jsxs)(`div`,{className:bC.modalHeader,children:[(0,x.jsx)(`h2`,{className:bC.modalTitle,children:e}),r,(0,x.jsx)(`button`,{onClick:t,"aria-label":`Close`,className:bC.modalClose,children:`×`})]}),(0,x.jsx)(`div`,{className:bC.modalBody,children:n})]})})}var TC={panel:`_panel_nvkty_1`,label:`_label_nvkty_13`,copy:`_copy_nvkty_23`,button:`_button_nvkty_30`};function EC({enabled:e=!0}){let[t,n]=(0,b.useState)(!1),r=Qk(),i=eA(),a=iA(),o=(0,b.useCallback)(async()=>{if(!t&&i){n(!0);try{let e=dg(window.localStorage);if(!e||!fg(e,r.id)){alert(`No previous launch config found for ${r.labels.name}. Run once from Settings first.`);return}let t=vg(e,_g(window.localStorage)),n=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...t,captureSnapshots:!0})}),i=await n.json().catch(()=>({}));if(n.status===429){alert(i.error||`Rate limit hit. Add an API key in Settings to bypass.`);return}if(!n.ok){alert(i.error||`Re-run failed: server responded with HTTP ${n.status}.`);return}if(i.redirect){k(window,i.visitorId),a(),pg(window.localStorage,t);let e=Array.isArray(t.actors)?t.actors:null;e&&e.length>0&&mg(window.localStorage,e,typeof t.scenarioId==`string`?t.scenarioId:void 0),window.location.href=fh(window.location.href,i.redirect)}else alert(`Re-run failed: server did not return a redirect. Check the server logs.`)}catch(e){alert(`Re-run failed: ${e}`)}finally{n(!1)}}},[t,i,r.id,r.labels.name,a]);return e?(0,x.jsxs)(`div`,{className:TC.panel,children:[(0,x.jsx)(`span`,{className:TC.label,children:`Re-run`}),(0,x.jsx)(`span`,{className:TC.copy,children:`Spin up a new run with the same leaders + scenario, seed bumped by one.`}),(0,x.jsx)(`button`,{type:`button`,className:TC.button,onClick:o,disabled:t||!i,children:t?`Launching…`:i?`Run again with seed+1 ›`:`Loading scenario…`})]}):null}var DC={card:`_card_1bn52_1`,empty:`_empty_1bn52_14`,headerRow:`_headerRow_1bn52_18`,kicker:`_kicker_1bn52_26`,lead:`_lead_1bn52_40`,leadMuted:`_leadMuted_1bn52_50`,leadCount:`_leadCount_1bn52_54`,refreshBtn:`_refreshBtn_1bn52_58`,grid:`_grid_1bn52_72`,tile:`_tile_1bn52_78`,tileTitle:`_tileTitle_1bn52_99`,tileMeta:`_tileMeta_1bn52_106`,tileCost:`_tileCost_1bn52_112`,tileCta:`_tileCta_1bn52_118`,moreNote:`_moreNote_1bn52_127`};function OC({hideWhenUnavailable:e=!0}={}){let{sessions:t,status:n,refresh:r}=Oe(),i=(0,b.useRef)(null),a=(0,b.useMemo)(()=>t.slice(0,3),[t]);if(n===`loading`||n===`unavailable`&&e)return null;let o=e=>{let t=new URL(window.location.href);t.searchParams.set(`replay`,e),t.searchParams.set(`tab`,`sim`),t.hash=``,window.location.assign(t.toString())},s=e=>new Date(e).toLocaleString(void 0,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`}),c=t.length===0,l=[DC.card,c?DC.empty:``].filter(Boolean).join(` `),u=[DC.kicker,c?DC.empty:``].filter(Boolean).join(` `),d=[DC.lead,c?DC.empty:``].filter(Boolean).join(` `);return(0,x.jsxs)(`div`,{ref:i,className:l,children:[(0,x.jsxs)(`div`,{className:DC.headerRow,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:u,children:[`▶ `,c?`Replay from cache`:`Watch a prior run`]}),c?(0,x.jsxs)(`div`,{className:d,children:[`No saved runs yet.`,` `,(0,x.jsxs)(`span`,{className:DC.leadMuted,children:[`Once any simulation completes it`,`'`,`s auto-cached here, so you can replay the full turn-by-turn playback — every decision, tool forge, and divergence — without re-spending credits.`]})]}):(0,x.jsxs)(`div`,{className:d,children:[`Don`,`'`,`t want to spend credits?`,` `,(0,x.jsxs)(`span`,{className:DC.leadMuted,children:[`Replay any of `,(0,x.jsx)(`strong`,{className:DC.leadCount,children:t.length}),` `,`cached simulation`,t.length===1?``:`s`,` turn-by-turn, complete with every decision, tool forge, and divergence.`]})]})]}),(0,x.jsx)(`button`,{type:`button`,onClick:r,"aria-label":`Refresh prior runs list`,title:`Refresh list`,className:DC.refreshBtn,children:`↻ Refresh`})]}),!c&&(0,x.jsx)(`div`,{className:DC.grid,children:a.map(e=>(0,x.jsxs)(`button`,{type:`button`,onClick:()=>o(e.id),"aria-label":`Replay ${e.title||e.scenarioName||e.scenarioId||e.id}`,className:DC.tile,children:[(0,x.jsx)(`span`,{className:DC.tileTitle,children:e.title||e.scenarioName||e.scenarioId||`Simulation`}),(0,x.jsxs)(`span`,{className:DC.tileMeta,children:[e.title&&e.scenarioName?`${e.scenarioName} · `:``,typeof e.turnCount==`number`?`${e.turnCount} turns · `:``,Rn(e)?`${Rn(e)} · `:``,s(e.createdAt)]}),typeof e.totalCostUSD==`number`&&e.totalCostUSD>0&&(0,x.jsxs)(`span`,{className:DC.tileCost,children:[`$`,e.totalCostUSD.toFixed(2)]}),(0,x.jsx)(`span`,{className:DC.tileCta,children:`Replay →`})]},e.id))}),!c&&t.length>3&&(0,x.jsxs)(`div`,{className:DC.moreNote,children:[`+ `,t.length-3,` more — use the `,(0,x.jsx)(`strong`,{children:`LOAD`}),` button in the top bar to browse the full list.`]})]})}var kC={padding:`4px 10px`,fontSize:`var(--font-xs)`,fontFamily:`var(--mono)`,fontWeight:600,background:`transparent`,color:`var(--text-3)`,border:`1px solid var(--border)`,cursor:`pointer`,textTransform:`uppercase`,letterSpacing:`0.04em`},AC={...kC,color:`var(--amber)`,background:`var(--bg-card)`,borderColor:`var(--amber)`};function jC({layout:e,actorCount:t,onChange:n}){return(0,x.jsxs)(`div`,{role:`group`,"aria-label":`Sim layout`,style:{display:`inline-flex`,gap:0},children:[(0,x.jsx)(`button`,{type:`button`,"data-layout":`side-by-side`,"aria-pressed":e===`side-by-side`,onClick:()=>n(`side-by-side`),style:{...e===`side-by-side`?AC:kC,borderRadius:`3px 0 0 3px`},title:`Side-by-side: per-actor columns with horizontal scroll for 3+`,children:`Side-by-side`}),(0,x.jsx)(`button`,{type:`button`,"data-layout":`constellation`,"aria-pressed":e===`constellation`,onClick:()=>n(`constellation`),style:{...e===`constellation`?AC:kC,borderRadius:`0 3px 3px 0`,borderLeft:`none`},title:`Constellation: radial cohort layout`,children:`Constellation`})]})}var MC={wrap:`_wrap_1k1fu_1`,svg:`_svg_1k1fu_11`,empty:`_empty_1k1fu_17`,edge:`_edge_1k1fu_25`,node:`_node_1k1fu_29`,label:`_label_1k1fu_42`,statLine:`_statLine_1k1fu_55`,statBadge:`_statBadge_1k1fu_62`,outcomeGlyph:`_outcomeGlyph_1k1fu_69`,outcomeSuccess:`_outcomeSuccess_1k1fu_76`,outcomeFailure:`_outcomeFailure_1k1fu_80`,outcomePending:`_outcomePending_1k1fu_84`,statBadgeMortality:`_statBadgeMortality_1k1fu_88`,edgeLabel:`_edgeLabel_1k1fu_93`,centerChip:`_centerChip_1k1fu_100`,centerChipTurn:`_centerChipTurn_1k1fu_104`,centerChipScenario:`_centerChipScenario_1k1fu_112`},NC=[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`];function PC(e){if(e.length<2)return{pairs:[],hasSpread:!1,hasAnyData:!1};let t=e.some(e=>Object.keys(e.hexaco??{}).length>0),n=[];for(let t=0;t<e.length;t+=1)for(let r=t+1;r<e.length;r+=1){let i=e[t],a=e[r],o=0;for(let e of NC){let t=(typeof i.hexaco?.[e]==`number`?i.hexaco[e]:.5)-(typeof a.hexaco?.[e]==`number`?a.hexaco[e]:.5);o+=t*t}n.push({a:i.name,b:a.name,distance:Math.sqrt(o),normalized:0})}let r=n.reduce((e,t)=>Math.max(e,t.distance),0);for(let e of n)e.normalized=r>0?e.distance/r:0;return{pairs:n,hasSpread:r>0,hasAnyData:t}}function FC(e,t){let n=e.actors[t];if(!n)return{pop:null,morale:null,decisions:0,tools:0,deaths:0,latestOutcome:`pending`};let r=`pending`;for(let e=n.events.length-1;e>=0;e--){let t=n.events[e];if(t.type!==`outcome`)continue;let i=String(t.data?.outcome??``);i.includes(`success`)?r=`success`:i.includes(`failure`)&&(r=`failure`);break}return{pop:n.popHistory.length>0?n.popHistory[n.popHistory.length-1]:null,morale:n.moraleHistory.length>0?n.moraleHistory[n.moraleHistory.length-1]:null,decisions:n.decisions??0,tools:n.tools??0,deaths:n.deaths??0,latestOutcome:r}}var IC=`Unknown`;function LC(e){return e?e.trim():``}function RC(e){let t=new Map;return e.actorIds.forEach((n,r)=>{let i=e.actors[n],a=LC(i?.leader?.archetype),o=a||`__unknown__`,s=a||IC,c=t.get(o);c?c.ids.push(n):t.set(o,{archetype:a,label:s,ids:[n],firstIndex:r})}),[...t.values()].sort((e,t)=>e.firstIndex-t.firstIndex)}var zC={legend:`_legend_1h9pr_1`,heading:`_heading_1h9pr_14`,pills:`_pills_1h9pr_24`,pill:`_pill_1h9pr_24`,pillFocused:`_pillFocused_1h9pr_56`,pillDimmed:`_pillDimmed_1h9pr_62`,pillCount:`_pillCount_1h9pr_66`,pillLabel:`_pillLabel_1h9pr_76`};function BC({cohorts:e,focusedArchetype:t,onFocusChange:n}){let r=e.reduce((e,t)=>e+t.ids.length,0);if(e.length<2||r<3)return null;let i=e=>{n&&n(t===e?null:e)};return(0,x.jsxs)(`div`,{className:zC.legend,role:`group`,"aria-label":`Cohort summary: ${e.length} archetypes across ${r} actors`,children:[(0,x.jsx)(`span`,{className:zC.heading,children:`COHORTS`}),(0,x.jsx)(`div`,{className:zC.pills,children:e.map(e=>{let r=t===e.archetype&&e.archetype!==``,a=t&&t!==e.archetype,o=`${zC.pill} ${r?zC.pillFocused:``} ${a?zC.pillDimmed:``}`;return(0,x.jsxs)(`button`,{type:`button`,className:o,onClick:()=>i(e.archetype),disabled:!n,"aria-pressed":r,"aria-label":`${e.label} cohort, ${e.ids.length} actor${e.ids.length===1?``:`s`}`,children:[(0,x.jsx)(`span`,{className:zC.pillCount,children:e.ids.length}),(0,x.jsx)(`span`,{className:zC.pillLabel,children:e.label})]},e.archetype||`__unknown__`)})})]})}var VC=18,HC=80,UC=9;function WC(e){if(e===0)return[];let t=Math.min(460,Math.max(120,60+12*e)),n=t+HC,r=[];for(let i=0;i<e;i+=1){let a=i/Math.max(1,e)*2*Math.PI-Math.PI/2;r.push({cx:n+t*Math.cos(a),cy:n+t*Math.sin(a),angle:a})}return r}function GC(e){return e===0?0:(Math.min(460,Math.max(120,60+12*e))+HC)*2}function KC({state:e,onActorClick:t}){let n=e.actorIds,r=b.useMemo(()=>WC(n.length),[n.length]),i=b.useMemo(()=>n.map(t=>({name:t,hexaco:e.actors[t]?.leader?.hexaco??{}})),[n,e.actors]),a=i.map(e=>`${e.name}:${Object.values(e.hexaco).join(`,`)}`).join(`|`),o=b.useMemo(()=>PC(i),[a]),s=b.useMemo(()=>{let e=new Map;for(let t of o.pairs)e.set(`${t.a}|${t.b}`,t.normalized),e.set(`${t.b}|${t.a}`,t.normalized);return e},[o]),c=Qk(),l=b.useMemo(()=>n.map(t=>FC(e,t)),[n,e]),u=(0,b.useMemo)(()=>RC(e),[e]),[d,f]=(0,b.useState)(null),p=(0,b.useMemo)(()=>{let e=new Map;for(let t of u)for(let n of t.ids)e.set(n,t.archetype);return e},[u]),m=e=>d===null||p.get(e)===d;if(n.length===0)return(0,x.jsx)(`div`,{className:MC.empty,children:`Constellation will appear when actors are launched.`});let h=GC(n.length);return(0,x.jsxs)(`div`,{className:MC.wrap,children:[(0,x.jsx)(BC,{cohorts:u,focusedArchetype:d,onFocusChange:f}),(0,x.jsxs)(`svg`,{className:MC.svg,viewBox:`0 0 ${h} ${h}`,width:h,height:h,role:`img`,"aria-label":`Constellation of ${n.length} actors`,children:[n.map((e,t)=>n.slice(t+1).map(i=>{let a=r[t],c=r[n.indexOf(i)];if(!a||!c)return null;let l=s.get(`${e}|${i}`)??0,u=m(e)&&m(i),f=d===null||u?1:.12,p=Math.max(.06,Math.min(.95,1-l))*f,h=o.hasSpread&&n.length<UC&&(d===null||u),g=(a.cx+c.cx)/2,_=(a.cy+c.cy)/2;return(0,x.jsxs)(b.Fragment,{children:[(0,x.jsx)(`line`,{"data-edge":`${e}|${i}`,className:MC.edge,x1:a.cx,y1:a.cy,x2:c.cx,y2:c.cy,strokeOpacity:p,strokeWidth:1.5}),h&&(0,x.jsx)(`text`,{className:MC.edgeLabel,x:g,y:_,textAnchor:`middle`,dominantBaseline:`middle`,"aria-hidden":`true`,children:l.toFixed(2)})]},`${e}|${i}`)})),n.map((n,i)=>{let a=r[i];if(!a)return null;let o=Pe(i),s=e.actors[n]?.leader?.archetype??``,c=a.cx+Math.cos(a.angle)*32,u=a.cy+Math.sin(a.angle)*32,f=a.angle>-Math.PI/2&&a.angle<Math.PI/2?`start`:`end`,p=d!==null&&!m(n)?.25:1;return(0,x.jsxs)(`g`,{opacity:p,children:[(0,x.jsx)(`circle`,{"data-actor":n,className:MC.node,cx:a.cx,cy:a.cy,r:VC,fill:o,onClick:()=>t(n),onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),t(n))},tabIndex:0,role:`button`,"aria-label":`Open report for ${n}`,children:(0,x.jsx)(`title`,{children:`${n}${s?` · ${s}`:``}`})}),(0,x.jsx)(`text`,{className:MC.label,x:c,y:u,textAnchor:f,dominantBaseline:`middle`,children:n}),(()=>{let e=l[i];if(!e)return null;let t=e.pop!==null&&e.morale!==null?`POP ${Math.round(e.pop)} · MORALE ${Math.round(e.morale)}%`:``,n=e.latestOutcome===`success`?`✓`:e.latestOutcome===`failure`?`⚠`:`…`,r=e.latestOutcome===`success`?MC.outcomeSuccess:e.latestOutcome===`failure`?MC.outcomeFailure:MC.outcomePending,a=e.deaths>=5;return(0,x.jsxs)(x.Fragment,{children:[t&&(0,x.jsx)(`text`,{className:MC.statLine,x:c,y:u+14,textAnchor:f,dominantBaseline:`middle`,children:t}),(0,x.jsxs)(`text`,{className:MC.statBadge,x:c,y:u+28,textAnchor:f,dominantBaseline:`middle`,children:[`D${e.decisions} · F${e.tools} `,(0,x.jsx)(`tspan`,{className:`${MC.outcomeGlyph} ${r}`,children:n}),a&&(0,x.jsx)(`tspan`,{className:MC.statBadgeMortality,children:` · ${e.deaths}†`})]})]})})()]},n)}),(()=>{let t=h/2,r=h/2,i=c.labels.actorNounPlural??`actors`;return(0,x.jsxs)(`g`,{className:MC.centerChip,role:`presentation`,children:[(0,x.jsxs)(`text`,{className:MC.centerChipTurn,x:t,y:r-6,textAnchor:`middle`,dominantBaseline:`middle`,children:[`T`,e.turn,`/`,e.maxTurns]}),(0,x.jsxs)(`text`,{className:MC.centerChipScenario,x:t,y:r+10,textAnchor:`middle`,dominantBaseline:`middle`,children:[c.labels.shortName,` · `,n.length,` `,i]})]})})()]})]})}function qC(e){return e.length>0?e[e.length-1]:0}function JC(e,t){return{id:e,name:t.leader?.name??e,archetype:t.leader?.archetype??``,population:qC(t.popHistory),morale:qC(t.moraleHistory),deaths:t.deaths,tools:t.toolNames?.size??t.tools??0,turn:t.popHistory.length,pending:!!t.pendingDecision}}function YC(e){return e.actorIds.map(t=>{let n=e.actors[t];return n?JC(t,n):null}).filter(e=>e!==null)}function XC(e){switch(e){case`name`:case`archetype`:return`asc`;case`deaths`:return`asc`;case`population`:case`morale`:case`tools`:case`turn`:return`desc`}}function ZC(e,t,n,r){let i=r===`asc`?1:-1,a;switch(n){case`name`:a=e.name.localeCompare(t.name);break;case`archetype`:a=e.archetype.localeCompare(t.archetype);break;case`population`:a=e.population-t.population;break;case`morale`:a=e.morale-t.morale;break;case`deaths`:a=e.deaths-t.deaths;break;case`tools`:a=e.tools-t.tools;break;case`turn`:a=e.turn-t.turn}return a===0?e.name.localeCompare(t.name):a*i}function QC(e,t,n){return[...e].sort((e,r)=>ZC(e,r,t,n))}var $C={wrap:`_wrap_1yfha_1`,scroll:`_scroll_1yfha_9`,table:`_table_1yfha_13`,th:`_th_1yfha_21`,numeric:`_numeric_1yfha_32`,activeSort:`_activeSort_1yfha_36`,sortButton:`_sortButton_1yfha_40`,sortGlyph:`_sortGlyph_1yfha_70`,row:`_row_1yfha_75`,rowClickable:`_rowClickable_1yfha_83`,colorCell:`_colorCell_1yfha_95`,colorDot:`_colorDot_1yfha_100`,nameCell:`_nameCell_1yfha_108`,actorName:`_actorName_1yfha_116`,pendingPill:`_pendingPill_1yfha_121`,archetypeCell:`_archetypeCell_1yfha_136`,numCell:`_numCell_1yfha_142`,moraleWrap:`_moraleWrap_1yfha_150`,moraleBar:`_moraleBar_1yfha_158`,moraleFill:`_moraleFill_1yfha_168`,moraleText:`_moraleText_1yfha_176`,empty:`_empty_1yfha_183`},ew=[{key:`name`,label:`Actor`,numeric:!1},{key:`archetype`,label:`Archetype`,numeric:!1},{key:`turn`,label:`Turn`,numeric:!0},{key:`population`,label:`Pop`,numeric:!0},{key:`morale`,label:`Morale`,numeric:!0},{key:`deaths`,label:`Deaths`,numeric:!0},{key:`tools`,label:`Tools`,numeric:!0}];function tw(e,t){return e?t===`asc`?`ascending`:`descending`:`none`}function nw({state:e,onActorClick:t}){let[n,r]=(0,b.useState)(`morale`),[i,a]=(0,b.useState)(`desc`),o=(0,b.useCallback)(e=>{r(t=>t===e?(a(e=>e===`asc`?`desc`:`asc`),t):(a(XC(e)),e))},[]),s=(0,b.useMemo)(()=>YC(e),[e]),c=(0,b.useMemo)(()=>QC(s,n,i),[s,n,i]),l=e=>n=>{t&&(n.key===`Enter`||n.key===` `)&&(n.preventDefault(),t(e))};return c.length===0?(0,x.jsx)(`div`,{className:$C.empty,role:`status`,children:`No actor data yet — events will populate this table as the run progresses.`}):(0,x.jsx)(`div`,{className:$C.wrap,"aria-label":`Actor roster (${c.length} actors)`,children:(0,x.jsx)(`div`,{className:$C.scroll,children:(0,x.jsxs)(`table`,{className:$C.table,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{children:[(0,x.jsx)(`th`,{"aria-hidden":`true`,className:$C.colorCell}),ew.map(e=>{let t=e.key===n;return(0,x.jsx)(`th`,{"aria-sort":tw(t,i),className:`${$C.th} ${e.numeric?$C.numeric:``} ${t?$C.activeSort:``}`,children:(0,x.jsxs)(`button`,{type:`button`,className:$C.sortButton,onClick:()=>o(e.key),"aria-label":`Sort by ${e.label}${t?` (${i===`asc`?`ascending`:`descending`} active)`:``}`,children:[(0,x.jsx)(`span`,{children:e.label}),(0,x.jsx)(`span`,{className:$C.sortGlyph,"aria-hidden":`true`,children:t?i===`asc`?`▲`:`▼`:`·`})]})},e.key)})]})}),(0,x.jsx)(`tbody`,{children:c.map(n=>{let r=e.actorIds.indexOf(n.id),i=r>=0?Pe(r):`var(--text-3)`;return(0,x.jsxs)(`tr`,{className:`${$C.row} ${t?$C.rowClickable:``}`,tabIndex:t?0:-1,onClick:t?()=>t(n.id):void 0,onKeyDown:t?l(n.id):void 0,"aria-label":`${n.name}, ${n.archetype}, turn ${n.turn}, population ${n.population}, morale ${n.morale}%, ${n.deaths} deaths, ${n.tools} tools`,children:[(0,x.jsx)(`td`,{className:$C.colorCell,"aria-hidden":`true`,children:(0,x.jsx)(`span`,{className:$C.colorDot,style:{background:i}})}),(0,x.jsxs)(`td`,{className:$C.nameCell,children:[(0,x.jsx)(`span`,{className:$C.actorName,children:n.name}),n.pending&&(0,x.jsx)(`span`,{className:$C.pendingPill,title:`Waiting on commander decision`,children:`pending`})]}),(0,x.jsx)(`td`,{className:$C.archetypeCell,children:n.archetype}),(0,x.jsxs)(`td`,{className:$C.numCell,children:[`T`,n.turn]}),(0,x.jsx)(`td`,{className:$C.numCell,children:n.population}),(0,x.jsx)(`td`,{className:$C.numCell,children:(0,x.jsxs)(`span`,{className:$C.moraleWrap,children:[(0,x.jsx)(`span`,{className:$C.moraleBar,"aria-hidden":`true`,children:(0,x.jsx)(`span`,{className:$C.moraleFill,style:{width:`${Math.min(100,Math.max(0,n.morale))}%`,background:i}})}),(0,x.jsxs)(`span`,{className:$C.moraleText,children:[n.morale,`%`]})]})}),(0,x.jsx)(`td`,{className:$C.numCell,children:n.deaths}),(0,x.jsx)(`td`,{className:$C.numCell,children:n.tools})]},n.id)})})]})})})}function rw(e,t){if(e.length===0)return 0;if(e.length===1)return e[0];let n=Math.max(0,Math.min(1,t))*(e.length-1),r=Math.floor(n),i=Math.ceil(n);if(r===i)return e[r];let a=n-r;return e[r]*(1-a)+e[i]*a}function iw(e,t){let n=e.actorIds.map(t=>e.actors[t]).filter(e=>!!e).map(e=>t(e));if(n.length===0)return[];let r=n.reduce((e,t)=>Math.max(e,t.length),0),i=[];for(let e=0;e<r;e++){let t=[];for(let r of n)r.length>e&&t.push(r[e]);if(t.length===0)continue;let r=[...t].sort((e,t)=>e-t);i.push({turn:e+1,n:r.length,min:r[0],q1:rw(r,.25),median:rw(r,.5),q3:rw(r,.75),max:r[r.length-1]})}return i}var aw=e=>e.popHistory,ow=e=>e.moraleHistory;function sw(e,t,n){let r=n-t,i=e=>r<=0?.5:(e-t)/r;return{turn:e.turn,n:e.n,min:i(e.min),q1:i(e.q1),median:i(e.median),q3:i(e.q3),max:i(e.max)}}function cw(e){if(e.length===0)return{lo:0,hi:1};let t=1/0,n=-1/0;for(let r of e)r.min<t&&(t=r.min),r.max>n&&(n=r.max);return!isFinite(t)||!isFinite(n)?{lo:0,hi:1}:t===n?{lo:t-1,hi:n+1}:{lo:t,hi:n}}var lw={panel:`_panel_1ox36_1`,heading:`_heading_1ox36_9`,headingLabel:`_headingLabel_1ox36_17`,headingHint:`_headingHint_1ox36_26`,charts:`_charts_1ox36_33`,chartWrap:`_chartWrap_1ox36_39`,chartHeader:`_chartHeader_1ox36_45`,chartTitle:`_chartTitle_1ox36_53`,chartLatest:`_chartLatest_1ox36_60`,chart:`_chart_1ox36_33`,envelope:`_envelope_1ox36_76`,iqr:`_iqr_1ox36_82`,median:`_median_1ox36_88`,empty:`_empty_1ox36_96`},uw=[{id:`morale`,label:`Morale`,unitSuffix:`%`,pick:ow,fixedRange:{lo:0,hi:100}},{id:`population`,label:`Population`,unitSuffix:``,pick:aw}],dw=360,fw=90,pw=8,mw=6;function hw({bands:e,fixedRange:t,unitSuffix:n}){if(e.length===0)return(0,x.jsx)(`div`,{className:lw.empty,role:`status`,children:`No turns recorded yet.`});let r=t??cw(e),i=e.map(e=>sw(e,r.lo,r.hi)),a=t=>e.length===1?180:pw+t/(e.length-1)*344,o=e=>mw+(1-e)*78,s=`${i.map((e,t)=>`${t===0?`M`:`L`} ${a(t)} ${o(e.max)}`).join(` `)} ${[...i].reverse().map(e=>{let t=i.indexOf(e);return`L ${a(t)} ${o(e.min)}`}).join(` `)} Z`,c=`${i.map((e,t)=>`${t===0?`M`:`L`} ${a(t)} ${o(e.q3)}`).join(` `)} ${[...i].reverse().map(e=>{let t=i.indexOf(e);return`L ${a(t)} ${o(e.q1)}`}).join(` `)} Z`,l=i.map((e,t)=>`${t===0?`M`:`L`} ${a(t)} ${o(e.median)}`).join(` `),u=e[e.length-1];return(0,x.jsxs)(`svg`,{className:lw.chart,viewBox:`0 0 ${dw} ${fw}`,width:dw,height:fw,role:`img`,"aria-label":`Quantile distribution across turns. Latest turn ${u.turn}: median ${u.median.toFixed(0)}${n}, range ${u.min.toFixed(0)}-${u.max.toFixed(0)}${n} across ${u.n} actor${u.n===1?``:`s`}.`,children:[(0,x.jsx)(`path`,{className:lw.envelope,d:s}),(0,x.jsx)(`path`,{className:lw.iqr,d:c}),(0,x.jsx)(`path`,{className:lw.median,d:l})]})}function gw({state:e}){let t=(0,b.useMemo)(()=>uw.map(t=>({def:t,bands:iw(e,t.pick)})),[e]);return t.some(e=>e.bands.length>0)?(0,x.jsxs)(`div`,{className:lw.panel,"aria-label":`Distribution across actors`,children:[(0,x.jsxs)(`div`,{className:lw.heading,children:[(0,x.jsx)(`span`,{className:lw.headingLabel,children:`DISTRIBUTION`}),(0,x.jsx)(`span`,{className:lw.headingHint,children:`median · IQR · min-max envelope`})]}),(0,x.jsx)(`div`,{className:lw.charts,children:t.map(({def:e,bands:t})=>{let n=t[t.length-1];return(0,x.jsxs)(`div`,{className:lw.chartWrap,children:[(0,x.jsxs)(`div`,{className:lw.chartHeader,children:[(0,x.jsx)(`span`,{className:lw.chartTitle,children:e.label}),n&&(0,x.jsxs)(`span`,{className:lw.chartLatest,children:[`T`,n.turn,` · median `,Math.round(n.median),e.unitSuffix,` · `,n.min.toFixed(0),`-`,n.max.toFixed(0),e.unitSuffix,` · n=`,n.n]})]}),(0,x.jsx)(hw,{bands:t,fixedRange:e.fixedRange,unitSuffix:e.unitSuffix})]},e.id)})})]}):null}var _w={overlay:`_overlay_prjqp_1`,modal:`_modal_prjqp_11`,dockOverlay:`_dockOverlay_prjqp_22`,dock:`_dock_prjqp_22`,head:`_head_prjqp_60`,actorName:`_actorName_prjqp_68`,closeBtn:`_closeBtn_prjqp_73`,body:`_body_prjqp_83`,section:`_section_prjqp_88`,sectionTitle:`_sectionTitle_prjqp_92`,list:`_list_prjqp_100`,decisionItem:`_decisionItem_prjqp_106`,decisionTitle:`_decisionTitle_prjqp_111`,decisionRationale:`_decisionRationale_prjqp_115`,empty:`_empty_prjqp_120`,turnArticle:`_turnArticle_prjqp_124`,turnHeader:`_turnHeader_prjqp_129`,turnList:`_turnList_prjqp_134`,turnEvent:`_turnEvent_prjqp_140`,turnEventType:`_turnEventType_prjqp_145`};function vw(e){let t=e.data??{};return t.title??t.choice??t.summary??e.type}function yw({actorName:e,actorIndex:t,state:n,onClose:r,mode:i=`modal`}){let a=Pt(i===`modal`&&e!==null);if(b.useEffect(()=>{if(e===null)return;let t=e=>{e.key===`Escape`&&(e.preventDefault(),r())};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e,r]),e===null)return null;let o=n.actors[e];if(!o)return null;let s=o.events??[],c=s.filter(e=>e.type===`decision_made`),l=new Map;for(let e of s){let t=e.turn??0,n=l.get(t)??[];n.push(e),l.set(t,n)}let u=[...l.keys()].sort((e,t)=>e-t),d=i===`dock`,f=d?_w.dockOverlay:_w.overlay,p=d?_w.dock:_w.modal,m=d?void 0:r,h=d?void 0:e=>e.stopPropagation();return(0,x.jsx)(`div`,{className:f,role:`presentation`,onClick:m,children:(0,x.jsxs)(`div`,{ref:a,className:p,role:`dialog`,"aria-modal":!d||void 0,"aria-label":`Report for ${e}`,tabIndex:-1,onClick:h,children:[(0,x.jsxs)(`header`,{className:_w.head,children:[(0,x.jsx)(`div`,{className:_w.actorName,children:e}),(0,x.jsx)(`button`,{type:`button`,"aria-label":`Close drill-in`,className:_w.closeBtn,onClick:r,children:`×`})]}),(0,x.jsxs)(`div`,{className:_w.body,children:[(0,x.jsx)(dS,{actorIndex:t,leader:o.leader,popHistory:o.popHistory,moraleHistory:o.moraleHistory}),c.length>0&&(0,x.jsxs)(`section`,{className:_w.section,children:[(0,x.jsxs)(`h3`,{className:_w.sectionTitle,children:[`Decisions (`,c.length,`)`]}),(0,x.jsx)(`ul`,{className:_w.list,children:c.map(e=>{let t=e.data?.choice??e.data?.title??`<choice>`,n=e.data?.rationale??``;return(0,x.jsxs)(`li`,{className:_w.decisionItem,children:[(0,x.jsxs)(`div`,{className:_w.decisionTitle,children:[`T`,e.turn??`?`,`: `,t]}),n&&(0,x.jsx)(`div`,{className:_w.decisionRationale,children:n})]},e.id)})})]}),(0,x.jsxs)(`section`,{className:_w.section,children:[(0,x.jsxs)(`h3`,{className:_w.sectionTitle,children:[`Timeline (`,s.length,` events)`]}),u.length===0&&(0,x.jsx)(`p`,{className:_w.empty,children:`No events captured yet.`}),u.map(e=>(0,x.jsxs)(`article`,{className:_w.turnArticle,children:[(0,x.jsxs)(`header`,{className:_w.turnHeader,children:[`Turn `,e]}),(0,x.jsx)(`ul`,{className:_w.turnList,children:(l.get(e)??[]).map(e=>(0,x.jsxs)(`li`,{className:_w.turnEvent,children:[(0,x.jsx)(`span`,{className:_w.turnEventType,children:e.type}),` `,vw(e)]},e.id))})]},e))]})]})]})})}var bw={root:`_root_1s21i_1`,scrollableBody:`_scrollableBody_1s21i_8`,leadersRow:`_leadersRow_1s21i_16`,introBar:`_introBar_1s21i_22`,introBody:`_introBody_1s21i_33`,introHeading:`_introHeading_1s21i_40`,introExpandButton:`_introExpandButton_1s21i_44`,introDismissButton:`_introDismissButton_1s21i_56`,progressBar:`_progressBar_1s21i_75`,progressLabel:`_progressLabel_1s21i_86`,progressTrack:`_progressTrack_1s21i_93`,progressFill:`_progressFill_1s21i_101`,progressPercent:`_progressPercent_1s21i_107`,centerState:`_centerState_1s21i_111`,centerStateHeading:`_centerStateHeading_1s21i_122`,centerStateHeadingLarger:`_centerStateHeadingLarger_1s21i_134`,centerStateHeadingAmber:`_centerStateHeadingAmber_1s21i_146`,centerStateCopy:`_centerStateCopy_1s21i_154`,centerStateCopyWide:`_centerStateCopyWide_1s21i_154`,centerStateSpinnerSmall:`_centerStateSpinnerSmall_1s21i_166`,centerStateSpinnerLarge:`_centerStateSpinnerLarge_1s21i_173`,emptyStateActions:`_emptyStateActions_1s21i_180`,buttonRun:`_buttonRun_1s21i_187`,buttonLoad:`_buttonLoad_1s21i_210`,buttonSettings:`_buttonSettings_1s21i_226`,tourHint:`_tourHint_1s21i_241`,tourLink:`_tourLink_1s21i_247`,tourAside:`_tourAside_1s21i_260`,replayCtaWrap:`_replayCtaWrap_1s21i_265`,flashCard:`_flashCard_1s21i_272`,flashOn:`_flashOn_1s21i_275`};function xw({onDismiss:e}){let[t,n]=(0,b.useState)(!1);return(0,x.jsxs)(`div`,{role:`region`,"aria-label":`How to read the simulation`,className:bw.introBar,children:[(0,x.jsxs)(`div`,{className:bw.introBody,children:[(0,x.jsx)(`b`,{className:bw.introHeading,children:`How to read this:`}),` `,t?(0,x.jsx)(x.Fragment,{children:`Multiple commanders with different HEXACO profiles run the same seed side by side. Each turn, departments analyze in parallel and may forge a new computational tool in a QuickJS WebAssembly sandbox or reuse an existing one. Commanders decide. The settlement diverges. Click any tile in Viz to drill into a colonist; click any forge card to inspect the generated code.`}):(0,x.jsxs)(x.Fragment,{children:[`multiple commanders, one seed, divergent histories. HEXACO shapes every LLM call.`,` `,(0,x.jsx)(`button`,{onClick:()=>n(!0),className:bw.introExpandButton,children:`more`})]})]}),(0,x.jsx)(`button`,{onClick:e,className:bw.introDismissButton,"aria-label":`Dismiss introduction`,children:`Got it`})]})}function Sw({state:e,sseStatus:t,onRun:n,onTour:r,verdict:i,shownRun:a,launching:o,interventionArtifact:s,interventionRunning:c,interventionState:l=e,onInterventionDismiss:u,forceLayout:d}){let f=Qk(),p=eA();if(s)return(0,x.jsx)(`div`,{className:bw.root,children:(0,x.jsx)(`div`,{className:bw.scrollableBody,children:(0,x.jsx)(Zx,{artifact:s,state:l,onDismiss:u})})});if(c)return(0,x.jsx)(`div`,{className:bw.root,children:(0,x.jsx)(`div`,{className:bw.scrollableBody,children:(0,x.jsx)(rS,{state:l,subject:c.subject,intervention:c.intervention})})});let m=h_(),h=D_(),[g,_]=(0,b.useState)(!1),v=o??g,[y,S]=(0,b.useState)(`side-by-side`),C=(0,b.useRef)(!1),w=(0,b.useCallback)(e=>{C.current=!0,S(e)},[]);(0,b.useEffect)(()=>{C.current||e.actorIds.length>50&&y!==`constellation`&&S(`constellation`)},[e.actorIds.length,y]);let T=d??y,[E,D]=(0,b.useState)(null),O=E?e.actorIds.indexOf(E):0,k=e.actorIds[0],A=e.actorIds[1],j=k?e.actors[k]:null,ee=A?e.actors[A]:null,te=Object.values(e.actors).some(e=>e.events.length>0),M=e.isRunning&&!te;(0,b.useEffect)(()=>{(te||e.isRunning)&&o===void 0&&_(!1)},[te,e.isRunning,o]);let N=(0,b.useCallback)(()=>{o===void 0&&_(!0),n?.()},[n,o]),ne=f.presets.find(e=>e.id==="default"),P=ne?.leaders??ne?.actors,re=(0,b.useMemo)(()=>typeof window>`u`?null:gg(window.localStorage),[]),ie=P?.[0]??re?.[0],F=P?.[1]??re?.[1],I=ie?.name?{name:ie.name,archetype:ie.archetype??``,unit:ie.unit??se(f,0),hexaco:ie.hexaco??{},instructions:ie.instructions??``,quote:``}:null,ae=F?.name?{name:F.name,archetype:F.archetype??``,unit:F.unit??se(f,1),hexaco:F.hexaco??{},instructions:F.instructions??``,quote:``}:null,[oe,ce]=(0,b.useState)(()=>typeof window>`u`||localStorage.getItem(`paracosm-intro-dismissed`)!==`1`),le=()=>{ce(!1),localStorage.setItem(`paracosm-intro-dismissed`,`1`)},L=j?.event,ue=L?`T${L.turn} \u2014 ${L.time}: ${L.title}`:``,de=(0,b.useMemo)(()=>{let e=i&&typeof i==`object`?i.winner:null;return t=>e===`tie`?`tie`:e===t?`winner`:e===`A`||e===`B`?`second`:null},[i]),fe=e.maxTurns>0?Math.min(100,Math.max(0,e.turn/e.maxTurns*100)):0,R=(0,b.useCallback)(()=>{let e=document.querySelector(`[data-paracosm-replay-cta="true"]`);e&&(e.scrollIntoView({behavior:`smooth`,block:`center`}),e.classList.add(bw.flashOn),window.setTimeout(()=>e.classList.remove(bw.flashOn),1200))},[]),z=(0,b.useCallback)(()=>{let e=new URL(window.location.href);e.searchParams.set(`tab`,`settings`),window.history.replaceState({},``,e.toString()),window.location.reload()},[]),pe=e.isRunning||e.isComplete||te||t===`connected`;return(0,x.jsxs)(`div`,{className:bw.root,children:[(0,x.jsxs)(`div`,{className:bw.scrollableBody,children:[e.isComplete&&i&&i.winner?(0,x.jsx)(jn,{verdict:i,shownRun:a}):null,T===`constellation`?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(KC,{state:e,onActorClick:e=>D(e)}),(0,x.jsx)(gw,{state:e}),(0,x.jsx)(nw,{state:e,onActorClick:e=>D(e)})]}):e.actorIds.length>=3?(0,x.jsx)(CS,{actors:e.actorIds.map(t=>({id:t,state:e.actors[t]})),crisisText:ue,toolRegistry:h}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`div`,{className:`leaders-row ${bw.leadersRow}`,children:[(0,x.jsx)(dS,{actorIndex:0,leader:j?.leader||I,popHistory:j?.popHistory||[],moraleHistory:j?.moraleHistory||[],verdictPlacement:de(`A`),event:j?.event,statuses:j?.statuses,pendingDecision:j?.pendingDecision}),(0,x.jsx)(dS,{actorIndex:1,leader:ee?.leader||ae,popHistory:ee?.popHistory||[],moraleHistory:ee?.moraleHistory||[],verdictPlacement:de(`B`),event:ee?.event,statuses:ee?.statuses,pendingDecision:ee?.pendingDecision})]}),(0,x.jsx)(CS,{actors:e.actorIds.slice(0,2).map(t=>({id:t,state:e.actors[t]})),crisisText:ue,toolRegistry:h})]}),e.isRunning&&!e.isComplete&&e.maxTurns>0&&(0,x.jsxs)(`div`,{className:bw.progressBar,children:[(0,x.jsxs)(`span`,{className:bw.progressLabel,children:[`Turn `,Math.max(1,e.turn),` / `,e.maxTurns]}),(0,x.jsx)(`div`,{className:bw.progressTrack,children:(0,x.jsx)(`div`,{className:bw.progressFill,style:{width:`${fe}%`}})}),(0,x.jsxs)(`span`,{className:bw.progressPercent,children:[Math.round(fe),`%`]})]}),oe&&(j?.events.length??0)>0&&(0,x.jsx)(xw,{onDismiss:le}),M&&!te&&!e.isComplete&&e.turn===0&&(0,x.jsxs)(`div`,{className:bw.centerState,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${bw.centerStateSpinnerSmall}`,"aria-hidden":`true`}),(0,x.jsx)(`div`,{className:bw.centerStateHeading,children:`Simulation starting...`}),(0,x.jsx)(`div`,{className:bw.centerStateCopy,children:`The Event Director is reading simulation state and generating the first event. Departments will analyze and forge tools once it arrives.`})]}),v&&!te&&!e.isRunning&&(0,x.jsxs)(`div`,{className:bw.centerState,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${bw.centerStateSpinnerLarge}`,"aria-hidden":`true`}),(0,x.jsx)(`div`,{className:bw.centerStateHeadingAmber,children:`Launching Simulation...`}),(0,x.jsx)(`div`,{className:bw.centerStateCopy,children:`Initializing the Event Director, departments, and agent personalities. First events will appear shortly.`})]}),!te&&!e.isComplete&&!v&&t===`connecting`&&(0,x.jsxs)(`div`,{className:bw.centerState,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${bw.centerStateSpinnerSmall}`,"aria-hidden":`true`}),(0,x.jsx)(`div`,{className:bw.centerStateHeading,children:`Connecting...`}),(0,x.jsx)(`div`,{className:bw.centerStateCopy,children:`Loading simulation state from the server. If a simulation is running, events will appear shortly.`})]}),!e.isRunning&&!e.isComplete&&!te&&t===`connected`&&!v&&typeof window<`u`&&new URLSearchParams(window.location.search).has(`replay`)&&(0,x.jsxs)(`div`,{className:bw.centerState,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:`spinner ${bw.centerStateSpinnerSmall}`,"aria-hidden":`true`}),(0,x.jsx)(`div`,{className:bw.centerStateHeading,children:`Loading replay…`}),(0,x.jsx)(`div`,{className:bw.centerStateCopy,children:`Streaming the cached run back from the server. Turns and events will populate as they arrive.`})]}),!e.isRunning&&!e.isComplete&&!te&&t===`connected`&&!v&&!(typeof window<`u`&&new URLSearchParams(window.location.search).has(`replay`))&&(0,x.jsxs)(`div`,{className:bw.centerState,children:[(0,x.jsx)(`div`,{className:bw.centerStateHeadingLarger,children:`No simulation running`}),(0,x.jsx)(`div`,{className:bw.centerStateCopyWide,children:`Configure your commanders with different HEXACO personality profiles, choose a scenario, and launch from the Settings tab. Or load a previously saved simulation.`}),(0,x.jsxs)(`div`,{className:bw.emptyStateActions,children:[n&&(0,x.jsx)(`button`,{onClick:N,disabled:v||!p,className:bw.buttonRun,children:v?`Launching…`:p?`Run Simulation`:`Loading scenario…`}),(0,x.jsx)(`button`,{onClick:R,className:bw.buttonLoad,children:`Load Prior Run`}),(0,x.jsx)(`button`,{onClick:z,className:bw.buttonSettings,children:`Settings`})]}),r&&(0,x.jsxs)(`div`,{className:bw.tourHint,children:[`First time here?`,` `,(0,x.jsx)(`button`,{type:`button`,onClick:r,className:bw.tourLink,children:`Take the guided tour →`}),(0,x.jsx)(`span`,{className:bw.tourAside,children:`(canned demo, no LLM cost)`})]}),(0,x.jsx)(`div`,{"data-paracosm-replay-cta":`true`,className:`${bw.replayCtaWrap} ${bw.flashCard}`,children:(0,x.jsx)(OC,{})})]}),pe&&T===`side-by-side`&&e.actorIds.length===2&&(0,x.jsx)($S,{state:e}),pe&&T===`side-by-side`&&e.actorIds.length>=3&&(0,x.jsx)(cC,{state:e}),(0,x.jsx)(AS,{state:e})]}),(0,x.jsx)(xC,{citationRegistry:m,toolRegistry:h,layoutToggle:(0,x.jsx)(jC,{layout:T,actorCount:e.actorIds.length,onChange:w})}),(0,x.jsx)(EC,{enabled:e.isComplete&&!e.isRunning}),(0,x.jsx)(yw,{actorName:E,actorIndex:O>=0?O:0,state:e,onClose:()=>D(null),mode:e.actorIds.length>=5?`dock`:`modal`})]})}function Cw(e,t){return e===`O`?t>.7?`creative`:t<.3?`conventional`:``:e===`C`?t>.7?`disciplined`:t<.3?`flexible`:``:e===`E`?t>.7?`charismatic`:t<.3?`reserved`:``:e===`A`?t>.7?`cooperative`:t<.3?`competitive`:``:e===`Em`?t>.7?`empathetic`:t<.3?`calm`:``:e===`HH`?t>.7?`sincere`:t<.3?`strategic`:``:``}function ww({label:e,shortLabel:t,value:n,onChange:r,sideColor:i}){let a=Cw(t,n),o=i||`var(--amber)`,s={flex:1,accentColor:o,"--pc-range-fill":o,"--pc-range-pct":`${Math.round(n*100)}%`};return(0,x.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`6px`},children:[(0,x.jsx)(`label`,{style:{fontSize:`var(--font-sm)`,color:`var(--text-2)`,minWidth:`32px`,fontWeight:700},children:t}),(0,x.jsx)(`input`,{type:`range`,min:`0`,max:`1`,step:`0.05`,value:n,onChange:e=>r(parseFloat(e.target.value)),className:`pc-range`,style:s,"aria-label":e,"aria-valuetext":n.toFixed(2)}),(0,x.jsx)(`span`,{style:{fontSize:`var(--font-md)`,fontFamily:`var(--mono)`,minWidth:`36px`,textAlign:`right`,color:`var(--text-1)`,fontWeight:600},children:n.toFixed(2)}),(0,x.jsx)(`span`,{style:{fontSize:`var(--font-3xs)`,color:`var(--text-3)`,minWidth:`55px`,fontFamily:`var(--mono)`},children:a})]})}var Tw={notice:`_notice_9kjix_1`,badge:`_badge_9kjix_16`,body:`_body_9kjix_30`,headline:`_headline_9kjix_35`,copy:`_copy_9kjix_43`,links:`_links_9kjix_56`,link:`_link_9kjix_56`};function Ew(){return(0,x.jsxs)(`div`,{className:Tw.notice,role:`note`,"aria-label":`Pluggable trait models`,children:[(0,x.jsx)(`span`,{className:Tw.badge,"aria-hidden":`true`,children:`NEW`}),(0,x.jsxs)(`div`,{className:Tw.body,children:[(0,x.jsx)(`div`,{className:Tw.headline,children:`Leaders accept pluggable trait models.`}),(0,x.jsxs)(`p`,{className:Tw.copy,children:[`The dashboard form below configures HEXACO leaders today. The API also accepts `,(0,x.jsx)(`code`,{children:`ai-agent`}),` leaders (six axes for AI-system decision-makers: exploration, verification-rigor, deference, risk-tolerance, transparency, instruction-following). Slider generalization for non-HEXACO models is queued; in the meantime, supply a`,` `,(0,x.jsx)(`code`,{children:`traitProfile`}),` field via`,` `,(0,x.jsx)(`code`,{children:`runSimulation(leader, ...)`}),` directly.`]}),(0,x.jsxs)(`div`,{className:Tw.links,children:[(0,x.jsx)(`a`,{href:`https://github.com/framerslab/paracosm/blob/master/docs/COOKBOOK.md#pluggable-traits-ai-agent-end-to-end`,target:`_blank`,rel:`noopener`,className:Tw.link,children:`Captured ai-agent end-to-end run`}),(0,x.jsx)(`a`,{href:`https://github.com/framerslab/paracosm/blob/master/docs/COOKBOOK.md#pluggable-traits-ai-agent-end-to-end`,target:`_blank`,rel:`noopener`,className:Tw.link,children:`Trait-model cookbook`})]})]})]})}var Dw={root:`_root_5ydsz_1`,heading:`_heading_5ydsz_11`,fieldRow:`_fieldRow_5ydsz_23`,field:`_field_5ydsz_23`,label:`_label_5ydsz_33`,presetLabel:`_presetLabel_5ydsz_33`,input:`_input_5ydsz_44`,presetSelect:`_presetSelect_5ydsz_44`,textarea:`_textarea_5ydsz_44`,textareaBlock:`_textareaBlock_5ydsz_61`,presetRow:`_presetRow_5ydsz_72`,hexacoGrid:`_hexacoGrid_5ydsz_91`},Ow=[{key:`openness`,label:`Openness`,short:`O`},{key:`conscientiousness`,label:`Conscientiousness`,short:`C`},{key:`extraversion`,label:`Extraversion`,short:`E`},{key:`agreeableness`,label:`Agreeableness`,short:`A`},{key:`emotionality`,label:`Emotionality`,short:`Em`},{key:`honestyHumility`,label:`Honesty-Humility`,short:`HH`}],kw=[{id:`visionary`,label:`The Visionary (high O, low C)`,hexaco:{openness:.95,conscientiousness:.35,extraversion:.85,agreeableness:.55,emotionality:.3,honestyHumility:.65}},{id:`engineer`,label:`The Engineer (high C, low O)`,hexaco:{openness:.25,conscientiousness:.97,extraversion:.3,agreeableness:.6,emotionality:.7,honestyHumility:.9}},{id:`diplomat`,label:`The Diplomat (high A, high HH)`,hexaco:{openness:.6,conscientiousness:.55,extraversion:.7,agreeableness:.9,emotionality:.5,honestyHumility:.85}},{id:`maverick`,label:`The Maverick (high O, high E, low A)`,hexaco:{openness:.9,conscientiousness:.4,extraversion:.95,agreeableness:.25,emotionality:.2,honestyHumility:.4}},{id:`guardian`,label:`The Guardian (high C, high Em, high HH)`,hexaco:{openness:.3,conscientiousness:.85,extraversion:.4,agreeableness:.7,emotionality:.85,honestyHumility:.95}},{id:`strategist`,label:`The Strategist (balanced, low Em)`,hexaco:{openness:.65,conscientiousness:.75,extraversion:.5,agreeableness:.45,emotionality:.2,honestyHumility:.55}},{id:`balanced`,label:`Balanced (all 0.50)`,hexaco:{openness:.5,conscientiousness:.5,extraversion:.5,agreeableness:.5,emotionality:.5,honestyHumility:.5}}];function Aw({label:e,sideColor:t,data:n,onChange:r}){let i=(0,b.useId)(),a=`${i}-name`,o=`${i}-archetype`,s=`${i}-unit`,c=`${i}-instructions`,l=`${i}-preset`,u=(e,t)=>r({...n,[e]:t}),d=(e,t)=>r({...n,hexaco:{...n.hexaco,[e]:t}});return(0,x.jsxs)(`div`,{className:Dw.root,style:{"--side-color":t},children:[(0,x.jsx)(`h3`,{className:Dw.heading,children:e}),(0,x.jsxs)(`div`,{className:`responsive-stack ${Dw.fieldRow}`,children:[(0,x.jsxs)(`div`,{className:Dw.field,children:[(0,x.jsx)(`label`,{htmlFor:a,className:Dw.label,children:`Name`}),(0,x.jsx)(`input`,{id:a,value:n.name,onChange:e=>u(`name`,e.target.value),className:Dw.input})]}),(0,x.jsxs)(`div`,{className:Dw.field,children:[(0,x.jsx)(`label`,{htmlFor:o,className:Dw.label,children:`Archetype`}),(0,x.jsx)(`input`,{id:o,value:n.archetype,onChange:e=>u(`archetype`,e.target.value),className:Dw.input})]}),(0,x.jsxs)(`div`,{className:Dw.field,children:[(0,x.jsx)(`label`,{htmlFor:s,className:Dw.label,children:`Unit`}),(0,x.jsx)(`input`,{id:s,value:n.unit,onChange:e=>u(`unit`,e.target.value),className:Dw.input})]})]}),(0,x.jsxs)(`div`,{className:Dw.textareaBlock,children:[(0,x.jsx)(`label`,{htmlFor:c,className:Dw.label,children:`Instructions`}),(0,x.jsx)(`textarea`,{id:c,value:n.instructions,onChange:e=>u(`instructions`,e.target.value),rows:3,className:Dw.textarea})]}),(0,x.jsx)(Ew,{}),(0,x.jsxs)(`div`,{className:Dw.presetRow,children:[(0,x.jsx)(`label`,{htmlFor:l,className:Dw.presetLabel,children:`Personality`}),(0,x.jsxs)(`select`,{id:l,className:`pc-select ${Dw.presetSelect}`,onChange:e=>{let t=kw.find(t=>t.id===e.target.value);t&&r({...n,hexaco:{...t.hexaco}})},defaultValue:``,children:[(0,x.jsx)(`option`,{value:``,disabled:!0,children:`Apply preset...`}),kw.map(e=>(0,x.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),(0,x.jsx)(`div`,{className:`responsive-grid-3 ${Dw.hexacoGrid}`,children:Ow.map(e=>(0,x.jsx)(ww,{label:e.label,shortLabel:e.short,value:n.hexaco[e.key]??.5,onChange:t=>d(e.key,t),sideColor:t},e.key))})]})}function jw(e){let t={scenario:e.scenario,webSearch:e.webSearch},n=e.seedUrl.trim(),r=e.seedText.trim(),i=e.provider?.trim(),a=e.model?.trim(),o=Number.parseInt(e.maxSearches,10);return n?t.seedUrl=n:r&&(t.seedText=r),Number.isFinite(o)&&o>0&&(t.maxSearches=o),i&&(t.provider=i),a&&(t.model=a),t}async function Mw(e){if(e.ok)return null;try{let t=await e.json();if(typeof t.error==`string`&&t.error.length>0)return t.error}catch{}return`The compile was refused (HTTP ${e.status}).`}var Nw={display:`block`,fontFamily:`var(--mono)`,fontSize:11,fontWeight:700,letterSpacing:`0.08em`,textTransform:`uppercase`,color:`var(--text-3)`,marginBottom:4},Pw={fontFamily:`var(--mono)`,fontSize:13,fontWeight:800,letterSpacing:`0.08em`,textTransform:`uppercase`,color:`var(--text-2)`},Fw={width:`100%`,padding:`6px 10px`,background:`var(--bg-card)`,color:`var(--text-3)`,border:`1px solid var(--border)`,borderRadius:3,cursor:`pointer`,fontFamily:`var(--mono)`,fontSize:10,fontWeight:800,letterSpacing:`0.08em`,textTransform:`uppercase`},Iw={card:`_card_m5xbp_1`,header:`_header_m5xbp_10`,title:`_title_m5xbp_20`,lead:`_lead_m5xbp_28`,btnRow:`_btnRow_m5xbp_34`,btn:`_btn_m5xbp_34`,amber:`_amber_m5xbp_53`,fileInput:`_fileInput_m5xbp_58`,editorWrap:`_editorWrap_m5xbp_62`,editor:`_editor_m5xbp_62`,statusBar:`_statusBar_m5xbp_83`,seedDetails:`_seedDetails_m5xbp_93`,seedSummary:`_seedSummary_m5xbp_97`,seedBody:`_seedBody_m5xbp_105`,input:`_input_m5xbp_112`,textarea:`_textarea_m5xbp_123`,checkboxLabel:`_checkboxLabel_m5xbp_136`,fineprint:`_fineprint_m5xbp_144`,progressWrap:`_progressWrap_m5xbp_151`,progressRow:`_progressRow_m5xbp_157`,progressStatus:`_progressStatus_m5xbp_166`,result:`_result_m5xbp_170`,actions:`_actions_m5xbp_178`,actionBtn:`_actionBtn_m5xbp_186`,primary:`_primary_m5xbp_203`,spacer:`_spacer_m5xbp_214`,memCount:`_memCount_m5xbp_218`},Lw={id:`my-scenario`,version:`1.0.0`,engineArchetype:`closed_turn_based_settlement`,labels:{name:`My Scenario`,shortName:`custom`,populationNoun:`agents`,settlementNoun:`settlement`,currency:`credits`},theme:{primaryColor:`#6366f1`,accentColor:`#818cf8`},setup:{defaultTurns:8,defaultSeed:100,defaultStartTime:2040,defaultPopulation:50,configurableSections:[`actors`,`departments`,`models`]},departments:[{id:`operations`,label:`Operations`,role:`Operations Lead`,icon:``,defaultModel:`gpt-5.4-mini`,instructions:`You analyze operations.`},{id:`research`,label:`Research`,role:`Head of Research`,icon:``,defaultModel:`gpt-5.4-mini`,instructions:`You analyze research.`}],metrics:[{id:`population`,label:`Population`,source:`metrics.population`,format:`number`}],effects:{environmental:{morale:.08},resource:{morale:.05}},ui:{headerMetrics:[{id:`population`,format:`number`}],tooltipFields:[],reportSections:[`crisis`],departmentIcons:{},setupSections:[`actors`]},policies:{toolForging:{enabled:!0},liveSearch:{enabled:!1,mode:`off`},bulletin:{enabled:!0},characterChat:{enabled:!0},sandbox:{timeoutMs:1e4,memoryMB:128}},presets:[]},Rw=`paracosm:editorCompileResult`;function zw(){try{let e=window.sessionStorage.getItem(Rw);if(!e)return null;let t=JSON.parse(e);return typeof t.message==`string`?{success:t.success===!0,message:t.message}:null}catch{return null}}function Bw({onAdminWrite:e}){let[t,n]=(0,b.useState)({adminWrite:!1,memoryScenarios:[]}),[r,i]=(0,b.useState)(``),[a,o]=(0,b.useState)(``),[s,c]=(0,b.useState)(``),[l,u]=(0,b.useState)(``),[d,f]=(0,b.useState)(!0),[p,m]=(0,b.useState)(`5`),[h,g]=(0,b.useState)(``),[_,v]=(0,b.useState)(``),[y,S]=(0,b.useState)(!1),[C,w]=(0,b.useState)(!1),[T,O]=(0,b.useState)([]),[k,A]=(0,b.useState)(()=>zw()),j=(0,b.useRef)(null),ee=(0,b.useRef)(null);(0,b.useEffect)(()=>{fetch(`/admin-config`).then(e=>e.json()).then(t=>{n(t),e?.(t.adminWrite===!0)}).catch(()=>{});try{window.sessionStorage.removeItem(Rw)}catch{}},[]);let M=(0,b.useCallback)(()=>{fetch(`/scenario`).then(e=>e.ok?e.json():null).then(e=>{e?.id&&i(JSON.stringify(e,null,2))}).catch(()=>{})},[]);(0,b.useEffect)(()=>(M(),D(window,M)),[M]),(0,b.useEffect)(()=>{if(!r.trim())o(``);else try{JSON.parse(r),o(``)}catch(e){o(String(e).replace(`SyntaxError: `,``))}},[r]);let N=()=>i(JSON.stringify(Lw,null,2)),ne=(0,b.useCallback)(async()=>{try{let e=await(await fetch(`/scenario`)).json();i(JSON.stringify(e,null,2)),A({success:!0,message:`Loaded active scenario: ${e.labels?.name||e.id}`})}catch(e){A({success:!1,message:`Failed to load: ${e}`})}},[]),P=()=>j.current?.click(),re=e=>{let t=e.target.files?.[0];if(!t)return;let n=new FileReader;n.onload=()=>{let e=n.result;i(e);try{JSON.parse(e),A({success:!0,message:`Imported ${t.name} (${(t.size/1024).toFixed(1)}KB)`})}catch{A({success:!1,message:`Imported ${t.name} but JSON is invalid`})}},n.readAsText(t),e.target.value=``},ie=()=>{if(r.trim())try{let e=JSON.parse(r),t=e.id||`scenario`,n=new Blob([JSON.stringify(e,null,2)],{type:`application/json`}),i=URL.createObjectURL(n),a=document.createElement(`a`);a.href=i,a.download=`${t}.json`,a.click(),URL.revokeObjectURL(i),A({success:!0,message:`Exported ${t}.json`})}catch{A({success:!1,message:`Fix JSON errors before exporting`})}},F=(0,b.useCallback)(async()=>{if(r.trim()&&!a){w(!0);try{let e=JSON.parse(r),t=await(await fetch(`/scenario/store`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scenario:e,saveToDisk:!1})})).json();t.stored?(E(window),A({success:!0,message:t.switchable?`Stored "${t.id}" in memory and added it to the scenario selector.`:`Stored "${t.id}" as draft JSON in memory. Compile it to make it runnable and switchable.`}),n(e=>({...e,memoryScenarios:[...new Set([...e.memoryScenarios,t.id])]}))):A({success:!1,message:t.error||`Store failed`})}catch(e){A({success:!1,message:String(e)})}w(!1)}},[r,a]),I=(0,b.useCallback)(async()=>{if(r.trim()&&!a&&t.adminWrite)try{let e=JSON.parse(r),t=B(),n=xe(t);if(n){A({success:!1,message:n});return}let i=await fetch(`/scenario/store`,{method:`POST`,headers:{"Content-Type":`application/json`,...t?{[fe]:t}:{}},body:JSON.stringify({scenario:e,saveToDisk:!0})}),a=await i.json();a.savedToDisk?(E(window),A({success:!0,message:a.switchable?`Saved "${a.id}" to disk at scenarios/${a.id}.json and loaded it into the live scenario catalog.`:`Saved "${a.id}" draft JSON to disk at scenarios/${a.id}.json. Compile it to make it runnable after restart.`})):i.status===401?(be(t),A({success:!1,message:`Disk write refused: the admin token is missing or wrong. ${R}`})):A({success:!1,message:a.error||`Disk write refused (HTTP ${i.status})`})}catch(e){A({success:!1,message:String(e)})}},[r,a,t.adminWrite]),ae=(0,b.useCallback)(async()=>{if(!r.trim()||a)return;let e;try{e=JSON.parse(r)}catch{A({success:!1,message:`Fix JSON errors before compiling`});return}S(!0),O([]),A(null);try{let t=jw({scenario:e,seedText:s,seedUrl:l,webSearch:d,maxSearches:p,provider:h,model:_}),n=await fetch(`/compile`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)}),r=await Mw(n);if(r!==null){A({success:!1,message:r}),S(!1);return}let i=n.body?.getReader();if(!i)throw Error(`No response stream`);let a=new TextDecoder,o=``;for(;;){let{done:e,value:t}=await i.read();if(e)break;o+=a.decode(t,{stream:!0});let n=o.split(`
125
125
  `);o=n.pop()||``;for(let e of n)if(e.startsWith(`data: `))try{let t=JSON.parse(e.slice(6));if(t.hook&&O(e=>{let n=e.findIndex(e=>e.hook===t.hook);if(n>=0){let r=[...e];return r[n]=t,r}return[...e,t]}),t.id){let e=null;try{let n=await fetch(`/scenario/switch`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t.id})});n.ok||(e=(await n.json().catch(()=>({}))).error??`HTTP ${n.status}`)}catch(t){e=String(t)}if(e){A({success:!1,message:`Compiled ${t.id}, but switching to it failed: ${e}`});continue}try{window.sessionStorage.setItem(Rw,JSON.stringify({success:!0,message:`Compiled: ${t.id} (${t.departments} departments, ${t.hooks} hooks). Configure actors below and launch.`}))}catch{}te(),window.location.reload();return}t.error&&A({success:!1,message:t.error})}catch{}}}catch(e){A({success:!1,message:String(e)})}S(!1)},[r,a,s,l,d,p,h,_]),oe=r.split(`
126
- `).length,se=new Blob([r]).size;return(0,x.jsxs)(`div`,{className:Iw.card,children:[(0,x.jsxs)(`div`,{className:Iw.header,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`h3`,{className:Iw.title,children:`Scenario Editor`}),(0,x.jsxs)(`p`,{className:Iw.lead,children:[`Write or import a scenario JSON draft. Add seed text or a URL to ground it, then compile or export.`,!t.adminWrite&&` Disk saves are disabled on this instance.`]})]}),(0,x.jsxs)(`div`,{className:Iw.btnRow,children:[(0,x.jsx)(`button`,{onClick:ne,className:[Iw.btn,Iw.amber].join(` `),"aria-label":`Load active scenario JSON`,children:`Load Active`}),(0,x.jsx)(`button`,{onClick:N,className:Iw.btn,"aria-label":`Load example scenario`,children:`Template`}),(0,x.jsx)(`button`,{onClick:P,className:Iw.btn,"aria-label":`Import JSON file`,children:`Import`}),(0,x.jsx)(`button`,{onClick:ie,className:Iw.btn,disabled:!r.trim()||!!a,"aria-label":`Export as JSON file`,children:`Export`}),(0,x.jsx)(`input`,{ref:j,type:`file`,accept:`.json,application/json`,onChange:re,className:Iw.fileInput})]})]}),(0,x.jsxs)(`div`,{className:Iw.editorWrap,children:[(0,x.jsx)(`textarea`,{ref:ee,value:r,onChange:e=>i(e.target.value),placeholder:`{\\n "id": "my-scenario",\\n "labels": { "name": "My World" },\\n "departments": [...]\\n}`,spellCheck:!1,"aria-label":`Scenario JSON editor`,className:Iw.editor}),(0,x.jsxs)(`div`,{className:Iw.statusBar,style:{"--status-color":a?`var(--rust)`:`var(--text-3)`},children:[(0,x.jsx)(`span`,{children:a||(r.trim()?`Valid JSON`:`Empty`)}),(0,x.jsxs)(`span`,{children:[oe,` lines, `,(se/1024).toFixed(1),`KB`]})]})]}),(0,x.jsxs)(`details`,{className:Iw.seedDetails,children:[(0,x.jsx)(`summary`,{className:Iw.seedSummary,children:`Seed Enrichment (optional)`}),(0,x.jsxs)(`div`,{className:Iw.seedBody,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:Nw,children:`Seed Text`}),(0,x.jsx)(`textarea`,{value:s,onChange:e=>c(e.target.value),placeholder:`Paste a prompt, notes, a brief, or source text to turn into research facts and category mapping.`,className:Iw.textarea})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:Nw,children:`Seed URL (fetched via Firecrawl)`}),(0,x.jsx)(`input`,{value:l,onChange:e=>u(e.target.value),placeholder:`https://example.com/article`,className:Iw.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:Nw,children:`Max Web Searches`}),(0,x.jsx)(`input`,{value:p,onChange:e=>m(e.target.value),inputMode:`numeric`,placeholder:`5`,className:Iw.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:Nw,children:`Compile Provider Override`}),(0,x.jsx)(`input`,{value:h,onChange:e=>g(e.target.value),placeholder:`anthropic or openai (optional)`,className:Iw.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:Nw,children:`Compile Model Override`}),(0,x.jsx)(`input`,{value:_,onChange:e=>v(e.target.value),placeholder:`gpt-5.4-mini, claude-sonnet-4-6, etc. (optional)`,className:Iw.input})]}),(0,x.jsxs)(`label`,{className:Iw.checkboxLabel,children:[(0,x.jsx)(`input`,{type:`checkbox`,checked:d,onChange:e=>f(e.target.checked)}),`Web search enrichment (requires Serper/Tavily/Firecrawl API keys)`]}),(0,x.jsx)(`p`,{className:Iw.fineprint,children:`If both seed text and a seed URL are provided, the URL takes precedence and the compiler ingests the fetched page.`})]})]}),T.length>0&&(0,x.jsx)(`div`,{className:Iw.progressWrap,children:T.map(e=>(0,x.jsxs)(`div`,{className:Iw.progressRow,children:[(0,x.jsx)(`span`,{children:e.status===`done`?`✔`:e.status===`generating`?`⏳`:e.status===`cached`?`✔`:`•`}),(0,x.jsx)(`span`,{children:e.hook}),(0,x.jsx)(`span`,{className:Iw.progressStatus,children:e.status})]},e.hook))}),k&&(0,x.jsx)(`div`,{className:Iw.result,style:{"--result-color":k.success?`var(--green)`:`var(--rust)`,"--result-bg":k.success?`rgba(106,173,72,.06)`:`rgba(224,101,48,.06)`},children:k.message}),(0,x.jsxs)(`div`,{className:Iw.actions,children:[(0,x.jsx)(`button`,{onClick:F,disabled:!r.trim()||!!a||C,className:Iw.actionBtn,"aria-label":`Store scenario in memory`,children:C?`Storing...`:`Store in Memory`}),(0,x.jsx)(`button`,{onClick:ae,disabled:!r.trim()||!!a||y,className:[Iw.actionBtn,Iw.primary].join(` `),"aria-label":`Compile scenario`,children:y?`Compiling...`:`Compile Scenario`}),t.adminWrite&&(0,x.jsx)(`button`,{onClick:I,disabled:!r.trim()||!!a,className:[Iw.actionBtn,Iw.amber].join(` `),"aria-label":`Save scenario to disk`,children:`Save to Disk`}),(0,x.jsx)(`span`,{className:Iw.spacer}),t.memoryScenarios.length>0&&(0,x.jsxs)(`span`,{className:Iw.memCount,children:[t.memoryScenarios.length,` in memory`]})]})]})}var Vw={intro:`_intro_v1quw_1`,label:`_label_v1quw_13`,row:`_row_v1quw_24`,input:`_input_v1quw_31`,btn:`_btn_v1quw_45`,amber:`_amber_v1quw_65`,status:`_status_v1quw_70`,refusal:`_refusal_v1quw_77`},Hw={none:`No token is saved in this browser.`,stored:`A token is saved in this browser. It is not shown back.`,held:`This browser could not store the token, so it is kept only until this page reloads.`};function Uw(){let e=(0,b.useRef)(null),[t,n]=(0,b.useState)(!1),[r,i]=(0,b.useState)(()=>ve()),[a,o]=(0,b.useState)(null);(0,b.useEffect)(()=>Se(()=>i(ve())),[]);let s=()=>{e.current&&(e.current.value=``),n(!1)},c=()=>{let t=e.current?.value??``;if(!t.trim())return;let n=ye(t);n===`unsendable`?o(z):(o(null),i(n),s())};return(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`p`,{className:Vw.intro,children:[`Admin writes on this server take its `,(0,x.jsx)(`code`,{children:`ADMIN_TOKEN`}),`: Save to Disk in the scenario editor below, Delete server data in the run actions menu, and Rename and Delete in a scenario's details. Enter the token once. The dashboard sends it only on those requests, as the `,(0,x.jsx)(`code`,{children:`X-Admin-Token`}),` header, and keeps it in this browser.`]}),(0,x.jsx)(`label`,{htmlFor:`admin-token`,className:Vw.label,children:`Token for this server`}),(0,x.jsxs)(`div`,{className:Vw.row,children:[(0,x.jsx)(`input`,{id:`admin-token`,type:`password`,autoComplete:`off`,spellCheck:!1,ref:e,onChange:e=>{n(e.target.value.trim()!==``),o(null)},onKeyDown:e=>{e.key===`Enter`&&c()},placeholder:r===`none`?`Not entered`:`Saved`,"aria-describedby":`admin-token-status`,className:Vw.input}),(0,x.jsx)(`button`,{type:`button`,onClick:c,disabled:!t,className:[Vw.btn,Vw.amber].join(` `),"aria-label":`Save admin token`,children:`Save`}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>{be(),i(`none`),o(null),s()},disabled:r===`none`&&!t,className:Vw.btn,"aria-label":`Clear admin token`,children:`Clear`})]}),(0,x.jsx)(`div`,{id:`admin-token-status`,role:`status`,className:Vw.status,children:Hw[r]}),a&&(0,x.jsx)(`p`,{role:`alert`,className:Vw.refusal,children:a})]})}var Ww={bar:`_bar_127em_1`,topRow:`_topRow_127em_15`,searchWrap:`_searchWrap_127em_22`,searchIcon:`_searchIcon_127em_30`,searchInput:`_searchInput_127em_35`,resetButton:`_resetButton_127em_50`,facetsRow:`_facetsRow_127em_76`,facetLabel:`_facetLabel_127em_83`,checkboxGroup:`_checkboxGroup_127em_93`,checkbox:`_checkbox_127em_93`,active:`_active_127em_115`,leaderSelect:`_leaderSelect_127em_128`,rangeWrap:`_rangeWrap_127em_142`,rangeInput:`_rangeInput_127em_151`,toolChip:`_toolChip_127em_162`,chipClear:`_chipClear_127em_176`,emptyHint:`_emptyHint_127em_188`};function Gw(e){return e.query!==``||e.types.size>0||e.leader!==null||e.turnRange!==null||e.toolHash!==``}function Kw({events:e,filters:t,onFiltersChange:n}){let r=(0,b.useMemo)(()=>$m(e),[e]),i=Gw(t),a=e=>{n({...t,...e})},o=e=>{let n=new Set(t.types);n.has(e)?n.delete(e):n.add(e),a({types:n})},s=e=>t.types.size===0||t.types.has(e);return(0,x.jsxs)(`div`,{className:Ww.bar,children:[(0,x.jsxs)(`div`,{className:Ww.topRow,children:[(0,x.jsxs)(`div`,{className:Ww.searchWrap,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Ww.searchIcon,children:`🔍`}),(0,x.jsx)(`input`,{type:`search`,"aria-label":`Filter log by text (type, leader, department, title, summary)`,placeholder:`Search type, leader, department, title, summary...`,value:t.query,onChange:e=>a({query:e.target.value}),className:Ww.searchInput})]}),t.toolHash&&(0,x.jsxs)(`span`,{className:Ww.toolChip,children:[`tool: `,t.toolHash,(0,x.jsx)(`button`,{type:`button`,"aria-label":`Clear tool filter`,className:Ww.chipClear,onClick:()=>a({toolHash:``,toolExact:!1}),children:`×`})]}),(0,x.jsx)(`button`,{type:`button`,className:Ww.resetButton,disabled:!i,onClick:()=>n(Jm()),children:`Reset filters`})]}),r.types.length>0&&(0,x.jsxs)(`div`,{className:Ww.facetsRow,children:[(0,x.jsx)(`span`,{className:Ww.facetLabel,children:`types`}),(0,x.jsx)(`div`,{className:Ww.checkboxGroup,children:r.types.map(e=>{let t=s(e);return(0,x.jsxs)(`label`,{className:[Ww.checkbox,t?Ww.active:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`input`,{type:`checkbox`,checked:t,onChange:()=>o(e)}),e]},e)})})]}),(r.actors.length>1||r.maxTurn>3)&&(0,x.jsxs)(`div`,{className:Ww.facetsRow,children:[r.actors.length>1&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:Ww.facetLabel,children:`leader`}),(0,x.jsxs)(`select`,{"aria-label":`Filter by leader`,className:Ww.leaderSelect,value:t.leader??``,onChange:e=>a({leader:e.target.value||null}),children:[(0,x.jsx)(`option`,{value:``,children:`all`}),r.actors.map(e=>(0,x.jsx)(`option`,{value:e,children:e},e))]})]}),r.maxTurn>3&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:Ww.facetLabel,children:`turns`}),(0,x.jsxs)(`div`,{className:Ww.rangeWrap,children:[(0,x.jsx)(`input`,{type:`number`,"aria-label":`Min turn`,min:0,max:r.maxTurn,value:t.turnRange?t.turnRange[0]:0,onChange:e=>{let n=Number(e.target.value);if(!Number.isFinite(n))return;let i=t.turnRange?.[1]??r.maxTurn;a({turnRange:[n,Math.max(n,i)]})},className:Ww.rangeInput}),(0,x.jsx)(`span`,{children:`to`}),(0,x.jsx)(`input`,{type:`number`,"aria-label":`Max turn`,min:0,max:r.maxTurn,value:t.turnRange?t.turnRange[1]:r.maxTurn,onChange:e=>{let n=Number(e.target.value);if(!Number.isFinite(n))return;let r=t.turnRange?.[0]??0;a({turnRange:[Math.min(r,n),n]})},className:Ww.rangeInput}),t.turnRange&&(0,x.jsx)(`button`,{type:`button`,className:Ww.chipClear,"aria-label":`Clear turn range`,onClick:()=>a({turnRange:null}),children:`×`})]})]})]}),t.types.size>0&&t.types.size===r.types.length&&(0,x.jsx)(`div`,{className:Ww.emptyHint,children:`All types selected — filter is a no-op on this axis.`})]})}var qw={panel:`_panel_aavxx_1`,header:`_header_aavxx_6`,heading:`_heading_aavxx_15`,filterBar:`_filterBar_aavxx_26`,filterLabel:`_filterLabel_aavxx_34`,filterValue:`_filterValue_aavxx_38`,emptyState:`_emptyState_aavxx_43`,event:`_event_aavxx_48`,eventSummary:`_eventSummary_aavxx_53`,index:`_index_aavxx_61`,type:`_type_aavxx_67`,leader:`_leader_aavxx_73`,turn:`_turn_aavxx_81`,title:`_title_aavxx_85`,department:`_department_aavxx_89`,outcome:`_outcome_aavxx_93`,dataBlock:`_dataBlock_aavxx_98`},Jw={status:`var(--teal)`,turn_start:`var(--rust)`,turn_done:`var(--rust)`,specialist_start:`var(--text-3)`,specialist_done:`var(--green)`,decision_pending:`var(--amber)`,decision_made:`var(--amber)`,outcome:`#e8b44a`,drift:`var(--teal)`,agent_reactions:`#6aad48`,bulletin:`var(--text-2)`,promotion:`var(--teal)`};function Yw(){return typeof window>`u`?rh(``,``):rh(window.location.search,window.location.hash)}function Xw({events:e}){let t=(0,b.useRef)(null),n=(0,b.useRef)(!0),[r,i]=(0,b.useState)(Yw);(0,b.useEffect)(()=>{let e=()=>i(Yw());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]);let a=(0,b.useCallback)(()=>{let e=t.current;e&&(n.current=e.scrollHeight-e.scrollTop-e.clientHeight<40)},[]);(0,b.useEffect)(()=>{if(!n.current)return;let e=t.current;e&&(e.scrollTop=e.scrollHeight)},[e.length]);let o=(0,b.useCallback)(e=>{i(t=>{try{let n=t.toolHash!==``&&e.toolHash===``;window.history.replaceState({},``,nh(window.location.href,e,n))}catch{}return e})},[]),s=Ym(e,r),c=r.query!==``||r.types.size>0||r.leader!==null||r.turnRange!==null||r.toolHash!==``;return(0,x.jsxs)(`div`,{ref:t,onScroll:a,className:`flex-1 overflow-y-auto p-4 font-mono text-xs ${qw.panel}`,role:`log`,"aria-label":`Event log`,"aria-live":`polite`,children:[(0,x.jsx)(`div`,{className:qw.header,children:(0,x.jsxs)(`h2`,{className:qw.heading,children:[`Event Log (`,s.length,c?` of ${e.length}`:``,` events)`]})}),(0,x.jsx)(Kw,{events:e,filters:r,onFiltersChange:o}),s.length===0&&(0,x.jsx)(`div`,{className:qw.emptyState,children:c?`No events matched the current filter. Adjust or press Reset.`:`No events yet. Run a simulation to see the raw SSE event stream.`}),s.map((e,t)=>{let n=Jw[e.type]||`var(--text-3)`,r=e.data&&Object.keys(e.data).length>0;return(0,x.jsxs)(`details`,{className:qw.event,style:{"--log-type-color":n},children:[(0,x.jsxs)(`summary`,{className:qw.eventSummary,children:[(0,x.jsx)(`span`,{className:qw.index,children:t}),(0,x.jsx)(`span`,{className:qw.type,children:e.type}),(0,x.jsx)(`span`,{className:qw.leader,children:e.leader}),e.data?.turn!=null&&(0,x.jsxs)(`span`,{className:qw.turn,children:[`T`,String(e.data.turn)]}),!!e.data?.title&&(0,x.jsx)(`span`,{className:qw.title,children:String(e.data.title)}),!!e.data?.department&&(0,x.jsx)(`span`,{className:qw.department,children:String(e.data.department)}),!!e.data?.outcome&&(0,x.jsx)(`span`,{className:qw.outcome,children:String(e.data.outcome)})]}),r&&(0,x.jsx)(`pre`,{className:qw.dataBlock,children:JSON.stringify(e.data,null,2)})]},t)})]})}var Zw=[{value:`economy`,label:`Economy`,description:`Cheapest path: gated research, cheap verdicts, tighter spend controls.`},{value:`balanced`,label:`Balanced`,description:`Current default mix for good quality per dollar on normal runs.`},{value:`quality`,label:`Quality`,description:`Push strategic roles and verdict synthesis upward when quality matters more than spend.`},{value:`deterministic_first`,label:`Deterministic First`,description:`Skip verdict synthesis and live-search escalation to reduce variance and cost.`}];function Qw(e){switch(e){case`hosted_demo`:return{label:`Hosted demo`,description:`Host-billed runs are capped and forced onto the economy guardrails.`};case`platform_api`:return{label:`Platform API`,description:"Authenticated `/api/v1/*` routes are enabled; demo-only assumptions are off."};default:return{label:`Local demo`,description:`Single-process local server. Good for product exploration, not a hosted control plane.`}}}var Y={root:`_root_34x3m_1`,content:`_content_34x3m_9`,scenarioRow:`_scenarioRow_34x3m_17`,scenarioLabel:`_scenarioLabel_34x3m_29`,scenarioSelect:`_scenarioSelect_34x3m_34`,scenarioActiveTag:`_scenarioActiveTag_34x3m_45`,scenarioActiveValue:`_scenarioActiveValue_34x3m_51`,h2:`_h2_34x3m_55`,lead:`_lead_34x3m_62`,scenarioTagline:`_scenarioTagline_34x3m_68`,scenarioSourceLink:`_scenarioSourceLink_34x3m_77`,leadHint:`_leadHint_34x3m_92`,leadStrong:`_leadStrong_34x3m_99`,leadersGrid:`_leadersGrid_34x3m_103`,leaderCardWrap:`_leaderCardWrap_34x3m_120`,leaderRemoveBtn:`_leaderRemoveBtn_34x3m_124`,leadersAddRow:`_leadersAddRow_34x3m_153`,leaderAddBtn:`_leaderAddBtn_34x3m_162`,leaderAddCap:`_leaderAddCap_34x3m_191`,fieldset:`_fieldset_34x3m_199`,legend:`_legend_34x3m_208`,demoBanner:`_demoBanner_34x3m_212`,demoBannerLabel:`_demoBannerLabel_34x3m_223`,simRow5:`_simRow5_34x3m_227`,grid3:`_grid3_34x3m_233`,grid2:`_grid2_34x3m_240`,input:`_input_34x3m_246`,locked:`_locked_34x3m_258`,lockTag:`_lockTag_34x3m_263`,fieldHint:`_fieldHint_34x3m_270`,keysIntro:`_keysIntro_34x3m_277`,keysIntroPara:`_keysIntroPara_34x3m_284`,keysIntroParaLast:`_keysIntroParaLast_34x3m_288`,keysIntroBoldNeutral:`_keysIntroBoldNeutral_34x3m_292`,keysIntroBoldGreen:`_keysIntroBoldGreen_34x3m_296`,keysIntroBoldAmber:`_keysIntroBoldAmber_34x3m_300`,keysIntroBoldRust:`_keysIntroBoldRust_34x3m_304`,keyEnvTag:`_keyEnvTag_34x3m_308`,modelTiersIntro:`_modelTiersIntro_34x3m_316`,demoMode:`_demoMode_34x3m_323`,demoModeStrong:`_demoModeStrong_34x3m_333`,launchRow:`_launchRow_34x3m_337`,launchBtn:`_launchBtn_34x3m_346`,launchStatus:`_launchStatus_34x3m_364`},$w=[{id:`config`,label:`Settings`},{id:`log`,label:`Event Log`}],eT={openness:.5,conscientiousness:.5,extraversion:.5,agreeableness:.5,emotionality:.5,honestyHumility:.5},tT={openai:[{value:`gpt-5.4-nano`,label:`gpt-5.4-nano ($0.20 / $1.25 per 1M)`},{value:`gpt-5.4-mini`,label:`gpt-5.4-mini ($0.75 / $4.50 per 1M)`},{value:`gpt-5.4`,label:`gpt-5.4 ($2.50 / $15.00 per 1M)`},{value:`gpt-5.4-pro`,label:`gpt-5.4-pro ($30 / $180 per 1M — avoid)`}],anthropic:[{value:`claude-haiku-4-5-20251001`,label:`Haiku 4.5 ($1 / $5 per 1M)`},{value:`claude-sonnet-4-6`,label:`Sonnet 4.6 ($3 / $15 per 1M)`},{value:`claude-opus-4-7`,label:`Opus 4.7 ($5 / $25 per 1M)`}]},nT={openai:{departments:`gpt-5.4`,commander:`gpt-5.4-mini`,director:`gpt-5.4-mini`,judge:`gpt-5.4-mini`,agentReactions:`gpt-5.4-nano`},anthropic:{departments:`claude-sonnet-4-6`,commander:`claude-haiku-4-5-20251001`,director:`claude-haiku-4-5-20251001`,judge:`claude-haiku-4-5-20251001`,agentReactions:`claude-haiku-4-5-20251001`}},rT={departments:{label:`Departments (forges)`,help:`Writes code, schemas, test cases. Quality matters — cheap tier produces broken forges.`},commander:{label:`Commander`,help:`Picks option from department reports. Mid-tier is fine.`},director:{label:`Event Director`,help:`Generates crisis events as structured JSON batches.`},judge:{label:`Judge (code review)`,help:`Reviews forged tool code for safety + correctness.`},agentReactions:{label:`Agent Reactions`,help:`One to two sentences per colonist per turn. Highest volume — pick cheapest.`}},iT=[`The Visionary`,`The Engineer`,`The Diplomat`,`The Maverick`,`The Guardian`,`The Strategist`,`The Steward`,`The Innovator`];function aT(e,t){return{name:`Actor ${String.fromCharCode(65+e%26)}`,archetype:iT[e]??`The Strategist`,unit:se(t,e),instructions:``,hexaco:{...eT}}}function oT(e){let t=e.presets.find(e=>e.id==="default");return t?.leaders??t?.actors}function sT(e,t,n,r,i){let a=oT(n);return e.map((e,o)=>{let s=i[o],c=a?.[o],l=e.unit===se(t,o);if(!c)return(a!==void 0&&r!==n.id||l)&&s?.unit===void 0?{...e,unit:se(n,o)}:e;let u=r===n.id&&!!e.unit&&!l;return{name:c.name,archetype:c.archetype,unit:u?e.unit:c.unit??se(n,o),instructions:c.instructions,hexaco:{...c.hexaco},...s}})}var cT=2,lT=8;function uT({events:e=[],initialSubTab:t=`config`}={}){let[n,r]=(0,b.useState)(t),i=(0,b.useCallback)(e=>{r(e),dh(e===`config`?null:e)},[]),a=Xk(),o=Qk(),s=Lm(),c=eA(),l=nA(),u=typeof window<`u`?gg(window.localStorage):null,[d]=(0,b.useState)(()=>typeof window<`u`?hg(window.localStorage):null),[f,p]=(0,b.useState)(()=>{let e=Math.max(cT,Math.min(lT,Math.max(oT(a)?.length??0,u?.length??0)));return sT(Array.from({length:e},(e,t)=>{let n=u?.[t];return n?.name?{name:n.name,archetype:n.archetype??``,unit:n.unit??se(a,t),instructions:n.instructions??``,hexaco:{...n.hexaco??eT}}:aT(t,a)}),a,a,d,[])}),m=(0,b.useRef)([]),h=(0,b.useRef)(a);(0,b.useEffect)(()=>{let e=h.current;h.current=a,p(t=>sT(t,e,a,d,m.current))},[a.id,a.presets.length]);let g=(0,b.useCallback)((e,t)=>{p(n=>n.map((n,r)=>{if(r!==e)return n;let i=Object.keys(t).filter(e=>t[e]!==n[e]);return m.current[e]={...m.current[e],...Object.fromEntries(i.map(e=>[e,t[e]]))},t}))},[]),_=(0,b.useCallback)(()=>{p(e=>e.length<lT?[...e,aT(e.length,a)]:e)},[a]),v=(0,b.useCallback)(e=>{m.current.splice(e,1),p(t=>t.length>cT?t.filter((t,n)=>n!==e):t)},[]),[y,S]=(0,b.useState)(a.setup.defaultTurns),[C,w]=(0,b.useState)(a.setup.defaultSeed),[T,E]=(0,b.useState)(a.setup.defaultStartTime),[O,A]=(0,b.useState)(a.setup.defaultTimePerTurn||0),[j,ee]=(0,b.useState)(a.setup.defaultPopulation),M=(0,b.useRef)(new Set);(0,b.useEffect)(()=>{let e=M.current;e.has(`turns`)||S(a.setup.defaultTurns),e.has(`seed`)||w(a.setup.defaultSeed),e.has(`startTime`)||E(a.setup.defaultStartTime),e.has(`timePerTurn`)||A(a.setup.defaultTimePerTurn||0),e.has(`population`)||ee(a.setup.defaultPopulation)},[a.id,a.setup.defaultTurns,a.setup.defaultSeed,a.setup.defaultStartTime,a.setup.defaultTimePerTurn,a.setup.defaultPopulation]);let[N,ne]=(0,b.useState)(`openai`),[P,re]=(0,b.useState)(!1),[ie,F]=(0,b.useState)(`balanced`),[I,ae]=(0,b.useState)(!1),[oe,ce]=(0,b.useState)(``),[le,L]=(0,b.useState)([]),[ue,de]=(0,b.useState)(a.id),[fe,R]=(0,b.useState)({}),[z,pe]=(0,b.useState)(!1),[me,he]=(0,b.useState)(!1),[ge,_e]=(0,b.useState)(`local_demo`),[B,ve]=(0,b.useState)({maxTurns:6,maxPopulation:30,maxActiveDepartments:3}),[ye,be]=(0,b.useState)(()=>{try{let e=localStorage.getItem(`paracosm:keyOverrides`);if(e){let t=JSON.parse(e);return{openai:t.openai||``,anthropic:t.anthropic||``,serper:t.serper||``,firecrawl:t.firecrawl||``,tavily:t.tavily||``,cohere:t.cohere||``}}}catch{}return{openai:``,anthropic:``,serper:``,firecrawl:``,tavily:``,cohere:``}});(0,b.useEffect)(()=>{try{localStorage.setItem(`paracosm:keyOverrides`,JSON.stringify(ye))}catch{}},[ye]);let[xe,Se]=(0,b.useState)(nT[N]??nT.openai);(0,b.useEffect)(()=>{let e=N;nT[e]&&Se(nT[e])},[N]);let Ce=xg(ye),we=!!fe.openai||!!fe.anthropic,Te=Ce||!z&&we,Ee=Ce||!z&&we,De=z&&!Ce?`economy`:ie,Oe=Qw(ge),ke=z&&!Ce,Ae=ke?`openai`:N,je=(0,b.useCallback)(()=>{fetch(`/scenarios`).then(e=>e.json()).then(e=>{L(e.scenarios||[]),de(e.active)}).catch(()=>{})},[]);(0,b.useEffect)(()=>(je(),fetch(`/admin-config`).then(e=>e.json()).then(e=>{e.keys&&R(e.keys),typeof e.hostedDemo==`boolean`&&pe(e.hostedDemo),typeof e.adminWrite==`boolean`&&he(e.adminWrite),typeof e.serverMode==`string`&&_e(e.serverMode),e.demoCaps&&typeof e.demoCaps.maxTurns==`number`&&ve({maxTurns:e.demoCaps.maxTurns,maxPopulation:e.demoCaps.maxPopulation??30,maxActiveDepartments:e.demoCaps.maxActiveDepartments??3})}).catch(()=>{}),D(window,je)),[je]);let Me=async e=>{if(e!==ue)try{(await fetch(`/scenario/switch`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:e})})).ok&&(te(),window.location.reload())}catch{}},Ne=(0,b.useCallback)(async()=>{if(o){ae(!0),ce(`Starting...`);try{let e={actors:f.map(e=>({...e,hexaco:e.hexaco})),provider:Ae,turns:y,seed:C,startTime:T,timePerTurn:O||void 0,population:j,liveSearch:P,activeDepartments:a.departments.map(e=>e.id),economics:{profileId:De},scenarioId:a.id};try{localStorage.setItem(`paracosm:lastLaunchConfig`,JSON.stringify(e))}catch{}mg(window.localStorage,f,a.id),Object.assign(e,bg(ye)),ye.serper&&(e.serperKey=ye.serper),ye.firecrawl&&(e.firecrawlKey=ye.firecrawl),ye.tavily&&(e.tavilyKey=ye.tavily),ye.cohere&&(e.cohereKey=ye.cohere),Ee&&(e.models={...xe});let t=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...e,captureSnapshots:!0})}),n=await t.json();if(t.status===429){ce(`Rate limited: ${n.error||`too many simulations`}`),ae(!1);return}if(n.redirect){l(),ce(`Running...`),k(window,n.visitorId);let e=sh(fh(window.location.href,n.redirect));c(e===`about`?`sim`:e)}else ce(`Error: ${n.error||`unknown`}`),ae(!1)}catch(e){ce(`Failed: ${e}`),ae(!1)}}},[f,y,C,T,O,j,Ae,P,c,l,a,o,ye,xe,Ee,De]),Fe=e=>[Y.input,e?Y.locked:``].filter(Boolean).join(` `);return(0,x.jsxs)(`div`,{className:Y.root,children:[(0,x.jsx)(qm,{options:$w,active:n,onChange:i,ariaLabel:`Settings sub-navigation`}),n===`log`&&(0,x.jsx)(Xw,{events:e}),n===`config`&&(0,x.jsxs)(`div`,{className:`settings-content ${Y.content}`,children:[(0,x.jsx)(OC,{}),le.length>0&&(0,x.jsxs)(`div`,{className:`responsive-stack ${Y.scenarioRow}`,children:[(0,x.jsx)(`label`,{htmlFor:`scenario-select`,style:Nw,className:Y.scenarioLabel,children:`Scenario`}),(0,x.jsx)(`select`,{id:`scenario-select`,className:`pc-select ${Y.scenarioSelect}`,value:ue,onChange:e=>Me(e.target.value),children:le.map(e=>{let t=e.description?.includes(`(memory)`)?` [memory]`:e.description?.includes(`(disk)`)?` [disk]`:e.description?.includes(`compiled`)?` [compiled]`:``;return(0,x.jsxs)(`option`,{value:e.id,children:[e.id===ue?`● `:``,e.name,` (`,e.departments,` depts)`,t]},e.id)})}),(0,x.jsxs)(`span`,{className:Y.scenarioActiveTag,children:[`Active: `,(0,x.jsx)(`strong`,{className:Y.scenarioActiveValue,children:ue})]})]}),(0,x.jsx)(`h2`,{className:Y.h2,children:a.labels.name}),a.labels.tagline&&(0,x.jsx)(`p`,{className:Y.scenarioTagline,children:a.labels.tagline}),(0,x.jsxs)(`p`,{className:Y.lead,children:[`Configure your leaders and launch. `,a.departments.length,` departments: `,a.departments.map(e=>e.label).join(`, `),`.`]}),a.sourceUrl&&(0,x.jsx)(`p`,{className:Y.scenarioSourceLink,children:(0,x.jsx)(`a`,{href:a.sourceUrl,target:`_blank`,rel:`noopener noreferrer`,children:`View scenario JSON on GitHub →`})}),(0,x.jsxs)(`p`,{className:Y.leadHint,children:[`Server mode: `,(0,x.jsx)(`strong`,{className:Y.leadStrong,children:Oe.label}),`. `,Oe.description]}),(0,x.jsx)(`div`,{className:`${f.length>2?`responsive-grid-cohort`:`responsive-grid-2`} ${Y.leadersGrid}`,children:f.map((e,t)=>(0,x.jsxs)(`div`,{className:Y.leaderCardWrap,style:{position:`relative`},children:[(0,x.jsx)(Aw,{label:`Commander ${String.fromCharCode(65+t%26)}`,sideColor:Pe(t),data:e,onChange:e=>g(t,e)}),f.length>cT&&(0,x.jsx)(`button`,{type:`button`,onClick:()=>v(t),className:Y.leaderRemoveBtn,"aria-label":`Remove ${e.name||`actor ${t+1}`} from the cohort`,title:`Remove this actor`,children:`✕`})]},t))}),(0,x.jsx)(`div`,{className:Y.leadersAddRow,children:f.length<lT?(0,x.jsxs)(`button`,{type:`button`,onClick:_,className:Y.leaderAddBtn,"aria-label":`Add another actor to the cohort`,children:[`+ Add actor (`,f.length,`/`,lT,`)`]}):(0,x.jsxs)(`span`,{className:Y.leaderAddCap,children:[`Max `,lT,` actors from Settings · use Quickstart's generate-N flow for larger cohorts.`]})}),(0,x.jsxs)(`fieldset`,{className:Y.fieldset,children:[(0,x.jsx)(`legend`,{style:Pw,className:Y.legend,children:`Simulation`}),ke&&(0,x.jsxs)(`div`,{className:Y.demoBanner,children:[(0,x.jsx)(`strong`,{className:Y.demoBannerLabel,children:`Demo caps will apply:`}),` `,`turns clamped to `,B.maxTurns,`, population to `,B.maxPopulation,`, active departments to `,B.maxActiveDepartments,`. Values you enter below are honored up to those ceilings. Add a session API key above to lift the caps.`]}),(0,x.jsxs)(`div`,{className:`responsive-grid-4 ${Y.simRow5}`,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`turns-input`,style:Nw,children:[`Turns`,ke&&(0,x.jsxs)(`span`,{className:Y.lockTag,title:`Hosted demo caps turns at ${B.maxTurns}. Add a session API key to unlock.`,children:[`🔒 demo:`,B.maxTurns]})]}),(0,x.jsx)(`input`,{id:`turns-input`,type:`number`,value:ke?B.maxTurns:y,onChange:e=>{M.current.add(`turns`),S(parseInt(e.target.value)||a.setup.defaultTurns)},min:1,max:20,disabled:ke,className:Fe(ke),title:ke?`Locked at ${B.maxTurns} in hosted demo mode. Add your own OpenAI or Anthropic key above to unlock full scope.`:``})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`ypt-input`,style:Nw,children:[s.Times,`/Turn`]}),(0,x.jsx)(`input`,{id:`ypt-input`,type:`number`,value:O,onChange:e=>{M.current.add(`timePerTurn`),A(parseInt(e.target.value)||0)},min:0,max:50,placeholder:`auto`,title:`${s.Times} per turn. 0 = accelerating schedule (default). 1 = 1 ${s.time} per turn. 5 = 5 ${s.times} per turn.`,className:Y.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{htmlFor:`seed-input`,style:Nw,children:`Seed`}),(0,x.jsx)(`input`,{id:`seed-input`,type:`number`,value:C,onChange:e=>{M.current.add(`seed`),w(parseInt(e.target.value)||a.setup.defaultSeed)},className:Y.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`time-input`,style:Nw,children:[`Start `,s.Time]}),(0,x.jsx)(`input`,{id:`time-input`,type:`number`,value:T,onChange:e=>{M.current.add(`startTime`),E(parseInt(e.target.value)||a.setup.defaultStartTime)},className:Y.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`pop-input`,style:Nw,children:[`Population`,ke&&(0,x.jsx)(`span`,{className:Y.lockTag,title:`Hosted demo caps population at 30. Add a session API key to unlock.`,children:`🔒 demo:30`})]}),(0,x.jsx)(`input`,{id:`pop-input`,type:`number`,value:ke?30:j,onChange:e=>{M.current.add(`population`),ee(parseInt(e.target.value)||a.setup.defaultPopulation)},disabled:ke,className:Fe(ke),title:ke?`Locked at 30 in hosted demo mode. Add your own OpenAI or Anthropic key above to unlock full scope.`:``})]})]}),(0,x.jsxs)(`div`,{className:`responsive-grid-3 ${Y.grid3}`,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`provider-select`,style:Nw,children:[`Provider`,ke&&(0,x.jsx)(`span`,{className:Y.lockTag,children:`🔒 demo:openai`})]}),(0,x.jsxs)(`select`,{id:`provider-select`,className:`pc-select ${Fe(ke)}`,value:Ae,onChange:e=>ne(e.target.value),disabled:ke,title:ke?`Locked to OpenAI in hosted demo mode. Add your own OpenAI or Anthropic key above to choose the provider.`:``,children:[(0,x.jsx)(`option`,{value:`openai`,children:`OpenAI`}),(0,x.jsx)(`option`,{value:`anthropic`,children:`Anthropic`})]})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{htmlFor:`search-select`,style:Nw,children:`Live Search`}),(0,x.jsxs)(`select`,{id:`search-select`,className:`pc-select ${Y.input}`,value:String(P),onChange:e=>re(e.target.value===`true`),children:[(0,x.jsx)(`option`,{value:`false`,children:`Off`}),(0,x.jsx)(`option`,{value:`true`,children:`On (requires search API keys)`})]})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`economics-select`,style:Nw,children:[`Economics`,ke&&(0,x.jsx)(`span`,{className:Y.lockTag,children:`🔒 forced:economy`})]}),(0,x.jsx)(`select`,{id:`economics-select`,className:`pc-select ${Fe(ke)}`,value:De,onChange:e=>F(e.target.value),disabled:ke,title:Zw.find(e=>e.value===De)?.description,children:Zw.map(e=>(0,x.jsx)(`option`,{value:e.value,children:e.label},e.value))}),(0,x.jsx)(`div`,{className:Y.fieldHint,children:Zw.find(e=>e.value===De)?.description})]})]})]}),(0,x.jsxs)(`fieldset`,{className:Y.fieldset,children:[(0,x.jsx)(`legend`,{style:Pw,className:Y.legend,children:`API Keys`}),(0,x.jsxs)(`div`,{className:Y.keysIntro,children:[(0,x.jsxs)(`p`,{className:Y.keysIntroPara,children:[(0,x.jsx)(`strong`,{className:Y.keysIntroBoldNeutral,children:`How key resolution works:`}),` The server checks for keys in this order: your session overrides below, then the server .env file. If a key exists in either place, it's used. Values entered here are never displayed back.`]}),(0,x.jsxs)(`p`,{className:Y.keysIntroPara,children:[(0,x.jsx)(`strong`,{className:Y.keysIntroBoldGreen,children:`Rate limiting:`}),` The hosted demo limits simulations per IP per day when using the server's API keys. Provide your own `,(0,x.jsx)(`strong`,{children:`OpenAI`}),` or `,(0,x.jsx)(`strong`,{children:`Anthropic`}),` key to bypass the rate limit and run unlimited simulations. Only one LLM provider key is required. If both are provided, the simulation uses whichever you select as the provider.`]}),(0,x.jsxs)(`p`,{className:Y.keysIntroPara,children:[(0,x.jsx)(`strong`,{className:Y.keysIntroBoldAmber,children:`Research and citations:`}),` Live web search requires at least one search key (Serper, Firecrawl, Tavily). Without any search key, departments fall back to the scenario's built-in research bundle. Cohere enables neural reranking of search results for higher-quality citations. These are optional enhancements, not required to run a simulation.`]}),(0,x.jsxs)(`p`,{className:Y.keysIntroParaLast,children:[(0,x.jsx)(`strong`,{className:Y.keysIntroBoldRust,children:`No keys at all?`}),` If neither a server .env key nor a session override exists for any LLM provider, the simulation cannot run. You need at least one OpenAI or Anthropic key configured somewhere.`]})]}),(0,x.jsx)(`div`,{className:`responsive-grid-2 ${Y.grid2}`,children:[[`openai`,`OpenAI`,`Required (or Anthropic). Powers commander, departments, crisis director.`],[`anthropic`,`Anthropic`,`Required (or OpenAI). Alternative LLM provider for all simulation roles.`],[`serper`,`Serper (search)`,`Optional. Enables live Google search for department research citations.`],[`firecrawl`,`Firecrawl (scrape)`,`Optional. Enables web page scraping for deeper research context.`],[`tavily`,`Tavily (search)`,`Optional. Additional search provider. Multiple providers improve coverage.`],[`cohere`,`Cohere (rerank)`,`Optional. Neural reranking of search results for citation quality.`]].map(([e,t,n])=>(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`key-${e}`,style:Nw,children:[t,fe[e]&&(0,x.jsx)(`span`,{className:Y.keyEnvTag,children:`(.env active)`})]}),(0,x.jsx)(`input`,{id:`key-${e}`,type:`password`,autoComplete:`off`,value:ye[e],onChange:t=>be(n=>({...n,[e]:t.target.value})),placeholder:fe[e]?`Using .env value`:`Not configured`,className:Y.input}),(0,x.jsx)(`div`,{className:Y.fieldHint,children:n})]},e))})]}),Te&&(N===`openai`||N===`anthropic`)&&(0,x.jsxs)(`fieldset`,{className:Y.fieldset,children:[(0,x.jsx)(`legend`,{style:Pw,className:Y.legend,children:`Model Tiers`}),(0,x.jsx)(`div`,{className:Y.modelTiersIntro,children:`Assign a model to each agent tier. Departments do the forging and benefit most from the flagship class. Agent reactions fan out to hundreds of parallel calls per turn and should be the cheapest class available. These overrides are only used when you run against your own API key.`}),(0,x.jsx)(`div`,{className:`responsive-grid-2 ${Y.grid2}`,children:Object.keys(rT).map(e=>(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{htmlFor:`model-${e}`,style:Nw,children:rT[e].label}),(0,x.jsx)(`select`,{id:`model-${e}`,className:`pc-select ${Y.input}`,value:xe[e],onChange:t=>Se(n=>({...n,[e]:t.target.value})),children:tT[N].map(e=>(0,x.jsx)(`option`,{value:e.value,children:e.label},e.value))}),(0,x.jsx)(`div`,{className:Y.fieldHint,children:rT[e].help})]},e))})]}),!Te&&(0,x.jsxs)(`div`,{className:Y.demoMode,children:[(0,x.jsx)(`strong`,{className:Y.demoModeStrong,children:`Demo mode.`}),` `,z?`Runs against the host API keys are capped to ${B.maxTurns} turns, ${B.maxPopulation} colonists, ${B.maxActiveDepartments} departments, and the cheapest model class. Add your own OpenAI or Anthropic key above to unlock full scope and per-tier model selection.`:`No API key configured. Add an OpenAI or Anthropic key above or set one in .env to enable simulations and the per-tier model picker.`]}),me&&(0,x.jsxs)(`fieldset`,{className:Y.fieldset,children:[(0,x.jsx)(`legend`,{style:Pw,className:Y.legend,children:`Admin Token`}),(0,x.jsx)(Uw,{})]}),(0,x.jsx)(Bw,{onAdminWrite:he}),(0,x.jsxs)(`div`,{className:`responsive-stack ${Y.launchRow}`,children:[(0,x.jsx)(`button`,{onClick:Ne,disabled:I||!o,"aria-label":I?`Simulation running`:o?`Launch simulation`:`Loading scenario`,className:Y.launchBtn,children:I?`Running...`:o?`Launch Simulation`:`Loading scenario…`}),oe&&(0,x.jsx)(`span`,{role:`status`,className:Y.launchStatus,children:oe})]})]})]})}function dT(e){let t=t=>{let n=e[t];return Number.isFinite(n)?n:.5};return{openness:t(`openness`),conscientiousness:t(`conscientiousness`),extraversion:t(`extraversion`),agreeableness:t(`agreeableness`),emotionality:t(`emotionality`),honestyHumility:t(`honestyHumility`)}}function fT(e,t=[]){return[...(e.presets?.[0]?.leaders??[]).map(e=>({name:e.name,archetype:e.archetype,unit:`Forked Branch`,hexaco:dT(e.hexaco),instructions:e.instructions})),...t]}var pT={openai:{quality:.3,economy:.1},anthropic:{quality:.75,economy:.6}};function mT(e,t,n,r){let i=Math.max(0,t-e)*pT[r][n];return`~$${(Math.ceil(i*10)/10).toFixed(2)}`}function hT(e){let t=[];for(let n of e.split(`
127
- `)){let e=n.trim();if(!e)continue;let r=/^(\d+)\s*:\s*([^:]+?)\s*:\s*(.+)$/.exec(e);if(!r)continue;let i=parseInt(r[1],10),a=r[2].trim(),o=r[3].trim();a&&t.push({turn:i,title:a,description:o})}return t}var gT=new Set([`kernelSnapshotAtStart`,`kernelSnapshotsAfterProgression`]);function _T(e){let t=e.scenarioExtensions;if(!t||typeof t!=`object`)return e;let n=Object.fromEntries(Object.entries(t).filter(([e])=>!gT.has(e)));return{...e,scenarioExtensions:n}}function vT(e){let t=e.scenarioExtensions?.kernelSnapshotsPerTurn;return Array.isArray(t)?t.map(e=>e?.turn).filter(e=>typeof e==`number`&&Number.isFinite(e)):[]}function yT(e){let t=e.trajectory?.timepoints?.length??0,n=vT(e),r=Math.max(t,...n);return r>0?r:6}function bT(e,t){return vT(e).includes(t)&&t<yT(e)}var xT={forkButton:`_forkButton_14oeq_1`,backdrop:`_backdrop_14oeq_28`,dialog:`_dialog_14oeq_40`,header:`_header_14oeq_58`,closeButton:`_closeButton_14oeq_75`,field:`_field_14oeq_92`,hint:`_hint_14oeq_122`,warning:`_warning_14oeq_128`,advanced:`_advanced_14oeq_139`,costEstimate:`_costEstimate_14oeq_173`,costDetail:`_costDetail_14oeq_191`,footer:`_footer_14oeq_196`,cancelButton:`_cancelButton_14oeq_224`,confirmButton:`_confirmButton_14oeq_228`};function ST(e){let{parentArtifact:t,atTurn:n,maxTurns:r,costPreset:i,provider:a,sessionCustomLeaders:o=[],onConfirm:s,onClose:c}=e,l=Xk(),u=Lm(),d=Pt(!0),f=fT(l,o),[p,m]=(0,b.useState)(0),[h,g]=(0,b.useState)(``),[_,v]=(0,b.useState)(``);(0,b.useEffect)(()=>{let e=e=>{e.key===`Escape`&&c()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[c]);let y=mT(n,r,i,a),S=Math.max(0,r-n),C=t.metadata.seed;return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-labelledby":`fork-modal-title`,className:xT.backdrop,onClick:c,children:(0,x.jsxs)(`div`,{ref:d,tabIndex:-1,className:xT.dialog,onClick:e=>e.stopPropagation(),children:[(0,x.jsxs)(`header`,{className:xT.header,children:[(0,x.jsxs)(`h3`,{id:`fork-modal-title`,children:[`Fork at `,u.Time,` `,n]}),(0,x.jsx)(`button`,{type:`button`,className:xT.closeButton,onClick:c,"aria-label":`Close fork modal`,children:`×`})]}),(0,x.jsxs)(`div`,{className:xT.field,children:[(0,x.jsx)(`label`,{htmlFor:`fork-leader-select`,children:`Override leader`}),f.length===0?(0,x.jsx)(`p`,{className:xT.warning,children:`No preset leaders available for this scenario. Add leaders in Settings or pick a scenario with presets to continue.`}):(0,x.jsx)(`select`,{id:`fork-leader-select`,value:p,onChange:e=>m(parseInt(e.target.value,10)),children:f.map((e,t)=>(0,x.jsxs)(`option`,{value:t,children:[e.name,` (`,e.archetype,`)`]},`${e.name}-${t}`))})]}),(0,x.jsxs)(`div`,{className:xT.field,children:[(0,x.jsx)(`label`,{htmlFor:`fork-seed`,children:`Seed override (optional)`}),(0,x.jsx)(`input`,{id:`fork-seed`,type:`number`,placeholder:C===void 0?`(use parent seed)`:`Parent seed: ${C}`,value:h,onChange:e=>g(e.target.value)}),(0,x.jsx)(`span`,{className:xT.hint,children:`Leave blank to resume from the parent's RNG state.`})]}),(0,x.jsxs)(`details`,{className:xT.advanced,children:[(0,x.jsx)(`summary`,{children:`Advanced: custom events`}),(0,x.jsx)(`textarea`,{rows:4,placeholder:`One event per line, format: "turn: title: description"
128
- Example: 5: Supply drop: Relief arrives with 3 months of food.`,value:_,onChange:e=>v(e.target.value)})]}),(0,x.jsxs)(`div`,{className:xT.costEstimate,role:`status`,children:[(0,x.jsx)(`span`,{children:`Estimated cost`}),(0,x.jsx)(`strong`,{children:y}),(0,x.jsxs)(`span`,{className:xT.costDetail,children:[`for `,S,` more `,S===1?u.time:u.times]})]}),(0,x.jsxs)(`footer`,{className:xT.footer,children:[(0,x.jsx)(`button`,{type:`button`,onClick:c,className:xT.cancelButton,children:`Cancel`}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>{let e=f[p];if(!e)return;let r=h.trim()?parseInt(h,10):void 0,i=r!==void 0&&Number.isFinite(r)?r:void 0,a=_.trim()?hT(_):void 0;s({parentArtifact:t,atTurn:n,leader:e,seedOverride:i,customEvents:a})},disabled:f.length===0,className:xT.confirmButton,children:`Fork`})]})]})})}var CT=`/retry-stats`;function wT(e=!0){let[t,n]=(0,b.useState)(null),[r,i]=(0,b.useState)(!1),[a,o]=(0,b.useState)(null),s=(0,b.useCallback)(async()=>{i(!0),o(null);try{let e=await fetch(CT,{credentials:`same-origin`});if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();n(t)}catch(e){o(e instanceof Error?e.message:String(e))}finally{i(!1)}},[]);return(0,b.useEffect)(()=>{e&&s()},[e,s]),{data:t,loading:r,error:a,refresh:s}}var X={backdrop:`_backdrop_vajsn_1`,dialog:`_dialog_vajsn_12`,titleRow:`_titleRow_vajsn_27`,title:`_title_vajsn_27`,escBtn:`_escBtn_vajsn_43`,totalLine:`_totalLine_vajsn_54`,totalAmount:`_totalAmount_vajsn_60`,cacheBlock:`_cacheBlock_vajsn_66`,cacheLabel:`_cacheLabel_vajsn_74`,cacheVerdict:`_cacheVerdict_vajsn_83`,cacheSubLine:`_cacheSubLine_vajsn_91`,cacheTokenRow:`_cacheTokenRow_vajsn_98`,cacheMultiplier:`_cacheMultiplier_vajsn_107`,emptyState:`_emptyState_vajsn_111`,table:`_table_vajsn_118`,tableSm:`_tableSm_vajsn_125`,headRow:`_headRow_vajsn_132`,th:`_th_vajsn_139`,thRight:`_thRight_vajsn_144`,bodyRow:`_bodyRow_vajsn_150`,stageCell:`_stageCell_vajsn_154`,stageLabel:`_stageLabel_vajsn_158`,stageDescription:`_stageDescription_vajsn_164`,bar:`_bar_vajsn_171`,barFill:`_barFill_vajsn_180`,numericCell:`_numericCell_vajsn_187`,numericCellGreen:`_numericCellGreen_vajsn_193`,numericCellMuted:`_numericCellMuted_vajsn_201`,section:`_section_vajsn_208`,sectionLabel:`_sectionLabel_vajsn_214`,sectionFootnote:`_sectionFootnote_vajsn_222`,sectionFootnoteTight:`_sectionFootnoteTight_vajsn_229`,subBlock:`_subBlock_vajsn_236`,subBlockLabel:`_subBlockLabel_vajsn_240`,cellSchemaName:`_cellSchemaName_vajsn_247`,cellNumericTight:`_cellNumericTight_vajsn_252`,cellAvgAttempts:`_cellAvgAttempts_vajsn_258`,cellFallback:`_cellFallback_vajsn_265`,cellRight1:`_cellRight1_vajsn_272`,cellRightGreen:`_cellRightGreen_vajsn_278`,cellRightRust:`_cellRightRust_vajsn_285`,cellRightMuted:`_cellRightMuted_vajsn_291`,cellRateColor:`_cellRateColor_vajsn_297`,cellConfColor:`_cellConfColor_vajsn_304`,statusInline:`_statusInline_vajsn_311`,statusErrorTag:`_statusErrorTag_vajsn_320`,rejectionWrap:`_rejectionWrap_vajsn_324`,rejectionLabel:`_rejectionLabel_vajsn_328`,rejectionCell:`_rejectionCell_vajsn_335`,perLeaderRow:`_perLeaderRow_vajsn_342`,leaderCard:`_leaderCard_vajsn_349`,leaderName:`_leaderName_vajsn_357`,leaderCost:`_leaderCost_vajsn_363`,leaderMeta:`_leaderMeta_vajsn_369`,perActorList:`_perActorList_vajsn_378`,perActorRow:`_perActorRow_vajsn_386`,perActorBarTrack:`_perActorBarTrack_vajsn_412`,perActorCost:`_perActorCost_vajsn_417`,perActorMeta:`_perActorMeta_vajsn_421`,perActorRank:`_perActorRank_vajsn_426`,perActorName:`_perActorName_vajsn_433`,perActorBarFill:`_perActorBarFill_vajsn_448`},TT={director:{label:`Event Director`,description:`Generates events each turn based on world state`},commander:{label:`Commander`,description:`Reads dept reports, picks options, promotes department heads`},departments:{label:`Department Analysis`,description:`5 specialists analyzing each event in parallel`},judge:{label:`Forge Judge`,description:`LLM safety + correctness review of every forged tool`},reactions:{label:`Agent Reactions`,description:`~100 colonists reacting to each turn's outcome`},other:{label:`Other`,description:`Uncategorized calls`}};function ET(e){return e<1e-4?`$0.0000`:`$${e<.01?e.toFixed(4):e.toFixed(2)}`}function DT(e){return e>=1e6?`${(e/1e6).toFixed(2)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function OT(e){return e>1.5?`var(--rust)`:e>1.1?`var(--amber)`:`var(--text-1)`}function kT(e){return e>.01?`var(--rust)`:e>0?`var(--amber)`:`var(--text-3)`}function AT({combined:e,leaderA:t,leaderB:n,leaderAName:r,leaderBName:i,actors:a,onClose:o}){(0,b.useEffect)(()=>{let e=e=>{e.key===`Escape`&&o()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o]);let s=Pt(!0),c=wT(!0),l=e.breakdown??{},u=Object.entries(l).map(([e,t])=>({site:e,...t})).sort((e,t)=>t.totalCostUSD-e.totalCostUSD),d=e.totalCostUSD||u.reduce((e,t)=>e+t.totalCostUSD,0),f=u[0]?.totalCostUSD??0;return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Cost breakdown`,onClick:o,className:X.backdrop,children:(0,x.jsxs)(`div`,{ref:s,tabIndex:-1,onClick:e=>e.stopPropagation(),className:X.dialog,children:[(0,x.jsxs)(`div`,{className:X.titleRow,children:[(0,x.jsx)(`h3`,{className:X.title,children:`COST BREAKDOWN`}),(0,x.jsx)(`button`,{onClick:o,"aria-label":`Close cost breakdown`,className:X.escBtn,children:`ESC`})]}),(0,x.jsxs)(`div`,{className:X.totalLine,children:[`Total: `,(0,x.jsx)(`span`,{className:X.totalAmount,children:ET(d)}),` · `,e.llmCalls.toLocaleString(),` calls`,` · `,DT(e.totalTokens),` tokens`]}),e.cacheReadTokens||e.cacheCreationTokens?(()=>{let t=e.cacheReadTokens??0,n=e.cacheCreationTokens??0,r=e.cacheSavingsUSD??0,i=t+n,a=i>0?t/i:0,o=`var(--text-3)`,s;return r>.001?(o=`var(--green)`,s=`Saved ${ET(r)} via prompt caching`):r<-.001?(o=`var(--amber)`,s=`Cache priming cost ${ET(-r)} so far · reuse will repay this`):t>0?(o=`var(--green)`,s=`Cache reuse breaking even with priming cost`):(o=`var(--amber)`,s=`Cache filled but nothing reused yet · retry run or check prompt stability`),(0,x.jsxs)(`div`,{className:X.cacheBlock,children:[(0,x.jsx)(`div`,{className:X.cacheLabel,children:`PROMPT CACHING`}),(0,x.jsx)(`div`,{className:X.cacheVerdict,style:{"--cache-verdict-color":o},children:s}),(0,x.jsxs)(`div`,{className:X.cacheSubLine,children:[Math.round(a*100),`% hit rate on cached input (`,DT(t),` reused / `,DT(i),` cache tokens)`]}),(0,x.jsxs)(`div`,{className:X.cacheTokenRow,children:[(0,x.jsxs)(`span`,{children:[`reads `,DT(t),` `,(0,x.jsx)(`span`,{className:X.cacheMultiplier,children:`@0.10×`})]}),(0,x.jsxs)(`span`,{children:[`creates `,DT(n),` `,(0,x.jsx)(`span`,{className:X.cacheMultiplier,children:`@1.25×`})]})]})]})})():null,u.length===0?(0,x.jsx)(`div`,{className:X.emptyState,children:`No LLM calls have been billed yet. Start a simulation to see spend by pipeline stage.`}):(0,x.jsxs)(`table`,{className:X.table,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.th,children:`STAGE`}),(0,x.jsx)(`th`,{className:X.thRight,children:`CALLS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`TOKENS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`COST`}),(0,x.jsx)(`th`,{className:X.thRight,children:`%`})]})}),(0,x.jsx)(`tbody`,{children:u.map(e=>{let t=TT[e.site]??{label:e.site,description:``},n=d>0?e.totalCostUSD/d*100:0,r=f>0?e.totalCostUSD/f*100:0;return(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsxs)(`td`,{className:X.stageCell,children:[(0,x.jsx)(`div`,{className:X.stageLabel,children:t.label}),(0,x.jsx)(`div`,{className:X.stageDescription,children:t.description}),(0,x.jsx)(`div`,{"aria-hidden":`true`,className:X.bar,children:(0,x.jsx)(`div`,{className:X.barFill,style:{"--bar-pct":`${r}%`}})})]}),(0,x.jsx)(`td`,{className:X.numericCell,children:e.calls.toLocaleString()}),(0,x.jsx)(`td`,{className:X.numericCell,children:DT(e.totalTokens)}),(0,x.jsx)(`td`,{className:X.numericCellGreen,children:ET(e.totalCostUSD)}),(0,x.jsxs)(`td`,{className:X.numericCellMuted,children:[n.toFixed(0),`%`]})]},e.site)})})]}),e.schemaRetries&&Object.keys(e.schemaRetries).length>0&&(0,x.jsxs)(`div`,{className:X.section,children:[(0,x.jsx)(`div`,{className:X.sectionLabel,children:`SCHEMA RELIABILITY`}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.th,children:`SCHEMA`}),(0,x.jsx)(`th`,{className:X.thRight,children:`CALLS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`AVG ATTEMPTS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`FALLBACKS`})]})}),(0,x.jsx)(`tbody`,{children:Object.entries(e.schemaRetries).sort((e,t)=>t[1].calls-e[1].calls).map(([e,t])=>{let n=t.calls>0?t.attempts/t.calls:0,r=OT(n),i=t.fallbacks>0?`var(--rust)`:`var(--text-3)`;return(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsx)(`td`,{className:X.cellSchemaName,children:e}),(0,x.jsx)(`td`,{className:X.cellNumericTight,children:t.calls}),(0,x.jsx)(`td`,{className:X.cellAvgAttempts,style:{"--avg-color":r},children:n.toFixed(2)}),(0,x.jsx)(`td`,{className:X.cellFallback,style:{"--fb-color":i,"--fb-weight":t.fallbacks>0?`700`:`400`},children:t.fallbacks})]},e)})})]}),(0,x.jsxs)(`div`,{className:X.sectionFootnote,children:[`1.00 = first-try success. Higher = model retrying on validation failures. Tune `,(0,x.jsx)(`code`,{className:`mono`,children:`maxRetries`}),` or tighten schema if a row stays above 1.3.`]})]}),e.forgeStats&&e.forgeStats.attempts>0&&(0,x.jsxs)(`div`,{className:X.section,children:[(0,x.jsx)(`div`,{className:X.sectionLabel,children:`FORGE RELIABILITY`}),(()=>{let t=e.forgeStats,n=t.attempts>0?t.approved/t.attempts:0,r=t.approved>0?t.approvedConfidenceSum/t.approved:0,i=n<.5?`var(--rust)`:n<.75?`var(--amber)`:`var(--green)`,a=r>0&&r<.6?`var(--amber)`:`var(--text-1)`;return(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.thRight,children:`ATTEMPTS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`APPROVED`}),(0,x.jsx)(`th`,{className:X.thRight,children:`REJECTED`}),(0,x.jsx)(`th`,{className:X.thRight,children:`APPROVAL RATE`}),(0,x.jsx)(`th`,{className:X.thRight,children:`AVG CONF`})]})}),(0,x.jsx)(`tbody`,{children:(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsx)(`td`,{className:X.cellRight1,children:t.attempts}),(0,x.jsx)(`td`,{className:X.cellRightGreen,children:t.approved}),(0,x.jsx)(`td`,{className:t.rejected>0?X.cellRightRust:X.cellRightMuted,children:t.rejected}),(0,x.jsxs)(`td`,{className:X.cellRateColor,style:{"--rate-color":i},children:[(n*100).toFixed(0),`%`]}),(0,x.jsx)(`td`,{className:X.cellConfColor,style:{"--conf-color":a},children:r>0?r.toFixed(2):`—`})]})})]})})(),(0,x.jsx)(`div`,{className:X.sectionFootnote,children:`Rejections come from shape check OR judge verdict. Retry-with-feedback usually recovers; persistent low approval rate suggests the department model is weak at writing schema-compliant code.`})]}),(()=>{let e=c.data;if(c.loading&&!e)return(0,x.jsx)(`div`,{className:X.statusInline,children:`RECENT RUNS — loading…`});if(c.error)return(0,x.jsxs)(`div`,{className:X.statusInline,children:[`RECENT RUNS — `,(0,x.jsxs)(`span`,{className:X.statusErrorTag,children:[`fetch failed (`,c.error,`)`]})]});if(!e||e.runCount===0)return null;let t=Object.entries(e.schemas).filter(([e])=>!e.startsWith(`compile:`)),n=Object.entries(e.schemas).filter(([e])=>e.startsWith(`compile:`)).map(([e,t])=>[e.replace(/^compile:/,``),t]),r=e.forges,i=e.caches,a=e.providerErrors,o=([e,t])=>{let n=OT(t.avgAttempts),r=kT(t.fallbackRate);return(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsx)(`td`,{className:X.cellSchemaName,children:e}),(0,x.jsx)(`td`,{className:X.cellNumericTight,children:t.calls}),(0,x.jsx)(`td`,{className:X.cellAvgAttempts,style:{"--avg-color":n},children:t.avgAttempts.toFixed(2)}),(0,x.jsxs)(`td`,{className:X.cellFallback,style:{"--fb-color":r,"--fb-weight":t.fallbacks>0?`700`:`400`},children:[(t.fallbackRate*100).toFixed(2),`%`]})]},e)};return(0,x.jsxs)(`div`,{className:X.section,children:[(0,x.jsxs)(`div`,{className:X.sectionLabel,children:[`RECENT RUNS (last `,e.runCount,`)`]}),t.length>0&&(0,x.jsxs)(`div`,{className:X.subBlock,children:[(0,x.jsx)(`div`,{className:X.subBlockLabel,children:`RUNTIME SCHEMAS`}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.th,children:`SCHEMA`}),(0,x.jsx)(`th`,{className:X.thRight,children:`CALLS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`AVG ATT`}),(0,x.jsx)(`th`,{className:X.thRight,children:`FALLBACK %`})]})}),(0,x.jsx)(`tbody`,{children:t.sort((e,t)=>t[1].calls-e[1].calls).map(o)})]})]}),n.length>0&&(0,x.jsxs)(`div`,{className:X.subBlock,children:[(0,x.jsx)(`div`,{className:X.subBlockLabel,children:`COMPILE HOOKS`}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.th,children:`HOOK`}),(0,x.jsx)(`th`,{className:X.thRight,children:`CALLS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`AVG ATT`}),(0,x.jsx)(`th`,{className:X.thRight,children:`FALLBACK %`})]})}),(0,x.jsx)(`tbody`,{children:n.sort((e,t)=>t[1].calls-e[1].calls).map(o)})]})]}),r&&r.runsPresent>0&&(0,x.jsxs)(`div`,{className:X.subBlock,children:[(0,x.jsx)(`div`,{className:X.subBlockLabel,children:`FORGES`}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.thRight,children:`RUNS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`ATTEMPTS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`ATTEMPT RATE`}),(0,x.jsx)(`th`,{className:X.thRight,children:`UNIQUE TOOLS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`EVENTUALLY APPROVED`}),(0,x.jsx)(`th`,{className:X.thRight,children:`TERMINAL FAILS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`AVG CONF`})]})}),(0,x.jsx)(`tbody`,{children:(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsx)(`td`,{className:X.cellRight1,children:r.runsPresent}),(0,x.jsx)(`td`,{className:X.cellRight1,children:r.totalAttempts}),(0,x.jsxs)(`td`,{className:X.cellRateColor,style:{"--rate-color":r.approvalRate<.5?`var(--rust)`:r.approvalRate<.75?`var(--amber)`:`var(--green)`},children:[(r.approvalRate*100).toFixed(1),`%`]}),(0,x.jsx)(`td`,{className:X.cellRight1,children:r.totalUniqueNames}),(0,x.jsxs)(`td`,{className:X.cellRateColor,style:{"--rate-color":r.uniqueApprovalRate<.8?`var(--rust)`:r.uniqueApprovalRate<.95?`var(--amber)`:`var(--green)`},children:[r.totalUniqueApproved,` (`,(r.uniqueApprovalRate*100).toFixed(0),`%)`]}),(0,x.jsx)(`td`,{className:X.cellFallback,style:{"--fb-color":r.totalUniqueTerminalRejections>0?`var(--rust)`:`var(--text-3)`,"--fb-weight":r.totalUniqueTerminalRejections>0?`700`:`400`},children:r.totalUniqueTerminalRejections}),(0,x.jsx)(`td`,{className:X.cellRight1,style:{fontWeight:700},children:r.avgApprovedConfidence>0?r.avgApprovedConfidence.toFixed(2):`—`})]})})]}),(0,x.jsx)(`div`,{className:X.sectionFootnoteTight,children:`ATTEMPT RATE counts every forge call including retries. EVENTUALLY APPROVED is the real quality signal — tools that landed in the toolbox. TERMINAL FAILS are tools the retry loop never recovered.`}),(()=>{let e=r.rejectionReasons,t=e.schema_extra_field+e.shape_check+e.parse_error+e.judge_correctness+e.other;if(t===0)return null;let n=e=>t>0?Math.round(e/t*100):0,i=(e,t)=>({"--rj-color":e>0?t:`var(--text-3)`,"--rj-weight":e>0?`700`:`400`});return(0,x.jsxs)(`div`,{className:X.rejectionWrap,children:[(0,x.jsxs)(`div`,{className:X.rejectionLabel,children:[`REJECTION REASONS (last `,r.runsPresent,` run`,r.runsPresent===1?``:`s`,`)`]}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.thRight,children:`SCHEMA EXTRA FIELD`}),(0,x.jsx)(`th`,{className:X.thRight,children:`SHAPE CHECK`}),(0,x.jsx)(`th`,{className:X.thRight,children:`PARSE ERROR`}),(0,x.jsx)(`th`,{className:X.thRight,children:`JUDGE CORRECTNESS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`OTHER`})]})}),(0,x.jsx)(`tbody`,{children:(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsxs)(`td`,{className:X.rejectionCell,style:i(e.schema_extra_field,`var(--amber)`),children:[e.schema_extra_field,` (`,n(e.schema_extra_field),`%)`]}),(0,x.jsxs)(`td`,{className:X.rejectionCell,style:i(e.shape_check,`var(--amber)`),children:[e.shape_check,` (`,n(e.shape_check),`%)`]}),(0,x.jsxs)(`td`,{className:X.rejectionCell,style:i(e.parse_error,`var(--rust)`),children:[e.parse_error,` (`,n(e.parse_error),`%)`]}),(0,x.jsxs)(`td`,{className:X.rejectionCell,style:i(e.judge_correctness,`var(--rust)`),children:[e.judge_correctness,` (`,n(e.judge_correctness),`%)`]}),(0,x.jsxs)(`td`,{className:X.cellRightMuted,children:[e.other,` (`,n(e.other),`%)`]})]})})]}),(0,x.jsx)(`div`,{className:X.sectionFootnoteTight,children:`SCHEMA EXTRA FIELD dominating means the LLM's return-keys don't match its declared outputSchema.properties — the target of the 2026-04-18 forge-guidance prompt fix. JUDGE CORRECTNESS = real logic bugs the judge caught.`})]})})()]}),a&&a.runsPresent>0&&(0,x.jsxs)(`div`,{className:X.subBlock,children:[(0,x.jsx)(`div`,{className:X.subBlockLabel,children:`PROVIDER ERRORS`}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.thRight,children:`RUNS W/ ERRORS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`TOTAL`}),(0,x.jsx)(`th`,{className:X.thRight,children:`AUTH`}),(0,x.jsx)(`th`,{className:X.thRight,children:`QUOTA`}),(0,x.jsx)(`th`,{className:X.thRight,children:`RATE`}),(0,x.jsx)(`th`,{className:X.thRight,children:`NET`}),(0,x.jsx)(`th`,{className:X.thRight,children:`OTHER`})]})}),(0,x.jsx)(`tbody`,{children:(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsx)(`td`,{className:X.cellRight1,children:a.runsPresent}),(0,x.jsx)(`td`,{className:X.cellRight1,style:{fontWeight:700},children:a.total}),(0,x.jsx)(`td`,{className:X.cellFallback,style:{"--fb-color":a.auth>0?`var(--rust)`:`var(--text-3)`,"--fb-weight":a.auth>0?`700`:`400`},children:a.auth}),(0,x.jsx)(`td`,{className:X.cellFallback,style:{"--fb-color":a.quota>0?`var(--rust)`:`var(--text-3)`,"--fb-weight":a.quota>0?`700`:`400`},children:a.quota}),(0,x.jsx)(`td`,{className:a.rate_limit>0?X.cellFallback:X.cellRightMuted,style:a.rate_limit>0?{"--fb-color":`var(--amber)`,"--fb-weight":`400`}:void 0,children:a.rate_limit}),(0,x.jsx)(`td`,{className:a.network>0?X.cellFallback:X.cellRightMuted,style:a.network>0?{"--fb-color":`var(--amber)`,"--fb-weight":`400`}:void 0,children:a.network}),(0,x.jsx)(`td`,{className:a.unknown>0?X.cellFallback:X.cellRightMuted,style:a.unknown>0?{"--fb-color":`var(--amber)`,"--fb-weight":`400`}:void 0,children:a.unknown})]})})]}),(0,x.jsx)(`div`,{className:X.sectionFootnoteTight,children:`AUTH/QUOTA are terminal (run aborts). RATE/NET/OTHER are non-terminal — the retry layer handles them.`})]}),i&&i.runsPresent>0&&(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:X.subBlockLabel,children:`PROMPT CACHE`}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.thRight,children:`RUNS WITH CACHE`}),(0,x.jsx)(`th`,{className:X.thRight,children:`READ TOKENS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`CREATE TOKENS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`READ RATIO`}),(0,x.jsx)(`th`,{className:X.thRight,children:`SAVINGS`})]})}),(0,x.jsx)(`tbody`,{children:(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsx)(`td`,{className:X.cellRight1,children:i.runsPresent}),(0,x.jsx)(`td`,{className:X.cellRight1,children:DT(i.totalReadTokens)}),(0,x.jsx)(`td`,{className:X.cellNumericTight,children:DT(i.totalCreationTokens)}),(0,x.jsxs)(`td`,{className:X.cellRateColor,style:{"--rate-color":i.readRatio>=.7?`var(--green)`:i.readRatio>=.4?`var(--amber)`:`var(--rust)`},children:[(i.readRatio*100).toFixed(0),`%`]}),(0,x.jsx)(`td`,{className:X.cellRateColor,style:{"--rate-color":i.totalSavingsUSD>0?`var(--green)`:`var(--text-2)`},children:ET(i.totalSavingsUSD)})]})})]}),(0,x.jsx)(`div`,{className:X.sectionFootnoteTight,children:`Read ratio >= 70% is healthy. Lower ratios mean the cache keeps getting invalidated.`})]})]})})(),a&&a.length>2&&(0,x.jsxs)(`div`,{className:X.section,children:[(0,x.jsxs)(`div`,{className:X.sectionLabel,children:[`PER ACTOR · `,a.length,` ACTORS`]}),(()=>{let e=[...a].sort((e,t)=>t.cost.totalCostUSD-e.cost.totalCostUSD),t=e[0]?.cost.totalCostUSD??0,n=e.reduce((e,t)=>e+t.cost.totalCostUSD,0);return(0,x.jsx)(`div`,{className:X.perActorList,children:e.map((e,r)=>{let i=t>0?e.cost.totalCostUSD/t*100:0,a=n>0?e.cost.totalCostUSD/n*100:0;return(0,x.jsxs)(`div`,{className:X.perActorRow,children:[(0,x.jsxs)(`div`,{className:X.perActorRank,children:[`#`,r+1]}),(0,x.jsx)(`div`,{className:X.perActorName,title:e.name,children:e.name}),(0,x.jsx)(`div`,{className:X.perActorBarTrack,"aria-hidden":`true`,children:(0,x.jsx)(`div`,{className:X.perActorBarFill,style:{width:`${i}%`}})}),(0,x.jsx)(`div`,{className:X.perActorCost,children:ET(e.cost.totalCostUSD)}),(0,x.jsxs)(`div`,{className:X.perActorMeta,children:[e.cost.llmCalls,` calls · `,DT(e.cost.totalTokens),` tok · `,a.toFixed(1),`%`]})]},e.actorId)})})})()]}),t&&n&&(t.totalCostUSD>0||n.totalCostUSD>0)&&(0,x.jsxs)(`div`,{className:X.section,children:[(0,x.jsx)(`div`,{className:X.sectionLabel,children:`PER LEADER`}),(0,x.jsxs)(`div`,{className:X.perLeaderRow,children:[(0,x.jsxs)(`div`,{className:X.leaderCard,children:[(0,x.jsx)(`div`,{className:X.leaderName,style:{"--leader-color":`var(--vis)`},children:r||`Leader A`}),(0,x.jsx)(`div`,{className:X.leaderCost,children:ET(t.totalCostUSD)}),(0,x.jsxs)(`div`,{className:X.leaderMeta,children:[t.llmCalls,` calls · `,DT(t.totalTokens),` tok`]})]}),(0,x.jsxs)(`div`,{className:X.leaderCard,children:[(0,x.jsx)(`div`,{className:X.leaderName,style:{"--leader-color":`var(--eng)`},children:i||`Leader B`}),(0,x.jsx)(`div`,{className:X.leaderCost,children:ET(n.totalCostUSD)}),(0,x.jsxs)(`div`,{className:X.leaderMeta,children:[n.llmCalls,` calls · `,DT(n.totalTokens),` tok`]})]})]})]})]})})}var jT={card:`_card_mk5ry_1`,headerRow:`_headerRow_mk5ry_11`,title:`_title_mk5ry_18`,range:`_range_mk5ry_24`,legend:`_legend_mk5ry_28`,legendItem:`_legendItem_mk5ry_35`,legendSwatch:`_legendSwatch_mk5ry_41`,legendLabel:`_legendLabel_mk5ry_48`,legendValue:`_legendValue_mk5ry_52`},MT=[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`],NT={openness:`var(--side-a, #e8b44a)`,conscientiousness:`var(--teal, #4ca8a8)`,extraversion:`#c44a1e`,agreeableness:`#6b9a6b`,emotionality:`#a86cb5`,honestyHumility:`#d2b48c`},PT={openness:`O`,conscientiousness:`C`,extraversion:`E`,agreeableness:`A`,emotionality:`Em`,honestyHumility:`HH`};function FT(e){if(e){for(let t of[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`])if(typeof e[t]!=`number`)return;return e}}function IT(e,t){let n=[];for(let r of e){if(r.type!==`personality_drift`||!r.data||r.leader!==void 0&&r.leader!==t)continue;let e=r.data.commander,i=r.data.turn;e&&typeof i==`number`&&n.push({turn:i,hexaco:e})}return n.sort((e,t)=>e.turn-t.turn)}function LT({events:e,actorName:t,baselineHexaco:n}){let r=FT(n),i=IT(e,t);if(i.length===0&&!r)return null;let a=r?[{turn:0,hexaco:r},...i]:i;if(a.length<2)return null;let o=a[0].turn,s=a[a.length-1].turn,c=Math.max(1,s-o),l=e=>6+68*(1-(Math.max(.05,Math.min(.95,e))-.05)/.9),u=e=>6+248*((e-o)/c);return(0,x.jsxs)(`div`,{className:jT.card,children:[(0,x.jsxs)(`div`,{className:jT.headerRow,children:[(0,x.jsx)(`span`,{className:jT.title,children:`PERSONALITY ARC`}),(0,x.jsxs)(`span`,{className:jT.range,children:[`turn `,o,` → `,s]})]}),(0,x.jsxs)(`svg`,{viewBox:`0 0 260 80`,width:`100%`,height:80,role:`img`,"aria-label":`HEXACO trajectory for ${t}`,children:[(0,x.jsx)(`line`,{x1:6,y1:l(.5),x2:254,y2:l(.5),stroke:`var(--border)`,strokeWidth:`0.5`,strokeDasharray:`2,3`}),MT.map(e=>{let t=a.map(t=>`${u(t.turn)},${l(t.hexaco[e])}`).join(` `);return(0,x.jsx)(`polyline`,{points:t,fill:`none`,stroke:NT[e],strokeWidth:`1.25`,strokeLinejoin:`round`,strokeLinecap:`round`,opacity:.85},e)})]}),(0,x.jsx)(`div`,{className:jT.legend,children:MT.map(e=>(0,x.jsxs)(`span`,{className:jT.legendItem,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:jT.legendSwatch,style:{"--trait-color":NT[e]}}),(0,x.jsx)(`span`,{className:jT.legendLabel,children:PT[e]}),(0,x.jsx)(`span`,{className:jT.legendValue,children:a[a.length-1].hexaco[e].toFixed(2)})]},e))})]})}var RT={crisis:`Crisis`,departments:`Department analysis`,decision:`Decision`,outcome:`Outcome`,quotes:`Agent voices`,causality:`Causality`},zT={timeline:`Turn timeline`,verdict:`Verdict`,trajectory:`Commander arcs`,cost:`Cost breakdown`,toolbox:`Forged toolbox`,references:`References`},BT=[`crisis`,`departments`,`decision`,`outcome`],VT=[`crisis`,`departments`,`decision`,`outcome`,`causality`];function HT(e){return e===`crisis`||e===`departments`||e===`decision`||e===`outcome`||e===`quotes`||e===`causality`}function UT(e){return e!==`quotes`}function WT(e){let t=[];for(let n of e??[])HT(n)&&!t.includes(n)&&t.push(n);return t}function GT(e){let t=WT(e.configuredSections),n=t.length>0?t:BT,r=n.filter(UT);for(let t of VT)t===`causality`&&!e.hasCausality||r.includes(t)||r.push(t);let i=e.hasQuotes?[`quotes`]:[],a=[`timeline`];return e.hasVerdict&&a.push(`verdict`),e.hasTrajectories&&a.push(`trajectory`),e.hasCost&&a.push(`cost`),e.hasToolbox&&a.push(`toolbox`),e.hasReferences&&a.push(`references`),{focusSections:n,eventSections:r,footerSections:i,artifacts:a}}var KT={section:`_section_36gyg_1`,header:`_header_36gyg_10`,kicker:`_kicker_36gyg_16`,winner:`_winner_36gyg_25`,headline:`_headline_36gyg_33`,divergence:`_divergence_36gyg_40`,body:`_body_36gyg_48`,bodyHeader:`_bodyHeader_36gyg_52`,nameA:`_nameA_36gyg_64`,nameB:`_nameB_36gyg_68`,statRow:`_statRow_36gyg_72`,statRowHead:`_statRowHead_36gyg_76`,statValueA:`_statValueA_36gyg_85`,statValueB:`_statValueB_36gyg_90`,statLabel:`_statLabel_36gyg_95`,bar:`_bar_36gyg_99`,barLeftWrap:`_barLeftWrap_36gyg_105`,barRightWrap:`_barRightWrap_36gyg_111`,barLeftFill:`_barLeftFill_36gyg_115`,barRightFill:`_barRightFill_36gyg_122`,viewWrap:`_viewWrap_36gyg_129`,viewBtn:`_viewBtn_36gyg_134`,empty:`_empty_36gyg_147`},qT=[{key:`population`,label:`Population`,format:`int`},{key:`morale`,label:`Morale`,format:`percent`},{key:`food`,label:`Food (mo)`,format:`decimal`},{key:`power`,label:`Power (kW)`,format:`decimal`},{key:`modules`,label:`Modules`,format:`decimal`},{key:`science`,label:`Science`,format:`int`},{key:`tools`,label:`Tools Forged`,format:`int`}];function JT(e,t){return t===`percent`?`${Math.round(e*100)}%`:t===`decimal`?e.toFixed(1):String(Math.round(e))}function YT({a:e,b:t,winner:n}){let r=Math.max(Math.abs(e),Math.abs(t),1),i=Math.max(0,e/r*100),a=Math.max(0,t/r*100),o=n===`a`?`var(--vis)`:`var(--border-hl)`,s=n===`b`?`var(--eng)`:`var(--border-hl)`;return(0,x.jsxs)(`div`,{className:KT.bar,children:[(0,x.jsx)(`div`,{className:KT.barLeftWrap,children:(0,x.jsx)(`div`,{className:KT.barLeftFill,style:{"--bar-pct":`${i}%`,"--bar-fill":o}})}),(0,x.jsx)(`div`,{className:KT.barRightWrap,children:(0,x.jsx)(`div`,{className:KT.barRightFill,style:{"--bar-pct":`${a}%`,"--bar-fill":s}})})]})}function XT(e){let t=e.verdict;if(t?.mode===`cohort`)return null;let n=t?.winnerName||``,r=t?.headline||t?.summary||``,i=t?.keyDivergence||``,a=t?.finalStats?.a,o=t?.finalStats?.b,s=vn(t?.finalStats),c=a&&o?s?[...s.map(e=>({key:e.id,label:yn(e),a:e.a,b:e.b,text:t=>bn(t,e.format,e.currency),better:e.better})),{key:`tools`,label:`Tools Forged`,a:Number(a.tools??0),b:Number(o.tools??0),text:e=>JT(e??0,`int`)}]:qT.map(e=>({key:e.key,label:e.label,a:Number(a[e.key]??0),b:Number(o[e.key]??0),text:t=>JT(t??0,e.format)})):[],l=e.onViewFullVerdict??(()=>{typeof document<`u`&&document.getElementById(`verdict`)?.scrollIntoView({behavior:`smooth`,block:`start`})});return(0,x.jsxs)(`section`,{"aria-label":`Run summary`,className:KT.section,children:[(0,x.jsxs)(`div`,{className:KT.header,children:[(0,x.jsx)(`div`,{className:KT.kicker,children:`Run Summary`}),n&&(0,x.jsxs)(`div`,{className:KT.winner,children:[n,` wins`]}),r&&(0,x.jsx)(`div`,{className:KT.headline,children:r}),i&&(0,x.jsx)(`div`,{className:KT.divergence,children:i})]}),a&&o?(0,x.jsxs)(`div`,{className:KT.body,children:[(0,x.jsxs)(`div`,{className:KT.bodyHeader,children:[(0,x.jsx)(`span`,{className:KT.nameA,children:e.leaderAName}),(0,x.jsx)(`span`,{children:`Final stats`}),(0,x.jsx)(`span`,{className:KT.nameB,children:e.leaderBName})]}),c.map(e=>{let{a:t,b:n}=e,r=Sn(t,n,e.better)??`tie`;return(0,x.jsxs)(`div`,{className:KT.statRow,children:[(0,x.jsxs)(`div`,{className:KT.statRowHead,children:[(0,x.jsx)(`span`,{className:KT.statValueA,style:{"--val-color":r===`a`?`var(--vis)`:`var(--text-2)`,"--val-weight":r===`a`?`700`:`500`},children:e.text(t)}),(0,x.jsx)(`span`,{className:KT.statLabel,children:e.label}),(0,x.jsx)(`span`,{className:KT.statValueB,style:{"--val-color":r===`b`?`var(--eng)`:`var(--text-2)`,"--val-weight":r===`b`?`700`:`500`},children:e.text(n)})]}),(0,x.jsx)(YT,{a:t??0,b:n??0,winner:r})]},e.key)}),(0,x.jsx)(`div`,{className:KT.viewWrap,children:(0,x.jsx)(`button`,{type:`button`,onClick:l,className:KT.viewBtn,children:`View full verdict ›`})})]}):(0,x.jsx)(`div`,{className:KT.empty,children:`Simulation in progress. Scoreboard will populate when the verdict arrives.`})]})}var ZT={morale:`higher`,population:`higher`,deaths:`lower`,tools:`higher`,turn:`higher`};function QT(e,t){if(e.length===0)return 0;if(e.length===1)return e[0];let n=Math.max(0,Math.min(1,t))*(e.length-1),r=Math.floor(n),i=Math.ceil(n);if(r===i)return e[r];let a=n-r;return e[r]*(1-a)+e[i]*a}function $T(e,t){switch(t){case`morale`:return e.morale;case`population`:return e.population;case`deaths`:return e.deaths;case`tools`:return e.tools;case`turn`:return e.turn}}function eE(e,t,n){let r=n??ZT[t];if(e.length===0)return{metric:t,direction:r,top:[],middle:[],bottom:[],median:0};let i=[...e.map(e=>$T(e,t))].sort((e,t)=>e-t),a=QT(i,.25),o=QT(i,.75),s=QT(i,.5),c=[],l=[],u=[],d=a===o;for(let n of e){if(d){l.push(n);continue}let e=$T(n,t);r===`higher`?e>o?c.push(n):e<a?u.push(n):l.push(n):e<a?c.push(n):e>o?u.push(n):l.push(n)}return{metric:t,direction:r,top:c,middle:l,bottom:u,median:s}}function tE(e,t){if(e.length===0||t.length===0)return{frontIds:[],dominationCount:{}};let n=(e,t,n)=>{let r=$T(e,n),i=$T(t,n);return ZT[n]===`higher`?r>=i:r<=i},r=(e,t,n)=>{let r=$T(e,n),i=$T(t,n);return ZT[n]===`higher`?r>i:r<i},i=(e,i)=>{let a=!1;for(let o of t){if(!n(e,i,o))return!1;r(e,i,o)&&(a=!0)}return a},a={};for(let t of e)a[t.id]=0;for(let t of e)for(let n of e)t.id!==n.id&&i(t,n)&&a[t.id]++;let o=[];for(let t of e){let n=!1;for(let r of e)if(t.id!==r.id&&i(r,t)){n=!0;break}n||o.push(t.id)}return{frontIds:o,dominationCount:a}}function nE(e,t){if(e.length===0)return{metric:t,median:0,deltas:{}};let n=QT([...e.map(e=>$T(e,t))].sort((e,t)=>e-t),.5),r={},i=ZT[t]===`higher`?1:-1;for(let a of e){let e=($T(a,t)-n)*i;r[a.id]=e+0}return{metric:t,median:n,deltas:r}}function rE(e,t=0){if(Math.abs(e)<.5/10**t)return`±0`;let n=e.toFixed(t);return e>0?`+${n}`:n}var iE={panel:`_panel_1c1w0_1`,header:`_header_1c1w0_12`,heading:`_heading_1c1w0_18`,subhead:`_subhead_1c1w0_26`,section:`_section_1c1w0_34`,sectionTitle:`_sectionTitle_1c1w0_40`,sectionHint:`_sectionHint_1c1w0_51`,quartileGrid:`_quartileGrid_1c1w0_59`,quartileBlock:`_quartileBlock_1c1w0_65`,metricHead:`_metricHead_1c1w0_75`,metricLabel:`_metricLabel_1c1w0_82`,metricMedian:`_metricMedian_1c1w0_89`,quartileRow:`_quartileRow_1c1w0_96`,quartileTag:`_quartileTag_1c1w0_102`,actorList:`_actorList_1c1w0_114`,actorPill:`_actorPill_1c1w0_124`,actorPillTop:`_actorPillTop_1c1w0_134`,actorPillBottom:`_actorPillBottom_1c1w0_140`,actorListEmpty:`_actorListEmpty_1c1w0_146`,paretoList:`_paretoList_1c1w0_153`,paretoItem:`_paretoItem_1c1w0_162`,paretoName:`_paretoName_1c1w0_176`,paretoArchetype:`_paretoArchetype_1c1w0_181`,paretoDominates:`_paretoDominates_1c1w0_185`,medianTable:`_medianTable_1c1w0_191`,medianHeaderRow:`_medianHeaderRow_1c1w0_201`,medianBodyRow:`_medianBodyRow_1c1w0_202`,medianActorCol:`_medianActorCol_1c1w0_215`,medianActorName:`_medianActorName_1c1w0_223`,medianActorArchetype:`_medianActorArchetype_1c1w0_228`,medianMetricCol:`_medianMetricCol_1c1w0_233`,deltaPositive:`_deltaPositive_1c1w0_252`,deltaNegative:`_deltaNegative_1c1w0_256`,deltaNeutral:`_deltaNeutral_1c1w0_260`},aE=[{metric:`morale`,label:`Morale`,suffix:`%`},{metric:`population`,label:`Population`,suffix:``},{metric:`deaths`,label:`Deaths`,suffix:``},{metric:`tools`,label:`Tools`,suffix:``}],oE=[`morale`,`population`,`deaths`,`tools`],sE=[{metric:`morale`,label:`Morale`,suffix:`%`,decimals:0},{metric:`population`,label:`Population`,suffix:``,decimals:0},{metric:`deaths`,label:`Deaths`,suffix:``,decimals:0}];function cE({state:e}){let t=(0,b.useMemo)(()=>YC(e),[e]);if(t.length<3)return null;let n=(0,b.useMemo)(()=>aE.map(({metric:e,label:n,suffix:r})=>({metric:e,label:n,suffix:r,ranking:eE(t,e)})),[t]),r=(0,b.useMemo)(()=>tE(t,oE),[t]),i=r.frontIds.map(e=>t.find(t=>t.id===e)).filter(e=>!!e),a=(0,b.useMemo)(()=>sE.map(({metric:e,label:n,suffix:r,decimals:i})=>({metric:e,label:n,suffix:r,decimals:i,benchmark:nE(t,e)})),[t]);return(0,x.jsxs)(`section`,{className:iE.panel,"aria-labelledby":`cohort-verdict-heading`,children:[(0,x.jsxs)(`header`,{className:iE.header,children:[(0,x.jsx)(`h3`,{id:`cohort-verdict-heading`,className:iE.heading,children:`Cohort verdict`}),(0,x.jsxs)(`p`,{className:iE.subhead,children:[t.length,` actors · ranked across morale, population, deaths, and forged tools. A single winner doesn't generalize past two — this is the cohort-aware reading.`]})]}),(0,x.jsxs)(`div`,{className:iE.section,children:[(0,x.jsx)(`h4`,{className:iE.sectionTitle,children:`Quartile rankings`}),(0,x.jsx)(`div`,{className:iE.quartileGrid,children:n.map(({metric:e,label:t,suffix:n,ranking:r})=>(0,x.jsxs)(`div`,{className:iE.quartileBlock,children:[(0,x.jsxs)(`div`,{className:iE.metricHead,children:[(0,x.jsx)(`span`,{className:iE.metricLabel,children:t}),(0,x.jsxs)(`span`,{className:iE.metricMedian,children:[`median `,Math.round(r.median),n]})]}),(0,x.jsxs)(`div`,{className:iE.quartileRow,children:[(0,x.jsx)(`span`,{className:iE.quartileTag,children:`Top 25%`}),(0,x.jsxs)(`ul`,{className:iE.actorList,children:[r.top.map(e=>(0,x.jsx)(`li`,{className:`${iE.actorPill} ${iE.actorPillTop}`,children:e.name},e.id)),r.top.length===0&&(0,x.jsx)(`li`,{className:iE.actorListEmpty,children:`—`})]})]}),(0,x.jsxs)(`div`,{className:iE.quartileRow,children:[(0,x.jsx)(`span`,{className:iE.quartileTag,children:`Bottom 25%`}),(0,x.jsxs)(`ul`,{className:iE.actorList,children:[r.bottom.map(e=>(0,x.jsx)(`li`,{className:`${iE.actorPill} ${iE.actorPillBottom}`,children:e.name},e.id)),r.bottom.length===0&&(0,x.jsx)(`li`,{className:iE.actorListEmpty,children:`—`})]})]})]},e))})]}),(0,x.jsxs)(`div`,{className:iE.section,children:[(0,x.jsx)(`h4`,{className:iE.sectionTitle,children:`Pareto front · trade-off candidates`}),(0,x.jsxs)(`p`,{className:iE.sectionHint,children:[i.length,` actor`,i.length===1?``:`s`,` not dominated by any other across all four metrics. Off-front actors are strictly worse than someone on it.`]}),(0,x.jsx)(`ul`,{className:iE.paretoList,children:i.map(e=>{let t=r.dominationCount[e.id]??0;return(0,x.jsxs)(`li`,{className:iE.paretoItem,children:[(0,x.jsx)(`span`,{className:iE.paretoName,children:e.name}),(0,x.jsx)(`span`,{className:iE.paretoArchetype,children:e.archetype}),(0,x.jsxs)(`span`,{className:iE.paretoDominates,children:[`dominates `,t,` other`,t===1?``:`s`]})]},e.id)})})]}),(0,x.jsxs)(`div`,{className:iE.section,children:[(0,x.jsx)(`h4`,{className:iE.sectionTitle,children:`Median benchmark · per-actor deltas`}),(0,x.jsx)(`p`,{className:iE.sectionHint,children:`Sign-normalized so positive = better than median. Lower deaths and higher morale both read as positive deltas.`}),(0,x.jsxs)(`div`,{className:iE.medianTable,role:`table`,"aria-label":`Per-actor delta-from-median`,children:[(0,x.jsxs)(`div`,{className:iE.medianHeaderRow,role:`row`,children:[(0,x.jsx)(`span`,{className:iE.medianActorCol,role:`columnheader`,children:`Actor`}),a.map(e=>(0,x.jsx)(`span`,{className:iE.medianMetricCol,role:`columnheader`,children:e.label},e.metric))]}),t.map(e=>(0,x.jsxs)(`div`,{className:iE.medianBodyRow,role:`row`,children:[(0,x.jsxs)(`span`,{className:iE.medianActorCol,role:`cell`,children:[(0,x.jsx)(`span`,{className:iE.medianActorName,children:e.name}),(0,x.jsx)(`span`,{className:iE.medianActorArchetype,children:e.archetype})]}),a.map(t=>{let n=t.benchmark.deltas[e.id]??0,r=n>0?iE.deltaPositive:n<0?iE.deltaNegative:iE.deltaNeutral;return(0,x.jsxs)(`span`,{className:`${iE.medianMetricCol} ${r}`,role:`cell`,children:[rE(n,t.decimals),t.suffix]},t.metric)})]},e.id))]})]})]})}function lE(e){switch(e){case`conservative_success`:return`var(--green)`;case`risky_success`:return`var(--amber)`;case`conservative_failure`:return`var(--rust-dim, var(--rust))`;case`risky_failure`:return`var(--rust)`;default:return`var(--text-3)`}}function uE(e,t){return!e||!t?`divergent`:e===t?`shared`:`divergent`}var dE=[{id:`population`,label:`Population`},{id:`morale`,label:`Morale`},{id:`foodMonthsReserve`,label:`Food`,unit:`mo`},{id:`powerKw`,label:`Power`,unit:`kW`},{id:`infrastructureModules`,label:`Modules`},{id:`scienceOutput`,label:`Science`}];function fE(e,t){let n=[],r=new Set;for(let i of e){let e=i.data?.metrics;if(!e||typeof i.turn!=`number`)continue;let a=e[t];if(typeof a==`number`){if(r.has(i.turn)){let e=n.findIndex(e=>e.turn===i.turn);e>=0&&(n[e]={turn:i.turn,value:a})}else r.add(i.turn),n.push({turn:i.turn,value:a})}}return n}function pE(e,t,n){let r=t??e.actorIds[0],i=n??e.actorIds[1],a=r?e.actors[r]?.events:void 0,o=i?e.actors[i]?.events:void 0;return dE.map(e=>({id:e.id,label:e.label,unit:e.unit,a:a?fE(a,e.id):[],b:o?fE(o,e.id):[]}))}function mE(e,t){let n=e.actorIds.map((n,r)=>{let i=e.actors[n]?.events;return{actorId:n,idx:r,name:e.actors[n]?.leader?.name??n,color:t(r),events:i}});return dE.map(e=>({id:e.id,label:e.label,unit:e.unit,a:[],b:[],series:n.map(t=>({actorId:t.actorId,name:t.name,color:t.color,points:t.events?fE(t.events,e.id):[]}))}))}function hE(e){return e.map(([e,t])=>{let n=t.a.events.get(0),r=t.b.events.get(0);return{turn:e,time:t.a.time??t.b.time,diverged:uE(n?.title,r?.title)===`divergent`,a:{title:n?.title,outcome:n?.outcome,category:n?.category},b:{title:r?.title,outcome:r?.outcome,category:r?.category}}})}var gE={section:`_section_5eeou_1`,title:`_title_5eeou_10`,grid:`_grid_5eeou_20`,cell:`_cell_5eeou_26`,diverged:`_diverged_5eeou_40`,cellHead:`_cellHead_5eeou_45`,cellTurn:`_cellTurn_5eeou_53`,badge:`_badge_5eeou_57`,legend:`_legend_5eeou_71`},_E={conservative_success:`SAFE WIN`,risky_success:`RISKY WIN`,conservative_failure:`SAFE LOSS`,risky_failure:`RISKY LOSS`},vE={conservative_success:`S✓`,risky_success:`R✓`,conservative_failure:`S✗`,risky_failure:`R✗`};function yE(e,t=!1){return e?t?vE[e]??`·`:_E[e]??e.replace(/_/g,` `).toUpperCase():`·`}function bE({outcome:e,sideColor:t,compact:n}){let r=lE(e);return(0,x.jsx)(`div`,{className:gE.badge,style:{"--side-color":t,"--outcome-color":r,"--badge-size":n?`11px`:`9px`,"--badge-spacing":n?`0`:`0.04em`},children:yE(e,n)})}function xE(e){let{turns:t,leaderAName:n,leaderBName:r,onJumpToTurn:i}=e,a=jy(Ny);if(t.length===0)return null;let o=e=>{i?i(e):typeof document<`u`&&document.getElementById(`turn-${e}`)?.scrollIntoView({behavior:`smooth`,block:`start`})};return(0,x.jsxs)(`section`,{"aria-label":`Run timeline strip`,className:gE.section,children:[(0,x.jsx)(`div`,{className:gE.title,children:`Run Strip`}),(0,x.jsx)(`div`,{role:`list`,className:gE.grid,style:{"--turn-count":String(t.length)},children:t.map(e=>(0,x.jsxs)(`button`,{type:`button`,role:`listitem`,onClick:()=>o(e.turn),"aria-label":`Jump to turn ${e.turn}${e.time?`, time `+e.time:``}${e.diverged?`, divergent`:``}`,className:[gE.cell,e.diverged?gE.diverged:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`div`,{className:gE.cellHead,children:[(0,x.jsxs)(`span`,{className:gE.cellTurn,children:[`T`,e.turn]}),e.time&&!a&&(0,x.jsxs)(`span`,{children:[`Y`,e.time]})]}),(0,x.jsx)(bE,{outcome:e.a.outcome,sideColor:`var(--vis)`,compact:a}),(0,x.jsx)(bE,{outcome:e.b.outcome,sideColor:`var(--eng)`,compact:a})]},e.turn))}),(0,x.jsxs)(`div`,{className:gE.legend,children:[(0,x.jsx)(`span`,{children:n}),(0,x.jsx)(`span`,{children:r})]})]})}var SE={section:`_section_1aa2r_1`,sectionHeader:`_sectionHeader_1aa2r_10`,sectionTitle:`_sectionTitle_1aa2r_17`,legend:`_legend_1aa2r_26`,legendA:`_legendA_1aa2r_32`,legendB:`_legendB_1aa2r_37`,grid:`_grid_1aa2r_42`,card:`_card_1aa2r_48`,cardHeader:`_cardHeader_1aa2r_58`,cardLabel:`_cardLabel_1aa2r_65`,cardRange:`_cardRange_1aa2r_70`,cardFooter:`_cardFooter_1aa2r_74`,lastA:`_lastA_1aa2r_81`,lastB:`_lastB_1aa2r_86`,cardFooterCohort:`_cardFooterCohort_1aa2r_94`,lastCohort:`_lastCohort_1aa2r_103`,legendCohort:`_legendCohort_1aa2r_112`,legendCohortEntry:`_legendCohortEntry_1aa2r_122`,legendCohortSlot:`_legendCohortSlot_1aa2r_141`,lastCohortSlot:`_lastCohortSlot_1aa2r_153`};function CE(e,t){return t===`mo`||t===`kW`?`${e.toFixed(1)}${t?` `+t:``}`:e>0&&e<1?`${Math.round(e*100)}%`:`${Math.round(e)}${t?` `+t:``}`}function wE(e){let t=e,n=``;do n=String.fromCharCode(65+t%26)+n,t=Math.floor(t/26)-1;while(t>=0);return n}function TE({metric:e,sideAColor:t,sideBColor:n}){let r=Array.isArray(e.series)&&e.series.length>=2,i=r?e.series.flatMap(e=>e.points):[...e.a,...e.b];if(i.length===0)return null;let a=1/0,o=-1/0,s=1/0,c=-1/0;for(let e of i)e.turn<a&&(a=e.turn),e.turn>o&&(o=e.turn),e.value<s&&(s=e.value),e.value>c&&(c=e.value);let l=Math.max(1e-6,c-s),u=Math.max(1,o-a),d=e=>4+192*((e-a)/u),f=e=>6+38*(1-(e-s)/l);if(r)return(0,x.jsxs)(`div`,{className:SE.card,children:[(0,x.jsxs)(`div`,{className:SE.cardHeader,children:[(0,x.jsx)(`span`,{className:SE.cardLabel,children:e.label}),(0,x.jsxs)(`span`,{className:SE.cardRange,children:[`T`,a,` → T`,o]})]}),(0,x.jsxs)(`svg`,{viewBox:`0 0 200 50`,width:`100%`,height:50,role:`img`,"aria-label":`${e.label} sparkline (${e.series.length} actors)`,children:[(0,x.jsx)(`line`,{x1:4,y1:25,x2:196,y2:25,stroke:`var(--border)`,strokeWidth:`0.5`,strokeDasharray:`2,3`}),e.series.map(e=>{let t=e.points.map(e=>`${d(e.turn)},${f(e.value)}`).join(` `);return t?(0,x.jsx)(`polyline`,{points:t,fill:`none`,stroke:e.color,strokeWidth:`1.5`,strokeLinejoin:`round`,strokeLinecap:`round`,opacity:.78,children:(0,x.jsx)(`title`,{children:e.name})},e.actorId):null})]}),(0,x.jsx)(`div`,{className:SE.cardFooterCohort,children:e.series.map((t,n)=>{let r=t.points[t.points.length-1]?.value,i=wE(n);return(0,x.jsxs)(`span`,{className:SE.lastCohort,style:{"--actor-color":t.color},title:t.name,children:[(0,x.jsx)(`span`,{className:SE.lastCohortSlot,"aria-hidden":`true`,children:i}),r==null?`·`:CE(r,e.unit)]},t.actorId)})})]});let p=e.a.map(e=>`${d(e.turn)},${f(e.value)}`).join(` `),m=e.b.map(e=>`${d(e.turn)},${f(e.value)}`).join(` `),h=e.a[e.a.length-1]?.value,g=e.b[e.b.length-1]?.value;return(0,x.jsxs)(`div`,{className:SE.card,children:[(0,x.jsxs)(`div`,{className:SE.cardHeader,children:[(0,x.jsx)(`span`,{className:SE.cardLabel,children:e.label}),(0,x.jsxs)(`span`,{className:SE.cardRange,children:[`T`,a,` → T`,o]})]}),(0,x.jsxs)(`svg`,{viewBox:`0 0 200 50`,width:`100%`,height:50,role:`img`,"aria-label":`${e.label} sparkline`,children:[(0,x.jsx)(`line`,{x1:4,y1:25,x2:196,y2:25,stroke:`var(--border)`,strokeWidth:`0.5`,strokeDasharray:`2,3`}),p&&(0,x.jsx)(`polyline`,{points:p,fill:`none`,stroke:t,strokeWidth:`1.5`,strokeLinejoin:`round`,strokeLinecap:`round`,opacity:.9}),m&&(0,x.jsx)(`polyline`,{points:m,fill:`none`,stroke:n,strokeWidth:`1.5`,strokeLinejoin:`round`,strokeLinecap:`round`,opacity:.9})]}),(0,x.jsxs)(`div`,{className:SE.cardFooter,children:[(0,x.jsx)(`span`,{className:SE.lastA,children:h==null?`·`:CE(h,e.unit)}),(0,x.jsx)(`span`,{className:SE.lastB,children:g==null?`·`:CE(g,e.unit)})]})]})}function EE(e){let{metrics:t,leaderAName:n,leaderBName:r}=e,i=e.sideAColor??`var(--vis)`,a=e.sideBColor??`var(--eng)`,o=t.length>0&&Array.isArray(t[0].series)&&t[0].series.length>=2,s=t.filter(e=>o?(e.series??[]).some(e=>e.points.length>0):e.a.length>0||e.b.length>0);if(s.length===0)return null;let c={"--side-a-color":i,"--side-b-color":a};return(0,x.jsxs)(`section`,{"aria-label":`Metric sparklines`,className:SE.section,style:c,children:[(0,x.jsxs)(`div`,{className:SE.sectionHeader,children:[(0,x.jsx)(`span`,{className:SE.sectionTitle,children:`Metric Trajectories`}),o?(0,x.jsx)(`span`,{className:SE.legendCohort,children:(s[0].series??[]).map((e,t)=>(0,x.jsxs)(`span`,{className:SE.legendCohortEntry,style:{"--actor-color":e.color},children:[(0,x.jsx)(`span`,{className:SE.legendCohortSlot,"aria-hidden":`true`,children:wE(t)}),e.name]},e.actorId))}):(0,x.jsxs)(`span`,{className:SE.legend,children:[(0,x.jsx)(`span`,{className:SE.legendA,children:n}),` · `,(0,x.jsx)(`span`,{className:SE.legendB,children:r})]})]}),(0,x.jsx)(`div`,{className:`responsive-grid-3 ${SE.grid}`,children:s.map(e=>(0,x.jsx)(TE,{metric:e,sideAColor:i,sideBColor:a},e.id))})]})}function DE(e,t){let[n,r]=(0,b.useState)(()=>typeof window<`u`?window.matchMedia(e).matches:t);return(0,b.useEffect)(()=>{if(typeof window>`u`)return;let t=window.matchMedia(e),n=()=>r(t.matches);return t.addEventListener(`change`,n),()=>t.removeEventListener(`change`,n)},[e]),n}function OE(e){let{items:t,scrollRoot:n}=e,[r,i]=(0,b.useState)(t[0]?.id),a=DE(`(min-width: 1024px)`,!0),o=DE(`(max-width: 767.98px)`,!1);(0,b.useEffect)(()=>{if(typeof window>`u`||t.length===0)return;let e=t.map(e=>document.getElementById(e.id)).filter(e=>e!=null);if(e.length===0)return;let r=new IntersectionObserver(e=>{let t=e.filter(e=>e.isIntersecting).sort((e,t)=>t.intersectionRatio-e.intersectionRatio);t[0]&&i(t[0].target.id)},{root:n??null,rootMargin:`-80px 0px -60% 0px`,threshold:[0,.25,.5,.75,1]});return e.forEach(e=>r.observe(e)),()=>r.disconnect()},[t,n]);let s=(0,b.useMemo)(()=>({display:`block`,padding:`4px 10px`,fontSize:`var(--font-xs)`,fontFamily:`var(--mono)`,fontWeight:700,letterSpacing:`0.04em`,textTransform:`uppercase`,color:`var(--text-3)`,textDecoration:`none`,borderRadius:3}),[]);return t.length===0?null:a?(0,x.jsx)(`nav`,{"aria-label":`Report sections`,style:{position:`sticky`,top:12,alignSelf:`flex-start`,width:160,marginLeft:12,padding:`10px 6px`,background:`var(--bg-panel)`,border:`1px solid var(--border)`,borderRadius:8,maxHeight:`calc(100vh - 40px)`,overflowY:`auto`},children:t.map(e=>(0,x.jsx)(`a`,{href:`#${e.id}`,style:{...s,color:r===e.id?`var(--amber)`:`var(--text-3)`,background:r===e.id?`color-mix(in srgb, var(--bg-canvas) 80%, var(--amber) 20%)`:`transparent`},children:e.label},e.id))}):(0,x.jsx)(`nav`,{"aria-label":`Report sections`,style:{background:`var(--bg-panel)`,borderBottom:`1px solid var(--border)`,padding:o?`8px 10px`:`6px 8px`,marginBottom:12,overflowX:`auto`,WebkitOverflowScrolling:`touch`,display:`flex`,gap:o?6:4,flexShrink:0},children:t.map(e=>{let t=r===e.id,n={...s,flexShrink:0,padding:`8px 12px`,borderRadius:4,border:`1px solid ${t?`var(--amber)`:`var(--border)`}`,background:t?`var(--amber)`:`var(--bg-card)`,color:t?`var(--bg-deep)`:`var(--text-3)`},i={...s,flexShrink:0,color:t?`var(--amber)`:`var(--text-3)`,borderBottom:t?`2px solid var(--amber)`:`2px solid transparent`};return(0,x.jsx)(`a`,{href:`#${e.id}`,style:o?n:i,children:e.label},e.id)})})}var Z={empty:`_empty_1pipo_1`,emptyMsg:`_emptyMsg_1pipo_8`,emptyMsgRunning:`_emptyMsgRunning_1pipo_15`,emptySpinner:`_emptySpinner_1pipo_23`,reportEmptySpinnerRotate:`_reportEmptySpinnerRotate_1pipo_1`,layout:`_layout_1pipo_43`,scroll:`_scroll_1pipo_50`,tldr:`_tldr_1pipo_58`,tldrTopRow:`_tldrTopRow_1pipo_69`,tldrTag:`_tldrTag_1pipo_76`,tldrHeadline:`_tldrHeadline_1pipo_85`,tldrSub:`_tldrSub_1pipo_92`,tldrStats:`_tldrStats_1pipo_99`,tldrStatLabel:`_tldrStatLabel_1pipo_108`,tldrStatValue:`_tldrStatValue_1pipo_113`,headerRow:`_headerRow_1pipo_118`,headerTitle:`_headerTitle_1pipo_127`,jumpBtn:`_jumpBtn_1pipo_134`,actorPairPicker:`_actorPairPicker_1pipo_149`,actorPairPickerLabel:`_actorPairPickerLabel_1pipo_164`,actorPairPickerToggle:`_actorPairPickerToggle_1pipo_172`,actorPairPickerToggleText:`_actorPairPickerToggleText_1pipo_209`,actorPairPickerSelect:`_actorPairPickerSelect_1pipo_218`,actorPairPickerVs:`_actorPairPickerVs_1pipo_237`,actorPairPickerHint:`_actorPairPickerHint_1pipo_245`,jumpInlineBtn:`_jumpInlineBtn_1pipo_251`,trajectoryGrid:`_trajectoryGrid_1pipo_262`,costBar:`_costBar_1pipo_269`,costLabel:`_costLabel_1pipo_282`,costAmount:`_costAmount_1pipo_289`,costMeta:`_costMeta_1pipo_295`,costBtn:`_costBtn_1pipo_299`,turnSection:`_turnSection_1pipo_312`,diverged:`_diverged_1pipo_321`,turnHeader:`_turnHeader_1pipo_326`,turnTitle:`_turnTitle_1pipo_333`,turnEventCount:`_turnEventCount_1pipo_340`,turnHeaderRight:`_turnHeaderRight_1pipo_348`,divergenceFlag:`_divergenceFlag_1pipo_354`,eventGrid:`_eventGrid_1pipo_367`,eventGridSpaced:`_eventGridSpaced_1pipo_373`,footerGrid:`_footerGrid_1pipo_380`,nActorEventTrack:`_nActorEventTrack_1pipo_387`,nActorEventTrackSpaced:`_nActorEventTrackSpaced_1pipo_397`,nActorFooterTrack:`_nActorFooterTrack_1pipo_408`,summarySection:`_summarySection_1pipo_426`,summaryLabel:`_summaryLabel_1pipo_430`,summaryVerdictWrap:`_summaryVerdictWrap_1pipo_442`,aboutDetails:`_aboutDetails_1pipo_446`,aboutSummary:`_aboutSummary_1pipo_457`,aboutBody:`_aboutBody_1pipo_465`,aboutBlockTitle:`_aboutBlockTitle_1pipo_472`,aboutChips:`_aboutChips_1pipo_478`,aboutChip:`_aboutChip_1pipo_478`,aboutChipNeutral:`_aboutChipNeutral_1pipo_494`,eventCard:`_eventCard_1pipo_504`,eventHeading:`_eventHeading_1pipo_511`,eventSubLabel:`_eventSubLabel_1pipo_519`,eventAwaiting:`_eventAwaiting_1pipo_526`,eventTitle:`_eventTitle_1pipo_531`,categoryPill:`_categoryPill_1pipo_538`,emergentPill:`_emergentPill_1pipo_548`,eventDescription:`_eventDescription_1pipo_556`,eventDecision:`_eventDecision_1pipo_564`,eventOutcomeRow:`_eventOutcomeRow_1pipo_571`,eventPolicies:`_eventPolicies_1pipo_578`,eventDetails:`_eventDetails_1pipo_584`,eventDetailsSummary:`_eventDetailsSummary_1pipo_588`,eventRationale:`_eventRationale_1pipo_596`,deptList:`_deptList_1pipo_606`,deptItem:`_deptItem_1pipo_613`,deptHead:`_deptHead_1pipo_621`,deptName:`_deptName_1pipo_627`,deptMeta:`_deptMeta_1pipo_632`,deptSummary:`_deptSummary_1pipo_638`,footerCard:`_footerCard_1pipo_644`,footerDetails:`_footerDetails_1pipo_651`,footerDetailsLast:`_footerDetailsLast_1pipo_655`,footerSummary:`_footerSummary_1pipo_659`,systemsRow:`_systemsRow_1pipo_667`,systemItem:`_systemItem_1pipo_676`,systemKey:`_systemKey_1pipo_680`,systemValue:`_systemValue_1pipo_684`,reactionsList:`_reactionsList_1pipo_689`,reactionItem:`_reactionItem_1pipo_696`,reactionHead:`_reactionHead_1pipo_704`,reactionName:`_reactionName_1pipo_711`,moodPill:`_moodPill_1pipo_716`,reactionQuote:`_reactionQuote_1pipo_726`,reactionRole:`_reactionRole_1pipo_731`,forkNotice:`_forkNotice_1pipo_737`};function kE(e,t){let[n,r]=(0,b.useState)(()=>{if(typeof window>`u`)return t;try{let n=window.localStorage.getItem(e);return n===null?t:n===`1`}catch{return t}});return[n,(0,b.useCallback)(t=>{r(t);try{window.localStorage.setItem(e,t?`1`:`0`)}catch{}},[e])]}function AE(){return{events:new Map,reactions:[],totalReactions:0}}function jE(e,t,n){let r=e.events.get(t);return r||(r={eventIndex:t,totalEvents:n,depts:{}},e.events.set(t,r)),n>r.totalEvents&&(r.totalEvents=n),r}function ME(e){let t=new Map;if(!e)return t;let n=new Map;for(let r of e){let e=r.turn;if(typeof e!=`number`)continue;let i=t.get(e);i||(i=AE(),t.set(e,i));let a=Number(r.data?.eventIndex??0),o=Number(r.data?.totalEvents??1);if(r.type===`turn_start`&&(r.data?.time!=null&&(i.time=r.data.time),r.data?.metrics&&(i.metrics=r.data.metrics),r.data?.title&&r.data?.title!==`Director generating...`&&!r.data?.totalEvents)){let e=jE(i,0,1);e.title=r.data.title,e.category=r.data.category,e.emergent=r.data.emergent,e.description=r.data.crisis||r.data.turnSummary||``}if(r.type===`event_start`){let e=jE(i,a,o);e.title=r.data?.title,e.category=r.data?.category,e.emergent=r.data?.emergent,e.description=r.data?.description||r.data?.turnSummary||``}if(r.type===`decision_made`&&n.set(a,{decision:String(r.data?.decision||``),rationale:String(r.data?.rationale||``),policies:Array.isArray(r.data?.selectedPolicies)?r.data.selectedPolicies.map(e=>typeof e==`string`?e:JSON.stringify(e)):[]}),r.type===`outcome`){let e=jE(i,a,o);e.outcome=String(r.data?.outcome||``);let t=n.get(a);t&&(e.decision=t.decision,e.rationale=t.rationale,e.policies=t.policies,n.delete(a))}if(r.type===`specialist_done`){let e=jE(i,a,o),t=r.data?.department;if(t){let n=(r.data?._filteredTools||[]).filter(e=>e?.approved!==!1).length;e.depts[t]={summary:r.data?.summary||``,tools:n,citations:Number(r.data?.citations??0),citationList:r.data?.citationList||[]}}}r.type===`agent_reactions`&&(i.reactions=(r.data?.reactions||[]).slice(0,3),i.totalReactions=Number(r.data?.totalReactions??0))}return t}function NE(e){return e===`pos`?`var(--green)`:e===`neg`?`var(--rust)`:`var(--text-1)`}function PE({state:e,verdict:t,shownRun:n,reportSections:r}){let i=h_(),a=D_(),[o,s]=kE(`paracosm-reports-refs-open`,!1),[c,l]=kE(`paracosm-reports-tools-open`,!1),[u,d]=(0,b.useState)(!1),{state:f,dispatch:p}=Gn(),m=eA(),h=nA(),g=Lm(),[_,v]=(0,b.useState)(null),y=f.parent,S=Xk(),C=Qk(),w=y?.metadata?.scenario,T=typeof w?.id==`string`&&w.id!==S.id,E=(0,b.useCallback)(t=>!y||e.isRunning||!C||T?!1:bT(y,t),[y,e.isRunning,C,T]),D=(0,b.useCallback)(async e=>{v(null);let t=`branch-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;p({type:`BRANCH_OPTIMISTIC`,localId:t,forkedAtTurn:e.atTurn,actorName:e.leader.name,actorArchetype:e.leader.archetype});let n=yT(e.parentArtifact),r=e.seedOverride??e.parentArtifact.metadata.seed??42;try{let i=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({actors:[e.leader],turns:n,seed:r,captureSnapshots:!0,customEvents:e.customEvents,forkFrom:{parentArtifact:_T(e.parentArtifact),atTurn:e.atTurn}})});if(!i.ok){let e=await i.json().catch(()=>({}));p({type:`BRANCH_ERROR`,localId:t,message:e.error??`HTTP ${i.status}`});return}let a=await i.json().catch(()=>({}));k(window,a.visitorId),h(),m(`studio`)}catch(e){p({type:`BRANCH_ERROR`,localId:t,message:String(e)})}},[p,m,h]),O=e.actorIds[0]??null,A=e.actorIds[1]??null,[j,ee]=(0,b.useState)(O),[te,M]=(0,b.useState)(A);(0,b.useEffect)(()=>{j&&!e.actorIds.includes(j)&&ee(O),te&&!e.actorIds.includes(te)&&M(A)},[e.actorIds,j,te,O,A]);let N=j??O,ne=te??A,P=e.actorIds.length>2,[re,ie]=(0,b.useState)(!P);(0,b.useEffect)(()=>{ie(!P)},[P]);let F=(0,b.useMemo)(()=>{let t=new Map;for(let n of e.actorIds)t.set(n,ME(e.actors[n]?.events));return t},[e]),I=(0,b.useMemo)(()=>{let e=N&&F.get(N)||new Map,t=ne&&F.get(ne)||new Map;return[...new Set([...e.keys(),...t.keys()])].sort((e,t)=>e-t).map(n=>[n,{a:e.get(n)??AE(),b:t.get(n)??AE()}])},[F,N,ne]),ae=(0,b.useMemo)(()=>{if(!P)return[];let t=new Set;for(let e of F.values())for(let n of e.keys())t.add(n);return[...t].sort((e,t)=>e-t).map(t=>{let n=new Map;for(let r of e.actorIds)n.set(r,F.get(r)?.get(t)??AE());return[t,n]})},[P,F,e.actorIds]),oe=N,se=ne,ce=oe?e.actors[oe]:null,le=se?e.actors[se]:null,L=ce?.leader?.name||`Leader A`,ue=le?.leader?.name||`Leader B`,de=(ce?.events.some(e=>e.type===`personality_drift`)??!1)||(le?.events.some(e=>e.type===`personality_drift`)??!1),fe=I.some(([,e])=>e.a.reactions.length>0||e.b.reactions.length>0),R=I.some(([,e])=>[...e.a.events.values(),...e.b.events.values()].some(e=>!!e.rationale)),z=(0,b.useMemo)(()=>GT({configuredSections:r,hasQuotes:fe,hasCausality:R,hasVerdict:!!t,hasTrajectories:de,hasCost:!!(e.cost&&e.cost.llmCalls>0),hasToolbox:a.list.length>0,hasReferences:i.list.length>0}),[r,fe,R,t,de,e.cost,a.list.length,i.list.length]),pe=(0,b.useMemo)(()=>hE(I),[I]),me=(0,b.useMemo)(()=>pE(e,N,ne),[e,N,ne]),he=(0,b.useMemo)(()=>P?mE(e,Pe):null,[P,e]),ge=(0,b.useMemo)(()=>{let e=[];pe.length>0&&e.push({id:`strip`,label:`Strip`}),me.some(e=>e.a.length>0||e.b.length>0)&&e.push({id:`sparklines`,label:`Metrics`}),de&&e.push({id:`trajectory`,label:`Trajectory`});for(let[t]of I)e.push({id:`turn-${t}`,label:`Turn ${t}`});return a.list.length>0&&e.push({id:`toolbox`,label:`Toolbox`}),e.push({id:`summary`,label:t?`Verdict`:`Summary`}),i.list.length>0&&e.push({id:`references`,label:`References`}),e},[t,pe.length,me,de,I,a.list.length,i.list.length]),_e=(0,b.useRef)(null),B=(0,b.useRef)(!0);return(0,b.useEffect)(()=>{B.current&&_e.current&&I.length>0&&_e.current.scrollTo({top:_e.current.scrollHeight,behavior:`smooth`})},[I.length]),!(ce?.events.length??0)&&!(le?.events.length??0)?e.isRunning?(0,x.jsx)(`div`,{className:Z.empty,children:(0,x.jsxs)(`div`,{className:`${Z.emptyMsg} ${Z.emptyMsgRunning??``}`,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:Z.emptySpinner,"aria-hidden":`true`}),(0,x.jsx)(`span`,{children:`Awaiting first turn — the report populates once the kernel reports an event.`})]})}):(0,x.jsx)(`div`,{className:Z.empty,children:(0,x.jsx)(`div`,{className:Z.emptyMsg,children:`Run a simulation first to see the report.`})}):(0,x.jsxs)(`div`,{className:`reports-layout ${Z.layout}`,children:[(0,x.jsxs)(`div`,{ref:_e,onScroll:()=>{let e=_e.current;e&&(B.current=e.scrollHeight-e.scrollTop-e.clientHeight<40)},className:`reports-content ${Z.scroll}`,role:`region`,"aria-label":`Turn-by-turn report`,children:[C&&T&&(0,x.jsxs)(`p`,{className:Z.forkNotice,role:`note`,children:[`This run is in `,w?.name??w?.id,`, and a fork runs in its parent's scenario. Switch to `,w?.name??w?.id,` to fork it.`]}),(()=>{let e=t,n=e?.winnerName||``,r=e?.headline||e?.summary||``;if(!t&&I.length===0)return null;let i=I.length,a=I[I.length-1],o=I[0],s=(e,t)=>{let n=e?.[t];return typeof n==`number`?n:0},c=s(a?.[1]?.a?.metrics,`population`),l=s(a?.[1]?.b?.metrics,`population`),u=s(a?.[1]?.a?.metrics,`morale`),d=s(a?.[1]?.b?.metrics,`morale`),f=s(o?.[1]?.a?.metrics,`population`)||c,p=s(o?.[1]?.b?.metrics,`population`)||l,m=ce?.events.filter(e=>e.type===`forge_attempt`&&e.data?.approved===!0).length??0,h=le?.events.filter(e=>e.type===`forge_attempt`&&e.data?.approved===!0).length??0,g=[{label:`Turns`,value:String(i)},{label:`Final pop`,value:`A ${c}${c<f?` (↓${f-c})`:``} · B ${l}${l<p?` (↓${p-l})`:``}`,tone:c+l<f+p?`neg`:`neutral`},{label:`Final morale`,value:`A ${Math.round(u*100)}% · B ${Math.round(d*100)}%`,tone:Math.min(u,d)<.3?`neg`:Math.min(u,d)>=.6?`pos`:`neutral`},{label:`Tools forged`,value:`A ${m} · B ${h}`}];return(0,x.jsxs)(`div`,{className:Z.tldr,children:[(0,x.jsxs)(`div`,{className:Z.tldrTopRow,children:[(0,x.jsx)(`span`,{className:Z.tldrTag,children:`TL;DR`}),n?(0,x.jsxs)(`span`,{className:Z.tldrHeadline,children:[n,` wins`]}):i>0?(0,x.jsxs)(`span`,{className:Z.tldrHeadline,children:[`Run `,i,` turn`,i===1?``:`s`,` — verdict pending`]}):null,r&&(0,x.jsx)(`span`,{className:Z.tldrSub,children:r})]}),(0,x.jsx)(`div`,{className:Z.tldrStats,children:g.map(e=>(0,x.jsxs)(`span`,{children:[(0,x.jsxs)(`span`,{className:Z.tldrStatLabel,children:[e.label,`:`]}),(0,x.jsx)(`span`,{className:Z.tldrStatValue,style:{"--tone-color":NE(e.tone)},children:e.value})]},e.label))})]})})(),(0,x.jsxs)(`div`,{className:Z.headerRow,children:[(0,x.jsx)(`h2`,{className:Z.headerTitle,children:`Turn-by-Turn Report`}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>{let e=document.getElementById(`summary`);e&&e.scrollIntoView({behavior:`smooth`,block:`start`})},className:Z.jumpBtn,children:t?`↓ See verdict + full summary`:`↓ Jump to summary`})]}),P&&(0,x.jsxs)(`div`,{className:Z.actorPairPicker,role:`region`,"aria-label":`Pair focus toggle`,children:[(0,x.jsxs)(`label`,{className:Z.actorPairPickerToggle,children:[(0,x.jsx)(`input`,{type:`checkbox`,checked:re,onChange:e=>ie(e.target.checked),"aria-label":`Toggle pair-focus view for strip, sparklines, and trajectory`}),(0,x.jsx)(`span`,{className:Z.actorPairPickerToggleText,children:`Focus pair`})]}),re?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`select`,{"aria-label":`Left side actor`,className:Z.actorPairPickerSelect,value:N??``,onChange:e=>ee(e.target.value||null),children:e.actorIds.map(t=>(0,x.jsx)(`option`,{value:t,disabled:t===ne,children:e.actors[t]?.leader?.name??t},t))}),(0,x.jsx)(`span`,{className:Z.actorPairPickerVs,children:`vs`}),(0,x.jsx)(`select`,{"aria-label":`Right side actor`,className:Z.actorPairPickerSelect,value:ne??``,onChange:e=>M(e.target.value||null),children:e.actorIds.map(t=>(0,x.jsx)(`option`,{value:t,disabled:t===N,children:e.actors[t]?.leader?.name??t},t))}),(0,x.jsxs)(`span`,{className:Z.actorPairPickerHint,children:[`strip + metrics + trajectory show this pair only · turn-by-turn below shows all `,e.actorIds.length,` actors`]})]}):(0,x.jsxs)(`span`,{className:Z.actorPairPickerHint,children:[`Showing all `,e.actorIds.length,` actors. Toggle on to focus on a 2-actor head-to-head view in the strip, sparklines, and trajectory cards.`]})]}),(!P||re)&&(0,x.jsx)(`section`,{id:`strip`,children:(0,x.jsx)(xE,{turns:pe,leaderAName:L,leaderBName:ue})}),(0,x.jsx)(`section`,{id:`sparklines`,children:!P||re?(0,x.jsx)(EE,{metrics:me,leaderAName:L,leaderBName:ue}):he&&(0,x.jsx)(EE,{metrics:he,leaderAName:``,leaderBName:``})}),(0,x.jsxs)(`section`,{id:`trajectory`,children:[de&&re&&(0,x.jsxs)(`div`,{className:`responsive-grid-2 ${Z.trajectoryGrid}`,children:[(0,x.jsx)(LT,{events:ce?.events??[],actorName:L,baselineHexaco:ce?.leader?.hexaco}),(0,x.jsx)(LT,{events:le?.events??[],actorName:ue,baselineHexaco:le?.leader?.hexaco})]}),de&&!re&&(0,x.jsx)(`div`,{className:`responsive-grid-2 ${Z.trajectoryGrid}`,children:e.actorIds.map(t=>{let n=e.actors[t];return n?.events.length?(0,x.jsx)(LT,{events:n.events,actorName:n.leader?.name||t,baselineHexaco:n.leader?.hexaco},t):null})})]}),e.cost&&e.cost.llmCalls>0&&(0,x.jsxs)(`div`,{className:Z.costBar,children:[(0,x.jsx)(`span`,{className:Z.costLabel,children:`Run cost`}),(0,x.jsxs)(`span`,{className:Z.costAmount,children:[`$`,e.cost.totalCostUSD<.01?e.cost.totalCostUSD.toFixed(4):e.cost.totalCostUSD.toFixed(2)]}),(0,x.jsxs)(`span`,{className:Z.costMeta,children:[`· `,e.cost.llmCalls,` LLM calls · `,(e.cost.totalTokens/1e3).toFixed(1),`k tokens`]}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>d(!0),className:Z.costBtn,children:`Per-stage breakdown ›`})]}),u&&e.cost&&e.cost.llmCalls>0&&(0,x.jsx)(AT,{combined:e.cost,leaderA:(oe?e.costByActor[oe]:void 0)??{totalTokens:0,totalCostUSD:0,llmCalls:0},leaderB:(se?e.costByActor[se]:void 0)??{totalTokens:0,totalCostUSD:0,llmCalls:0},leaderAName:ce?.leader?.name,leaderBName:le?.leader?.name,actors:P?e.actorIds.map(t=>({actorId:t,name:e.actors[t]?.leader?.name||t,cost:e.costByActor[t]??{totalTokens:0,totalCostUSD:0,llmCalls:0}})):void 0,onClose:()=>d(!1)}),!P&&I.map(([e,t])=>{let n=t.a,r=t.b,i=n.time||r.time||`?`,a=Math.max(...[...n.events.values()].map(e=>e.totalEvents),...[...r.events.values()].map(e=>e.totalEvents),1),o=n.events.get(0)?.title,s=r.events.get(0)?.title,c=!!(o&&s&&o!==s);return(0,x.jsxs)(`section`,{id:`turn-${e}`,className:[Z.turnSection,c?Z.diverged:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`div`,{className:Z.turnHeader,children:[(0,x.jsxs)(`span`,{className:Z.turnTitle,children:[`Turn `,e,` — Y`,i,a>1&&(0,x.jsxs)(`span`,{className:Z.turnEventCount,children:[a,` events`]})]}),(0,x.jsxs)(`div`,{className:Z.turnHeaderRight,children:[(0,x.jsx)(`span`,{className:[Z.divergenceFlag,c?Z.diverged:``].filter(Boolean).join(` `),children:c?`DIVERGENT`:`SHARED`}),E(e)&&(0,x.jsxs)(`button`,{type:`button`,className:xT.forkButton,onClick:()=>v(e),"aria-label":`Fork at ${g.time} ${e}`,children:[`↳ Fork at `,g.Time,` `,e]})]})]}),Array.from({length:a}).map((e,t)=>(0,x.jsxs)(`div`,{className:`responsive-grid-2 ${t<a-1?Z.eventGridSpaced:Z.eventGrid}`,children:[(0,x.jsx)(IE,{block:n.events.get(t),eventIndex:t,totalEvents:a,name:L,sideColor:`var(--vis)`,sections:z.eventSections}),(0,x.jsx)(IE,{block:r.events.get(t),eventIndex:t,totalEvents:a,name:ue,sideColor:`var(--eng)`,sections:z.eventSections})]},t)),(0,x.jsxs)(`div`,{className:`responsive-grid-2 ${Z.footerGrid}`,children:[(0,x.jsx)(LE,{data:n,name:L,sideColor:`var(--vis)`,showQuotes:z.footerSections.includes(`quotes`)}),(0,x.jsx)(LE,{data:r,name:ue,sideColor:`var(--eng)`,showQuotes:z.footerSections.includes(`quotes`)})]})]},e)}),P&&ae.map(([t,n])=>{let r=[],i,a=1;for(let t of e.actorIds){let e=n.get(t);if(!e)continue;i??=e.time;for(let t of e.events.values())t.totalEvents>a&&(a=t.totalEvents);let o=e.events.get(0)?.title;o&&r.push(o)}let o=new Set(r).size>1,s=i??`?`;return(0,x.jsxs)(`section`,{id:`turn-${t}`,className:[Z.turnSection,o?Z.diverged:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`div`,{className:Z.turnHeader,children:[(0,x.jsxs)(`span`,{className:Z.turnTitle,children:[`Turn `,t,` — Y`,s,a>1&&(0,x.jsxs)(`span`,{className:Z.turnEventCount,children:[a,` events`]})]}),(0,x.jsxs)(`div`,{className:Z.turnHeaderRight,children:[(0,x.jsx)(`span`,{className:[Z.divergenceFlag,o?Z.diverged:``].filter(Boolean).join(` `),children:o?`DIVERGENT`:`SHARED`}),E(t)&&(0,x.jsxs)(`button`,{type:`button`,className:xT.forkButton,onClick:()=>v(t),"aria-label":`Fork at ${g.time} ${t}`,children:[`↳ Fork at `,g.Time,` `,t]})]})]}),Array.from({length:a}).map((t,r)=>(0,x.jsx)(`div`,{className:r<a-1?Z.nActorEventTrackSpaced:Z.nActorEventTrack,children:e.actorIds.map((t,i)=>{let o=n.get(t)?.events.get(r),s=e.actors[t]?.leader?.name??t;return(0,x.jsx)(IE,{block:o,eventIndex:r,totalEvents:a,name:s,sideColor:i===0?`var(--vis)`:i===1?`var(--eng)`:`var(--amber)`,sections:z.eventSections},t)})},r)),(0,x.jsx)(`div`,{className:Z.nActorFooterTrack,children:e.actorIds.map((t,r)=>{let i=n.get(t);if(!i)return null;let a=e.actors[t]?.leader?.name??t;return(0,x.jsx)(LE,{data:i,name:a,sideColor:r===0?`var(--vis)`:r===1?`var(--eng)`:`var(--amber)`,showQuotes:z.footerSections.includes(`quotes`)},t)})})]},t)}),(0,x.jsx)(`section`,{id:`toolbox`,children:a.list.length>0&&(0,x.jsxs)(`details`,{open:c,onToggle:e=>{let t=e.currentTarget.open;t&&!c&&B_({name:`forge_toolbox_open`,from:`reports`}),l(t)},className:K.pageFold,children:[(0,x.jsx)(`summary`,{className:K.pageFoldSummary,children:`FORGED TOOLBOX`}),(0,x.jsx)(Nb,{inPage:!0})]})}),(0,x.jsxs)(`section`,{id:`summary`,className:Z.summarySection,children:[(0,x.jsx)(`div`,{className:Z.summaryLabel,children:`Run Summary · Verdict · Winner`}),(0,x.jsx)(XT,{verdict:t,leaderAName:L,leaderBName:ue}),(0,x.jsx)(cE,{state:e}),t&&(0,x.jsx)(`div`,{className:Z.summaryVerdictWrap,children:(0,x.jsx)(jn,{verdict:t,shownRun:n})})]}),(0,x.jsx)(`section`,{id:`references`,children:i.list.length>0&&(0,x.jsx)(hC,{registry:i,title:`References`,collapsible:!0,defaultOpen:o,onToggle:s})}),(0,x.jsxs)(`details`,{className:Z.aboutDetails,children:[(0,x.jsx)(`summary`,{className:Z.aboutSummary,children:`What's in this report?`}),(0,x.jsxs)(`div`,{className:Z.aboutBody,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:Z.aboutBlockTitle,children:`Scenario focus`}),(0,x.jsx)(`div`,{className:Z.aboutChips,children:z.focusSections.map(e=>(0,x.jsx)(`span`,{className:Z.aboutChip,children:RT[e]},e))})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:Z.aboutBlockTitle,children:`This run produced`}),(0,x.jsx)(`div`,{className:Z.aboutChips,children:z.artifacts.map(e=>(0,x.jsx)(`span`,{className:Z.aboutChipNeutral,children:zT[e]},e))})]})]})]})]}),(0,x.jsx)(OE,{items:ge,scrollRoot:_e.current}),_!==null&&y&&(0,x.jsx)(ST,{parentArtifact:y,atTurn:_,maxTurns:yT(y),costPreset:`economy`,provider:`openai`,onConfirm:D,onClose:()=>v(null)})]})}var FE={positive:`var(--green)`,negative:`var(--rust)`,anxious:`var(--amber)`,defiant:`var(--rust)`,hopeful:`var(--green)`,resigned:`var(--text-3)`,neutral:`var(--text-2)`};function IE({block:e,eventIndex:t,totalEvents:n,name:r,sideColor:i,sections:a}){let o={"--side-color":i};if(!e||!e.title)return(0,x.jsxs)(`div`,{className:Z.eventCard,children:[(0,x.jsxs)(`h4`,{className:Z.eventHeading,style:o,children:[r,n>1&&(0,x.jsxs)(`span`,{className:Z.eventSubLabel,children:[`Event `,t+1,`/`,n]})]}),(0,x.jsx)(`span`,{className:Z.eventAwaiting,children:`Awaiting data...`})]});let s={crisis:(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:Z.eventTitle,children:[e.title,e.category&&(0,x.jsx)(`span`,{className:Z.categoryPill,children:e.category}),e.emergent&&(0,x.jsx)(`span`,{className:Z.emergentPill,children:`EMERGENT`})]}),e.description&&(0,x.jsx)(`div`,{className:Z.eventDescription,children:e.description})]},`crisis`),decision:e.decision?(0,x.jsx)(`div`,{className:Z.eventDecision,children:e.decision},`decision`):null,outcome:e.outcome?(0,x.jsxs)(`div`,{className:Z.eventOutcomeRow,children:[(0,x.jsx)(MS,{outcome:e.outcome}),Array.isArray(e.policies)&&e.policies.length>0&&(0,x.jsx)(`span`,{className:Z.eventPolicies,children:e.policies.map(e=>String(e)).join(` / `)})]},`outcome`):null,causality:e.rationale?(0,x.jsxs)(`details`,{className:Z.eventDetails,children:[(0,x.jsx)(`summary`,{className:Z.eventDetailsSummary,style:o,children:`Rationale`}),(0,x.jsx)(`div`,{className:Z.eventRationale,style:o,children:e.rationale})]},`causality`):null,departments:Object.keys(e.depts).length>0?(0,x.jsxs)(`details`,{className:Z.eventDetails,open:!0,children:[(0,x.jsxs)(`summary`,{className:Z.eventDetailsSummary,style:o,children:[`Departments (`,Object.keys(e.depts).length,`)`]}),(0,x.jsx)(`div`,{className:Z.deptList,children:Object.entries(e.depts).map(([e,t])=>(0,x.jsxs)(`div`,{className:Z.deptItem,style:o,children:[(0,x.jsxs)(`div`,{className:Z.deptHead,children:[(0,x.jsx)(`span`,{className:Z.deptName,children:e.charAt(0).toUpperCase()+e.slice(1)}),(0,x.jsxs)(`span`,{className:Z.deptMeta,children:[t.citations,`c `,t.tools,`t`]})]}),t.summary&&(0,x.jsx)(`div`,{className:Z.deptSummary,children:t.summary}),(0,x.jsx)(PS,{citations:t.citationList,label:``})]},e))})]},`departments`):null};return(0,x.jsxs)(`div`,{className:Z.eventCard,children:[(0,x.jsxs)(`h4`,{className:Z.eventHeading,style:o,children:[r,n>1&&(0,x.jsxs)(`span`,{className:Z.eventSubLabel,children:[`Event `,t+1,`/`,n]})]}),a.map(e=>s[e]).filter(Boolean)]})}function LE({data:e,name:t,sideColor:n,showQuotes:r}){let i=e.metrics;if(!i&&(!r||e.reactions.length===0))return(0,x.jsx)(`div`,{});let a={"--side-color":n};return(0,x.jsxs)(`div`,{className:Z.footerCard,children:[i&&(0,x.jsxs)(`details`,{className:e.reactions.length?Z.footerDetails:Z.footerDetailsLast,children:[(0,x.jsxs)(`summary`,{className:Z.footerSummary,style:a,children:[t,` · Systems State`]}),(0,x.jsx)(`div`,{className:Z.systemsRow,children:Object.entries(i).map(([e,t])=>(0,x.jsxs)(`span`,{className:Z.systemItem,children:[(0,x.jsxs)(`span`,{className:Z.systemKey,children:[e,`: `]}),(0,x.jsx)(`span`,{className:Z.systemValue,children:typeof t==`number`?Number.isInteger(t)?t:t.toFixed(2):String(t)})]},e))})]}),r&&e.reactions.length>0&&(0,x.jsxs)(`details`,{open:!0,children:[(0,x.jsxs)(`summary`,{className:Z.footerSummary,style:a,children:[`Agent Voices (`,e.totalReactions||e.reactions.length,`)`]}),(0,x.jsx)(`div`,{className:Z.reactionsList,children:e.reactions.map((e,t)=>(0,x.jsxs)(`div`,{className:Z.reactionItem,children:[(0,x.jsxs)(`div`,{className:Z.reactionHead,children:[(0,x.jsx)(`span`,{className:Z.reactionName,style:a,children:String(e.name)}),(0,x.jsx)(`span`,{className:Z.moodPill,style:{"--mood-color":FE[String(e.mood)]||`var(--text-3)`},children:String(e.mood||``).toUpperCase()})]}),(0,x.jsxs)(`div`,{className:Z.reactionQuote,children:[`“`,String(e.quote||``),`”`]}),!!e.role&&(0,x.jsxs)(`div`,{className:Z.reactionRole,children:[String(e.role),` `,e.department?`in ${String(e.department)}`:``]})]},t))})]})]})}var Q={layout:`_layout_1l1dk_1`,sidebar:`_sidebar_1l1dk_15`,sidebarHeading:`_sidebarHeading_1l1dk_31`,sidebarLead:`_sidebarLead_1l1dk_38`,actorFilter:`_actorFilter_1l1dk_45`,actorFilterLabel:`_actorFilterLabel_1l1dk_64`,actorFilterSelect:`_actorFilterSelect_1l1dk_74`,agentBtn:`_agentBtn_1l1dk_96`,selected:`_selected_1l1dk_110`,agentName:`_agentName_1l1dk_115`,agentMeta:`_agentMeta_1l1dk_119`,agentMood:`_agentMood_1l1dk_124`,chatArea:`_chatArea_1l1dk_131`,memoryBar:`_memoryBar_1l1dk_138`,memoryLabel:`_memoryLabel_1l1dk_145`,memoryBelief:`_memoryBelief_1l1dk_152`,memoryStance:`_memoryStance_1l1dk_157`,hexacoStrip:`_hexacoStrip_1l1dk_162`,hexacoLabel:`_hexacoLabel_1l1dk_174`,hexacoTrait:`_hexacoTrait_1l1dk_180`,hexacoBar:`_hexacoBar_1l1dk_184`,healthSignal:`_healthSignal_1l1dk_188`,messages:`_messages_1l1dk_192`,emptyState:`_emptyState_1l1dk_207`,emptyTitle:`_emptyTitle_1l1dk_213`,emptyCopy:`_emptyCopy_1l1dk_218`,eventCtx:`_eventCtx_1l1dk_225`,eventGroup:`_eventGroup_1l1dk_235`,eventGroupLast:`_eventGroupLast_1l1dk_239`,eventGroupLabel:`_eventGroupLabel_1l1dk_243`,eventRow:`_eventRow_1l1dk_252`,eventTurn:`_eventTurn_1l1dk_258`,eventTitle:`_eventTitle_1l1dk_265`,eventCategory:`_eventCategory_1l1dk_270`,memoryItem:`_memoryItem_1l1dk_275`,memoryTime:`_memoryTime_1l1dk_282`,relationshipsRow:`_relationshipsRow_1l1dk_287`,relationshipChip:`_relationshipChip_1l1dk_293`,bubbleWrap:`_bubbleWrap_1l1dk_297`,fromUser:`_fromUser_1l1dk_301`,fromAgent:`_fromAgent_1l1dk_305`,bubbleName:`_bubbleName_1l1dk_309`,bubble:`_bubble_1l1dk_297`,user:`_user_1l1dk_327`,typingBubble:`_typingBubble_1l1dk_332`,typingLabel:`_typingLabel_1l1dk_344`,dot:`_dot_1l1dk_359`,"chat-dot-bounce":`_chat-dot-bounce_1l1dk_1`,inputRow:`_inputRow_1l1dk_375`,inputField:`_inputField_1l1dk_392`,sendBtn:`_sendBtn_1l1dk_412`},RE={positive:`var(--green)`,negative:`var(--rust)`,anxious:`var(--amber)`,defiant:`var(--rust)`,hopeful:`var(--green)`,resigned:`var(--text-3)`,neutral:`var(--text-2)`};function zE(e){return e===`positive`?`var(--green)`:e===`negative`?`var(--rust)`:`var(--border)`}function BE({memory:e,events:t,scenario:n}){let r=[];for(let e of t.actorIds){let n=t.actors[e];if(n){for(let e of n.events)if(e.type===`turn_start`&&e.data.title&&e.data.title!==`Director generating...`){let t=e.data.turn;r.some(e=>e.turn===t)||r.push({turn:t,time:e.data.time||0,title:String(e.data.title),category:String(e.data.category||``)})}}}r.sort((e,t)=>e.turn-t.turn);let i=n.labels.eventNoun||`events`,a=e.recentMemories?.length>0,o=e.relationships?.length>0;return!r.length&&!a?null:(0,x.jsxs)(`div`,{className:Q.eventCtx,children:[r.length>0&&(0,x.jsxs)(`div`,{className:a?Q.eventGroup:Q.eventGroupLast,children:[(0,x.jsxs)(`div`,{className:Q.eventGroupLabel,style:{"--group-color":`var(--rust)`},children:[i.toUpperCase(),` EXPERIENCED`]}),r.map(e=>(0,x.jsxs)(`div`,{className:Q.eventRow,children:[(0,x.jsxs)(`span`,{className:Q.eventTurn,children:[`T`,e.turn,` `,e.time]}),(0,x.jsx)(`span`,{className:Q.eventTitle,children:e.title}),e.category&&(0,x.jsx)(`span`,{className:Q.eventCategory,children:e.category})]},e.turn))]}),a&&(0,x.jsxs)(`div`,{className:o?Q.eventGroup:Q.eventGroupLast,children:[(0,x.jsx)(`div`,{className:Q.eventGroupLabel,style:{"--group-color":`var(--amber)`},children:`RECENT MEMORIES`}),e.recentMemories.slice(0,3).map((e,t)=>(0,x.jsxs)(`div`,{className:Q.memoryItem,style:{"--valence-border":zE(e.valence)},children:[(0,x.jsxs)(`span`,{className:Q.memoryTime,children:[`Y`,e.time]}),` `,e.content]},t))]}),o&&(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:Q.eventGroupLabel,style:{"--group-color":`var(--teal)`},children:`RELATIONSHIPS`}),(0,x.jsx)(`div`,{className:Q.relationshipsRow,children:e.relationships.map((e,t)=>(0,x.jsxs)(`span`,{className:Q.relationshipChip,style:{"--rel-color":e.sentiment>0?`var(--green)`:`var(--rust)`},children:[e.name,` `,e.sentiment>0?`+`:``,e.sentiment.toFixed(1)]},t))})]})]})}function VE({state:e,onChatUsage:t}){let n=Xk(),[r,i]=(0,b.useState)(null),[a,o]=(0,b.useState)(()=>new Map),[s,c]=(0,b.useState)(()=>new Map),[l,u]=(0,b.useState)(``),[d,f]=(0,b.useState)(!1),p=(0,b.useRef)(null),m=(0,b.useRef)(!0),h=()=>{let e=p.current;e&&(m.current=e.scrollHeight-e.scrollTop-e.clientHeight<40)},g=(0,b.useMemo)(()=>{let t=new Map;for(let n of e.actorIds){let r=e.actors[n];if(!r)continue;let i=new Map;for(let e of r.events)if(e.type===`agent_reactions`){let t=e.data.reactions||[];for(let e of t)e.name&&i.set(e.name,{name:e.name,role:e.role||``,department:e.department||``,mood:e.mood||`neutral`,age:e.age,marsborn:e.marsborn,agentId:e.agentId,memory:e.memory,hexaco:e.hexaco,psychScore:e.psychScore,boneDensity:e.boneDensity,radiation:e.radiation})}i.size>0&&t.set(n,Array.from(i.values()))}return t},[e]),_=e.actorIds.length>=2,[v,y]=(0,b.useState)(`all`);(0,b.useEffect)(()=>{if(!_)v!==null&&y(null);else if(v!==`all`&&!(v&&g.has(v))){if(e.actorIds.length>=5){let t=e.actorIds.find(e=>(g.get(e)?.length??0)>0);y(t??`all`)}else y(`all`)}},[_,g,e.actorIds,v]);let[S,C]=(0,b.useState)(null),w=(0,b.useMemo)(()=>{if(v&&v!==`all`)return g.get(v)??[];let e=[],t=new Set;for(let n of g.values())for(let r of n)t.has(r.name)||(t.add(r.name),e.push(r));return e},[g,v]),T=(0,b.useMemo)(()=>{let e=new Set;for(let t of w){let n=(t.department||``).trim();n&&e.add(n)}return[...e].sort((e,t)=>e.localeCompare(t))},[w]);(0,b.useEffect)(()=>{S&&!T.includes(S)&&C(null)},[T,S]);let E=(0,b.useMemo)(()=>S?w.filter(e=>(e.department||``).trim()===S):w,[w,S]),D=E.find(e=>e.name===r),O=e=>{if(v&&v!==`all`)return v;for(let[t,n]of g)if(n.some(t=>t.name===e))return t},k=e=>{let t=O(e);return t?`${t}\u0000${e}`:e},A=r?a.get(k(r))??[]:[];(0,b.useEffect)(()=>{m.current&&p.current&&p.current.scrollTo({top:p.current.scrollHeight,behavior:`smooth`})},[A,d]),(0,b.useEffect)(()=>{let e=()=>{let e=window.location.hash.match(/^#chat=([^&]+)/);if(!e)return;let t=decodeURIComponent(e[1]);t&&E.some(e=>e.name===t)&&i(t)};return e(),window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[E]);let j=e=>{i(e);let t=k(e);o(n=>{if(n.has(t))return n;let r=E.find(t=>t.name===e),i=r?{role:`agent`,name:r.name,text:`${r.role} in ${r.department}, age ${r.age||`?`}. I lived through this simulation — ask me about specific turns, the commander's decisions, crises I witnessed, people I worked with, or how my department handled what came up. Try: "what did you think of the commander's choice in turn 1?", "who do you trust on the team?", or "what was the worst moment for you?"`}:{role:`agent`,text:`Connected.`},a=new Map(n);return a.set(t,[i]),a})},ee=(e,t)=>{o(n=>{let r=new Map(n);return r.set(e,t(n.get(e)??[])),r})},te=(e,t)=>{c(n=>{let r=new Map(n);return r.set(e,t(n.get(e)??[])),r})},M=async()=>{if(!l.trim()||!r||d)return;let e=r,n=O(e),i=k(e),a=l.trim();u(``),f(!0),ee(i,e=>[...e,{role:`user`,text:a}]);let o=[...s.get(i)??[],{role:`user`,content:a}];te(i,()=>o);try{let r=(()=>{try{return JSON.parse(localStorage.getItem(`paracosm:keyOverrides`)||`{}`)}catch{return{}}})(),s=await(await fetch(`/chat`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({agentId:e,...n?{leader:n}:{},message:a,history:o,...r.openai?{apiKey:r.openai}:{},...r.anthropic?{anthropicKey:r.anthropic}:{}})})).json();if(s.reply){ee(i,t=>[...t,{role:`agent`,name:s.colonist||e,text:s.reply}]),te(i,e=>[...e,{role:`assistant`,content:s.reply}]);let n=s.usage;n&&t&&t({totalTokens:n.totalTokens??0,costUSD:n.costUSD??0})}else ee(i,e=>[...e,{role:`agent`,text:s.error||`No response`}])}catch(e){ee(i,t=>[...t,{role:`agent`,text:`Chat failed: ${e}`}])}f(!1)};return(0,x.jsxs)(`div`,{className:`chat-layout ${Q.layout}`,role:`region`,"aria-label":`Agent chat`,children:[(0,x.jsxs)(`div`,{className:`chat-sidebar ${Q.sidebar}`,children:[(0,x.jsx)(`h3`,{className:Q.sidebarHeading,children:E.length?`${E.length} Agents`:`Agent Chat`}),(0,x.jsx)(`p`,{className:Q.sidebarLead,children:E.length?`Talk to any ${n.labels.populationNoun.replace(/s$/,``)} from the simulation. Each agent has persistent memory, personality, and relationships shaped by the crises they experienced.`:`Chat becomes available after the first turn completes. Start a simulation and come back once agents have reacted to the first crisis. Each agent has persistent memory, personality, and relationships shaped by the crises they experience.`}),_&&g.size>0&&(0,x.jsxs)(`div`,{className:Q.actorFilter,children:[(0,x.jsx)(`label`,{className:Q.actorFilterLabel,htmlFor:`chat-actor-filter`,children:`Lead actor`}),(0,x.jsxs)(`select`,{id:`chat-actor-filter`,className:Q.actorFilterSelect,value:v??``,onChange:e=>y(e.target.value||null),"aria-label":`Filter chat agents by lead actor`,children:[(0,x.jsxs)(`option`,{value:`all`,children:[`All leaders (`,(()=>{let e=new Set;for(let t of g.values())for(let n of t)e.add(n.name);return e.size})(),`)`]}),e.actorIds.map(t=>{let n=g.get(t)?.length??0,r=e.actors[t]?.leader?.name||t;return(0,x.jsxs)(`option`,{value:t,disabled:n===0,children:[r,` (`,n,`)`]},t)})]})]}),T.length>1&&(0,x.jsxs)(`div`,{className:Q.actorFilter,children:[(0,x.jsx)(`label`,{className:Q.actorFilterLabel,htmlFor:`chat-department-filter`,children:`Department`}),(0,x.jsxs)(`select`,{id:`chat-department-filter`,className:Q.actorFilterSelect,value:S??``,onChange:e=>C(e.target.value||null),"aria-label":`Filter chat agents by department`,children:[(0,x.jsxs)(`option`,{value:``,children:[`All departments (`,w.length,`)`]}),T.map(e=>{let t=w.filter(t=>(t.department||``).trim()===e).length;return(0,x.jsxs)(`option`,{value:e,children:[e,` (`,t,`)`]},e)})]})]}),E.map(e=>(0,x.jsxs)(`button`,{onClick:()=>j(e.name),className:[Q.agentBtn,r===e.name?Q.selected:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`span`,{className:Q.agentName,children:e.name}),(0,x.jsxs)(`div`,{className:Q.agentMeta,children:[e.role,` `,e.department]}),(0,x.jsx)(`div`,{className:Q.agentMood,style:{"--mood-color":RE[e.mood]||`var(--text-3)`},children:e.mood.toUpperCase()})]},e.name))]}),(0,x.jsxs)(`div`,{className:Q.chatArea,children:[D?.memory&&(D.memory.beliefs?.length>0||D.memory.stances?.length>0)&&(0,x.jsxs)(`div`,{className:Q.memoryBar,children:[(0,x.jsx)(`span`,{className:Q.memoryLabel,children:`MEMORY `}),D.memory.beliefs?.slice(0,2).map((e,t)=>(0,x.jsx)(`span`,{className:Q.memoryBelief,children:e},t)),D.memory.stances?.map((e,t)=>(0,x.jsxs)(`span`,{className:Q.memoryStance,style:{"--stance-color":e.value>0?`var(--green)`:`var(--rust)`},children:[e.topic,`: `,e.value>.5?`confident`:e.value>0?`cautious`:`wary`]},t))]}),r&&D?.hexaco&&(0,x.jsxs)(`div`,{className:Q.hexacoStrip,children:[(0,x.jsx)(`span`,{className:Q.hexacoLabel,children:`HEXACO`}),[`O`,`C`,`E`,`A`,`Em`,`HH`].map(e=>{let t=D.hexaco[e],n=Math.round(t*4),r=`█`.repeat(n)+`░`.repeat(4-n);return(0,x.jsxs)(`span`,{title:`${e}: ${t.toFixed(2)}`,className:Q.hexacoTrait,children:[e,` `,(0,x.jsx)(`span`,{className:Q.hexacoBar,children:r}),` `,t.toFixed(2)]},e)}),typeof D.psychScore==`number`&&(0,x.jsxs)(`span`,{className:Q.healthSignal,style:{"--signal-color":D.psychScore<.4?`var(--rust)`:`var(--text-2)`},children:[`psych `,(D.psychScore*100).toFixed(0),`%`]}),typeof D.boneDensity==`number`&&D.boneDensity>0&&(0,x.jsxs)(`span`,{className:Q.healthSignal,style:{"--signal-color":D.boneDensity<70?`var(--rust)`:`var(--text-3)`},children:[`bone `,D.boneDensity.toFixed(0),`%`]}),typeof D.radiation==`number`&&D.radiation>0&&(0,x.jsxs)(`span`,{className:Q.healthSignal,style:{"--signal-color":D.radiation>2e3?`var(--rust)`:`var(--text-3)`},children:[`rad `,D.radiation.toFixed(0),`mSv`]})]}),(0,x.jsxs)(`div`,{ref:p,onScroll:h,className:Q.messages,role:`log`,"aria-live":`polite`,"aria-relevant":`additions`,"aria-label":D?.name?`Messages with ${D.name}`:`Chat messages`,children:[!r&&(0,x.jsxs)(`div`,{className:Q.emptyState,children:[(0,x.jsx)(`div`,{className:Q.emptyTitle,children:E.length?`Select an agent to start chatting.`:`No agents available yet.`}),(0,x.jsx)(`div`,{className:Q.emptyCopy,children:E.length?`Each agent is a simulated ${n.labels.populationNoun.replace(/s$/,``)} with a unique HEXACO personality, persistent memory of events they survived, evolving stances on topics, and relationships with other agents. Their responses reflect their actual simulation experience.`:`Run a simulation from the Settings tab. Once the first turn completes, agents become available for conversation. The chat system uses each agent's personality profile, memory, and event history to generate authentic in-character responses.`})]}),r&&D?.memory&&(0,x.jsx)(BE,{memory:D.memory,events:e,scenario:n}),A.map((e,t)=>(0,x.jsxs)(`div`,{className:[Q.bubbleWrap,e.role===`user`?Q.fromUser:Q.fromAgent].join(` `),children:[e.name&&(0,x.jsx)(`div`,{className:Q.bubbleName,children:e.name}),(0,x.jsx)(`div`,{className:[Q.bubble,e.role===`user`?Q.user:``].filter(Boolean).join(` `),children:e.text})]},t)),d&&r&&(0,x.jsxs)(`div`,{className:[Q.bubbleWrap,Q.fromAgent].join(` `),"aria-live":`polite`,"aria-label":`${D?.name||`Agent`} is typing`,children:[(0,x.jsx)(`div`,{className:Q.bubbleName,children:D?.name||r}),(0,x.jsxs)(`div`,{className:Q.typingBubble,children:[(0,x.jsx)(`span`,{className:Q.typingLabel,children:`typing`}),(0,x.jsx)(`span`,{className:Q.dot,"aria-hidden":`true`,style:{"--dot-delay":`0ms`},children:`.`}),(0,x.jsx)(`span`,{className:Q.dot,"aria-hidden":`true`,style:{"--dot-delay":`160ms`},children:`.`}),(0,x.jsx)(`span`,{className:Q.dot,"aria-hidden":`true`,style:{"--dot-delay":`320ms`},children:`.`})]})]})]}),(0,x.jsxs)(`div`,{className:Q.inputRow,children:[(0,x.jsx)(`input`,{value:l,onChange:e=>u(e.target.value),onKeyDown:e=>e.key===`Enter`&&M(),disabled:!r||d,"aria-label":r?`Message ${D?.name||`agent`}`:`Select an agent first`,placeholder:r?`Ask ${D?.name||`agent`}...`:`Select a ${n.labels.populationNoun.replace(/s$/,``)} first`,className:Q.inputField}),(0,x.jsx)(`button`,{onClick:M,disabled:!r||d||!l.trim(),className:Q.sendBtn,children:`Send`})]})]})]})}var $={kbd:`_kbd_1cg4c_2`,kbdKey:`_kbdKey_1cg4c_8`,kbdLabel:`_kbdLabel_1cg4c_18`,empty:`_empty_1cg4c_22`,emptySpinner:`_emptySpinner_1cg4c_34`,emptySpinnerRotate:`_emptySpinnerRotate_1cg4c_1`,root:`_root_1cg4c_54`,toolbarStrip:`_toolbarStrip_1cg4c_62`,toolbarTopRow:`_toolbarTopRow_1cg4c_71`,modePillsWrap:`_modePillsWrap_1cg4c_76`,overflowToggle:`_overflowToggle_1cg4c_95`,overflowToggleOpen:`_overflowToggleOpen_1cg4c_109`,helpBtn:`_helpBtn_1cg4c_114`,forgeToolboxKey:`_forgeToolboxKey_1cg4c_130`,toolsRow:`_toolsRow_1cg4c_163`,paletteBtn:`_paletteBtn_1cg4c_177`,toolBtn:`_toolBtn_1cg4c_191`,settingsBtn:`_settingsBtn_1cg4c_204`,settingsBtnOpen:`_settingsBtnOpen_1cg4c_217`,modeHint:`_modeHint_1cg4c_222`,ecologyNone:`_ecologyNone_1cg4c_232`,ecologyBack:`_ecologyBack_1cg4c_243`,diffLine:`_diffLine_1cg4c_255`,phoneTabRow:`_phoneTabRow_1cg4c_264`,phoneTab:`_phoneTab_1cg4c_264`,phoneTabActive:`_phoneTabActive_1cg4c_291`,leadersRow:`_leadersRow_1cg4c_297`,leadersRowNarrow:`_leadersRowNarrow_1cg4c_306`,sideWrap:`_sideWrap_1cg4c_311`,sideWrapHidden:`_sideWrapHidden_1cg4c_318`,leadersRowLinesBelow:`_leadersRowLinesBelow_1cg4c_322`,turnLinesSlot:`_turnLinesSlot_1cg4c_327`,footerKeys:`_footerKeys_1cg4c_342`,srOnly:`_srOnly_1cg4c_355`,jumpLatest:`_jumpLatest_1cg4c_367`,"paracosm-jump-pulse":`_paracosm-jump-pulse_1cg4c_1`,jumpLatestBehind:`_jumpLatestBehind_1cg4c_390`,toast:`_toast_1cg4c_395`,"paracosm-toast-in":`_paracosm-toast-in_1cg4c_1`,toastKicker:`_toastKicker_1cg4c_416`,toastKickerMeta:`_toastKickerMeta_1cg4c_428`,toastBody:`_toastBody_1cg4c_432`,toastBodyMd:`_toastBodyMd_1cg4c_437`,vignette:`_vignette_1cg4c_442`,"paracosm-vignette":`_paracosm-vignette_1cg4c_1`,cohortViewBar:`_cohortViewBar_1cg4c_458`,cohortViewModeToggle:`_cohortViewModeToggle_1cg4c_469`,cohortViewModeButton:`_cohortViewModeButton_1cg4c_478`,cohortViewModeButtonActive:`_cohortViewModeButtonActive_1cg4c_509`,cohortPairPicker:`_cohortPairPicker_1cg4c_518`,cohortPairPickerLabel:`_cohortPairPickerLabel_1cg4c_526`,cohortPairPickerSelect:`_cohortPairPickerSelect_1cg4c_535`,cohortPairPickerVs:`_cohortPairPickerVs_1cg4c_558`,cohortPairPickerHint:`_cohortPairPickerHint_1cg4c_566`};function HE(e){return(0,b.useMemo)(()=>UE(e),[e])}function UE(e){let t={};for(let n of e.actorIds){let r=e.actors[n];if(!r)continue;t[n]=[];let i=new Map;for(let e of r.events)if((e.type===`event_start`||e.type===`turn_start`)&&e.turn!=null){let t=e.data?.category;if(typeof t==`string`&&t.length>0){let n=i.get(e.turn)??[];n.includes(t)||n.push(t),i.set(e.turn,n)}}let a=r.events.filter(e=>e.type===`systems_snapshot`);for(let e=0;e<r.agentSnapshots.length;e++){let o=r.agentSnapshots[e],s=a[e]?.data||{},c=s.turn||e+1,l=r.events.find(e=>e.type===`turn_done`&&e.data?.turn===c)?.data?.metrics??{},u=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,d=o.map(e=>({agentId:e.agentId,name:e.name,department:e.department,role:e.role,rank:e.rank,alive:e.alive,marsborn:e.marsborn,psychScore:e.psychScore,age:e.age,generation:e.generation,partnerId:e.partnerId,childrenIds:e.childrenIds||[],featured:e.featured,mood:e.mood,shortTermMemory:e.shortTermMemory||[]}));t[n].push({turn:c,time:s.time||0,cells:d,population:s.population||d.filter(e=>e.alive).length,morale:s.morale||0,foodReserve:typeof s.foodReserve==`number`?s.foodReserve:u(l.foodMonthsReserve),waterLitersPerDay:u(l.waterLitersPerDay),powerKw:u(l.powerKw),pressurizedVolumeM3:u(l.pressurizedVolumeM3),deaths:s.deaths||0,births:s.births||0,eventCategories:i.get(c)??[]})}}return t}var WE={region:`_region_1xlv9_1`,narrow:`_narrow_1xlv9_12`,canvasWrap:`_canvasWrap_1xlv9_18`,canvas:`_canvas_1xlv9_18`,revealCover:`_revealCover_1xlv9_38`,cornerBtn:`_cornerBtn_1xlv9_48`,focusBtn:`_focusBtn_1xlv9_70`,divergenceEmpty:`_divergenceEmpty_1xlv9_75`,divergenceEmptyMsg:`_divergenceEmptyMsg_1xlv9_86`,tileTooltip:`_tileTooltip_1xlv9_98`,tileKindLabel:`_tileKindLabel_1xlv9_117`,tileCoords:`_tileCoords_1xlv9_125`,tileNearestName:`_tileNearestName_1xlv9_131`,tileNearestRole:`_tileNearestRole_1xlv9_136`,tileNearestDeath:`_tileNearestDeath_1xlv9_142`,tileNearestBirth:`_tileNearestBirth_1xlv9_148`,tileNearestPattern:`_tileNearestPattern_1xlv9_154`,tileAmbient:`_tileAmbient_1xlv9_160`,hoverTooltip:`_hoverTooltip_1xlv9_164`,hoverHeader:`_hoverHeader_1xlv9_182`,hoverFeaturedPill:`_hoverFeaturedPill_1xlv9_192`,hoverRole:`_hoverRole_1xlv9_201`,hoverMood:`_hoverMood_1xlv9_209`,hoverMoodValue:`_hoverMoodValue_1xlv9_213`,psychBlock:`_psychBlock_1xlv9_217`,psychLabel:`_psychLabel_1xlv9_221`,psychSvg:`_psychSvg_1xlv9_227`,hoverHint:`_hoverHint_1xlv9_234`};function GE(e){let t=e>>>0;return()=>{t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}function KE(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t>>>0}function qE(e,t,n,r,i=8){return{x:Math.max(i,Math.min(n-i,e)),y:Math.max(i,Math.min(r-i,t))}}function JE(e){let t=new Set;for(let n of e)t.add(n.department||`unknown`);return[...t].sort()}function YE(e,t,n){let r=new Map;if(n.length===0)return r;let i=e/2,a=t/2,o=Math.min(e,t)*.32,s=Math.min(e,t)*.14;if(n.length===1)return r.set(n[0],{cx:i,cy:a,r:s*1.5}),r;for(let e=0;e<n.length;e++){let t=Math.PI*2*e/n.length-Math.PI/2;r.set(n[e],{cx:i+Math.cos(t)*o,cy:a+Math.sin(t)*o,r:s})}return r}function XE(e,t,n){let r=YE(t,n,JE(e)),i=new Map;for(let a of e){let e=r.get(a.department||`unknown`)??{cx:t/2,cy:n/2,r:40},o=GE(KE(`${a.agentId}|${t}x${n}|dept`)),s=o()*Math.PI*2,c=Math.sqrt(o())*e.r;i.set(a.agentId,qE(e.cx+Math.cos(s)*c,e.cy+Math.sin(s)*c,t,n))}return i}function ZE(e,t,n){let r=new Map,i=new Set,a=new Map(e.map(e=>[e.agentId,e])),o=[];for(let t of e)if(!i.has(t.agentId)&&t.partnerId&&a.has(t.partnerId)&&!i.has(t.partnerId)){let e=a.get(t.partnerId),n=t.childrenIds.map(e=>a.get(e)).filter(e=>!!e);o.push([t,e,...n]),i.add(t.agentId),i.add(e.agentId);for(let e of n)i.add(e.agentId)}let s=e.filter(e=>!i.has(e.agentId)),c=Math.max(50,(t-80)/Math.max(1,o.length));return o.forEach((e,i)=>{let a=40+c*i+c/2;e.forEach((i,o)=>{let s=GE(KE(`${i.agentId}|fam`)),c=o/e.length*Math.PI*2,l=14+s()*6;r.set(i.agentId,qE(a+Math.cos(c)*l,40+Math.sin(c)*l,t,n))})}),s.forEach((e,i)=>{let a=GE(KE(`${e.agentId}|solo`)),o=40+(t-80)*(i+.5)/Math.max(1,s.length),c=n-40-a()*40;r.set(e.agentId,qE(o,c,t,n))}),r}function QE(e,t,n){let r={positive:-1,hopeful:-.6,neutral:0,anxious:.4,negative:.8,defiant:.6,resigned:.7},i=new Map;for(let a of e){let e=(r[a.mood]??0)*.5+.5,o=GE(KE(`${a.agentId}|mood`)),s=40+(t-80)*e,c=40+(n-80)*o();i.set(a.agentId,qE(s,c,t,n))}return i}function $E(e,t,n){let r=new Map;for(let i of e){let e=Math.max(0,Math.min(80,i.age??30))/80,a=GE(KE(`${i.agentId}|age`)),o=40+(t-80)*a(),s=40+(n-80)*e;r.set(i.agentId,qE(o,s,t,n))}return r}function eD(e,t,n,r){return t===`families`?ZE(e,n,r):t===`mood`?QE(e,n,r):t===`age`?$E(e,n,r):XE(e,n,r)}function tD(e,t,n,r,i=1,a,o=!1,s=0,c=``,l=!1,u=`rgba(216, 204, 176, 0.9)`,d=`rgba(10, 8, 6, 0.55)`){e.save(),.5+.5*Math.sin(s*.003);let f=c.trim().toLowerCase().split(/\s+/).filter(Boolean),p=f.length>0,m=e=>{if(!p)return!1;let t=`${e.name} ${e.department} ${e.role} ${e.mood}`.toLowerCase();return f.every(e=>t.includes(e))};for(let c of t){if(!c.alive)continue;let t=n.get(c.agentId);if(!t)continue;let l=a?.has(c.agentId)??!1;if(o&&!l)continue;let u=m(c),d=p&&!u,f=c.featured?5:3,h=c.featured?.95:.75,g=d?.25:1;if(c.featured&&!d){let n=f+6,a=.42*i;e.strokeStyle=r,e.lineWidth=1,e.globalAlpha=a,e.beginPath(),e.arc(t.x,t.y,n,0,Math.PI*2),e.stroke()}if(u){let n=.7+.3*Math.sin(s*.006);e.strokeStyle=`rgba(248, 225, 150, 1)`,e.lineWidth=2.2,e.globalAlpha=i*n,e.beginPath(),e.arc(t.x,t.y,f+6,0,Math.PI*2),e.stroke()}l&&!d&&(e.strokeStyle=`rgba(232, 180, 74, 0.9)`,e.lineWidth=2,e.globalAlpha=i,e.beginPath(),e.arc(t.x,t.y,f+3,0,Math.PI*2),e.stroke()),e.strokeStyle=l?`rgba(224, 101, 48, 1)`:r,e.lineWidth=c.featured||l||u?1.6:1,e.globalAlpha=(l?1:h)*i*g,e.beginPath(),e.arc(t.x,t.y,f,0,Math.PI*2),e.stroke()}if(l){e.font=`9px ui-monospace, monospace`,e.textAlign=`center`,e.textBaseline=`top`;for(let r of t){if(!r.alive)continue;let t=n.get(r.agentId);if(!t)continue;let s=a?.has(r.agentId)??!1;if(o&&!s||!r.featured&&!s)continue;let c=m(r);if(p&&!c)continue;let l=r.name.split(/\s+/)[0],f=t.y+(r.featured?12:10),h=e.measureText(l).width;e.fillStyle=d,e.fillRect(t.x-h/2-3,f-1,h+6,10),e.fillStyle=s?`rgba(232, 180, 74, 0.95)`:u,e.globalAlpha=i,e.fillText(l,t.x,f)}}e.restore()}var nD={birth:`rgba(154, 205, 96, 0.8)`,death:`rgba(168, 152, 120, 0.7)`,forge_approved:`rgba(232, 180, 74, 0.8)`,forge_rejected:`rgba(224, 101, 48, 0.7)`,reuse:`rgba(232, 180, 74, 0.6)`,crisis:`rgba(196, 74, 30, 0.8)`},rD=6;function iD(e,t){e.save();for(let n of t){let t=nD[n.kind]??`rgba(255,255,255,0.6)`,r=n.progress,i=1-r;if(e.globalAlpha=i,n.kind===`birth`||n.kind===`death`||n.kind===`crisis`){let a=4+r*14;if(e.strokeStyle=t,e.lineWidth=1.2,e.beginPath(),e.arc(n.x,n.y,a,0,Math.PI*2),e.stroke(),n.kind!==`crisis`){let a=2+r*22,o=n.kind===`birth`?1.8:1.4;e.fillStyle=t;for(let t=0;t<rD;t++){let r=t/rD*Math.PI*2+(n.kind===`birth`?.3:-.2),s=n.x+Math.cos(r)*a,c=n.y+Math.sin(r)*a;e.globalAlpha=i*.9,e.beginPath(),e.arc(s,c,o,0,Math.PI*2),e.fill()}}}else if(n.kind===`reuse`&&typeof n.endX==`number`&&typeof n.endY==`number`){let a=n.x+(n.endX-n.x)*r,o=n.y+(n.endY-n.y)*r,s=e.createRadialGradient(a,o,0,a,o,8);s.addColorStop(0,`rgba(248, 225, 150, 0.95)`),s.addColorStop(.4,t),s.addColorStop(1,`rgba(232, 180, 74, 0)`),e.fillStyle=s,e.globalAlpha=i,e.beginPath(),e.arc(a,o,8,0,Math.PI*2),e.fill(),e.fillStyle=`rgba(248, 225, 150, 0.95)`,e.beginPath(),e.arc(a,o,2,0,Math.PI*2),e.fill()}else e.fillStyle=t,e.beginPath(),e.arc(n.x,n.y,3,0,Math.PI*2),e.fill()}e.restore()}var aD={medical:`rgba(78, 205, 196, 0.9)`,engineering:`rgba(232, 180, 74, 0.9)`,agriculture:`rgba(106, 173, 72, 0.9)`,psychology:`rgba(155, 107, 158, 0.9)`,governance:`rgba(224, 101, 48, 0.9)`,research:`rgba(149, 107, 216, 0.9)`,science:`rgba(149, 107, 216, 0.9)`,ops:`rgba(200, 122, 58, 0.9)`,operations:`rgba(200, 122, 58, 0.9)`};function oD(e){return aD[(e||``).toLowerCase()]??`rgba(168, 152, 120, 0.9)`}function sD(e,t,n){e.save(),e.font=`10px ui-monospace, monospace`,e.fillStyle=n.sideColor,e.textBaseline=`top`,e.textAlign=`left`;let r=n.actorName.toUpperCase();e.fillText(r,10,10);let i=e.measureText(r).width,a=(n.actorArchetype||``).trim().replace(/^The\s+/i,``);if(a){e.font=`bold 8px ui-monospace, monospace`;let t=a.toUpperCase(),r=e.measureText(t).width,o=10+i+8;e.fillStyle=n.labelBg??`rgba(10, 8, 6, 0.5)`,e.fillRect(o,9,r+10,13),e.strokeStyle=n.sideColor,e.lineWidth=1,e.strokeRect(o+.5,9.5,r+10-1,12),e.fillStyle=n.sideColor,e.textBaseline=`middle`,e.fillText(t,o+5,16),e.textBaseline=`top`,e.font=`10px ui-monospace, monospace`}e.fillStyle=n.textMuted??`rgba(216, 204, 176, 0.75)`;let o=t?.time,s=n.timeUnitShort??`t`,c=typeof o==`number`?typeof n.startTime==`number`?`T${t?.turn??0} · ${o} · ${s} ${Math.max(0,o-n.startTime)}`:`T${t?.turn??0} · ${o}`:`T${t?.turn??0}`;if(e.fillText(c,10,24),!t){e.restore();return}if(n.deptLabels&&n.cells&&n.positions&&n.cells.length>0){let t=new Map;for(let e of n.cells){if(!e.alive)continue;let r=n.positions.get(e.agentId);if(!r)continue;let i=(e.department||`unknown`).toLowerCase(),a=t.get(i)??{xs:[],ys:[]};a.xs.push(r.x),a.ys.push(r.y),t.set(i,a)}e.font=`bold 9px ui-monospace, monospace`,e.textBaseline=`middle`,e.textAlign=`center`;let r=[];for(let[n,i]of t.entries()){if(i.xs.length===0)continue;let t=i.xs.reduce((e,t)=>e+t,0)/i.xs.length,a=Math.min(...i.ys),o=Math.max(14,a-14),s=`${n.toUpperCase()} ${i.xs.length}`,c=e.measureText(s);r.push({dept:n,cx:t,w:c.width+8,h:14,label:s,idealY:o})}r.sort((e,t)=>e.idealY-t.idealY);let i=[],a=(e,t)=>Math.abs(e.cx-t.cx)<(e.w+t.w)/2+2&&Math.abs(e.y-t.y)<(e.h+t.h)/2+2;for(let e of r){let t=e.idealY;for(let n=0;n<10;n++){let r=e.idealY-n*16,o=e.idealY+n*16,s=n===0?e.idealY:r>=10?r:o;if(!i.some(t=>a({cx:e.cx,w:e.w,y:s,h:e.h},t))){t=s;break}}i.push({...e,y:t})}for(let t of i)e.fillStyle=n.labelBg??`rgba(10, 8, 6, 0.85)`,e.fillRect(t.cx-t.w/2,t.y-t.h/2,t.w,t.h),e.strokeStyle=oD(t.dept),e.lineWidth=1,e.strokeRect(t.cx-t.w/2+.5,t.y-t.h/2+.5,t.w-1,t.h-1),e.fillStyle=oD(t.dept),e.fillText(t.label,t.cx,t.y)}e.font=`10px ui-monospace, monospace`,e.textAlign=`left`,e.textBaseline=`bottom`,e.fillStyle=n.sideColor;let l=n.previousSnapshot?t.population-n.previousSnapshot.population:0,u=l>0?`↑`:l<0?`↓`:``,d=l>0?`rgba(106, 173, 72, 0.95)`:l<0?`rgba(196, 74, 30, 0.95)`:`rgba(216, 204, 176, 0.75)`;if(e.fillText(`POP ${t.population}`,10,n.height-20),u){let r=`POP ${t.population}`,i=e.measureText(r).width+6;e.fillStyle=d,e.fillText(`${u}${Math.abs(l)}`,10+i,n.height-20),e.fillStyle=n.sideColor}(t.deaths>0||t.births>0)&&(e.fillStyle=n.textMuted??`rgba(216, 204, 176, 0.65)`,e.fillText(`+${t.births} -${t.deaths}`,10,n.height-8)),n.lagTurns&&n.lagTurns>0&&(e.textAlign=`right`,e.fillStyle=`rgba(232, 180, 74, 0.75)`,e.fillText(`lagging ${n.lagTurns}`,n.width-10,n.height-8)),e.restore()}function cD(e,t,n,r,i){if(t.length===0||r.length===0)return;let a=new Map;for(let e of r){if(e.approved===!1)continue;let t=(e.department||`unknown`).toLowerCase();a.set(t,(a.get(t)??0)+1)}if(a.size===0)return;let o=new Map;for(let e of t){if(!e.alive)continue;let t=n.get(e.agentId);if(!t)continue;let r=(e.department||`unknown`).toLowerCase(),i=o.get(r)??{x:0,y:0,count:0};i.x+=t.x,i.y+=t.y,i.count+=1,o.set(r,i)}let s=Math.max(...a.values());e.save(),e.globalCompositeOperation=`lighter`;for(let[t,n]of a.entries()){let r=o.get(t);if(!r||r.count===0)continue;let a=r.x/r.count,c=r.y/r.count,l=n/s,u=30+l*50,d=.2+l*.25,f=e.createRadialGradient(a,c,0,a,c,u);f.addColorStop(0,dD(i,d)),f.addColorStop(.6,dD(i,d*.4)),f.addColorStop(1,dD(i,0)),e.fillStyle=f,e.beginPath(),e.arc(a,c,u,0,Math.PI*2),e.fill(),e.globalCompositeOperation=`source-over`,e.fillStyle=dD(i,.95),e.font=`bold 11px ui-monospace, monospace`,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(`${n}`,a,c),e.globalCompositeOperation=`lighter`}e.restore()}function lD(e,t,n,r,i=`rgba(216, 204, 176, 0.6)`){let a=e=>typeof e==`number`?e:null,o=a(t.foodReserve),s=a(t.waterLitersPerDay),c=a(t.powerKw),l=a(t.pressurizedVolumeM3);if(o==null&&s==null&&c==null&&l==null)return;let u=(e,t,n)=>e<=t?1:e>=n?0:1-(e-t)/(n-t),d=e=>e<.33?`rgba(106, 173, 72, ${.06+e*.1})`:e<.66?`rgba(232, 180, 74, ${.08+(e-.33)*.2})`:`rgba(196, 74, 30, ${.12+(e-.66)*.3})`,f=n/2,p=r/2;e.save(),o!=null&&(e.fillStyle=d(u(o,3,18)),e.fillRect(0,0,f,p)),s!=null&&(e.fillStyle=d(u(s,200,1200)),e.fillRect(f,0,f,p)),c!=null&&(e.fillStyle=d(u(c,150,600)),e.fillRect(0,p,f,p)),l!=null&&(e.fillStyle=d(u(l,1500,4e3)),e.fillRect(f,p,f,p));let m=p+8;e.font=`bold 9px ui-monospace, monospace`,e.fillStyle=i,e.textAlign=`left`,e.textBaseline=`top`,o!=null&&e.fillText(`FOOD ${o.toFixed(1)}mo`,8,40),s!=null&&(e.textAlign=`right`,e.fillText(`WATER ${Math.round(s)}L/d`,n-8,40)),c!=null&&(e.textAlign=`left`,e.fillText(`POWER ${Math.round(c)}kW`,8,m)),l!=null&&(e.textAlign=`right`,e.fillText(`VOL ${Math.round(l)}m³`,n-8,m)),e.textBaseline=`alphabetic`,e.textAlign=`start`,e.restore()}function uD(e,t,n,r,i,a){if(!r||r.size===0)return;let o=.6+.4*Math.sin(i*.004);e.save();for(let i of t){if(!i.alive||!r.has(i.agentId))continue;let t=n.get(i.agentId);t&&(e.strokeStyle=a,e.lineWidth=2,e.globalAlpha=.9,e.beginPath(),e.arc(t.x,t.y,9,0,Math.PI*2),e.stroke(),e.lineWidth=1,e.globalAlpha=.45*o,e.beginPath(),e.arc(t.x,t.y,14+o*3,0,Math.PI*2),e.stroke(),e.globalAlpha=.2*o,e.beginPath(),e.arc(t.x,t.y,20+o*5,0,Math.PI*2),e.stroke())}e.restore()}function dD(e,t){let n=e.trim();if(n.startsWith(`#`)){let e=parseInt(n.slice(1),16);if(n.length===7)return`rgba(${e>>16&255},${e>>8&255},${e&255},${t})`}let r=n.match(/rgba?\(([^)]+)\)/);if(r){let e=r[1].split(`,`).map(e=>e.trim());if(e.length>=3)return`rgba(${e[0]},${e[1]},${e[2]},${t})`}return n}function fD(){return{items:[]}}function pD(e,t){for(e.items.push({...t,age:0,progress:0});e.items.length>30;)e.items.shift()}function mD(e){let t=[];for(let n of e.items){let e=n.age+1;e>=n.totalFrames||t.push({...n,age:e,progress:e/n.totalFrames})}e.items=t}function hD(e){return e.items}function gD(e,t){let n=new Map(e.map(e=>[e.agentId,e]));return{born:t.filter(e=>!n.has(e.agentId)&&e.alive&&!((e.age??0)>=18)),died:t.filter(e=>n.get(e.agentId)?.alive===!0&&!e.alive)}}var _D=new Set([`political`,`social`,`infrastructure`,`medical`,`resource`,`environmental`]);function vD(e,t,n,r){let i=(0,b.useRef)(fD()),a=(0,b.useRef)(new Set),[o,s]=(0,b.useState)(0),c=(0,b.useRef)(-1),l=(0,b.useRef)(!0),u=(0,b.useRef)(typeof document<`u`?!document.hidden:!0),d=jy(Fy);return(0,b.useEffect)(()=>{let t=e.snapshot,r=e.previousSnapshot;if(!t||t.turn===c.current||(c.current=t.turn,!r))return;let o=n(),{born:s,died:l}=gD(r.cells,t.cells);for(let e of s){let t=o.get(e.agentId);t&&pD(i.current,{kind:`birth`,x:t.x,y:t.y,totalFrames:30,sourceId:e.agentId})}for(let e of l){let t=o.get(e.agentId);t&&pD(i.current,{kind:`death`,x:t.x,y:t.y,totalFrames:60,sourceId:e.agentId})}let u=e.eventCategories??t.eventCategories??[];if(u.length>0){let e=Array.from(o.values());if(e.length>0){let n=e.reduce((e,t)=>e+t.x,0)/e.length,r=e.reduce((e,t)=>e+t.y,0)/e.length;for(let e of u){let o=e.toLowerCase();if(!_D.has(o))continue;let s=`crisis|${t.turn}|${o}`;a.current.has(s)||(a.current.add(s),pD(i.current,{kind:`crisis`,x:n,y:r,totalFrames:90}))}}}},[e.snapshot,e.previousSnapshot,e.eventCategories,n]),(0,b.useEffect)(()=>{if(!r)return;let t=r();if(t.size!==0){for(let n of e.forgeAttempts??[]){let e=`forge|${n.turn}|${n.eventIndex}|${n.department}|${n.name}|${n.approved?`a`:`r`}`;if(a.current.has(e))continue;a.current.add(e);let r=t.get((n.department||`unknown`).toLowerCase());r&&pD(i.current,{kind:n.approved?`forge_approved`:`forge_rejected`,x:r.x,y:r.y,totalFrames:n.approved?30:22})}for(let n of e.reuseCalls??[]){let e=`reuse|${n.turn}|${n.originDept}|${n.callingDept}|${n.name}`;if(a.current.has(e))continue;a.current.add(e);let r=t.get((n.originDept||`unknown`).toLowerCase()),o=t.get((n.callingDept||`unknown`).toLowerCase());r&&o&&pD(i.current,{kind:`reuse`,x:r.x,y:r.y,endX:o.x,endY:o.y,totalFrames:40})}}},[e.forgeAttempts,e.reuseCalls,r]),(0,b.useEffect)(()=>{let e=()=>{u.current=!document.hidden};document.addEventListener(`visibilitychange`,e);let n=t.current,r=null;return n&&(r=new IntersectionObserver(e=>{for(let t of e)l.current=t.isIntersecting},{threshold:0}),r.observe(n)),()=>{document.removeEventListener(`visibilitychange`,e),r?.disconnect()}},[t]),(0,b.useEffect)(()=>{if(d){s(e=>e+1);return}let e=0,t=performance.now(),n=r=>{!l.current||!u.current||r-t<33.333333333333336||(t=r,mD(i.current),s(e=>e+1)),e=requestAnimationFrame(n)};return e=requestAnimationFrame(n),()=>cancelAnimationFrame(e)},[d]),{flares:hD(i.current),tickClock:o}}function yD(e,t){let n=new Map;for(let r of e){if(!r.alive)continue;let e=t.get(r.agentId);if(!e)continue;let i=(r.department||`unknown`).toLowerCase(),a=n.get(i)??{x:0,y:0,n:0};a.x+=e.x,a.y+=e.y,a.n+=1,n.set(i,a)}let r=new Map;for(let[e,t]of n.entries())r.set(e,{x:t.x/t.n,y:t.y/t.n});return r}var bD={medical:`#4ecdc4`,engineering:`#e8b44a`,agriculture:`#6aad48`,psychology:`#9b6b9e`,governance:`#e06530`,research:`#956bd8`,science:`#956bd8`,ops:`#c87a3a`,operations:`#c87a3a`};function xD(e){return bD[(e||``).toLowerCase()]??`#a89878`}function SD({cells:e,size:t=44}){let{slices:n,alive:r}=(0,b.useMemo)(()=>{let t=new Map,n=0;for(let r of e){if(!r.alive)continue;let e=(r.department||`unknown`).toLowerCase();t.set(e,(t.get(e)??0)+1),n+=1}let r=[...t.entries()].sort((e,t)=>t[1]-e[1]),i=[];for(let[e,t]of r)i.push({dept:e,count:t,frac:t/Math.max(1,n),color:xD(e)});return{slices:i,alive:n}},[e]);if(r===0)return(0,x.jsx)(`div`,{style:{width:t,height:t,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`var(--text-4)`,fontSize:`var(--font-3xs)`,fontFamily:`var(--mono)`},"aria-label":`No live members`,children:`—`});let i=t/2,a=i-6,o=i,s=i,c=-Math.PI/2;return(0,x.jsxs)(`svg`,{width:t,height:t,viewBox:`0 0 ${t} ${t}`,role:`img`,"aria-label":`Department breakdown: ${n.map(e=>`${e.dept} ${e.count}`).join(`, `)}`,children:[n.map((e,t)=>{let n=e.frac*Math.PI*2,r=c,l=c+n;c=l;let u=o+Math.cos(r)*i,d=s+Math.sin(r)*i,f=o+Math.cos(l)*i,p=s+Math.sin(l)*i,m=o+Math.cos(r)*a,h=s+Math.sin(r)*a,g=o+Math.cos(l)*a,_=s+Math.sin(l)*a,v=+(n>Math.PI),y=[`M ${u.toFixed(2)} ${d.toFixed(2)}`,`A ${i} ${i} 0 ${v} 1 ${f.toFixed(2)} ${p.toFixed(2)}`,`L ${g.toFixed(2)} ${_.toFixed(2)}`,`A ${a} ${a} 0 ${v} 0 ${m.toFixed(2)} ${h.toFixed(2)}`,`Z`].join(` `);return(0,x.jsx)(`path`,{d:y,fill:e.color,opacity:.85,children:(0,x.jsx)(`title`,{children:`${e.dept}: ${e.count} (${Math.round(e.frac*100)}%)`})},`${e.dept}-${t}`)}),(0,x.jsx)(`text`,{x:o,y:s,textAnchor:`middle`,dominantBaseline:`central`,fontSize:10,fontFamily:`ui-monospace, monospace`,fontWeight:800,fill:`var(--text-1)`,children:r})]})}var CD={"tab.living":`Who's alive this turn — agents on the scenario grid.`,"tab.mood":`Aggregate mood mix per leader: hopeful / neutral / anxious / negative.`,"tab.forge":`Computational tools the agents forged in the QuickJS WebAssembly sandbox this turn.`,"tab.ecology":`Resource and environment metrics: power, food, water, radiation.`,"tab.divergence":`Per-metric A-vs-B deltas across all turns.`,"badge.forge":`Forge attempts on this turn — click FORGE for details.`,"badge.divergence":`Metrics diverged this turn — click DIVERGENCE for the rail.`,"stat.morale":`Aggregate morale across all alive agents (0–100%).`,"stat.moodMix":`Distribution of agents across the four mood tiers, weighted by morale.`,"stat.alive":`Living agents in this colony at the current turn.`,"stat.age":`Age distribution of living agents (4 bins: <20 / 20–40 / 40–60 / 60+).`,"stat.paired":`Alive agents currently in a partnership pair.`,"stat.earth":`Agents born on Earth (vs Native — born after the colony's first birth event).`,"stat.native":`Agents born in the colony itself (Marsborn / Lunarborn / scenario-specific).`,"stat.depts":`Agent count by department. Hover a wedge for the dept name.`,"chip.rising":`Aggregate morale trending up vs the previous turn.`},wD={strip:`_strip_1twpk_1`,narrow:`_narrow_1twpk_15`,col:`_col_1twpk_20`,colNarrow:`_colNarrow_1twpk_27`,colPaired:`_colPaired_1twpk_31`,row:`_row_1twpk_35`,rowBaseline:`_rowBaseline_1twpk_40`,label:`_label_1twpk_46`,moraleValue:`_moraleValue_1twpk_51`,bar:`_bar_1twpk_57`,moraleFill:`_moraleFill_1twpk_64`,value2:`_value2_1twpk_71`,valueRust:`_valueRust_1twpk_75`,valueNative:`_valueNative_1twpk_79`,moodHeader:`_moodHeader_1twpk_84`,moodEmpty:`_moodEmpty_1twpk_90`,moodBar:`_moodBar_1twpk_95`,moodSegment:`_moodSegment_1twpk_103`,moodLegend:`_moodLegend_1twpk_109`,ageBars:`_ageBars_1twpk_117`,ageBarCol:`_ageBarCol_1twpk_124`,ageBarFill:`_ageBarFill_1twpk_133`,ageScale:`_ageScale_1twpk_143`,deptBlock:`_deptBlock_1twpk_150`,deptLabel:`_deptLabel_1twpk_158`};function TD({snapshot:e,sideColor:t}){let n=jy(My),r=e.cells.filter(e=>e.alive),i=r.reduce((e,t)=>{let n=t.mood||`neutral`;return e[n]=(e[n]??0)+1,e},{}),a=[`positive`,`hopeful`,`neutral`,`anxious`,`negative`,`defiant`,`resigned`],o={positive:`var(--green)`,hopeful:`#9acd60`,neutral:`var(--text-4)`,anxious:`var(--amber)`,negative:`var(--rust)`,defiant:`#c44a1e`,resigned:`var(--text-3)`},s=r.length||1,c=[0,0,0,0];for(let e of r){let t=e.age??30;t<20?c[0]++:t<40?c[1]++:t<60?c[2]++:c[3]++}let l=Math.max(1,...c),u=r.filter(e=>!!e.partnerId).length,d=r.filter(e=>(e.generation??0)===0).length,f=Math.round(e.morale*100),p=f>=60?`var(--green)`:f>=30?`var(--amber)`:`var(--rust)`,m={"--side-color":t};return(0,x.jsxs)(`div`,{className:[wD.strip,n?wD.narrow:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`div`,{className:[wD.col,wD.colNarrow].join(` `),children:[(0,x.jsxs)(`div`,{className:wD.rowBaseline,children:[(0,x.jsx)(`span`,{className:wD.label,title:CD[`stat.morale`],children:`MORALE`}),(0,x.jsxs)(`span`,{className:wD.moraleValue,style:{"--morale-color":p},children:[f,`%`]})]}),(0,x.jsx)(`div`,{className:wD.bar,children:(0,x.jsx)(`div`,{className:wD.moraleFill,style:{"--morale-pct":`${Math.max(2,f)}%`,"--morale-color":p}})}),typeof e.foodReserve==`number`&&(0,x.jsxs)(`div`,{className:wD.row,children:[(0,x.jsx)(`span`,{children:`FOOD`}),(0,x.jsxs)(`span`,{className:wD.value2,children:[e.foodReserve.toFixed(1),`mo`]})]}),(0,x.jsxs)(`div`,{className:wD.row,children:[(0,x.jsx)(`span`,{children:`DEATHS`}),(0,x.jsx)(`span`,{className:wD.valueRust,children:e.deaths})]})]}),(0,x.jsxs)(`div`,{className:wD.col,children:[(0,x.jsxs)(`div`,{className:wD.moodHeader,children:[(0,x.jsx)(`span`,{className:wD.label,title:CD[`stat.moodMix`],children:`MOOD MIX`}),(0,x.jsxs)(`span`,{className:wD.value2,title:CD[`stat.alive`],children:[r.length,` alive`]})]}),r.length===0?(0,x.jsx)(`div`,{className:wD.moodEmpty,children:`no survivors`}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{className:wD.moodBar,children:a.map(e=>{let t=i[e]||0;if(t===0)return null;let n=t/s*100;return(0,x.jsx)(`div`,{title:`${e}: ${t}`,className:wD.moodSegment,style:{"--segment-pct":`${n}%`,"--segment-bg":o[e]||`var(--text-4)`}},e)})}),(0,x.jsx)(`div`,{className:wD.moodLegend,children:a.filter(e=>(i[e]||0)>0).map(e=>`${Math.round((i[e]||0)/s*100)}% ${e}`).slice(0,3).join(` · `)})]})]}),(0,x.jsxs)(`div`,{className:wD.col,children:[(0,x.jsx)(`div`,{className:wD.label,title:CD[`stat.age`],children:`AGE`}),(0,x.jsx)(`div`,{className:wD.ageBars,children:c.map((e,n)=>(0,x.jsx)(`div`,{className:wD.ageBarCol,children:(0,x.jsx)(`div`,{title:`${[`<20`,`20-40`,`40-60`,`60+`][n]}: ${e} colonists`,className:wD.ageBarFill,style:{"--age-height":`${e/l*100}%`,"--age-min":e>0?`2px`:`0`,"--age-bg":e>0?t:`transparent`}})},n))}),(0,x.jsxs)(`div`,{className:wD.ageScale,children:[(0,x.jsx)(`span`,{children:`<20`}),(0,x.jsx)(`span`,{children:`20`}),(0,x.jsx)(`span`,{children:`40`}),(0,x.jsx)(`span`,{children:`60+`})]})]}),(0,x.jsxs)(`div`,{className:[wD.col,wD.colPaired].join(` `),children:[(0,x.jsxs)(`div`,{className:wD.row,children:[(0,x.jsx)(`span`,{className:wD.label,title:CD[`stat.paired`],children:`PAIRED`}),(0,x.jsxs)(`span`,{className:wD.value2,children:[u,`/`,r.length]})]}),(0,x.jsxs)(`div`,{className:wD.row,children:[(0,x.jsx)(`span`,{title:CD[`stat.earth`],children:`EARTH`}),(0,x.jsx)(`span`,{className:wD.value2,children:d})]}),(0,x.jsxs)(`div`,{className:wD.row,children:[(0,x.jsx)(`span`,{title:CD[`stat.native`],children:`NATIVE`}),(0,x.jsx)(`span`,{className:wD.valueNative,style:m,children:r.length-d})]})]}),!n&&(0,x.jsxs)(`div`,{className:wD.deptBlock,"aria-label":`Department breakdown`,title:CD[`stat.depts`],children:[(0,x.jsx)(SD,{cells:e.cells,size:44}),(0,x.jsx)(`span`,{className:wD.deptLabel,children:`Depts`})]})]})}var ED={cols:12,rows:6,seedRadius:2},DD=[[1,0],[2,1],[0,2],[1,2],[2,2]],OD=[[0,1],[1,1],[2,1]],kD=[[0,0],[1,0],[0,1],[1,1]],AD=[[1,0],[2,0],[0,1],[3,1],[1,2],[2,2]],jD=[[1,0],[2,0],[3,0],[0,1],[1,1],[2,1]],MD=[[1,0],[2,0],[0,1],[1,1],[1,2]];function ND(e){switch(e){case`positive`:case`hopeful`:return kD;case`neutral`:return AD;case`anxious`:return OD;case`resigned`:return jD;case`defiant`:case`negative`:return DD;default:return OD}}function PD(e,t,n,r,i,a,o){let s=r/a,c=i/o,l=Math.max(1,Math.min(s,c)-2);e.save(),e.fillStyle=`rgba(106, 173, 72, 0.25)`,e.strokeStyle=`rgba(154, 205, 96, 0.95)`,e.lineWidth=2;for(let u of t){if(!u.alive||(u.generation??0)===0)continue;let t=n.get(u.agentId);if(!t)continue;let d=Math.floor(t.x/Math.max(1,r)*a),f=Math.floor(t.y/Math.max(1,i)*o),p=(s-l)/2,m=(c-l)/2,h=d*s+p,g=f*c+m;e.fillRect(h,g,l,l),e.strokeRect(h+.5,g+.5,l-1,l-1);let _=h+l/2,v=g+l/2,y=l*.4;e.beginPath(),e.moveTo(_-y,v),e.lineTo(_+y,v),e.moveTo(_,v-y),e.lineTo(_,v+y),e.stroke()}e.restore()}function FD(e,t,n,r,i,a,o,s=`rgba(168, 152, 120, 0.85)`,c=`rgba(168, 152, 120, 0.08)`){let l=r/a,u=i/o,d=Math.max(1,Math.min(l,u)-2);e.save(),e.lineWidth=2,e.strokeStyle=s,e.fillStyle=c;for(let s of t){if(s.alive)continue;let t=n.get(s.agentId);if(!t)continue;let c=Math.floor(t.x/Math.max(1,r)*a),f=Math.floor(t.y/Math.max(1,i)*o),p=(l-d)/2,m=(u-d)/2,h=c*l+p,g=f*u+m;e.fillRect(h,g,d,d),e.strokeRect(h+.5,g+.5,d-1,d-1),e.beginPath(),e.moveTo(h+4,g+4),e.lineTo(h+d-4,g+d-4),e.moveTo(h+d-4,g+4),e.lineTo(h+4,g+d-4),e.stroke()}e.restore()}function ID(e,t,n,r,i){let{cols:a,rows:o,grid:s}=e,c=Math.floor(t/Math.max(1,r)*a),l=Math.floor(n/Math.max(1,i)*o);return c<0||c>=a||l<0||l>=o?null:s[l*a+c]>0?{col:c,row:l}:null}function LD(e,t,n,r,i){return{col:Math.floor(e.x/Math.max(1,t)*r),row:Math.floor(e.y/Math.max(1,n)*i)}}function RD(e){switch(e){case`birth`:return kD;case`forge`:return DD;case`crisis`:return MD;case`death`:return[];default:return null}}function zD(e,t){return{cols:e,rows:t,grid:new Uint8Array(e*t),next:new Uint8Array(e*t),frame:0}}function BD(e,t,n,r,i,a=`all`){let{cols:o,rows:s,grid:c}=e;c.fill(0);let l=RD(a);for(let e=0;e<t.length;e+=1){let a=t[e];if(!a.alive)continue;let u=n.get(a.agentId);if(!u)continue;let d=Math.floor(u.x/Math.max(1,r)*o),f=Math.floor(u.y/Math.max(1,i)*s),p=l??ND(a.mood);for(let[e,t]of p){let n=d+e-1,r=f+t-1;n<0||n>=o||r<0||r>=s||(c[r*o+n]=8)}}}function VD(e,t,n,r){let{cols:i,rows:a,grid:o}=e,s=Math.floor(t.x/Math.max(1,n)*i),c=Math.floor(t.y/Math.max(1,r)*a);if(t.kind===`death`){for(let e=-1;e<=1;e+=1)for(let t=-1;t<=1;t+=1){let n=s+t,r=c+e;n<0||n>=i||r<0||r>=a||(o[r*i+n]=0)}return}let l;switch(t.kind){case`birth`:l=kD;break;case`forge_approved`:l=DD;break;case`forge_rejected`:l=OD;break;case`reuse`:l=jD;break;case`crisis`:l=MD;break;default:l=OD}for(let[e,t]of l){let n=s+e-1,r=c+t-1;n<0||n>=i||r<0||r>=a||(o[r*i+n]=8)}}function HD(e){let{cols:t,rows:n,grid:r,next:i}=e;i.fill(0);for(let e=0;e<n;e++)for(let a=0;a<t;a++){let o=0;for(let i=-1;i<=1;i++)for(let s=-1;s<=1;s++){if(s===0&&i===0)continue;let c=a+s,l=e+i;c<0||c>=t||l<0||l>=n||r[l*t+c]>0&&(o+=1)}let s=r[e*t+a],c=s>0;c&&o===2||o===3?i[e*t+a]=c?Math.max(4,s):8:c&&s>1&&(i[e*t+a]=Math.max(0,s-2))}r.set(i),e.frame+=1}function UD(e,t,n,r,i,a=1){let{cols:o,rows:s,grid:c}=t;if(a<=0)return;let l=n/o,u=r/s,d=Math.max(1,Math.min(l,u)-2),f=(l-d)/2,p=(u-d)/2;e.save();for(let t=0;t<s;t++)for(let n=0;n<o;n++){let r=c[t*o+n];if(r===0)continue;let s=Math.min(1,r/8*.9*a);e.fillStyle=i,e.globalAlpha=s,e.fillRect(n*l+f,t*u+p,d,d)}e.restore()}function WD(e,t){return e<0||Math.abs(t-e)>1}function GD(e,t,n,r){return r||n<=0?e:e*(1-(1-Math.max(0,Math.min(1,t/n)))**3)}function KD(e,t,n,r){for(let i=e.length-1;i>=0;i--){let a=e[i];if(!a.alive)continue;let o=t.get(a.agentId);if(!o)continue;let s=(a.featured?5:3)+18,c=n-o.x,l=r-o.y;if(c*c+l*l<=s*s)return a}return null}var qD=[`O`,`C`,`E`,`A`,`Em`,`HH`];function JD(e,t){let n=t/2,r=t/2,i=t/2-8;return qD.map((t,a)=>{let o=Math.PI*2*a/qD.length-Math.PI/2,s=Math.max(0,Math.min(1,e[t])),c=i*s;return`${n+Math.cos(o)*c},${r+Math.sin(o)*c}`}).join(` `)}function YD(e,t,n){let r=t/2,i=t/2,a=t/2,o=Math.PI*2*n/qD.length-Math.PI/2;return{x:r+Math.cos(o)*a,y:i+Math.sin(o)*a,label:e}}function XD({profile:e,colonyMean:t,size:n=160}){let r=JD(e,n),i=t?JD(t,n):null,a=n/2,o=n/2,s=n/2-8;return(0,x.jsxs)(`svg`,{width:n,height:n,role:`img`,"aria-label":`HEXACO profile radar`,children:[[.25,.5,.75,1].map(e=>(0,x.jsx)(`circle`,{cx:a,cy:o,r:s*e,fill:`none`,stroke:`var(--border)`,strokeDasharray:e===1?void 0:`2 3`},e)),qD.map((e,t)=>{let r=YD(e,n,t);return(0,x.jsx)(`text`,{x:r.x,y:r.y,fontSize:`9`,fontFamily:`var(--mono)`,fill:`var(--text-3)`,textAnchor:`middle`,dominantBaseline:`middle`,children:r.label},e)}),i&&(0,x.jsx)(`polygon`,{points:i,fill:`none`,stroke:`var(--text-3)`,strokeWidth:`1`,strokeDasharray:`3 3`}),(0,x.jsx)(`polygon`,{points:r,fill:`color-mix(in srgb, var(--amber) 25%, transparent)`,stroke:`var(--amber)`,strokeWidth:`1.5`})]})}var ZD={backdrop:`_backdrop_gccy2_1`,popover:`_popover_gccy2_8`,headerRow:`_headerRow_gccy2_25`,headerName:`_headerName_gccy2_34`,headerSubline:`_headerSubline_gccy2_42`,featuredPill:`_featuredPill_gccy2_49`,closeBtn:`_closeBtn_gccy2_59`,section:`_section_gccy2_72`,sectionLast:`_sectionLast_gccy2_77`,statsGrid:`_statsGrid_gccy2_81`,statKey:`_statKey_gccy2_88`,statValue:`_statValue_gccy2_92`,statValueUpper:`_statValueUpper_gccy2_96`,sectionLabel:`_sectionLabel_gccy2_101`,hexacoRow:`_hexacoRow_gccy2_110`,hexacoRadarWrap:`_hexacoRadarWrap_gccy2_116`,hexacoTopAxes:`_hexacoTopAxes_gccy2_120`,memoryList:`_memoryList_gccy2_126`,memoryItem:`_memoryItem_gccy2_132`,chatBtn:`_chatBtn_gccy2_143`},QD={O:`Openness`,C:`Conscientiousness`,E:`Extraversion`,A:`Agreeableness`,Em:`Emotionality`,HH:`Honesty-Humility`};function $D(e){if(!e)return``;let t=Object.entries(e);return t.sort((e,t)=>t[1]-e[1]),t.slice(0,2).map(([e,t])=>`${QD[e]} ${t.toFixed(2)}`).join(` · `)}function eO(e){let{payload:t,containerW:n,containerH:r,sideColor:i,hexacoById:a,snapshots:o,onClose:s,onOpenChat:c}=e,l=(0,b.useRef)(null);(0,b.useEffect)(()=>{if(!t)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),s())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[t,s]);let u=(0,b.useMemo)(()=>{if(t&&a)return a.get(t.cell.agentId)??a.get(t.cell.name)},[t,a]),d=(0,b.useMemo)(()=>{if(!t)return[];let e=[...t.cell.shortTermMemory??[]];if(o)for(let n=o.length-1;n>=0&&e.length<3;n--){let r=o[n].cells.find(e=>e.agentId===t.cell.agentId);if(r){for(let t of r.shortTermMemory??[])if(t&&!e.includes(t)&&e.push(t),e.length>=3)break}}return e.slice(0,3)},[t,o]),f=jy(Ny);if(!t)return null;let p=f?Math.min(320,n-16):320,m=Math.min(360,r-20),h=f?Math.max(8,(n-p)/2):t.x+p+10>n?Math.max(10,t.x-p-10):Math.min(n-p-10,t.x+10),g=f?Math.max(8,(r-m)/2):t.y-m-10<0?Math.min(r-m-10,t.y+10):Math.max(10,t.y-m-10),_=t.cell,v=typeof _.psychScore==`number`?Math.round(_.psychScore*100):null,y=(()=>{let e=_.generation??0;return e===0?`Earth-born`:e===1?`First-native`:`Gen ${e}`})(),S=Math.max(120,r-g-10),C={"--side-color":i,"--pop-left":`${h}px`,"--pop-top":`${g}px`,"--pop-width":`${p}px`,"--pop-max-height":`${S}px`};return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{onClick:s,className:ZD.backdrop}),(0,x.jsxs)(`div`,{ref:l,role:`dialog`,"aria-label":`${_.name} drilldown`,className:ZD.popover,style:C,children:[(0,x.jsxs)(`div`,{className:ZD.headerRow,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:ZD.headerName,children:_.name}),(0,x.jsxs)(`div`,{className:ZD.headerSubline,children:[_.role,` · `,_.rank,_.featured&&(0,x.jsx)(`span`,{className:ZD.featuredPill,children:`FEATURED`})]})]}),(0,x.jsx)(`button`,{type:`button`,onClick:s,"aria-label":`Close drilldown`,className:ZD.closeBtn,children:`×`})]}),(0,x.jsx)(`div`,{className:ZD.section,children:(0,x.jsxs)(`div`,{className:ZD.statsGrid,children:[(0,x.jsx)(`span`,{className:ZD.statKey,children:`DEPT`}),(0,x.jsx)(`span`,{className:ZD.statValueUpper,children:_.department}),(0,x.jsx)(`span`,{className:ZD.statKey,children:`AGE`}),(0,x.jsx)(`span`,{className:ZD.statValue,children:_.age??`—`}),(0,x.jsx)(`span`,{className:ZD.statKey,children:`MOOD`}),(0,x.jsx)(`span`,{className:ZD.statValue,children:_.mood}),v!==null&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:ZD.statKey,children:`PSYCH`}),(0,x.jsxs)(`span`,{className:ZD.statValue,children:[v,`%`]})]}),(0,x.jsx)(`span`,{className:ZD.statKey,children:`ORIGIN`}),(0,x.jsx)(`span`,{className:ZD.statValue,children:y}),(0,x.jsx)(`span`,{className:ZD.statKey,children:`PARTNER`}),(0,x.jsx)(`span`,{className:ZD.statValue,children:_.partnerId?`yes`:`—`}),(0,x.jsx)(`span`,{className:ZD.statKey,children:`CHILDREN`}),(0,x.jsx)(`span`,{className:ZD.statValue,children:_.childrenIds?.length??0})]})}),u&&(0,x.jsxs)(`div`,{className:ZD.section,children:[(0,x.jsx)(`div`,{className:ZD.sectionLabel,children:`HEXACO`}),(0,x.jsxs)(`div`,{className:ZD.hexacoRow,children:[(0,x.jsx)(`div`,{className:ZD.hexacoRadarWrap,children:(0,x.jsx)(XD,{profile:u,size:120})}),(0,x.jsx)(`div`,{className:ZD.hexacoTopAxes,children:$D(u)})]})]}),d.length>0&&(0,x.jsxs)(`div`,{className:ZD.section,children:[(0,x.jsx)(`div`,{className:ZD.sectionLabel,children:`Recent memory`}),(0,x.jsx)(`ul`,{className:ZD.memoryList,children:d.map((e,t)=>(0,x.jsxs)(`li`,{className:ZD.memoryItem,children:[`"`,e,`"`]},t))})]}),c&&(0,x.jsx)(`div`,{className:ZD.sectionLast,children:(0,x.jsxs)(`button`,{type:`button`,onClick:()=>c(_.name),className:ZD.chatBtn,children:[`Open chat with `,_.name.split(` `)[0]]})})]})]})}var tO={backdrop:`_backdrop_18xl4_1`,drawer:`_drawer_18xl4_8`,header:`_header_18xl4_25`,closeBtn:`_closeBtn_18xl4_32`,row:`_row_18xl4_45`,rowLabel:`_rowLabel_18xl4_53`,pillRow:`_pillRow_18xl4_58`,pill:`_pill_18xl4_58`,pillActive:`_pillActive_18xl4_76`,resetBtn:`_resetBtn_18xl4_81`},nO={deptLabels:!1,crosshair:!0,alerts:!0,sound:!1};function rO(e){let t={...nO};for(let n of Object.keys(nO))typeof e[n]==`boolean`&&(t[n]=e[n]);return t}function iO({open:e,settings:t,onChange:n,onClose:r}){let i=Pt(e);if((0,b.useEffect)(()=>{if(!e)return;let t=e=>{e.key===`Escape`&&(e.preventDefault(),r())};return document.addEventListener(`keydown`,t),()=>document.removeEventListener(`keydown`,t)},[e,r]),!e)return null;let a=(e,r)=>{n({...t,[e]:r})};return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{onClick:r,className:tO.backdrop}),(0,x.jsxs)(`div`,{ref:i,role:`dialog`,"aria-label":`Grid viz settings`,tabIndex:-1,className:tO.drawer,children:[(0,x.jsxs)(`div`,{className:tO.header,children:[(0,x.jsx)(`span`,{style:Pw,children:`Viz Settings`}),(0,x.jsx)(`button`,{type:`button`,onClick:r,"aria-label":`Close settings`,className:tO.closeBtn,children:`×`})]}),(0,x.jsxs)(aO,{label:`Dept labels`,children:[(0,x.jsx)(oO,{active:t.deptLabels,onClick:()=>a(`deptLabels`,!0),label:`on`}),(0,x.jsx)(oO,{active:!t.deptLabels,onClick:()=>a(`deptLabels`,!1),label:`off`})]}),(0,x.jsxs)(aO,{label:`Crosshair`,children:[(0,x.jsx)(oO,{active:t.crosshair,onClick:()=>a(`crosshair`,!0),label:`on`}),(0,x.jsx)(oO,{active:!t.crosshair,onClick:()=>a(`crosshair`,!1),label:`off`})]}),(0,x.jsxs)(aO,{label:`Alert toasts`,children:[(0,x.jsx)(oO,{active:t.alerts,onClick:()=>a(`alerts`,!0),label:`on`}),(0,x.jsx)(oO,{active:!t.alerts,onClick:()=>a(`alerts`,!1),label:`off`})]}),(0,x.jsxs)(aO,{label:`Sound cues`,children:[(0,x.jsx)(oO,{active:t.sound,onClick:()=>a(`sound`,!0),label:`on`}),(0,x.jsx)(oO,{active:!t.sound,onClick:()=>a(`sound`,!1),label:`off`})]}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>n(nO),style:Fw,className:tO.resetBtn,children:`Reset defaults`})]})]})}function aO({label:e,children:t}){return(0,x.jsxs)(`div`,{className:tO.row,children:[(0,x.jsx)(`span`,{style:Nw,className:tO.rowLabel,children:e}),(0,x.jsx)(`div`,{className:tO.pillRow,children:t})]})}function oO({active:e,onClick:t,label:n}){return(0,x.jsx)(`button`,{type:`button`,onClick:t,className:[tO.pill,e?tO.pillActive:``].filter(Boolean).join(` `),children:n})}var sO={drawer:`_drawer_tksc5_1`,header:`_header_tksc5_17`,headerLabel:`_headerLabel_tksc5_26`,closeBtn:`_closeBtn_tksc5_34`,sortRow:`_sortRow_tksc5_47`,sortChip:`_sortChip_tksc5_54`,active:`_active_tksc5_69`,body:`_body_tksc5_74`,empty:`_empty_tksc5_80`,deptHeader:`_deptHeader_tksc5_86`,row:`_row_tksc5_95`,deceased:`_deceased_tksc5_115`,swatch:`_swatch_tksc5_119`,rowName:`_rowName_tksc5_128`,featuredPill:`_featuredPill_tksc5_135`,deceasedToggle:`_deceasedToggle_tksc5_144`},cO={positive:`rgba(106, 173, 72, 1)`,hopeful:`rgba(154, 205, 96, 1)`,neutral:`rgba(107, 95, 80, 1)`,anxious:`rgba(232, 180, 74, 1)`,negative:`rgba(224, 101, 48, 1)`,defiant:`rgba(196, 74, 30, 1)`,resigned:`rgba(168, 152, 120, 1)`},lO=[{key:`dept`,label:`Dept`},{key:`name`,label:`Name`},{key:`psych`,label:`Psych`},{key:`age`,label:`Age`}];function uO({open:e,cells:t,actorName:n,sideColor:r,searchQuery:i,hoveredId:a,onHover:o,onSelect:s,onClose:c}){let[l,u]=(0,b.useState)(!1),[d,f]=(0,b.useState)(`dept`),p=Lm(),{alive:m,deceased:h,matchSet:g}=(0,b.useMemo)(()=>{let e=[],n=[];for(let r of t)r.alive?e.push(r):n.push(r);d===`dept`?e.sort((e,t)=>e.department.localeCompare(t.department)||e.name.localeCompare(t.name)):d===`name`?e.sort((e,t)=>e.name.localeCompare(t.name)):d===`psych`?e.sort((e,t)=>(t.psychScore??0)-(e.psychScore??0)):d===`age`&&e.sort((e,t)=>(t.age??0)-(e.age??0)),n.sort((e,t)=>e.name.localeCompare(t.name));let r=i.trim().toLowerCase().split(/\s+/).filter(Boolean),a=new Set;if(r.length>0)for(let e of t){let t=`${e.name} ${e.department} ${e.role} ${e.mood}`.toLowerCase();r.every(e=>t.includes(e))&&a.add(e.agentId)}return{alive:e,deceased:n,matchSet:a}},[t,i,d]),_=(0,b.useMemo)(()=>{if(d!==`dept`)return[[`__flat__`,m]];let e=new Map;for(let t of m){let n=(t.department||`unknown`).toLowerCase(),r=e.get(n)??[];r.push(t),e.set(n,r)}return[...e.entries()].sort((e,t)=>e[0].localeCompare(t[0]))},[m,d]);if(!e)return null;let v={"--side-color":r},y=(e,t,n)=>({"--row-color":t?`var(--text-4)`:`var(--text-2)`,"--row-bg":n?`var(--bg-card)`:e?`color-mix(in srgb, ${r} 13%, transparent)`:`transparent`,"--row-border":e?r:`transparent`,"--row-opacity":t?`0.55`:`1`});return(0,x.jsxs)(`div`,{className:sO.drawer,children:[(0,x.jsxs)(`div`,{className:sO.header,style:v,children:[(0,x.jsxs)(`span`,{className:sO.headerLabel,style:v,children:[n,` Roster · `,m.length]}),(0,x.jsx)(`button`,{type:`button`,onClick:c,"aria-label":`Close roster`,className:sO.closeBtn,children:`×`})]}),(0,x.jsx)(`div`,{className:sO.sortRow,children:lO.map(e=>{let t=d===e.key;return(0,x.jsx)(`button`,{type:`button`,onClick:()=>f(e.key),"aria-pressed":t,className:[sO.sortChip,t?sO.active:``].filter(Boolean).join(` `),children:e.label},e.key)})}),(0,x.jsxs)(`div`,{className:sO.body,children:[_.length===0&&(0,x.jsxs)(`div`,{className:sO.empty,children:[`No living `,p.people,`.`]}),_.map(([e,t])=>(0,x.jsxs)(`div`,{children:[d===`dept`&&(0,x.jsxs)(`div`,{className:sO.deptHeader,children:[e,` · `,t.length]}),t.map(e=>{let t=g.has(e.agentId),n=a===e.agentId,r=i.trim().length>0&&!t;return(0,x.jsxs)(`button`,{type:`button`,onMouseEnter:()=>o(e.agentId),onMouseLeave:()=>o(null),onClick:()=>s(e),title:`${e.name} · ${e.role} · ${e.mood}`,className:sO.row,style:y(t,r,n),children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:sO.swatch,style:{"--swatch-bg":cO[e.mood]??cO.neutral}}),(0,x.jsx)(`span`,{className:sO.rowName,children:e.name}),e.featured&&(0,x.jsx)(`span`,{className:sO.featuredPill,style:v,children:`★`})]},e.agentId)})]},e)),h.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`button`,{type:`button`,onClick:()=>u(e=>!e),className:sO.deceasedToggle,children:[l?`▼`:`▶`,` Deceased · `,h.length]}),l&&h.map(e=>{let t=a===e.agentId;return(0,x.jsxs)(`button`,{type:`button`,onMouseEnter:()=>o(e.agentId),onMouseLeave:()=>o(null),onClick:()=>s(e),title:`${e.name} · ${e.role} · deceased`,className:[sO.row,sO.deceased].join(` `),style:y(!1,!0,t),children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:sO.swatch,style:{"--swatch-bg":`var(--text-4)`}}),(0,x.jsx)(`span`,{className:sO.rowName,children:e.name})]},e.agentId)})]})]})]})}function dO({snapshot:e,previousSnapshot:t,sideColor:n,onSelect:r}){let[i,a]=(0,b.useState)([]),o=(0,b.useRef)(new Set);(0,b.useEffect)(()=>{if(!e)return;let n=e.cells.filter(e=>e.alive&&e.featured),r=t?new Set(t.cells.filter(e=>e.alive&&e.featured).map(e=>e.agentId)):o.current,i=n.filter(e=>!r.has(e.agentId));if(o.current=new Set(n.map(e=>e.agentId)),i.length===0)return;let s=performance.now()+6e3;a(i.slice(0,2).map(t=>({cell:t,turn:e.turn,expiresAt:s})))},[e,t]),(0,b.useEffect)(()=>{if(i.length===0)return;let e=Math.max(0,i[0].expiresAt-performance.now()),t=setTimeout(()=>a([]),e);return()=>clearTimeout(t)},[i]);let s=(0,b.useMemo)(()=>i,[i]);return s.length===0?null:(0,x.jsx)(`div`,{"aria-live":`polite`,style:{position:`absolute`,bottom:12,right:12,display:`flex`,flexDirection:`column`,gap:4,pointerEvents:`none`,zIndex:7,maxWidth:240},children:s.map(e=>(0,x.jsxs)(`button`,{type:`button`,onClick:()=>r?.(e.cell),"aria-label":`Spotlight: ${e.cell.name} · ${e.cell.department}`,title:`${e.cell.name} · ${e.cell.role} · ${e.cell.department} · mood: ${e.cell.mood}`,style:{pointerEvents:`auto`,display:`flex`,alignItems:`center`,gap:6,padding:`4px 10px`,background:`var(--bg-panel)`,border:`1px solid ${n}66`,borderLeft:`3px solid ${n}`,borderRadius:3,fontFamily:`var(--mono)`,fontSize:`var(--font-xs)`,color:`var(--text-2)`,textAlign:`left`,cursor:`pointer`,boxShadow:`0 4px 14px rgba(0, 0, 0, 0.4)`,animation:`paracosm-spotlight-in 380ms ease-out`,whiteSpace:`nowrap`,overflow:`hidden`,textOverflow:`ellipsis`,maxWidth:`100%`},children:[(0,x.jsx)(`span`,{style:{color:n,fontSize:`var(--font-2xs)`,flexShrink:0},"aria-hidden":`true`,children:`★`}),(0,x.jsx)(`span`,{style:{color:`var(--text-1)`,fontWeight:700,overflow:`hidden`,textOverflow:`ellipsis`},children:e.cell.name}),(0,x.jsx)(`span`,{style:{color:`var(--text-3)`,fontSize:`var(--font-2xs)`,flexShrink:0,textTransform:`uppercase`,letterSpacing:`0.04em`},children:e.cell.department})]},e.cell.agentId))})}function fO(e){let t=[];return typeof e.foodReserve==`number`&&t.push(`food reserve ${e.foodReserve.toFixed(1)} months`),typeof e.waterLitersPerDay==`number`&&t.push(`water ${Math.round(e.waterLitersPerDay)} litres a day`),typeof e.powerKw==`number`&&t.push(`power ${Math.round(e.powerKw)} kW`),typeof e.pressurizedVolumeM3==`number`&&t.push(`pressurized volume ${Math.round(e.pressurizedVolumeM3)} cubic metres`),t.map(e=>`, ${e}`).join(``)}function pO(e,t){if(e.startsWith(`var(`)&&t){let n=e.slice(4,-1).trim(),r=getComputedStyle(t).getPropertyValue(n).trim();if(r)return r}return e}function mO(e){let{snapshot:t,previousSnapshot:n,snapshotHistory:r,actorName:i,actorArchetype:a,startTime:o,sideColor:s,side:c,lagTurns:l,clusterMode:u=`departments`,initialPopulation:d=20,mode:f,hexacoById:p,leaderHexaco:m,forgeAttempts:h,reuseCalls:g,divergedIds:_,siblingHoveredId:v,onHoverChange:y,searchQuery:S=``,palette:C=0,settings:w=nO,focusedSide:T=null,onToggleFocus:E,onOpenChat:D,eventFilter:O=`all`,chronicleHover:k=null}=e,A=T===c,j=jy(My),ee=jy(Fy),te=Lm(),M=(0,b.useRef)(null),N=(0,b.useRef)(null),ne=(0,b.useRef)(null),[P,re]=(0,b.useState)({w:0,h:0}),[ie,F]=(0,b.useState)(null),[I,ae]=(0,b.useState)(null),[oe,se]=(0,b.useState)(null),[ce,le]=(0,b.useState)(!1),[L,ue]=(0,b.useState)(null),[de,fe]=(0,b.useState)(!1);(0,b.useEffect)(()=>{if(ee){fe(!0);return}let e=requestAnimationFrame(()=>fe(!0));return()=>cancelAnimationFrame(e)},[ee]);let R=(0,b.useRef)(zD(ED.cols,ED.rows)),z=(0,b.useRef)(-1),pe=(0,b.useRef)(``),me=(0,b.useRef)(``),he=(0,b.useRef)(null),ge=(0,b.useRef)(null),_e=(0,b.useRef)(-1/0),B=(0,b.useRef)({id:null,intensity:0});(0,b.useEffect)(()=>{let e=N.current;if(!e)return;let t=new ResizeObserver(e=>{for(let t of e){let e=Math.max(0,Math.round(t.contentRect.width)),n=Math.max(0,Math.round(t.contentRect.height));re(t=>t.w===e&&t.h===n?t:{w:e,h:n})}});return t.observe(e),()=>t.disconnect()},[]),(0,b.useEffect)(()=>{let e=ne.current;if(!e||P.w===0||P.h===0)return;let t=Math.min(2,window.devicePixelRatio||1);e.width=Math.round(P.w*t),e.height=Math.round(P.h*t),e.style.width=`${P.w}px`,e.style.height=`${P.h}px`;let n=e.getContext(`2d`);n&&n.setTransform(t,0,0,t,0,0)},[P.w,P.h]);let ve=(()=>{if(u!==`departments`)return u;switch(f){case`mood`:return`mood`;case`forge`:return`age`;case`divergence`:return`families`;default:return`departments`}})(),ye=(0,b.useMemo)(()=>!t||P.w===0?new Map:eD(t.cells,ve,P.w,P.h),[t,ve,P.w,P.h]),be=(0,b.useMemo)(()=>t?yD(t.cells,ye):new Map,[t,ye]),xe=vD({snapshot:t,previousSnapshot:n,forgeAttempts:h,reuseCalls:g,eventCategories:t?.eventCategories},N,()=>ye,()=>be),Se=f===`forge`?.7:f===`ecology`?0:1,Ce=(0,b.useMemo)(()=>{if(f!==`mood`||!t)return s;let e=t.cells.filter(e=>e.alive);if(e.length===0)return s;let n={};for(let t of e)n[t.mood]=(n[t.mood]||0)+1;let r=`neutral`,i=0;for(let[e,t]of Object.entries(n))t>i&&(i=t,r=e);switch(r){case`positive`:case`hopeful`:return`var(--green)`;case`anxious`:return`var(--amber)`;case`negative`:case`defiant`:return`var(--rust)`;case`resigned`:return`var(--text-3)`;default:return s}},[f,t,s]);(0,b.useEffect)(()=>{let e=ne.current;if(!e||!t||P.w===0||P.h===0)return;let r=e.getContext(`2d`);if(!r)return;let c=xe.flares.filter(e=>O===`all`?!0:O===`birth`?e.kind===`birth`:O===`death`?e.kind===`death`:O===`crisis`?e.kind===`crisis`:O!==`forge`||e.kind===`forge_approved`||e.kind===`forge_rejected`||e.kind===`reuse`),u=pO(s,M.current),d=M.current?getComputedStyle(M.current):null,p=(e,t)=>{if(!e.startsWith(`#`)||e.length!==7)return null;let n=parseInt(e.slice(1),16);return`rgba(${n>>16&255}, ${n>>8&255}, ${n&255}, ${t})`},m=d&&p(d.getPropertyValue(`--bg-deep`).trim(),.85)||`rgba(10, 8, 6, 0.85)`,g=d&&p(d.getPropertyValue(`--text-2`).trim(),.8)||`rgba(216, 204, 176, 0.75)`,y=d&&p(d.getPropertyValue(`--text-2`).trim(),.22)||`rgba(216, 204, 176, 0.22)`,b=d&&p(d.getPropertyValue(`--text-2`).trim(),.7)||`rgba(216, 204, 176, 0.7)`,x=d&&p(d.getPropertyValue(`--text-2`).trim(),.95)||`rgba(216, 204, 176, 0.95)`,C=d&&p(d.getPropertyValue(`--text-3`).trim(),.85)||`rgba(168, 152, 120, 0.85)`,T=d&&p(d.getPropertyValue(`--text-3`).trim(),.08)||`rgba(168, 152, 120, 0.08)`,E=d&&p(d.getPropertyValue(`--text-2`).trim(),.6)||`rgba(216, 204, 176, 0.6)`;r.clearRect(0,0,P.w,P.h);let D=R.current,k=f!==pe.current,A=t.turn!==z.current,j=O!==me.current,N=i!==he.current,re=z.current;if(A||k||j||N){z.current=t.turn,pe.current=f,me.current=O,he.current=i,BD(D,t.cells,ye,P.w,P.h,O);let e;e=ee?3:f===`mood`?0:f===`ecology`?2:f===`forge`?8:f===`divergence`?12:5;for(let t=0;t<e;t+=1)HD(D);!ee&&(A&&WD(re,t.turn)||N)&&(_e.current=performance.now()),ge.current=c.length?`${c[0].kind}|${c[0].x}|${c[0].y}`:null}else if(c.length>0){let e=`${c[0].kind}|${c[0].x}|${c[0].y}`;e!==ge.current&&(ge.current=e,VD(D,c[0],P.w,P.h),ee||HD(D))}let F=GD(typeof document<`u`&&document.documentElement.classList.contains(`light`)?.22:.65,performance.now()-_e.current,500,ee);if(UD(r,D,P.w,P.h,u,F),O===`death`?FD(r,t.cells,ye,P.w,P.h,ED.cols,ED.rows,C,T):O===`birth`&&PD(r,t.cells,ye,P.w,P.h,ED.cols,ED.rows),iD(r,c),f!==`ecology`&&tD(r,t.cells,ye,u,Se,_,f===`divergence`,ee?0:performance.now(),S,!0,g,m),f===`forge`&&h&&h.length>0&&cD(r,t.cells,ye,h.map(e=>({department:e.department,turn:e.turn,approved:e.approved})),u),f===`ecology`&&lD(r,t,P.w,P.h,E),f===`divergence`&&uD(r,t.cells,ye,_,ee?0:performance.now(),u),sD(r,t,{actorName:i,actorArchetype:a,startTime:o,sideColor:u,width:P.w,height:P.h,lagTurns:l,cells:t.cells,positions:ye,previousSnapshot:n,labelBg:m,textMuted:g,deptLabels:w.deptLabels,timeUnitShort:te.Time}),ie){let e=ye.get(ie.cell.agentId);e&&(r.save(),r.strokeStyle=u,r.lineWidth=2,r.globalAlpha=1,r.beginPath(),r.arc(e.x,e.y,10,0,Math.PI*2),r.stroke(),r.restore())}if(I&&!ie&&w.crosshair){r.save(),r.strokeStyle=y,r.lineWidth=.5,r.setLineDash([3,4]),r.beginPath(),r.moveTo(0,I.y),r.lineTo(P.w,I.y),r.moveTo(I.x,0),r.lineTo(I.x,P.h),r.stroke(),r.setLineDash([]),r.restore();let e=null;for(let n of t.cells){if(!n.alive)continue;let t=ye.get(n.agentId);if(!t)continue;let r=t.x-I.x,i=t.y-I.y,a=r*r+i*i;a>1600||(!e||a<e.d2)&&(e={id:n.agentId,name:n.name,dx:r,dy:i,d2:a})}e&&(r.save(),r.strokeStyle=b,r.setLineDash([2,3]),r.lineWidth=.6,r.beginPath(),r.moveTo(I.x,I.y),r.lineTo(I.x+e.dx,I.y+e.dy),r.stroke(),r.setLineDash([]),r.fillStyle=x,r.font=`bold 11px ui-monospace, monospace`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(`\u2192 ${e.name.split(` `)[0]}`,I.x+6,I.y+6),r.restore())}if(v&&v!==ie?.cell.agentId){let e=ye.get(v);e&&(r.save(),r.strokeStyle=`rgba(232, 180, 74, 0.75)`,r.lineWidth=1.4,r.globalAlpha=.85,r.setLineDash([3,3]),r.beginPath(),r.arc(e.x,e.y,11,0,Math.PI*2),r.stroke(),r.setLineDash([]),r.restore())}},[xe.tickClock,t,ye,P.w,P.h,s,i,l,xe.flares,f,Se,ie,_,v,ee,S,I,w,a,o,h,O]);let we=(0,b.useCallback)(e=>{if(!t)return;let n=e.currentTarget.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top;ae({x:r,y:i});let a=KD(t.cells,ye,r,i);if(a){F(e=>e&&e.cell.agentId===a.agentId?e:{cell:a,x:r,y:i}),ue(null),y?.(a.agentId);return}ie&&(F(null),y?.(null));let o=ED.cols,s=ED.rows,c=O===`death`||O===`birth`?(()=>{let e=Math.floor(r/Math.max(1,P.w)*o),n=Math.floor(i/Math.max(1,P.h)*s);if(e<0||e>=o||n<0||n>=s)return null;for(let r of t.cells){if(O===`death`&&r.alive||O===`birth`&&(!r.alive||(r.generation??0)===0))continue;let t=ye.get(r.agentId);if(!t)continue;let i=LD(t,P.w,P.h,o,s);if(i.col===e&&i.row===n)return{col:e,row:n,kind:O===`death`?`death`:`birth`,nearest:r}}return null})():(()=>{let e=ID(R.current,r,i,P.w,P.h);if(!e)return null;let n=null,a=1/0;for(let r of t.cells){if(!r.alive)continue;let t=ye.get(r.agentId);if(!t)continue;let i=LD(t,P.w,P.h,o,s),c=(i.col-e.col)**2+(i.row-e.row)**2;c<a&&(a=c,n=r)}return{col:e.col,row:e.row,kind:`life`,nearest:n}})();c?ue({x:r,y:i,...c}):L&&ue(null)},[t,ye,ie,y,O,P.w,P.h,L]),Te=(0,b.useCallback)(()=>{F(null),ue(null),ae(null),y?.(null)},[y]),Ee=(0,b.useCallback)(e=>{if(!t)return;let n=e.currentTarget.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top,a=KD(t.cells,ye,r,i);a?(se({cell:a,x:r,y:i}),F(null),ue(null),B.current={id:a.agentId,intensity:1}):L?.nearest&&(se({cell:L.nearest,x:r,y:i}),F(null),ue(null))},[t,ye,L]),De=(0,b.useRef)(null),Oe=(0,b.useCallback)(e=>{if(!t)return;let n=e.touches[0];if(!n)return;let r=e.currentTarget.getBoundingClientRect(),i=n.clientX-r.left,a=n.clientY-r.top,o=KD(t.cells,ye,i,a);o?De.current===o.agentId?(se({cell:o,x:i,y:a}),F(null),De.current=null,B.current={id:o.agentId,intensity:1}):(F({cell:o,x:i,y:a}),ae({x:i,y:a}),De.current=o.agentId,y?.(o.agentId)):(F(null),ae(null),De.current=null,y?.(null))},[t,ye,y]);(0,b.useEffect)(()=>{oe&&t&&(t.cells.find(e=>e.agentId===oe.cell.agentId)||se(null))},[oe,t]),(0,b.useEffect)(()=>{oe||(De.current=null)},[oe]);let ke=pO(f===`mood`?Ce:s,M.current),Ae={birth:`rgba(154, 205, 96, 0.95)`,death:`rgba(200, 95, 80, 0.95)`,forge:`rgba(232, 180, 74, 0.95)`,crisis:`rgba(196, 74, 30, 0.95)`},je={birth:`rgba(154, 205, 96, 0.55)`,death:`rgba(200, 95, 80, 0.55)`,forge:`rgba(232, 180, 74, 0.55)`,crisis:`rgba(196, 74, 30, 0.55)`},Me=k&&k.side===c?Ae[k.kind]:t?t.morale>=.6?`rgba(106, 173, 72, 0.55)`:t.morale>=.3?`rgba(232, 180, 74, 0.55)`:`rgba(196, 74, 30, 0.65)`:`${s}33`,Ne=k&&k.side===c?`0 0 24px ${je[k.kind]}`:t?t.morale>=.6?`0 0 16px rgba(106, 173, 72, 0.18)`:t.morale>=.3?`0 0 16px rgba(232, 180, 74, 0.12)`:`0 0 20px rgba(196, 74, 30, 0.25)`:`none`;return(0,x.jsxs)(`div`,{ref:M,"data-testid":`living-colony-grid-${c}`,role:`region`,"aria-label":`${i} ${te.place} viz`,className:[WE.region,j?WE.narrow:``].filter(Boolean).join(` `),children:[t&&(0,x.jsx)(TD,{snapshot:t,sideColor:s}),(0,x.jsxs)(`div`,{ref:N,className:WE.canvasWrap,style:{"--tint-color":ke,"--wrap-border":Me,"--wrap-glow":Ne},children:[(0,x.jsx)(`canvas`,{ref:ne,role:`img`,"aria-label":t?`${i} ${te.place}, turn ${t.turn}. ${t.cells.filter(e=>e.alive).length} alive, morale ${Math.round(t.morale*100)}%${fO(t)}. ${t.births} births, ${t.deaths} deaths this turn. Click a ${te.person} glyph for drilldown.`:`${i} ${te.place} — waiting for first turn.`,onMouseMove:we,onMouseLeave:Te,onClick:Ee,onTouchStart:Oe,className:WE.canvas,style:{"--canvas-cursor":ie?`pointer`:`default`}}),(0,x.jsx)(`div`,{"aria-hidden":`true`,className:WE.revealCover,style:{"--reveal-opacity":de?`0`:`1`}}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>le(e=>!e),"aria-label":ce?`Close roster`:`Open roster`,title:ce?`Close roster`:`Open roster`,className:WE.cornerBtn,style:{"--right-offset":E?`36px`:`8px`,"--btn-color":ce?`var(--amber)`:`var(--text-3)`,"--btn-border":ce?`var(--amber)`:`var(--border)`},children:`☰`}),E&&(0,x.jsx)(`button`,{type:`button`,onClick:()=>E(c),"aria-label":A?`Restore split view`:`Focus this panel`,title:A?`Restore split view`:`Focus this panel`,className:`${WE.cornerBtn} ${WE.focusBtn}`,style:{"--btn-color":A?`var(--amber)`:`var(--text-3)`,"--btn-border":A?`var(--amber)`:`var(--border)`},children:A?`⤡`:`⤢`}),(0,x.jsx)(dO,{snapshot:t,previousSnapshot:n,sideColor:pO(s,M.current),onSelect:e=>{let t=ye.get(e.agentId);t&&se({cell:e,x:t.x,y:t.y})}}),(0,x.jsx)(uO,{open:ce,cells:t?.cells??[],actorName:i,sideColor:pO(s,M.current),searchQuery:S,hoveredId:ie?.cell.agentId??v??null,onHover:e=>{if(e){let n=t?.cells.find(t=>t.agentId===e),r=n?ye.get(e):null;if(n&&r){F({cell:n,x:r.x,y:r.y}),y?.(e);return}}F(null),y?.(null)},onSelect:e=>{let t=ye.get(e.agentId);t&&se({cell:e,x:t.x,y:t.y})},onClose:()=>le(!1)}),f===`divergence`&&t&&(_?.size??0)===0&&(0,x.jsx)(`div`,{className:WE.divergenceEmpty,children:(0,x.jsx)(`div`,{className:WE.divergenceEmptyMsg,children:`Both timelines identical this turn — no divergence yet`})}),L&&!ie&&!oe&&(()=>{let e=Math.min(Math.max(8,L.x+12),Math.max(8,P.w-220-8)),t=Math.max(8,L.y-84),n=L.kind===`birth`?`+ BIRTH MARKER`:L.kind===`death`?`× DEATH MARKER`:`◼ CONWAY CELL`,r=L.kind===`birth`?`rgba(154, 205, 96, 0.95)`:L.kind===`death`?`rgba(168, 152, 120, 0.95)`:s;return(0,x.jsxs)(`div`,{className:WE.tileTooltip,style:{"--tt-left":`${e}px`,"--tt-top":`${t}px`,"--kind-color":r},children:[(0,x.jsx)(`div`,{className:WE.tileKindLabel,children:n}),(0,x.jsxs)(`div`,{className:WE.tileCoords,children:[`tile (`,L.col,`, `,L.row,`)`]}),L.nearest?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{className:WE.tileNearestName,children:L.nearest.name}),(0,x.jsxs)(`div`,{className:WE.tileNearestRole,children:[L.nearest.role,` · `,L.nearest.department.toUpperCase()]}),L.kind===`death`?(0,x.jsxs)(`div`,{className:WE.tileNearestDeath,children:[`deceased · mood at death: `,L.nearest.mood]}):L.kind===`birth`?(0,x.jsxs)(`div`,{className:WE.tileNearestBirth,children:[`native-born · generation `,L.nearest.generation??0]}):(0,x.jsxs)(`div`,{className:WE.tileNearestPattern,children:[`pattern seeded by nearest colonist's mood: `,L.nearest.mood]})]}):(0,x.jsx)(`div`,{className:WE.tileAmbient,children:`ambient CA cell`}),L.kind===`life`&&(()=>{let e=R.current,t=e.cols,n=e.rows,r=e.grid[L.row*t+L.col]??0,i=0;for(let r=-1;r<=1;r++)for(let a=-1;a<=1;a++){if(r===0&&a===0)continue;let o=L.row+r,s=L.col+a;o<0||o>=n||s<0||s>=t||e.grid[o*t+s]>=1&&i++}return(0,x.jsxs)(`div`,{className:WE.tileNearestPattern,children:[`age `,r,` · `,i,` neighbors alive`]})})()]})})(),ie&&!oe&&(()=>{let e=Math.min(Math.max(8,ie.x+12),Math.max(8,P.w-200-8)),t=Math.min(Math.max(8,ie.y-80-8),Math.max(8,P.h-80-8));return(0,x.jsxs)(`div`,{className:WE.hoverTooltip,style:{"--tt-left":`${e}px`,"--tt-top":`${t}px`,"--side-color":s},children:[(0,x.jsxs)(`div`,{className:WE.hoverHeader,children:[ie.cell.name,ie.cell.featured&&(0,x.jsx)(`span`,{className:WE.hoverFeaturedPill,children:`FEATURED`})]}),(0,x.jsxs)(`div`,{className:WE.hoverRole,children:[ie.cell.department.toUpperCase(),` · `,ie.cell.role,typeof ie.cell.age==`number`?` · age ${ie.cell.age}`:``]}),(0,x.jsxs)(`div`,{className:WE.hoverMood,children:[`mood: `,(0,x.jsx)(`span`,{className:WE.hoverMoodValue,children:ie.cell.mood}),typeof ie.cell.psychScore==`number`?` · psych ${Math.round(ie.cell.psychScore*100)}%`:``]}),r&&r.length>=2&&(()=>{let e=[];for(let t of r){let n=t.cells.find(e=>e.agentId===ie.cell.agentId);n&&typeof n.psychScore==`number`&&e.push(Math.max(0,Math.min(1,n.psychScore)))}if(e.length<2)return null;let t=136/Math.max(1,e.length-1),n=e.map((e,n)=>{let r=2+n*t,i=2+(1-e)*16;return`${n===0?`M`:`L`}${r.toFixed(1)},${i.toFixed(1)}`}).join(` `);return(0,x.jsxs)(`div`,{className:WE.psychBlock,children:[(0,x.jsx)(`div`,{className:WE.psychLabel,children:`PSYCH TRAJECTORY`}),(0,x.jsxs)(`svg`,{viewBox:`0 0 140 20`,preserveAspectRatio:`none`,width:140,height:20,role:`img`,"aria-label":`Psychological trajectory across ${e.length} turns`,className:WE.psychSvg,children:[(0,x.jsx)(`line`,{x1:2,x2:138,y1:10,y2:10,stroke:`var(--border)`,strokeWidth:.4,strokeDasharray:`2 2`}),(0,x.jsx)(`path`,{d:n,fill:`none`,stroke:s,strokeWidth:1}),(0,x.jsx)(`circle`,{cx:2+(e.length-1)*t,cy:2+(1-e[e.length-1])*16,r:1.6,fill:s})]})]})})(),(0,x.jsx)(`div`,{className:WE.hoverHint,children:`click for drilldown`})]})})(),(0,x.jsx)(eO,{payload:oe,containerW:P.w,containerH:P.h,sideColor:pO(s,M.current),hexacoById:p,snapshots:r,onClose:()=>se(null),onOpenChat:D})]})]})}var hO={track:`_track_1u01e_1`,trackInner:`_trackInner_1u01e_29`,column:`_column_1u01e_38`,columnHeader:`_columnHeader_1u01e_64`,columnHeaderSlot:`_columnHeaderSlot_1u01e_80`,columnHeaderText:`_columnHeaderText_1u01e_89`,columnHeaderName:`_columnHeaderName_1u01e_96`,columnHeaderArchetype:`_columnHeaderArchetype_1u01e_105`,columnHeaderPop:`_columnHeaderPop_1u01e_116`,columnBody:`_columnBody_1u01e_125`,columnPlaceholder:`_columnPlaceholder_1u01e_133`,columnPlaceholderShimmer:`_columnPlaceholderShimmer_1u01e_145`,"cohort-shimmer":`_cohort-shimmer_1u01e_1`,columnPlaceholderLabel:`_columnPlaceholderLabel_1u01e_159`};function gO(e){let t=[],n=[],r=new Map;for(let i of e){if(i.type===`forge_attempt`){let e=i.data||{},n=e.approved===!0||e.approved===`true`;t.push({turn:Number(e.turn??0),eventIndex:Number(e.eventIndex??0),department:String(e.department||``),name:String(e.name||``),approved:n,confidence:typeof e.confidence==`number`?e.confidence:void 0}),e.name&&e.department&&n&&!r.has(String(e.name))&&r.set(String(e.name),String(e.department));continue}if(i.type!==`specialist_done`)continue;let e=i.data||{},a=String(e.department||``),o=Array.isArray(e.forgedTools)?e.forgedTools:[];for(let t of o){let o=t,s=String(o.name||``);if(!s||s===`unnamed`)continue;let c=typeof o.firstForgedDepartment==`string`?String(o.firstForgedDepartment):r.get(s),l=typeof o.firstForgedTurn==`number`?o.firstForgedTurn:void 0,u=Number(i.turn??e.turn??0);(c&&l!==void 0&&l<u||c&&c!==a)&&n.push({turn:u,originDept:c,callingDept:a,name:s})}}return{attempts:t,reuses:n}}function _O(e){let{actorIndex:t,actorId:n,state:r,snaps:i,currentTurn:a,gridMode:o,palette:s,gridSettings:c,hexacoById:l,searchQuery:u,chronicleFilter:d,chronicleHover:f,startTime:p,onOpenChat:m}=e,h=(0,b.useRef)(null),[g,_]=(0,b.useState)(t<4);(0,b.useEffect)(()=>{if(g)return;let e=h.current;if(!e)return;if(typeof IntersectionObserver>`u`){_(!0);return}let t=new IntersectionObserver(e=>{for(let n of e)if(n.isIntersecting){_(!0),t.disconnect();return}},{rootMargin:`240px 360px`});return t.observe(e),()=>t.disconnect()},[g]);let v=r.actors[n]??null,y=v?.leader??null,S=i[a],C=a>0?i[a-1]:void 0,w=Pe(t),T=y?.name||`Leader ${t+1}`,E=(0,b.useMemo)(()=>v?gO(v.events):{attempts:[],reuses:[]},[v]),D=y?.hexaco?{O:y.hexaco.O??y.hexaco.openness??.5,C:y.hexaco.C??y.hexaco.conscientiousness??.5,E:y.hexaco.E??y.hexaco.extraversion??.5,A:y.hexaco.A??y.hexaco.agreeableness??.5,Em:y.hexaco.Em??y.hexaco.emotionality??.5,HH:y.hexaco.HH??y.hexaco.honestyHumility??.5}:void 0;return(0,x.jsxs)(`div`,{ref:h,className:hO.column,style:{"--actor-color":w},"aria-label":`Living swarm grid for actor ${t+1}: ${T}`,children:[(0,x.jsxs)(`header`,{className:hO.columnHeader,children:[(0,x.jsxs)(`span`,{className:hO.columnHeaderSlot,children:[`A`,t+1]}),(0,x.jsxs)(`div`,{className:hO.columnHeaderText,children:[(0,x.jsx)(`span`,{className:hO.columnHeaderName,children:T}),y?.archetype&&(0,x.jsx)(`span`,{className:hO.columnHeaderArchetype,children:y.archetype})]}),(0,x.jsxs)(`span`,{className:hO.columnHeaderPop,title:`Population alive · morale`,children:[S?.population??`—`,` · `,S?Math.round(S.morale*100):`—`,`%`]})]}),(0,x.jsx)(`div`,{className:hO.columnBody,children:g?(0,x.jsx)(mO,{snapshot:S,previousSnapshot:C,snapshotHistory:i,actorName:T,actorArchetype:y?.archetype??``,leaderUnit:y?.unit??``,sideColor:w,side:`a`,mode:o,hexacoById:l,leaderHexaco:D,forgeAttempts:E.attempts,reuseCalls:E.reuses,searchQuery:u,palette:s,settings:c,startTime:p,onOpenChat:m,eventFilter:d,chronicleHover:f}):(0,x.jsxs)(`div`,{className:hO.columnPlaceholder,"aria-hidden":`true`,children:[(0,x.jsx)(`div`,{className:hO.columnPlaceholderShimmer}),(0,x.jsx)(`span`,{className:hO.columnPlaceholderLabel,children:`Loading swarm…`})]})})]})}function vO({state:e,snapshotMap:t,currentTurn:n,gridMode:r,palette:i,gridSettings:a,hexacoById:o,searchQuery:s,chronicleFilter:c,chronicleHover:l,startTime:u,onOpenChat:d}){let f=e.actorIds;return(0,x.jsx)(`div`,{className:hO.track,role:`region`,"aria-label":`Cohort swarm grid: ${f.length} actors`,children:(0,x.jsx)(`div`,{className:hO.trackInner,children:f.map((f,p)=>(0,x.jsx)(_O,{actorId:f,actorIndex:p,state:e,snaps:t[f]??[],currentTurn:n,gridMode:r,palette:i,gridSettings:a,hexacoById:o,searchQuery:s,chronicleFilter:c,chronicleHover:l,startTime:u,onOpenChat:d},f))})})}function yO(e){let t=(e.decision||``).split(/[.;]/)[0].trim(),n=t.length>80?t.slice(0,77)+`...`:t,r=e.outcome.startsWith(`risky`),i=e.outcome.endsWith(`success`),a=n.length===0?`held position`:r?i?`gambled on`:`took the risk of`:`chose`,o=n.length===0?``:n.replace(/^(select|implement|issue|move|expand|reduce|slow|initiate|start|deliver)\s+/i,``).replace(/\s+$/,``),s=o.length>0?`${e.actorName} ${a} ${o.toLowerCase()}`:`${e.actorName} ${a}`,c=typeof e.dominantDeaths==`number`&&e.dominantDeaths>0&&e.dominantDeaths<e.deaths;return`${s}${e.deaths>0&&e.dominantCause?c?`, ${e.deaths} lost, ${e.dominantDeaths} to ${e.dominantCause}`:`, ${e.deaths} lost to ${e.dominantCause}`:e.deaths>0?`, ${e.deaths} lost`:``}${e.moraleDelta<=-.08?`; morale cracked`:e.moraleDelta>=.08?`; morale steadied`:``}`}var bO={banner:`_banner_gzmtg_1`,headline:`_headline_gzmtg_12`,collapseBtn:`_collapseBtn_gzmtg_20`,turnLabel:`_turnLabel_gzmtg_39`,title:`_title_gzmtg_43`,categoryPill:`_categoryPill_gzmtg_48`,lineA:`_lineA_gzmtg_58`,lineB:`_lineB_gzmtg_62`,line:`_line_gzmtg_58`,lineLabel:`_lineLabel_gzmtg_78`,lineBody:`_lineBody_gzmtg_85`,lineMore:`_lineMore_gzmtg_91`};function xO(e,t){let n=e.leader?.name??``;if(!n)return null;let r=``,i=``,a=null,o=0,s=0,c=``,l=``,u=0;for(let n of e.events)if((n.data?.turn??-1)===t+1){if((n.type===`turn_start`||n.type===`event_start`)&&(c=String(n.data?.title??c),l=String(n.data?.category??l),u=Number(n.data?.time??u)),n.type===`outcome`){i=String(n.data?.outcome??i);let e=n.data?._decision;typeof e==`string`&&e.length>0&&(r=e);let t=n.data?.systemDeltas?.morale;typeof t==`number`&&Number.isFinite(t)&&(s+=t)}if(n.type===`turn_done`){let e=n.data?.deathCauses;e&&typeof e==`object`&&(a=e)}n.type===`systems_snapshot`&&(o=Number(n.data?.deaths)||0)}let d=o,f=null,p;if(a){let e=0,t=0;for(let[n,r]of Object.entries(a))typeof r!=`number`||r<=0||(e+=r,r>t&&(t=r,f=n));e>0&&(d=e,p=t)}return{actorName:n,decision:r,outcome:i,deaths:d,dominantCause:f,dominantDeaths:p,moraleDelta:s,eventTitle:c,eventCategory:l,time:u}}var SO=6;function CO({state:e,currentTurn:t,linesTarget:n}){let r=e.actorIds.length>2,[i,a]=(0,b.useState)(r),o=(0,b.useMemo)(()=>{let n=[];for(let r of e.actorIds){let i=e.actors[r];n.push({actorId:r,summary:i?xO(i,t):null})}return n},[e.actorIds,e.actors,t]).filter(e=>e.summary!==null),s=o.find(e=>e.summary.eventTitle)?.summary.eventTitle||``,c=o.find(e=>e.summary.eventCategory)?.summary.eventCategory||``,l=o.find(e=>e.summary.time)?.summary.time||0;if(!s)return null;let u=o.slice(0,SO),d=o.length-u.length,f=!i,p=o.length>0,m=f?(0,x.jsxs)(x.Fragment,{children:[u.map((e,t)=>(0,x.jsxs)(`div`,{className:o.length<=2?t===0?bO.lineA:bO.lineB:bO.line,children:[(0,x.jsx)(`span`,{className:bO.lineLabel,children:o.length<=2?t===0?`A`:`B`:e.summary.actorName}),(0,x.jsxs)(`span`,{className:bO.lineBody,children:[`: `,yO(e.summary)]})]},e.actorId)),d>0&&(0,x.jsxs)(`div`,{className:bO.lineMore,children:[`+`,d,` more `,`·`,` see cohort grid below for the rest`]})]}):null;return(0,x.jsxs)(`div`,{role:`status`,"aria-label":`Current turn narrative`,className:bO.banner,children:[(0,x.jsxs)(`div`,{className:bO.headline,children:[(0,x.jsxs)(`span`,{className:bO.turnLabel,children:[`T`,t+1,l?` \u00b7 ${l}`:``]}),(0,x.jsx)(`span`,{className:bO.title,children:s}),c&&(0,x.jsx)(`span`,{className:bO.categoryPill,children:c}),p&&(0,x.jsx)(`button`,{type:`button`,onClick:()=>a(e=>!e),"aria-expanded":!i,"aria-label":i?`Expand per-actor outcomes`:`Collapse per-actor outcomes`,className:bO.collapseBtn,children:i?`\u25be ${o.length} actors`:`▴ hide`})]}),m&&(n?(0,Ay.createPortal)(m,n):m)]})}var wO=[.5,1,2,4];function TO({currentTurn:e,maxTurn:t,time:n,playing:r,speed:i,onTurnChange:a,onPlayPause:o,onStepBack:s,onStepForward:c,onSpeedChange:l}){let u={background:`var(--bg-card)`,color:`var(--text-2)`,border:`1px solid var(--border)`,borderRadius:4,padding:`4px 10px`,fontFamily:`var(--mono)`,fontSize:`var(--font-xs)`,cursor:`pointer`};return(0,x.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:8,padding:`6px 12px`,background:`var(--bg-panel)`,borderTop:`1px solid var(--border)`},children:[(0,x.jsx)(`button`,{type:`button`,onClick:s,disabled:e<=0,"aria-label":`Previous turn`,style:u,children:`<<`}),(0,x.jsx)(`button`,{type:`button`,onClick:o,disabled:t<=1,"aria-label":r?`Pause`:`Play`,style:u,children:r?`■`:`▶`}),(0,x.jsx)(`button`,{type:`button`,onClick:c,disabled:e>=t-1,"aria-label":`Next turn`,style:u,children:`>>`}),(0,x.jsx)(`input`,{type:`range`,min:0,max:Math.max(0,t-1),value:e,onChange:e=>a(Number(e.target.value)),style:{flex:1},"aria-label":`Scrub timeline`}),(0,x.jsxs)(`span`,{style:{fontFamily:`var(--mono)`,fontSize:`var(--font-2xs)`,color:`var(--text-3)`,whiteSpace:`nowrap`},children:[`T`,e+1,`/`,t,` `,n?`\u00b7 ${n}`:``]}),(0,x.jsx)(`select`,{"aria-label":`Playback speed`,value:i,onChange:e=>l(Number(e.target.value)),style:{fontFamily:`var(--mono)`,fontSize:`var(--font-2xs)`,background:`var(--bg-card)`,color:`var(--text-2)`,border:`1px solid var(--border)`,borderRadius:4,padding:`2px 6px`},children:wO.map(e=>(0,x.jsxs)(`option`,{value:e,children:[e,`x`]},e))})]})}var EO=[{key:`living`,label:`LIVING`,hint:`Full field + {person} seeds + all events`},{key:`mood`,label:`MOOD`,hint:`{Person} mood cloud emphasized; births / deaths`},{key:`forge`,label:`FORGE`,hint:`Field dimmed; tool forge attempts + reuse arcs between departments`},{key:`ecology`,label:`ECOLOGY`,hint:`Glyphs hidden; food, water, power and volume tint a quadrant each`},{key:`divergence`,label:`DIVERGENCE`,hint:`Only {people} alive here but dead on the other side`}];function DO(e,t){return e.replace(/\{person\}/g,t.person).replace(/\{Person\}/g,t.Person).replace(/\{people\}/g,t.people).replace(/\{People\}/g,t.People)}function OO(e,t){return DO(EO.find(t=>t.key===e)?.hint??``,t)}function kO({mode:e,onChange:t,counts:n,labels:r}){if(jy(`(max-width: 480px)`)){let i=EO.find(t=>t.key===e),a=n?.[e],o=`calc(${`${i?.label??``}${typeof a==`number`&&a>0?` · ${a}`:``}`.length} * (1ch + 0.08em) + 44px)`;return(0,x.jsx)(`select`,{"aria-label":`Grid viz mode`,value:e,onChange:e=>t(e.target.value),title:DO(EO.find(t=>t.key===e)?.hint??``,r),style:{flex:`1 1 auto`,width:o,minWidth:o,padding:`8px 10px`,fontSize:16,fontFamily:`var(--mono)`,fontWeight:800,letterSpacing:`0.08em`,textTransform:`uppercase`,background:`var(--bg-card)`,color:`var(--text-1)`,border:`1px solid var(--border)`,borderRadius:6,cursor:`pointer`,minHeight:44},children:EO.map(e=>{let t=n?.[e.key],r=typeof t==`number`&&t>0?` · ${t}`:``;return(0,x.jsxs)(`option`,{value:e.key,children:[e.label,r]},e.key)})})}return(0,x.jsx)(`div`,{role:`tablist`,"aria-label":`Grid viz mode`,style:{display:`flex`,gap:0,padding:`4px 6px`,background:`var(--bg-panel)`,border:`1px solid var(--border)`,borderRadius:6,overflowX:`auto`,scrollbarWidth:`thin`},children:EO.map((i,a)=>{let o=e===i.key,s=n?.[i.key],c=DO(i.hint,r);return(0,x.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":o,"data-grid-mode":i.key,onClick:()=>t(i.key),title:c,style:{flex:`1 0 auto`,padding:`5px 8px`,fontSize:`var(--font-3xs)`,fontFamily:`var(--mono)`,fontWeight:800,letterSpacing:`0.1em`,border:`1px solid var(--border)`,borderLeft:a===0?`1px solid var(--border)`:`none`,borderRadius:a===0?`3px 0 0 3px`:a===EO.length-1?`0 3px 3px 0`:0,background:o?`var(--amber)`:`var(--bg-card)`,color:o?`var(--bg-deep)`:`var(--text-3)`,cursor:`pointer`,textTransform:`uppercase`,transition:`background 120ms, color 120ms`,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:4,whiteSpace:`nowrap`},children:[(0,x.jsx)(`span`,{children:i.label}),typeof s==`number`&&s>0&&(0,x.jsx)(`span`,{style:{padding:`0 4px`,borderRadius:2,background:o?`rgba(10, 8, 6, 0.25)`:`var(--bg-deep)`,color:o?`var(--bg-deep)`:`var(--amber)`,fontSize:`var(--font-3xs)`,fontWeight:700,letterSpacing:`0.05em`,minWidth:14,textAlign:`center`},children:s})]},i.key)})})}var AO={backdrop:`_backdrop_bxhar_1`,dialog:`_dialog_bxhar_12`,phone:`_phone_bxhar_26`,header:`_header_bxhar_30`,title:`_title_bxhar_37`,closeBtn:`_closeBtn_bxhar_47`,section:`_section_bxhar_60`,sectionTitle:`_sectionTitle_bxhar_64`,rows:`_rows_bxhar_75`,row:`_row_bxhar_75`,rowKey:`_rowKey_bxhar_89`,rowVal:`_rowVal_bxhar_96`,swatchWrap:`_swatchWrap_bxhar_101`,swatch:`_swatch_bxhar_101`,footer:`_footer_bxhar_117`,kbd:`_kbd_bxhar_123`};function jO({open:e,onClose:t}){let n=jy(Ny),r=Lm();if(!e)return null;let i=[AO.dialog,n?AO.phone:``].filter(Boolean).join(` `);return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Grid viz help`,onClick:t,className:AO.backdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:i,children:[(0,x.jsxs)(`div`,{className:AO.header,children:[(0,x.jsxs)(`h2`,{className:AO.title,children:[`Living `,r.Place,` Grid — Legend`]}),(0,x.jsx)(`button`,{type:`button`,onClick:t,"aria-label":`Close help`,className:AO.closeBtn,children:`×`})]}),(0,x.jsxs)(MO,{title:`Modes`,children:[(0,x.jsx)(NO,{k:`LIVING`,v:`Full chemistry + ${r.person} glyphs + event flares`}),(0,x.jsx)(NO,{k:`MOOD`,v:`Emphasizes ${r.person} seeds + mood-coded chemistry clouds`}),(0,x.jsx)(NO,{k:`FORGE`,v:`Dims field, highlights forge attempts + reuse arcs`}),(0,x.jsx)(NO,{k:`ECOLOGY`,v:`Hides glyphs; food, water, power and volume tint a quadrant each`}),(0,x.jsx)(NO,{k:`DIVERGENCE`,v:`Only shows ${r.people} alive here but dead on the other side`})]}),(0,x.jsxs)(MO,{title:`Grid elements`,children:[(0,x.jsx)(NO,{k:(0,x.jsx)(PO,{color:`rgba(232, 180, 74, 0.9)`}),v:`Warm amber = high vitality (${r.place} thriving)`}),(0,x.jsx)(NO,{k:(0,x.jsx)(PO,{color:`rgba(196, 74, 30, 0.9)`}),v:`Rust red = stress concentration (decay / anxiety)`}),(0,x.jsx)(NO,{k:`○ small ring`,v:`Alive ${r.person}, hover for identity`}),(0,x.jsx)(NO,{k:`◎ thick ring`,v:`Featured ${r.person} (drives narrative this turn)`}),(0,x.jsx)(NO,{k:`○ amber halo`,v:`Diverged ${r.person} — alive here but dead on the other side`}),(0,x.jsx)(NO,{k:`DEPT label`,v:`Cluster centroid label showing dept + live count`})]}),(0,x.jsxs)(MO,{title:`Event flares`,children:[(0,x.jsx)(NO,{k:(0,x.jsx)(PO,{color:`rgba(154, 205, 96, 0.8)`}),v:`Green bloom — birth`}),(0,x.jsx)(NO,{k:(0,x.jsx)(PO,{color:`rgba(168, 152, 120, 0.7)`}),v:`Grey wave — death`}),(0,x.jsx)(NO,{k:(0,x.jsx)(PO,{color:`rgba(232, 180, 74, 0.8)`}),v:`Amber dot — forge approved`}),(0,x.jsx)(NO,{k:(0,x.jsx)(PO,{color:`rgba(224, 101, 48, 0.7)`}),v:`Red flash — forge rejected`}),(0,x.jsx)(NO,{k:(0,x.jsx)(PO,{color:`rgba(232, 180, 74, 0.6)`}),v:`Amber arc — tool reuse across departments`}),(0,x.jsx)(NO,{k:(0,x.jsx)(PO,{color:`rgba(196, 74, 30, 0.8)`}),v:`Red ring — crisis shockwave (category-gated)`})]}),(0,x.jsxs)(MO,{title:`Keyboard`,children:[(0,x.jsx)(NO,{k:`1 / 2 / 3 / 4 / 5`,v:`Switch mode (Living / Mood / Forge / Ecology / Divergence)`}),(0,x.jsx)(NO,{k:`← / →`,v:`Step turn back / forward`}),(0,x.jsx)(NO,{k:`Space`,v:`Play / pause timeline`}),(0,x.jsx)(NO,{k:`?`,v:`Toggle this help overlay`}),(0,x.jsx)(NO,{k:`Esc`,v:`Close popover / this overlay`}),(0,x.jsx)(NO,{k:`click glyph`,v:`Open ${r.person} drilldown (HEXACO radar, memory, chat)`})]}),(0,x.jsxs)(`div`,{className:AO.footer,children:[`Press `,(0,x.jsx)(`kbd`,{className:AO.kbd,children:`?`}),` anytime to reopen.`]})]})})}function MO({title:e,children:t}){return(0,x.jsxs)(`div`,{className:AO.section,children:[(0,x.jsx)(`div`,{className:AO.sectionTitle,children:e}),(0,x.jsx)(`div`,{className:AO.rows,children:t})]})}function NO({k:e,v:t}){return(0,x.jsxs)(`div`,{className:AO.row,children:[(0,x.jsx)(`span`,{className:AO.rowKey,children:e}),(0,x.jsx)(`span`,{className:AO.rowVal,children:t})]})}function PO({color:e}){return(0,x.jsx)(`span`,{className:AO.swatchWrap,children:(0,x.jsx)(`span`,{className:AO.swatch,style:{"--swatch-color":e}})})}var FO={wrap:`_wrap_10kb4_1`,legend:`_legend_10kb4_8`,legendRight:`_legendRight_10kb4_19`,legendA:`_legendA_10kb4_24`,legendB:`_legendB_10kb4_28`,legendKey:`_legendKey_10kb4_32`,svg:`_svg_10kb4_36`,tooltip:`_tooltip_10kb4_44`,tooltipTurn:`_tooltipTurn_10kb4_63`,tooltipRowA:`_tooltipRowA_10kb4_71`,tooltipRowB:`_tooltipRowB_10kb4_78`,tooltipBold:`_tooltipBold_10kb4_85`};function IO({snapsA:e,snapsB:t,currentTurn:n,onJumpToTurn:r,hoveredTurn:i,onHoverTurnChange:a}){let o=Math.max(e.length,t.length);if(o<2)return null;let s=(e,t)=>{if(e.length===0)return``;let n=588/Math.max(1,o-1),r=[],i=!1;return e.forEach((e,a)=>{let o=t(e);if(o===null){i=!1;return}let s=6+a*n,c=3+(1-o)*22;r.push(`${i?`L`:`M`}${s.toFixed(1)},${c.toFixed(1)}`),i=!0}),r.join(` `)},c=e.some(e=>typeof e.foodReserve==`number`),l=t.some(e=>typeof e.foodReserve==`number`),u=c||l,d=[...e,...t].map(e=>e.foodReserve).filter(e=>typeof e==`number`),f=Math.max(18,...d),p=Math.max(1,...e.map(e=>e.population),...t.map(e=>e.population)),m=e=>typeof e.foodReserve==`number`?Math.max(0,Math.min(1,e.foodReserve/f)):null,h=e=>Math.max(0,Math.min(1,e.population/p)),g=e=>Math.max(0,Math.min(1,e.morale)),_=6+n*(588/Math.max(1,o-1)),v=typeof i==`number`?6+i*(588/Math.max(1,o-1)):null,y=(e,t)=>{let n=(e-t.left)/t.width*600,r=Math.round((n-6)/588*(o-1));return Math.max(0,Math.min(o-1,r))};return(0,x.jsxs)(`div`,{className:FO.wrap,children:[(0,x.jsxs)(`div`,{className:FO.legend,children:[(0,x.jsxs)(`span`,{children:[`MORALE · POP`,u?` · FOOD`:``,` · T1 → T`,o]}),(0,x.jsxs)(`span`,{className:FO.legendRight,children:[(0,x.jsx)(`span`,{className:FO.legendA,children:`A`}),(0,x.jsx)(`span`,{className:FO.legendB,children:`B`}),(0,x.jsx)(`span`,{className:FO.legendKey,children:`— morale`}),(0,x.jsx)(`span`,{className:FO.legendKey,children:`··· pop`}),u&&(0,x.jsx)(`span`,{className:FO.legendKey,children:`- - food`})]})]}),(0,x.jsxs)(`svg`,{viewBox:`0 0 600 28`,preserveAspectRatio:`none`,role:`img`,"aria-label":`Timeline sparkline of morale, population${u?`, and food`:``} across both leaders`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();r(y(e.clientX,t))},onMouseMove:e=>{if(!a)return;let t=e.currentTarget.getBoundingClientRect();a(y(e.clientX,t))},onMouseLeave:()=>{a?.(null)},className:FO.svg,height:28,children:[(0,x.jsx)(`line`,{x1:6,x2:594,y1:14,y2:14,stroke:`var(--border)`,strokeWidth:.5,strokeDasharray:`2 2`}),c&&(0,x.jsx)(`path`,{d:s(e,m),fill:`none`,stroke:`var(--vis)`,strokeWidth:.8,strokeDasharray:`3 2`,opacity:.45}),l&&(0,x.jsx)(`path`,{d:s(t,m),fill:`none`,stroke:`var(--eng)`,strokeWidth:.8,strokeDasharray:`3 2`,opacity:.45}),(0,x.jsx)(`path`,{d:s(e,h),fill:`none`,stroke:`var(--vis)`,strokeWidth:.7,strokeDasharray:`1 2`,opacity:.5}),(0,x.jsx)(`path`,{d:s(t,h),fill:`none`,stroke:`var(--eng)`,strokeWidth:.7,strokeDasharray:`1 2`,opacity:.5}),(0,x.jsx)(`path`,{d:s(e,g),fill:`none`,stroke:`var(--vis)`,strokeWidth:1.3}),(0,x.jsx)(`path`,{d:s(t,g),fill:`none`,stroke:`var(--eng)`,strokeWidth:1.3}),v!==null&&i!==n&&(0,x.jsx)(`line`,{x1:v,x2:v,y1:0,y2:28,stroke:`var(--text-3)`,strokeWidth:.75,strokeDasharray:`2 3`,opacity:.7}),(0,x.jsx)(`line`,{x1:_,x2:_,y1:0,y2:28,stroke:`var(--amber)`,strokeWidth:1})]}),typeof i==`number`&&(()=>{let n=e[i],r=t[i];if(!n&&!r)return null;let a=i/Math.max(1,o-1)*100,s={"--hover-left":`calc(${a}% + 8px)`,"--hover-translate":a>75?`translateX(calc(-100% - 16px))`:`none`};return(0,x.jsxs)(`div`,{className:FO.tooltip,style:s,children:[(0,x.jsxs)(`div`,{className:FO.tooltipTurn,children:[`T`,i+1,n?.time?` · ${n.time}`:``]}),n&&(0,x.jsxs)(`div`,{className:FO.tooltipRowA,children:[(0,x.jsx)(`span`,{className:FO.tooltipBold,children:`A`}),(0,x.jsxs)(`span`,{children:[`pop `,n.population]}),(0,x.jsxs)(`span`,{children:[`· `,Math.round(n.morale*100),`% mor`]}),typeof n.foodReserve==`number`&&(0,x.jsxs)(`span`,{children:[`· `,n.foodReserve.toFixed(1),`mo`]}),(n.births>0||n.deaths>0)&&(0,x.jsxs)(`span`,{children:[`· +`,n.births,`/-`,n.deaths]})]}),r&&(0,x.jsxs)(`div`,{className:FO.tooltipRowB,children:[(0,x.jsx)(`span`,{className:FO.tooltipBold,children:`B`}),(0,x.jsxs)(`span`,{children:[`pop `,r.population]}),(0,x.jsxs)(`span`,{children:[`· `,Math.round(r.morale*100),`% mor`]}),typeof r.foodReserve==`number`&&(0,x.jsxs)(`span`,{children:[`· `,r.foodReserve.toFixed(1),`mo`]}),(r.births>0||r.deaths>0)&&(0,x.jsxs)(`span`,{children:[`· +`,r.births,`/-`,r.deaths]})]})]})})()]})}var LO={bar:`_bar_3ptrn_1`,heading:`_heading_3ptrn_11`,filterRow:`_filterRow_3ptrn_21`,filterChip:`_filterChip_3ptrn_27`,active:`_active_3ptrn_42`,dotsRow:`_dotsRow_3ptrn_49`,dot:`_dot_3ptrn_49`,hovered:`_hovered_3ptrn_78`,current:`_current_3ptrn_84`},RO=[{key:`all`,label:`All`},{key:`birth`,label:`Births`},{key:`death`,label:`Deaths`},{key:`forge`,label:`Forges`},{key:`crisis`,label:`Crises`}],zO={birth:`rgba(154, 205, 96, 0.95)`,death:`rgba(200, 95, 80, 0.95)`,forge:`rgba(232, 180, 74, 0.95)`,crisis:`rgba(196, 74, 30, 0.95)`},BO={birth:`+`,death:`×`,forge:`▲`,crisis:`⚡`};function VO({eventsA:e,eventsB:t,currentTurn:n,onJumpToTurn:r,onHoverTurnChange:i,hoveredTurn:a,onForgeSelect:o,filter:s,onFilterChange:c,onHoverEventChange:l,onJumpToReports:u}){let d=(0,b.useMemo)(()=>{let n=[],r=(e,t)=>{for(let r of e){let e=Number(r.turn??r.data?.turn??0);if(!(e<=0)){if(r.type===`birth`)n.push({turn:e,kind:`birth`,side:t,label:`T${e}: birth (${t.toUpperCase()})`});else if(r.type===`death`){let i=typeof r.data?.name==`string`?r.data.name:``;n.push({turn:e,kind:`death`,side:t,label:`T${e}: ${i?i+` died`:`death`} (${t.toUpperCase()})`})}else if(r.type===`forge_attempt`){let i=typeof r.data?.name==`string`?r.data.name:`tool`,a=r.data?.approved===!0;n.push({turn:e,kind:`forge`,side:t,label:`T${e}: ${a?`forged`:`rejected`} ${i} (${t.toUpperCase()})`,toolName:i,eventId:r.id})}else if(r.type===`event_start`||r.type===`director_crisis`){let i=typeof r.data?.category==`string`?r.data.category:``;i&&[`political`,`social`,`infrastructure`,`medical`,`resource`,`environmental`].includes(i)&&n.push({turn:e,kind:`crisis`,side:t,label:`T${e}: ${i} crisis (${t.toUpperCase()})`})}}}};return r(e,`a`),r(t,`b`),n.sort((e,t)=>e.turn-t.turn),n.slice(-60)},[e,t]),[f,p]=(0,b.useState)(`all`),m=s??f,h=e=>{s===void 0&&p(e),c?.(e)},g=(0,b.useMemo)(()=>m===`all`?d:d.filter(e=>e.kind===m),[d,m]);return d.length===0?null:(0,x.jsxs)(`div`,{"aria-label":`Event filter`,className:LO.bar,children:[(0,x.jsxs)(`span`,{className:LO.heading,children:[`Events (`,g.length,m===`all`?``:`/${d.length}`,`)`]}),(0,x.jsx)(`div`,{className:LO.filterRow,children:RO.map(e=>{let t=m===e.key;return(0,x.jsx)(`button`,{type:`button`,onClick:()=>h(e.key),"aria-pressed":t,className:[LO.filterChip,t?LO.active:``].filter(Boolean).join(` `),children:e.label},e.key)})}),(0,x.jsx)(`div`,{className:LO.dotsRow,children:g.map((e,t)=>{let s=Math.max(0,e.turn-1),c=s===n,d=a===s,f=[LO.dot,c?LO.current:``,d?LO.hovered:``].filter(Boolean).join(` `),p={"--kind-color":zO[e.kind],"--side-shift":e.side===`a`?`-2px`:`2px`};return(0,x.jsx)(`button`,{type:`button`,onClick:t=>{t.shiftKey&&u?(t.preventDefault(),u(e.turn)):e.kind===`forge`&&e.toolName&&o&&o(e.toolName,e.side,e.eventId,t.currentTarget)!==!1||r(s)},onMouseEnter:()=>{i?.(s),l?.({kind:e.kind,side:e.side,turn:e.turn})},onMouseLeave:()=>{i?.(null),l?.(null)},onFocus:()=>{i?.(s),l?.({kind:e.kind,side:e.side,turn:e.turn})},onBlur:()=>{i?.(null),l?.(null)},title:`${e.label}${u?` · Shift+click to open in Reports`:``}`,"aria-label":e.label,className:f,style:p,children:BO[e.kind]},`${e.turn}-${e.side}-${e.kind}-${t}`)})})]})}var HO={bar:`_bar_n16b7_1`,row:`_row_n16b7_9`,label:`_label_n16b7_21`,track:`_track_n16b7_26`,fill:`_fill_n16b7_35`,count:`_count_n16b7_42`};function UO(e){let t=0;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.type===`turn_done`){let e=Number(r.turn??r.data?.turn??0);if(e>0){t=e;break}}}let n=t+1,r=new Set,i=!1;for(let t of e){let e=Number(t.turn??t.data?.turn??0);if(t.type===`specialist_done`&&e===n){let e=typeof t.data?.department==`string`?t.data.department:``;e&&r.add(e),i=!0}if(t.type===`turn_done`&&e===n)return{inFlightTurn:null,deptsReported:new Set}}return{inFlightTurn:i?n:null,deptsReported:r}}function WO({eventsA:e,eventsB:t,totalDepartments:n}){let r=(0,b.useMemo)(()=>UO(e),[e]),i=(0,b.useMemo)(()=>UO(t),[t]);if(r.inFlightTurn===null&&i.inFlightTurn===null)return null;let a=Math.max(1,n),o=(e,t,n)=>{if(n.inFlightTurn===null)return null;let r=Math.min(100,n.deptsReported.size/a*100);return(0,x.jsxs)(`div`,{className:HO.row,style:{"--side-color":t},children:[(0,x.jsx)(`span`,{className:HO.label,children:e}),(0,x.jsxs)(`span`,{children:[`T`,n.inFlightTurn]}),(0,x.jsx)(`div`,{className:HO.track,children:(0,x.jsx)(`div`,{className:HO.fill,style:{"--bar-pct":`${r}%`}})}),(0,x.jsxs)(`span`,{className:HO.count,children:[n.deptsReported.size,`/`,a]})]})};return(0,x.jsxs)(`div`,{"aria-live":`polite`,className:HO.bar,children:[o(`A`,`var(--vis)`,r),o(`B`,`var(--eng)`,i)]})}var GO={bar:`_bar_3c24d_1`,icon:`_icon_3c24d_11`,label:`_label_3c24d_21`,input:`_input_3c24d_29`,dropdown:`_dropdown_3c24d_42`,option:`_option_3c24d_65`,sidePill:`_sidePill_3c24d_86`,optionName:`_optionName_3c24d_96`,optionMeta:`_optionMeta_3c24d_106`,featuredPill:`_featuredPill_3c24d_115`,moreNote:`_moreNote_3c24d_124`,matchCount:`_matchCount_3c24d_132`,clearBtn:`_clearBtn_3c24d_140`};function KO({value:e,onChange:t,matches:n,onPick:r}){let i=(0,b.useRef)(null),[a,o]=(0,b.useState)(!1),s=n.length,c=Lm();(0,b.useEffect)(()=>{let e=e=>{let t=e.target?.tagName;t!==`INPUT`&&t!==`TEXTAREA`&&t!==`SELECT`&&e.key===`/`&&(e.preventDefault(),i.current?.focus())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]);let l=a&&e.trim().length>0&&n.length>0;return(0,x.jsxs)(`div`,{className:GO.bar,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:GO.icon,title:`Search agents`,children:`🔍`}),(0,x.jsx)(`span`,{className:GO.label,children:`Find`}),(0,x.jsx)(`input`,{ref:i,type:`text`,value:e,onChange:e=>t(e.target.value),onFocus:()=>o(!0),onBlur:()=>setTimeout(()=>o(!1),120),placeholder:`${c.person} name, dept, mood… (space-separate to AND-match; / to focus)`,"aria-label":`Search ${c.people} by name, department, role, or mood`,className:GO.input}),l&&(0,x.jsxs)(`div`,{role:`listbox`,className:GO.dropdown,children:[n.slice(0,10).map((e,t)=>(0,x.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":`false`,onMouseDown:t=>{t.preventDefault(),r?.(e)},className:GO.option,style:{"--result-color":e.sideColor},children:[(0,x.jsx)(`span`,{className:GO.sidePill,children:e.side.toUpperCase()}),(0,x.jsx)(`span`,{className:GO.optionName,children:e.cell.name}),(0,x.jsxs)(`span`,{className:GO.optionMeta,children:[e.cell.department?.toUpperCase?.()||``,` · `,e.cell.mood,typeof e.cell.age==`number`?` · age ${e.cell.age}`:``]}),e.cell.featured&&(0,x.jsx)(`span`,{className:GO.featuredPill,children:`FEATURED`})]},`${e.side}-${e.cell.agentId}-${t}`)),n.length>10&&(0,x.jsxs)(`div`,{className:GO.moreNote,children:[`+ `,n.length-10,` more…`]})]}),e&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`span`,{className:GO.matchCount,style:{"--count-color":s>0?`var(--amber)`:`var(--rust)`},children:[s,` match`,s===1?``:`es`]}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>t(``),"aria-label":`Clear search`,className:GO.clearBtn,children:`clear`})]})]})}function qO(e,t,n,r=.04,i=`sine`){let a=e.currentTime,o=e.createOscillator(),s=e.createGain();o.type=i,o.frequency.setValueAtTime(t,a),s.gain.setValueAtTime(0,a),s.gain.linearRampToValueAtTime(r,a+.008),s.gain.exponentialRampToValueAtTime(1e-4,a+n),o.connect(s),s.connect(e.destination),o.start(a),o.stop(a+n+.02)}function JO(e,t){switch(t){case`birth`:qO(e,880,.18,.05,`triangle`),setTimeout(()=>qO(e,1320,.12,.03,`triangle`),70);break;case`death`:qO(e,160,.35,.05,`sine`);break;case`forge`:qO(e,660,.12,.04,`sine`);break;case`crisis`:qO(e,220,.22,.05,`sawtooth`),setTimeout(()=>qO(e,180,.18,.045,`sawtooth`),120)}}function YO(e){let t=(0,b.useRef)(null),n=(0,b.useRef)(new Set),r=(0,b.useRef)(-1),i=(0,b.useRef)(-1),a=()=>{if(!e.enabled)return null;if(t.current)return t.current;try{let e=window.AudioContext??window.webkitAudioContext;return e?(t.current=new e,t.current):null}catch{return null}};(0,b.useEffect)(()=>{if(!e.enabled)return;let n=()=>{let e=t.current;e&&e.state===`suspended`&&e.resume().catch(()=>{})};return window.addEventListener(`click`,n),window.addEventListener(`keydown`,n),()=>{window.removeEventListener(`click`,n),window.removeEventListener(`keydown`,n)}},[e.enabled]),(0,b.useEffect)(()=>{if(!e.enabled)return;let t=(e,t,r,i)=>{if(!e||!t||e.turn===i.current)return;i.current=e.turn;let o=a();if(!o)return;let s=gD(t.cells,e.cells),c=0,l=0;for(let t of s.born){let i=`${r}|t${e.turn}|birth|${t.agentId}`;n.current.has(i)||(n.current.add(i),c+=1)}for(let t of s.died){let i=`${r}|t${e.turn}|death|${t.agentId}`;n.current.has(i)||(n.current.add(i),l+=1)}c>0&&JO(o,`birth`),l>0&&setTimeout(()=>JO(o,`death`),c>0?300:0)};t(e.snapshotA,e.prevSnapshotA,`a`,r),t(e.snapshotB,e.prevSnapshotB,`b`,i)},[e.enabled,e.snapshotA,e.prevSnapshotA,e.snapshotB,e.prevSnapshotB]),(0,b.useEffect)(()=>{if(!e.enabled)return;let t=a();if(!t)return;let r=(e,r)=>{for(let i of e){if(!i.approved)continue;let e=`${r}|forge|${i.turn}|${i.eventIndex}|${i.name}`;n.current.has(e)||(n.current.add(e),JO(t,`forge`))}};r(e.forgeAttemptsA,`a`),r(e.forgeAttemptsB,`b`)},[e.enabled,e.forgeAttemptsA,e.forgeAttemptsB])}var XO={backdrop:`_backdrop_nnlpn_1`,dialog:`_dialog_nnlpn_12`,header:`_header_nnlpn_24`,title:`_title_nnlpn_31`,closeBtn:`_closeBtn_nnlpn_41`,sidesRow:`_sidesRow_nnlpn_54`,sideBlock:`_sideBlock_nnlpn_61`,sideName:`_sideName_nnlpn_71`,statsGrid:`_statsGrid_nnlpn_81`,cell:`_cell_nnlpn_87`,cellLabel:`_cellLabel_nnlpn_93`,cellValue:`_cellValue_nnlpn_101`,empty:`_empty_nnlpn_108`,divergenceBox:`_divergenceBox_nnlpn_113`,divergenceLabel:`_divergenceLabel_nnlpn_125`,divergenceCount:`_divergenceCount_nnlpn_132`,divergenceCopy:`_divergenceCopy_nnlpn_138`};function ZO(e){if(e.length===0)return null;let t=0,n=0,r=0,i=0,a=0,o=0,s=1/0,c=1/0;for(let l of e)t+=l.births,n+=l.deaths,l.population>r&&(r=l.population),i+=l.morale,typeof l.foodReserve==`number`&&(a+=l.foodReserve,o++,l.foodReserve<c&&(c=l.foodReserve)),l.morale<s&&(s=l.morale);return{turns:e.length,totalBirths:t,totalDeaths:n,peakPop:r,finalPop:e[e.length-1].population,avgMorale:i/e.length,minMorale:s===1/0?0:s,avgFood:o>0?a/o:void 0,minFood:o>0?c:void 0}}function QO(e){let{open:t,onClose:n}=e,r=Lm();(0,b.useEffect)(()=>{if(!t)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),n())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[t,n]);let i=(0,b.useMemo)(()=>ZO(e.snapsA),[e.snapsA]),a=(0,b.useMemo)(()=>ZO(e.snapsB),[e.snapsB]);if(!t)return null;let o=(e,t,n)=>(0,x.jsxs)(`div`,{className:XO.cell,children:[(0,x.jsx)(`span`,{className:XO.cellLabel,children:e}),(0,x.jsx)(`span`,{className:XO.cellValue,style:n?{"--val-color":n}:void 0,children:t})]}),s=(e,t,n,r,i)=>(0,x.jsxs)(`div`,{className:XO.sideBlock,style:{"--side-color":t},children:[(0,x.jsx)(`div`,{className:XO.sideName,children:e}),n?(0,x.jsxs)(`div`,{className:XO.statsGrid,children:[o(`Turns`,`${n.turns}`),o(`Final pop`,`${n.finalPop}`,t),o(`Peak pop`,`${n.peakPop}`),o(`Total births`,`${n.totalBirths}`,`rgba(106, 173, 72, 0.95)`),o(`Total deaths`,`${n.totalDeaths}`,`rgba(200, 95, 80, 0.95)`),o(`Avg morale`,`${Math.round(n.avgMorale*100)}%`),o(`Min morale`,`${Math.round(n.minMorale*100)}%`,n.minMorale<.3?`var(--rust)`:`var(--text-1)`),n.minFood!==void 0&&o(`Min food`,`${n.minFood.toFixed(1)}mo`,n.minFood<3?`var(--rust)`:`var(--text-1)`),o(`Tools forged`,`${r}`,`var(--amber)`),o(`Tool reuses`,`${i}`,`var(--amber)`)]}):(0,x.jsx)(`div`,{className:XO.empty,children:`No snapshots yet.`})]});return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Run summary`,onClick:n,className:XO.backdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:XO.dialog,children:[(0,x.jsxs)(`div`,{className:XO.header,children:[(0,x.jsxs)(`h2`,{className:XO.title,children:[`Run Summary · `,e.snapsA.length||e.snapsB.length,` turns`]}),(0,x.jsx)(`button`,{type:`button`,onClick:n,"aria-label":`Close run summary`,className:XO.closeBtn,children:`×`})]}),(0,x.jsxs)(`div`,{className:XO.sidesRow,children:[s(e.actorNameA,`var(--vis)`,i,e.forgeApprovedA,e.reuseCountA),s(e.actorNameB,`var(--eng)`,a,e.forgeApprovedB,e.reuseCountB)]}),(0,x.jsxs)(`div`,{className:XO.divergenceBox,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:XO.divergenceLabel,children:`Divergence`}),(0,x.jsx)(`div`,{className:XO.divergenceCount,children:e.divergedCount})]}),(0,x.jsxs)(`div`,{className:XO.divergenceCopy,children:[r.People,` alive on one side but dead on the other at the final snapshot — a measure of how much the two leaders' decisions diverged the outcomes.`]})]})]})})}var $O={anchor:`_anchor_ypvfl_1`,trigger:`_trigger_ypvfl_5`,triggerOpen:`_triggerOpen_ypvfl_21`,recDot:`_recDot_ypvfl_27`,"paracosm-rec-pulse":`_paracosm-rec-pulse_ypvfl_1`,menu:`_menu_ypvfl_36`,item:`_item_ypvfl_51`,itemRecording:`_itemRecording_ypvfl_71`,itemKey:`_itemKey_ypvfl_75`,itemKeyRecording:`_itemKeyRecording_ypvfl_81`,itemDesc:`_itemDesc_ypvfl_85`},ek=8,tk=4,nk={top:0,left:0,visibility:`hidden`},rk=`a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`;function ik(e){let t=e.getBoundingClientRect(),n=t.left+t.width/2,r=t.top+t.height/2;if(n<0||r<0||n>window.innerWidth||r>window.innerHeight)return!1;for(let t=e.parentElement;t&&t!==document.body;t=t.parentElement){let e=getComputedStyle(t);if(e.overflowX===`visible`&&e.overflowY===`visible`)continue;let i=t.getBoundingClientRect();if(n<i.left||n>i.right||r<i.top||r>i.bottom)return!1}return!0}function ak({recording:e,onExportPng:t,onExportJson:n,onToggleRecording:r}){let[i,a]=(0,b.useState)(!1),[o,s]=(0,b.useState)(null),c=(0,b.useRef)(null),l=(0,b.useRef)(null),u=(0,b.useRef)(null),d=(0,b.useRef)(!1),f=()=>Array.from(u.current?.querySelectorAll(`[role="menuitem"]`)??[]),p=(0,b.useCallback)(e=>{a(!1),e&&l.current?.focus()},[]);(0,b.useLayoutEffect)(()=>{if(!i){s(null);return}let e=()=>{let e=l.current;if(!e)return;if(!ik(e)){a(!1);return}let t=e.getBoundingClientRect(),n=window.innerHeight-t.bottom-tk-ek,r=t.top-tk-ek,i=(u.current?.scrollHeight??0)>n&&r>n;s({...i?{bottom:window.innerHeight-t.top+tk,maxHeight:Math.max(0,r)}:{top:t.bottom+tk,maxHeight:Math.max(0,n)},...t.right>=188?{right:Math.max(ek,window.innerWidth-t.right)}:{left:Math.max(ek,t.left)}})};e(),window.addEventListener(`resize`,e),document.addEventListener(`scroll`,e,!0);let t=()=>{let e=l.current?.getBoundingClientRect();return e?`${e.left} ${e.top} ${e.right} ${e.bottom}`:``},n=t(),r=0,o=()=>{let i=t();i!==n&&(n=i,e()),r=requestAnimationFrame(o)};return r=requestAnimationFrame(o),()=>{cancelAnimationFrame(r),window.removeEventListener(`resize`,e),document.removeEventListener(`scroll`,e,!0)}},[i]),(0,b.useLayoutEffect)(()=>{i&&o&&d.current&&(d.current=!1,u.current?.querySelector(`[role="menuitem"]`)?.focus({preventScroll:!0}))},[i,o]),(0,b.useEffect)(()=>{if(!i)return;let e=e=>{let t=e.target;c.current?.contains(t)||u.current?.contains(t)||a(!1)},t=e=>{e.key===`Escape`&&a(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[i]);let m=e=>{let t=f(),n=t.indexOf(document.activeElement);if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault();let r=e.key===`ArrowDown`?1:-1;t[n<0?r>0?0:t.length-1:(n+r+t.length)%t.length]?.focus()}else if(e.key===`Home`||e.key===`End`)e.preventDefault(),t[e.key===`Home`?0:t.length-1]?.focus();else if(e.key===`Escape`)e.preventDefault(),p(!0);else if(e.key===`Tab`){e.preventDefault();let t=l.current;if(p(!0),!e.shiftKey&&t){let e=Array.from(document.querySelectorAll(rk)).filter(e=>!u.current?.contains(e)&&e.getClientRects().length>0);e[e.indexOf(t)+1]?.focus()}}},h=e=>()=>{p(!0),e()};return(0,x.jsxs)(`div`,{ref:c,className:$O.anchor,children:[(0,x.jsxs)(`button`,{ref:l,type:`button`,onClick:()=>{i||(d.current=!0),a(e=>!e)},"aria-expanded":i,"aria-haspopup":`menu`,"aria-label":`Export options`,title:e?`Recording in progress — click for options`:`Export options`,className:[$O.trigger,i?$O.triggerOpen:``].filter(Boolean).join(` `),children:[e&&(0,x.jsx)(`span`,{"aria-hidden":`true`,className:$O.recDot}),`EXPORT ▼`]}),i&&(0,Ay.createPortal)((0,x.jsxs)(`div`,{ref:u,role:`menu`,className:$O.menu,style:o??nk,onKeyDown:m,children:[(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:h(t),className:$O.item,children:[(0,x.jsx)(`span`,{className:$O.itemKey,children:`PNG`}),(0,x.jsx)(`span`,{className:$O.itemDesc,children:`Current frame`})]}),(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:h(r),className:[$O.item,e?$O.itemRecording:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`span`,{className:[$O.itemKey,e?$O.itemKeyRecording:``].filter(Boolean).join(` `),children:e?`STOP`:`REC`}),(0,x.jsx)(`span`,{className:$O.itemDesc,children:e?`End recording & download`:`Timelapse to webm`})]}),(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:h(n),className:$O.item,children:[(0,x.jsx)(`span`,{className:$O.itemKey,children:`JSON`}),(0,x.jsx)(`span`,{className:$O.itemDesc,children:`Replay snapshot`})]})]}),document.body)]})}var ok={strip:`_strip_deb88_1`,text:`_text_deb88_20`,expand:`_expand_deb88_24`},sk=120;function ck({text:e,turn:t}){let[n,r]=(0,b.useState)(!1),i=e.length>sk,a=i&&!n?`${e.slice(0,119)}…`:e;return(0,x.jsxs)(`div`,{className:ok.strip,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,"data-turn":t,children:[(0,x.jsx)(`span`,{className:ok.text,children:a}),i&&(0,x.jsx)(`button`,{type:`button`,className:ok.expand,onClick:()=>r(e=>!e),"aria-expanded":n,children:n?`Less`:`More`})]})}var lk={bar:`_bar_1u6wg_1`,glyphRow:`_glyphRow_1u6wg_21`,label:`_label_1u6wg_28`,glyph:`_glyph_1u6wg_21`,band:`_band_1u6wg_39`,agent:`_agent_1u6wg_43`,featured:`_featured_1u6wg_49`,turn:`_turn_1u6wg_56`,fullLegend:`_fullLegend_1u6wg_68`,popover:`_popover_1u6wg_89`,popHeading:`_popHeading_1u6wg_107`,deptSwatch:`_deptSwatch_1u6wg_135`,closeBtn:`_closeBtn_1u6wg_145`};function uk({departments:e}){let[t,n]=(0,b.useState)(!1),r=Pt(t),i=(0,b.useRef)(null);return(0,b.useEffect)(()=>{if(!t)return;let e=e=>{e.key===`Escape`&&n(!1)},r=e=>{let t=e.target;t&&i.current&&!i.current.contains(t)&&n(!1)};return window.addEventListener(`keydown`,e),window.addEventListener(`mousedown`,r),()=>{window.removeEventListener(`keydown`,e),window.removeEventListener(`mousedown`,r)}},[t]),(0,x.jsxs)(`div`,{className:lk.bar,"aria-label":`Visualization legend`,ref:i,children:[(0,x.jsxs)(`span`,{className:lk.glyphRow,children:[(0,x.jsx)(dk,{type:`band`}),(0,x.jsx)(`span`,{className:lk.label,children:`Department band`}),(0,x.jsx)(dk,{type:`agent`}),(0,x.jsx)(`span`,{className:lk.label,children:`Agent`}),(0,x.jsx)(dk,{type:`featured`}),(0,x.jsx)(`span`,{className:lk.label,children:`Featured agent`}),(0,x.jsx)(dk,{type:`turn`}),(0,x.jsx)(`span`,{className:lk.label,children:`Turn marker`})]}),(0,x.jsx)(`button`,{type:`button`,className:lk.fullLegend,onClick:()=>n(e=>!e),"aria-expanded":t,"aria-haspopup":`dialog`,children:`Show full legend`}),t&&(0,x.jsxs)(`div`,{className:lk.popover,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`viz-legend-heading`,tabIndex:-1,ref:r,children:[(0,x.jsx)(`h3`,{id:`viz-legend-heading`,className:lk.popHeading,children:`What you’re looking at`}),(0,x.jsxs)(`section`,{children:[(0,x.jsx)(`h4`,{children:`Departments (tile color)`}),(0,x.jsx)(`ul`,{className:lk.deptList,children:e.map(e=>(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`span`,{className:lk.deptSwatch,style:{background:e.color},"aria-hidden":`true`}),e.label]},e.id))})]}),(0,x.jsxs)(`section`,{children:[(0,x.jsx)(`h4`,{children:`Mood tiers (chip glyph)`}),(0,x.jsxs)(`ul`,{className:lk.moodList,children:[(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`▼`}),` low (under 25% morale)`]}),(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`▽`}),` tense (25–50%)`]}),(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`△`}),` steady (50–75%)`]}),(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`▲`}),` rising (over 75%)`]})]})]}),(0,x.jsx)(`button`,{type:`button`,className:lk.closeBtn,onClick:()=>n(!1),"aria-label":`Close legend`,children:`Close (Esc)`})]})]})}function dk({type:e}){switch(e){case`band`:return(0,x.jsx)(`span`,{className:`${lk.glyph} ${lk.band}`,"aria-hidden":`true`});case`agent`:return(0,x.jsx)(`span`,{className:`${lk.glyph} ${lk.agent}`,"aria-hidden":`true`});case`featured`:return(0,x.jsx)(`span`,{className:`${lk.glyph} ${lk.featured}`,"aria-hidden":`true`});case`turn`:return(0,x.jsx)(`span`,{className:`${lk.glyph} ${lk.turn}`,"aria-hidden":`true`,children:`T`})}}var fk={panel:`_panel_15qsw_1`,eyebrow:`_eyebrow_15qsw_15`,empty:`_empty_15qsw_23`,chipRow:`_chipRow_15qsw_27`,chip:`_chip_15qsw_27`,chipLight:`_chipLight_15qsw_47`,chipStrong:`_chipStrong_15qsw_53`,chipDept:`_chipDept_15qsw_59`,chipCount:`_chipCount_15qsw_63`},pk=8;function mk({diff:e,departmentLabels:t}){let n=Array.from(e.entries()).filter(([,e])=>e.magnitude>0).sort(([,e],[,t])=>t.magnitude-e.magnitude).slice(0,pk);return n.length===0?(0,x.jsxs)(`div`,{className:fk.panel,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:fk.eyebrow,children:`Divergence detail`}),(0,x.jsx)(`span`,{className:fk.empty,children:`No department-level divergence at this turn.`})]}):(0,x.jsxs)(`div`,{className:fk.panel,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:fk.eyebrow,children:`Divergence detail`}),(0,x.jsx)(`ul`,{className:fk.chipRow,children:n.map(([e,n])=>{let r=t[e]??e,i=n.magnitude>=.5,a=`${r}: A has ${n.aState.agentCount} agents (${n.aState.dominantMood} mood); B has ${n.bState.agentCount} agents (${n.bState.dominantMood} mood)`;return(0,x.jsxs)(`li`,{className:`${fk.chip} ${i?fk.chipStrong:fk.chipLight}`,title:a,"aria-label":a,children:[(0,x.jsx)(`span`,{className:fk.chipDept,children:r}),(0,x.jsxs)(`span`,{className:fk.chipCount,children:[`A `,n.aState.agentCount,` / B `,n.bState.agentCount]})]},e)})})]})}var hk=.2;function gk(e,t){return{population:e.population,morale:e.morale,deathsThisTurn:e.deaths,birthsThisTurn:e.births,eventCategories:e.eventCategories??[],year:e.time}}var _k={nameA:`Leader A`,nameB:`Leader B`,person:`colonist`,people:`colonists`,places:`colonies`};function vk(e,t,n,r=_k){if(!e||!t)return`Awaiting first turn snapshot.`;let i=e.year??t.year;if(e.deathsThisTurn!==t.deathsThisTurn){let a=e.deathsThisTurn>t.deathsThisTurn,o=a?r.nameA:r.nameB,s=a?r.nameB:r.nameA,c=Math.max(e.deathsThisTurn,t.deathsThisTurn),l=Math.min(e.deathsThisTurn,t.deathsThisTurn),u=e=>e===0?`none`:`${e} ${e===1?r.person:r.people}`;return`Turn ${n}, year ${i}: ${o} lost ${u(c)}; ${s} lost ${u(l)}.`}if(Math.abs(e.morale-t.morale)>=hk){let a=e.morale<t.morale,o=a?r.nameA:r.nameB,s=a?r.nameB:r.nameA,c=a?e.morale:t.morale,l=a?t.morale:e.morale;return`Turn ${n}, year ${i}: ${o}'s morale collapsed to ${yk(c)}; ${s} held ${yk(l)}.`}let a=e.eventCategories.join(`|`),o=t.eventCategories.join(`|`);return a&&o&&a!==o?`Turn ${n}, year ${i}: different events. ${r.nameA}: ${e.eventCategories.join(`, `)}; ${r.nameB}: ${t.eventCategories.join(`, `)}.`:n===1&&a&&a===o?`Turn 1, year ${i}: identical first event (${e.eventCategories.join(`, `)}). Both ${r.places} start from the same state.`:`Turn ${n}, year ${i}: ${r.nameA} and ${r.nameB} tracked closely. See sub-tabs for details.`}function yk(e){return`${Math.round(e*100)}%`}function bk(e,t){let n=new Map,r=new Map(e.map(e=>[e.cellKey,e])),i=new Map(t.map(e=>[e.cellKey,e])),a=new Set([...r.keys(),...i.keys()]);for(let e of a){let t=r.get(e)??xk(e),a=i.get(e)??xk(e),o=Math.max(t.agentCount,a.agentCount,1),s=Math.abs(t.agentCount-a.agentCount)/o,c=t.dominantMood===a.dominantMood?0:1,l=t.department===a.department?0:1,u=(s+c+l)/3;n.set(e,{magnitude:u,aState:t,bState:a})}return n}function xk(e){return{cellKey:e,department:``,agentCount:0,dominantMood:`steady`}}var Sk={medical:`#4ecdc4`,engineering:`#e8b44a`,agriculture:`#6aad48`,psychology:`#9b6b9e`,governance:`#e06530`};function Ck(e,t){let n=new Set,r=new Set;if(!e||!t)return{aliveOnlyA:n,aliveOnlyB:r};let i=new Map(e.cells.map(e=>[e.agentId,e])),a=new Map(t.cells.map(e=>[e.agentId,e]));for(let[e,t]of i){let r=a.get(e);!t.alive||r&&r.alive||n.add(e)}for(let[e,t]of a){let n=i.get(e);!t.alive||n&&n.alive||r.add(e)}return{aliveOnlyA:n,aliveOnlyB:r}}function wk(e){if(!e)return[];let t=new Map;for(let n of e.cells){if(!n.alive)continue;let e=n.department||`unknown`,r=t.get(e);r||(r={count:0,moods:{}},t.set(e,r)),r.count+=1;let i=n.mood||`neutral`;r.moods[i]=(r.moods[i]??0)+1}let n=[];for(let[e,r]of t){let t=Object.entries(r.moods).sort((e,t)=>t[1]-e[1])[0]?.[0]??`neutral`;n.push({cellKey:e,department:e,agentCount:r.count,dominantMood:t})}return n}function Tk({k:e,v:t}){return(0,x.jsxs)(`span`,{className:$.kbd,children:[(0,x.jsx)(`kbd`,{className:$.kbdKey,children:e}),(0,x.jsx)(`span`,{className:$.kbdLabel,children:t})]})}function Ek(e){return e?[e.foodReserve,e.waterLitersPerDay,e.powerKw,e.pressurizedVolumeM3].some(e=>typeof e==`number`):!1}var Dk=`button, a[href], summary, [role="button"], [role="link"], [role="menuitem"], [role="option"], [role="checkbox"], [role="radio"], [role="switch"], [role="tab"]`;function Ok({state:e,onNavigateToChat:t}){let n=HE(e),r=e.actorIds[0],i=e.actorIds[1],[a,o]=(0,b.useState)(r),[s,c]=(0,b.useState)(i);(0,b.useEffect)(()=>{a&&!e.actorIds.includes(a)&&o(r),s&&!e.actorIds.includes(s)&&c(i)},[e.actorIds,a,s,r,i]);let l=a??r,u=s??i,d=(l?n[l]:void 0)??[],f=(u?n[u]:void 0)??[],p=l?e.actors[l]:null,m=u?e.actors[u]:null,h=e.actorIds.length>2,[g,_]=(0,b.useState)(h?`cohort`:`pair`);(0,b.useEffect)(()=>{_(h?`cohort`:`pair`)},[h]);let v=Math.max(d.length,f.length),[y,S]=(0,b.useState)(0),[C,w]=(0,b.useState)(!1),[T,E]=(0,b.useState)(1),[D,O]=(0,b.useState)(()=>{try{let e=localStorage.getItem(`paracosm:gridMode`);if(e===`living`||e===`mood`||e===`forge`||e===`ecology`||e===`divergence`)return e}catch{}return`living`}),k=(0,b.useCallback)(e=>{O(e);try{localStorage.setItem(`paracosm:gridMode`,e)}catch{}},[]),{toast:A}=Ht(),j=(0,b.useRef)(0),ee=(0,b.useRef)(0);(0,b.useEffect)(()=>{let e=ee.current;ee.current=v,v>e&&!C&&S(v-1)},[v,C]),(0,b.useEffect)(()=>{if(!C)return;let e=2e3/T;return j.current=window.setInterval(()=>{S(e=>e>=v-1?(w(!1),e):e+1)},e),()=>clearInterval(j.current)},[C,T,v]);let te=(0,b.useCallback)(()=>{v<=1||w(e=>(!e&&y>=v-1&&S(0),!e))},[y,v]),M=(0,b.useCallback)(()=>{w(!1),S(e=>Math.max(0,e-1))},[]),N=(0,b.useCallback)(()=>{w(!1),S(e=>Math.min(v-1,e+1))},[v]),ne=(0,b.useCallback)(e=>{w(!1),S(e)},[]),P=eA(),re=(0,b.useCallback)(e=>{P(`reports`),requestAnimationFrame(()=>{let t=document.getElementById(`turn-${e}`);t&&t.scrollIntoView({behavior:`smooth`,block:`start`})})},[P]),[ie,F]=(0,b.useState)(!1),I=Xk(),ae=Lm(),[oe,ce]=(0,b.useState)(null),[le,L]=(0,b.useState)(null),[ue,de]=(0,b.useState)(null),[fe,R]=(0,b.useState)(`all`),[z,pe]=(0,b.useState)(null),[me,he]=(0,b.useState)(``),[ge,_e]=(0,b.useState)(null),[B,ve]=(0,b.useState)(()=>{try{let e=localStorage.getItem(`paracosm:gridSettings`);if(e){let t=JSON.parse(e);if(t.__v===3)return rO(t);localStorage.removeItem(`paracosm:gridSettings`)}}catch{}return nO}),ye=(0,b.useCallback)(e=>{ve(e);try{localStorage.setItem(`paracosm:gridSettings`,JSON.stringify({...e,__v:3}))}catch{}},[]);(0,b.useEffect)(()=>{if(!B.alerts||!e.isRunning)return;let t=new Set([`event_start`,`director_crisis`]),n=`paracosm:seenCrisisToasts`,r=()=>{try{let e=sessionStorage.getItem(n);return e?new Set(JSON.parse(e)):new Set}catch{return new Set}},i=e=>{try{let t=[...e].slice(-200);sessionStorage.setItem(n,JSON.stringify(t))}catch{}},a=r(),o=(()=>{let n=null,r=[];l&&r.push({side:`a`,actorName:l}),u&&r.push({side:`b`,actorName:u});for(let{side:i,actorName:o}of r){let r=e.actors[o];if(!r)continue;let s=r.events;for(let e=s.length-1;e>=0;e--){let r=s[e];if(!t.has(r.type))continue;let o=Number(r.turn??r.data?.turn??0),c=typeof r.data?.category==`string`?r.data.category:``;if(!c)continue;let l=`${i}:${o}:${c}`;if(a.has(l))continue;let u=typeof r.data?.title==`string`?r.data.title:``;(!n||o>n.turn)&&(n={key:l,side:i,turn:o,category:c,title:u});break}}return n})();o&&(a.add(o.key),i(a),_e(e=>e&&e.key===o.key?e:{...o,expiresAt:performance.now()+5500}))},[e.actorIds,e.actors,B.alerts,e.isRunning]),(0,b.useEffect)(()=>{if(!ge)return;let e=ge.expiresAt-performance.now();if(e<=0){_e(null);return}let t=setTimeout(()=>_e(null),e);return()=>clearTimeout(t)},[ge]);let[be,xe]=(0,b.useState)(null),Se=`paracosm:seenThresholdAlerts`,Ce=(0,b.useCallback)(()=>{try{let e=sessionStorage.getItem(Se);return e?new Set(JSON.parse(e)):new Set}catch{return new Set}},[]),we=(0,b.useCallback)(e=>{try{sessionStorage.setItem(Se,JSON.stringify([...e].slice(-200)))}catch{}},[]);(0,b.useEffect)(()=>{if(!B.alerts||!e.isRunning)return;let t=Ce(),n=(e,n)=>{t.has(e)||(t.add(e),xe({key:e,...n,expiresAt:performance.now()+5500}))},r=(e,t)=>{if(t.length<2)return;let r=t[t.length-1],i=t[t.length-2],a=i.morale-r.morale;a>=.2&&n(`${e}|${r.turn}|morale-crash`,{side:e,turn:r.turn,kind:`morale-crash`,message:`Morale crashed ${Math.round(a*100)}% → ${Math.round(r.morale*100)}% this turn`}),typeof r.foodReserve==`number`&&typeof i.foodReserve==`number`&&r.foodReserve<3&&i.foodReserve>=3&&n(`${e}|${r.turn}|food-low`,{side:e,turn:r.turn,kind:`food-low`,message:`Food reserve fell below 3mo (${r.foodReserve.toFixed(1)}mo remaining)`})};r(`a`,d),r(`b`,f),we(t)},[d,f,B.alerts,Ce,we,e.isRunning]),(0,b.useEffect)(()=>{if(!be)return;let e=be.expiresAt-performance.now();if(e<=0){xe(null);return}let t=setTimeout(()=>xe(null),e);return()=>clearTimeout(t)},[be]);let[Te,Ee]=(0,b.useState)(()=>{try{let e=localStorage.getItem(`paracosm:gridPalette`);if(e===`cool`||e===`mono`||e===`amber`)return e}catch{}return`amber`}),De=(0,b.useCallback)(e=>{Ee(e);try{localStorage.setItem(`paracosm:gridPalette`,e)}catch{}},[]),Oe=(0,b.useCallback)(()=>{De(Te===`amber`?`cool`:Te===`cool`?`mono`:`amber`)},[Te,De]),[ke,Ae]=(0,b.useState)(!1),[je,Me]=(0,b.useState)(!1),[Ne,Pe]=(0,b.useState)(!1),Fe=ev(),Ie=D_(),Le=(0,b.useCallback)((t,n,r,i)=>{let a=n===`a`?l:u,o=a?e.actorIds.indexOf(a):-1,s=o>=0?Ie.getEntryFor(o,t):void 0;if(!s)return!1;let c=s.attempts.find(e=>e.eventId===r)?.attempt;return Fe.openTrace({actorIndex:o,toolName:t,attempt:c},i,`viz`),!0},[l,u,e.actorIds,Ie,Fe]),[Re,ze]=(0,b.useState)(null),Be=(0,b.useCallback)(e=>{ze(t=>t===e?null:e)},[]),Ve=d[y]??d[d.length-1],He=f[y]??f[f.length-1],Ue=Ve?.turn??0,We=He?.turn??0,Ge=I.presets.find(e=>e.id==="default"),Ke=Ge?.leaders??Ge?.actors,qe=Ke?.[0]?{name:Ke[0].name,archetype:Ke[0].archetype,unit:se(I,0),hexaco:Ke[0].hexaco,instructions:Ke[0].instructions,quote:``}:null,Je=Ke?.[1]?{name:Ke[1].name,archetype:Ke[1].archetype,unit:se(I,1),hexaco:Ke[1].hexaco,instructions:Ke[1].instructions,quote:``}:null,Ye=p?.leader??qe,Xe=m?.leader??Je,Ze=(0,b.useRef)(null),[Qe,$e]=(0,b.useState)(!1),et=(0,b.useRef)(null),tt=(0,b.useRef)([]),nt=(0,b.useRef)(null),rt=(0,b.useRef)(0),it=(0,b.useCallback)(()=>{let e=Ze.current;if(!e)return;let t=e.getBoundingClientRect(),n=Math.max(640,Math.round(t.width)),r=Math.max(360,Math.round(t.height)),i=document.createElement(`canvas`);if(i.width=n,i.height=r,!i.getContext(`2d`))return;nt.current=i;let a=i.captureStream(30),o=`video/webm;codecs=vp9`;typeof MediaRecorder<`u`&&!MediaRecorder.isTypeSupported(o)&&(o=`video/webm;codecs=vp8`,MediaRecorder.isTypeSupported(o)||(o=`video/webm`));let s;try{s=new MediaRecorder(a,{mimeType:o,videoBitsPerSecond:4e6})}catch{console.warn(`MediaRecorder unavailable — timelapse skipped`);return}tt.current=[],s.ondataavailable=e=>{e.data&&e.data.size>0&&tt.current.push(e.data)},s.onstop=()=>{rt.current&&cancelAnimationFrame(rt.current),rt.current=0;let e=new Blob(tt.current,{type:o}),t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`paracosm-timelapse-${new Date().toISOString().replace(/[:.]/g,`-`).slice(0,19)}.webm`,document.body.appendChild(n),n.click(),document.body.removeChild(n),setTimeout(()=>URL.revokeObjectURL(t),1e3)},et.current=s,$e(!0),s.start();let c=()=>{let e=nt.current,t=Ze.current;if(!e||!t)return;let n=e.getContext(`2d`);if(!n)return;n.fillStyle=getComputedStyle(t).getPropertyValue(`--bg-deep`).trim()||`#0a0806`,n.fillRect(0,0,e.width,e.height);let r=t.getBoundingClientRect(),i=e.width/Math.max(1,r.width),a=e.height/Math.max(1,r.height),o=Array.from(t.querySelectorAll(`canvas`));for(let e of o){let t=e.getBoundingClientRect();t.width!==0&&t.height!==0&&n.drawImage(e,(t.left-r.left)*i,(t.top-r.top)*a,t.width*i,t.height*a)}rt.current=requestAnimationFrame(c)};rt.current=requestAnimationFrame(c)},[]),at=(0,b.useCallback)(()=>{let e=et.current;if(e){try{e.stop()}catch{}et.current=null,$e(!1)}},[]);(0,b.useEffect)(()=>()=>{if(et.current)try{et.current.stop()}catch{}rt.current&&cancelAnimationFrame(rt.current)},[]);let ot=(0,b.useCallback)(()=>{let e={exportedAt:new Date().toISOString(),leaderA:{name:Ye?.name??`Leader A`,archetype:Ye?.archetype??``},leaderB:{name:Xe?.name??`Leader B`,archetype:Xe?.archetype??``},currentTurn:y,snapshots:{a:d,b:f},events:{a:p?.events??[],b:m?.events??[]}},t=new Blob([JSON.stringify(e,null,2)],{type:`application/json`}),n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=`paracosm-replay-${new Date().toISOString().replace(/[:.]/g,`-`).slice(0,19)}.json`,document.body.appendChild(r),r.click(),document.body.removeChild(r),setTimeout(()=>URL.revokeObjectURL(n),1e3)},[y,Ye,Xe,d,f,p,m]),st=(0,b.useCallback)(()=>{let e=Ze.current;if(!e)return;let t=Array.from(e.querySelectorAll(`canvas`));if(t.length===0)return;let n=e.getBoundingClientRect(),r=document.createElement(`canvas`);r.width=Math.round(n.width*2),r.height=Math.round(n.height*2);let i=r.getContext(`2d`);if(i){i.fillStyle=getComputedStyle(e).getPropertyValue(`--bg-deep`).trim()||`#0a0806`,i.fillRect(0,0,r.width,r.height),i.scale(2,2);for(let e of t){let t=e.getBoundingClientRect();t.width!==0&&t.height!==0&&i.drawImage(e,t.left-n.left,t.top-n.top,t.width,t.height)}r.toBlob(e=>{if(!e)return;let t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`paracosm-viz-t${y+1}-${new Date().toISOString().replace(/[:.]/g,`-`).slice(0,19)}.png`,document.body.appendChild(n),n.click(),document.body.removeChild(n),setTimeout(()=>URL.revokeObjectURL(t),1e3)},`image/png`)}},[y]),[ct,lt]=(0,b.useState)(0),ut=(0,b.useRef)(-1);(0,b.useEffect)(()=>{ut.current===-1||Math.abs(y-ut.current)>=2&&lt(e=>e+1),ut.current=y},[y]),(0,b.useEffect)(()=>{let e=e=>{let t=e.target instanceof Element?e.target:null,n=t?.tagName;n!==`INPUT`&&n!==`TEXTAREA`&&n!==`SELECT`&&(e.key!==`Escape`&&t?.closest(`[role="dialog"]`)||(e.key!==` `&&e.key!==`Spacebar`||!t?.closest(Dk))&&(e.key===`ArrowLeft`?(e.preventDefault(),M()):e.key===`ArrowRight`?(e.preventDefault(),N()):e.key===` `||e.key===`Spacebar`?(e.preventDefault(),te()):e.key===`?`||e.shiftKey&&e.key===`/`?(e.preventDefault(),F(e=>!e)):e.key===`Escape`&&ie?(e.preventDefault(),F(!1)):e.key===`1`?(e.preventDefault(),k(`living`)):e.key===`2`?(e.preventDefault(),k(`mood`)):e.key===`3`?(e.preventDefault(),k(`forge`)):e.key===`4`?(e.preventDefault(),k(`ecology`)):e.key===`5`&&(e.preventDefault(),k(`divergence`))))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[M,N,te,ie,k]);let dt=(0,b.useMemo)(()=>{let e=me.trim().toLowerCase().split(/\s+/).filter(Boolean);if(e.length===0)return[];let t=t=>{let n=`${t.name} ${t.department} ${t.role} ${t.mood}`.toLowerCase();return e.every(e=>n.includes(e))};return[...(Ve?.cells??[]).filter(e=>e.alive&&t(e)).map(e=>({cell:e,side:`a`,actorName:Ye?.name??`Leader A`,sideColor:`#e8b44a`})),...(He?.cells??[]).filter(e=>e.alive&&t(e)).map(e=>({cell:e,side:`b`,actorName:Xe?.name??`Leader B`,sideColor:`#4ecdc4`}))]},[me,Ve,He,Ye,Xe]),ft=(0,b.useMemo)(()=>Ck(Ve,He),[Ve,He]),pt=(0,b.useMemo)(()=>{let t={a:{attempts:[],reuses:[]},b:{attempts:[],reuses:[]}},n=[];l&&n.push({side:`a`,actorName:l}),u&&n.push({side:`b`,actorName:u});for(let{side:r,actorName:i}of n){let n=e.actors[i];if(!n)continue;let a=new Map;for(let e of n.events){if(e.type===`forge_attempt`){let n=e.data||{};t[r].attempts.push({turn:Number(n.turn??0),eventIndex:Number(n.eventIndex??0),department:String(n.department||``),name:String(n.name||``),approved:n.approved===!0||n.approved===`true`,confidence:typeof n.confidence==`number`?n.confidence:void 0}),n.name&&n.department&&n.approved===!0&&!a.has(String(n.name))&&a.set(String(n.name),String(n.department));continue}if(e.type!==`specialist_done`)continue;let n=e.data||{},i=String(n.department||``),o=Array.isArray(n.forgedTools)?n.forgedTools:[];for(let s of o){let o=s,c=String(o.name||``);if(!c||c===`unnamed`)continue;let l=typeof o.firstForgedDepartment==`string`?String(o.firstForgedDepartment):a.get(c),u=typeof o.firstForgedTurn==`number`?o.firstForgedTurn:void 0,d=Number(e.turn??n.turn??0);(l&&u!==void 0&&u<d||l&&l!==i)&&t[r].reuses.push({turn:d,originDept:l,callingDept:i,name:c})}}}return t},[e]);YO({enabled:B.sound,snapshotA:d[d.length-1],prevSnapshotA:d[d.length-2],snapshotB:f[f.length-1],prevSnapshotB:f[f.length-2],forgeAttemptsA:pt.a.attempts,forgeAttemptsB:pt.b.attempts});let mt=(0,b.useMemo)(()=>{let t=new Map;for(let n of e.actorIds){let r=e.actors[n];if(r)for(let e of r.events){if(e.type!==`agent_reactions`)continue;let n=e.data?.reactions||[];for(let e of n){let n=e.hexaco;if(!n)continue;let r=e.agentId||e.name;r&&t.set(r,n)}}}return t},[e]),ht=(0,b.useCallback)(e=>{t?.(e)},[t]),gt=jy(My),_t=jy(Ny),vt=jy(Py),[yt,bt]=(0,b.useState)(null),xt=Ye?.name??`Leader A`,St=Xe?.name??`Leader B`,Ct=(0,b.useMemo)(()=>vk(d[y]?gk(d[y],d[y-1]):null,f[y]?gk(f[y],f[y-1]):null,y+1,{nameA:xt,nameB:St,person:ae.person,people:ae.people,places:ae.places}),[d,f,y,xt,St,ae.person,ae.people,ae.places]),wt=(0,b.useMemo)(()=>I.departments.map(e=>({id:e.id,label:e.label,color:Sk[e.id]??`#a89878`})),[I.departments]),Tt=(0,b.useMemo)(()=>Object.fromEntries(I.departments.map(e=>[e.id,e.label])),[I.departments]),[Et,Dt]=(0,b.useState)(()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`paracosm:vizDiffOverlay`)===`1`}catch{return!1}}),Ot=(0,b.useCallback)(e=>{Dt(e);try{window.localStorage.setItem(`paracosm:vizDiffOverlay`,e?`1`:`0`)}catch{}},[]);(0,b.useEffect)(()=>{let e=e=>{let t=e.target;t&&t.matches(`input, textarea, [contenteditable=true]`)||(e.key===`d`||e.key===`D`)&&(e.preventDefault(),Ot(!Et))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[Et,Ot]);let kt=(0,b.useMemo)(()=>Et?bk(wk(d[y]),wk(f[y])):null,[Et,d,f,y]);if(v===0)return e.isRunning?(0,x.jsxs)(`div`,{className:`viz-content ${$.empty}`,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:$.emptySpinner,"aria-hidden":`true`}),(0,x.jsxs)(`span`,{children:[`Awaiting first turn snapshot — the `,ae.place,` viz will populate once the kernel reports state.`]})]}):typeof window<`u`&&new URLSearchParams(window.location.search).has(`replay`)?(0,x.jsxs)(`div`,{className:`viz-content ${$.empty}`,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:$.emptySpinner,"aria-hidden":`true`}),(0,x.jsxs)(`span`,{children:[`Loading replay — the `,ae.place,` viz will populate as the cached events stream in.`]})]}):(0,x.jsxs)(`div`,{className:`viz-content ${$.empty}`,children:[`Run a simulation to see the `,ae.place,` visualization.`]});let At=Ve&&He?`A vs B: ${He.population-Ve.population>=0?`+`:``}${He.population-Ve.population} pop, ${He.morale-Ve.morale>=0?`+`:``}${Math.round((He.morale-Ve.morale)*100)}% morale${typeof Ve.foodReserve==`number`&&typeof He.foodReserve==`number`?`, ${He.foodReserve-Ve.foodReserve>0?`+`:``}${(He.foodReserve-Ve.foodReserve).toFixed(1)}mo food`:``}`:``,jt=_t?Re??`a`:Re,Mt=y>0?d[y-1]??d[d.length-2]:void 0,Nt=y>0?f[y-1]??f[f.length-2]:void 0,Pt=dt,Ft=(0,x.jsxs)(`button`,{type:`button`,onClick:()=>Ot(!Et),"aria-label":Et?`Hide A-vs-B diff overlay (D)`:`Show A-vs-B diff overlay (D)`,"aria-pressed":Et,title:`Highlight where Leader A and Leader B diverged this turn (press D)`,className:$.helpBtn,children:[`Diff `,Et?`on`:`off`]}),It=(0,x.jsx)(`button`,{type:`button`,onClick:()=>F(!0),"aria-label":`Open help overlay (shortcut: ?)`,title:`What do these colors / symbols / modes mean? (press ?)`,className:$.helpBtn,children:`? Help`}),Lt=_t&&g===`pair`;return(0,x.jsxs)(`div`,{ref:Ze,className:`viz-content ${$.root}`,children:[h&&(0,x.jsxs)(`div`,{className:$.cohortViewBar,role:`region`,"aria-label":`Cohort view controls`,children:[(0,x.jsxs)(`div`,{className:$.cohortViewModeToggle,role:`tablist`,"aria-label":`Swarm grid view mode`,children:[(0,x.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":g===`cohort`,onClick:()=>_(`cohort`),className:[$.cohortViewModeButton,g===`cohort`?$.cohortViewModeButtonActive:``].filter(Boolean).join(` `),title:`Show every actor's living-swarm panel side-by-side with horizontal scroll`,children:[`All `,e.actorIds.length,` actors`]}),(0,x.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":g===`pair`,onClick:()=>_(`pair`),className:[$.cohortViewModeButton,g===`pair`?$.cohortViewModeButtonActive:``].filter(Boolean).join(` `),title:`Focus on a 2-actor head-to-head with the original pair-mode diff overlay + sympathy hover`,children:`Focus pair`})]}),g===`pair`&&(0,x.jsxs)(`div`,{className:$.cohortPairPicker,children:[(0,x.jsx)(`select`,{"aria-label":`Left panel actor`,className:$.cohortPairPickerSelect,value:l??``,onChange:e=>o(e.target.value||void 0),children:e.actorIds.map(t=>(0,x.jsx)(`option`,{value:t,disabled:t===u,children:e.actors[t]?.leader?.name??t},t))}),(0,x.jsx)(`span`,{className:$.cohortPairPickerVs,children:`vs`}),(0,x.jsx)(`select`,{"aria-label":`Right panel actor`,className:$.cohortPairPickerSelect,value:u??``,onChange:e=>c(e.target.value||void 0),children:e.actorIds.map(t=>(0,x.jsx)(`option`,{value:t,disabled:t===l,children:e.actors[t]?.leader?.name??t},t))})]})]}),(0,x.jsx)(CO,{state:e,currentTurn:y,linesTarget:Lt?yt:null}),(0,x.jsx)(ck,{text:Ct,turn:y+1}),(0,x.jsx)(uk,{departments:wt}),Et&&kt&&(0,x.jsx)(mk,{diff:kt,departmentLabels:Tt}),(0,x.jsxs)(`div`,{className:$.toolbarStrip,children:[(0,x.jsxs)(yC,{label:`toolbar keys`,rowClassName:$.toolbarTopRow,children:[(0,x.jsx)(`div`,{className:$.modePillsWrap,children:(0,x.jsx)(kO,{mode:D,onChange:k,counts:{forge:pt.a.attempts.filter(e=>e.approved).length+pt.b.attempts.filter(e=>e.approved).length,divergence:(ft.aliveOnlyA?.size??0)+(ft.aliveOnlyB?.size??0)},labels:ae})}),D===`forge`&&(0,x.jsx)(`button`,{type:`button`,"aria-haspopup":`dialog`,onClick:e=>Fe.openToolbox(e.currentTarget,`viz`),className:$.forgeToolboxKey,children:Qv(Ie.list.length)}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>Pe(e=>!e),"aria-label":Ne?vt?`Hide more tools`:`Hide advanced tools`:vt?`Show more tools (diff, help, palette, stats, export, settings)`:`Show advanced tools (palette, stats, export, settings)`,"aria-expanded":Ne,title:Ne?`Hide tools`:vt?`Diff · Help · Palette · Stats · Export · Settings`:`Palette · Stats · Export · Settings`,className:[$.overflowToggle,Ne?$.overflowToggleOpen:``].filter(Boolean).join(` `),children:`⋯`}),!vt&&Ft,!vt&&It]}),Ne&&(0,x.jsxs)(yC,{label:`Viz tools`,role:`toolbar`,ariaLabel:`Viz tools`,rowClassName:$.toolsRow,children:[vt&&Ft,vt&&It,(0,x.jsx)(`button`,{type:`button`,onClick:Oe,"aria-label":`Palette: ${Te}. Click to cycle.`,title:`Palette: ${Te.toUpperCase()} (click to cycle)`,className:$.paletteBtn,style:{"--palette-bg":Te===`amber`?`linear-gradient(135deg, #e8b44a 0 40%, #c44a1e 100%)`:Te===`cool`?`linear-gradient(135deg, #4ecdc4 0 40%, #9b6bd8 100%)`:`linear-gradient(135deg, #f5f0e4 0 40%, #6b5f50 100%)`},children:Te}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>Me(!0),"aria-label":`Open run summary`,title:`Run summary (cumulative totals)`,className:$.toolBtn,children:`STATS`}),(0,x.jsx)(ak,{recording:Qe,onExportPng:st,onExportJson:ot,onToggleRecording:Qe?at:it}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>Ae(e=>!e),"aria-label":`Open grid settings`,"aria-expanded":ke,title:`Viz settings`,className:[$.settingsBtn,ke?$.settingsBtnOpen:``].filter(Boolean).join(` `),children:`⚙`})]}),(0,x.jsx)(`div`,{className:$.modeHint,children:OO(D,ae)}),D===`ecology`&&!e.actorIds.some(e=>{let t=n[e]??[];return Ek(t[y]??t[t.length-1])})&&(0,x.jsxs)(`div`,{role:`status`,className:$.ecologyNone,children:[(0,x.jsx)(`span`,{children:`ECOLOGY draws food, water, power and pressurized volume. This run holds none of them.`}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>k(`living`),className:$.ecologyBack,children:`Back to LIVING`})]})]}),(0,x.jsx)(KO,{value:me,onChange:he,matches:Pt,onPick:e=>{he(e.cell.name)}}),(0,x.jsx)(WO,{eventsA:p?.events??[],eventsB:m?.events??[],totalDepartments:I.departments.length}),(0,x.jsx)(VO,{eventsA:p?.events??[],eventsB:m?.events??[],currentTurn:y,onJumpToTurn:ne,hoveredTurn:ue,onHoverTurnChange:de,filter:fe,onFilterChange:R,onHoverEventChange:pe,onJumpToReports:re,onForgeSelect:Le}),(0,x.jsx)(IO,{snapsA:d,snapsB:f,currentTurn:y,onJumpToTurn:ne,hoveredTurn:ue,onHoverTurnChange:de}),g===`pair`&&At&&(0,x.jsx)(`div`,{className:$.diffLine,children:At}),g===`pair`&&_t&&(0,x.jsx)(`div`,{role:`tablist`,"aria-label":`Leader panel selector`,className:$.phoneTabRow,children:[`a`,`b`].map(e=>{let t=e===`a`?Ye?.name??`Leader A`:Xe?.name??`Leader B`,n=e===`a`?`var(--vis)`:`var(--eng)`,r=jt===e;return(0,x.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":r,onClick:()=>ze(e),className:[$.phoneTab,r?$.phoneTabActive:``].filter(Boolean).join(` `),style:r?{"--tab-color":n}:void 0,children:t},e)})}),g===`cohort`&&(0,x.jsx)(vO,{state:e,snapshotMap:n,currentTurn:y,gridMode:D,palette:Te===`cool`?1:Te===`mono`?2:0,gridSettings:B,hexacoById:mt,searchQuery:me,chronicleFilter:fe,chronicleHover:z,startTime:I.setup?.defaultStartTime,onOpenChat:ht}),g===`pair`&&(0,x.jsxs)(`div`,{className:[`leaders-row`,$.leadersRow,gt?$.leadersRowNarrow:``,Lt?$.leadersRowLinesBelow:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`div`,{className:[$.sideWrap,jt===`b`?$.sideWrapHidden:``].filter(Boolean).join(` `),children:(0,x.jsx)(mO,{snapshot:Ve,previousSnapshot:Mt,snapshotHistory:d,actorName:Ye?.name??`Leader A`,actorArchetype:Ye?.archetype??``,leaderUnit:Ye?.unit??``,sideColor:`var(--vis)`,side:`a`,lagTurns:Ue<We?We-Ue:0,mode:D,hexacoById:mt,leaderHexaco:Ye?.hexaco?{O:Ye.hexaco.O??Ye.hexaco.openness??.5,C:Ye.hexaco.C??Ye.hexaco.conscientiousness??.5,E:Ye.hexaco.E??Ye.hexaco.extraversion??.5,A:Ye.hexaco.A??Ye.hexaco.agreeableness??.5,Em:Ye.hexaco.Em??Ye.hexaco.emotionality??.5,HH:Ye.hexaco.HH??Ye.hexaco.honestyHumility??.5}:void 0,forgeAttempts:pt.a.attempts,reuseCalls:pt.a.reuses,divergedIds:ft.aliveOnlyA,siblingHoveredId:le,onHoverChange:ce,searchQuery:me,palette:Te===`cool`?1:Te===`mono`?2:0,settings:B,startTime:I.setup?.defaultStartTime,focusedSide:jt,onToggleFocus:_t?void 0:Be,onOpenChat:ht,eventFilter:fe,chronicleHover:z})}),(0,x.jsx)(`div`,{className:[$.sideWrap,jt===`a`?$.sideWrapHidden:``].filter(Boolean).join(` `),children:(0,x.jsx)(mO,{snapshot:He,previousSnapshot:Nt,snapshotHistory:f,actorName:Xe?.name??`Leader B`,actorArchetype:Xe?.archetype??``,leaderUnit:Xe?.unit??``,sideColor:`var(--eng)`,side:`b`,lagTurns:We<Ue?Ue-We:0,mode:D,hexacoById:mt,leaderHexaco:Xe?.hexaco?{O:Xe.hexaco.O??Xe.hexaco.openness??.5,C:Xe.hexaco.C??Xe.hexaco.conscientiousness??.5,E:Xe.hexaco.E??Xe.hexaco.extraversion??.5,A:Xe.hexaco.A??Xe.hexaco.agreeableness??.5,Em:Xe.hexaco.Em??Xe.hexaco.emotionality??.5,HH:Xe.hexaco.HH??Xe.hexaco.honestyHumility??.5}:void 0,forgeAttempts:pt.b.attempts,reuseCalls:pt.b.reuses,divergedIds:ft.aliveOnlyB,siblingHoveredId:oe,onHoverChange:L,searchQuery:me,palette:Te===`cool`?1:Te===`mono`?2:0,settings:B,startTime:I.setup?.defaultStartTime,focusedSide:jt,onToggleFocus:_t?void 0:Be,onOpenChat:ht,eventFilter:fe,chronicleHover:z})}),Lt&&(0,x.jsx)(`section`,{ref:bt,role:`status`,"aria-label":`Turn outcomes`,className:$.turnLinesSlot})]}),(0,x.jsx)(TO,{currentTurn:y,maxTurn:v,time:Ve?.time??He?.time??0,playing:C,speed:T,onTurnChange:ne,onPlayPause:te,onStepBack:M,onStepForward:N,onSpeedChange:E}),(0,x.jsxs)(`div`,{className:$.footerKeys,children:[(0,x.jsx)(Tk,{k:`?`,v:`help`}),(0,x.jsx)(Tk,{k:`1-5`,v:`mode`}),(0,x.jsx)(Tk,{k:`← →`,v:`scrub turn`}),(0,x.jsx)(Tk,{k:`space`,v:`play / pause`}),(0,x.jsx)(Tk,{k:`click`,v:`${ae.person} drilldown`}),(0,x.jsx)(Tk,{k:`esc`,v:`close popover`})]}),(0,x.jsx)(`div`,{"aria-live":`polite`,"aria-atomic":`true`,className:$.srOnly,children:Ve&&He?`Turn ${Math.max(Ve.turn,He.turn)}. ${Ye?.name??`A`} ${ae.place}: ${Ve.cells.filter(e=>e.alive).length} alive, ${Ve.births} born, ${Ve.deaths} died, morale ${Math.round(Ve.morale*100)}%. ${Xe?.name??`B`} ${ae.place}: ${He.cells.filter(e=>e.alive).length} alive, ${He.births} born, ${He.deaths} died, morale ${Math.round(He.morale*100)}%.`:``}),v>1&&y<v-1&&(0,x.jsxs)(`button`,{type:`button`,onClick:()=>ne(v-1),"aria-label":`Jump to latest turn (T${v})`,className:$.jumpLatest,children:[`↓`,` Latest · T`,v,(0,x.jsxs)(`span`,{className:$.jumpLatestBehind,children:[`(`,v-1-y,` turn`,v-1-y==1?``:`s`,` behind)`]})]}),(0,x.jsx)(jO,{open:ie,onClose:()=>F(!1)}),(0,x.jsx)(iO,{open:ke,settings:B,onChange:ye,onClose:()=>Ae(!1)}),(0,x.jsx)(QO,{open:je,onClose:()=>Me(!1),snapsA:d,snapsB:f,actorNameA:Ye?.name??`Leader A`,actorNameB:Xe?.name??`Leader B`,forgeApprovedA:pt.a.attempts.filter(e=>e.approved).length,forgeApprovedB:pt.b.attempts.filter(e=>e.approved).length,reuseCountA:pt.a.reuses.length,reuseCountB:pt.b.reuses.length,divergedCount:(ft.aliveOnlyA?.size??0)+(ft.aliveOnlyB?.size??0)}),be&&(0,x.jsxs)(`div`,{role:`status`,"aria-live":`assertive`,onClick:()=>xe(null),className:$.toast,style:{"--toast-top":ge?`68px`:`8px`,"--side-color":be.side===`a`?`var(--vis)`:`var(--eng)`,"--left-accent":be.kind===`morale-crash`?`var(--rust)`:`var(--amber)`},title:`Click to dismiss`,children:[(0,x.jsxs)(`div`,{className:$.toastKicker,style:{"--kicker-color":be.kind===`morale-crash`?`var(--rust)`:`var(--amber)`},children:[(0,x.jsx)(`span`,{children:be.kind===`morale-crash`?`▼ Alert`:`⚠ Alert`}),(0,x.jsxs)(`span`,{className:$.toastKickerMeta,children:[be.side.toUpperCase(),` · T`,be.turn]})]}),(0,x.jsx)(`div`,{className:$.toastBody,children:be.message})]},be.key),ge&&(0,x.jsxs)(`div`,{role:`status`,"aria-live":`polite`,onClick:()=>_e(null),className:$.toast,style:{"--side-color":ge.side===`a`?`var(--vis)`:`var(--eng)`,"--left-accent":`var(--rust)`},title:`Click to dismiss`,children:[(0,x.jsxs)(`div`,{className:$.toastKicker,children:[(0,x.jsx)(`span`,{children:`⚡ Crisis`}),(0,x.jsxs)(`span`,{className:$.toastKickerMeta,children:[ge.side.toUpperCase(),` · T`,ge.turn,` · `,ge.category]})]}),(0,x.jsx)(`div`,{className:$.toastBodyMd,children:ge.title||`${ge.category} crisis unfolding`})]},ge.key),ct>0&&(0,x.jsx)(`div`,{"aria-hidden":`true`,className:$.vignette},ct),(0,x.jsx)(`style`,{children:`
126
+ `).length,se=new Blob([r]).size;return(0,x.jsxs)(`div`,{className:Iw.card,children:[(0,x.jsxs)(`div`,{className:Iw.header,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`h3`,{className:Iw.title,children:`Scenario Editor`}),(0,x.jsxs)(`p`,{className:Iw.lead,children:[`Write or import a scenario JSON draft. Add seed text or a URL to ground it, then compile or export.`,!t.adminWrite&&` Disk saves are disabled on this instance.`]})]}),(0,x.jsxs)(`div`,{className:Iw.btnRow,children:[(0,x.jsx)(`button`,{onClick:ne,className:[Iw.btn,Iw.amber].join(` `),"aria-label":`Load active scenario JSON`,children:`Load Active`}),(0,x.jsx)(`button`,{onClick:N,className:Iw.btn,"aria-label":`Load example scenario`,children:`Template`}),(0,x.jsx)(`button`,{onClick:P,className:Iw.btn,"aria-label":`Import JSON file`,children:`Import`}),(0,x.jsx)(`button`,{onClick:ie,className:Iw.btn,disabled:!r.trim()||!!a,"aria-label":`Export as JSON file`,children:`Export`}),(0,x.jsx)(`input`,{ref:j,type:`file`,accept:`.json,application/json`,onChange:re,className:Iw.fileInput})]})]}),(0,x.jsxs)(`div`,{className:Iw.editorWrap,children:[(0,x.jsx)(`textarea`,{ref:ee,value:r,onChange:e=>i(e.target.value),placeholder:`{\\n "id": "my-scenario",\\n "labels": { "name": "My World" },\\n "departments": [...]\\n}`,spellCheck:!1,"aria-label":`Scenario JSON editor`,className:Iw.editor}),(0,x.jsxs)(`div`,{className:Iw.statusBar,style:{"--status-color":a?`var(--rust)`:`var(--text-3)`},children:[(0,x.jsx)(`span`,{children:a||(r.trim()?`Valid JSON`:`Empty`)}),(0,x.jsxs)(`span`,{children:[oe,` lines, `,(se/1024).toFixed(1),`KB`]})]})]}),(0,x.jsxs)(`details`,{className:Iw.seedDetails,children:[(0,x.jsx)(`summary`,{className:Iw.seedSummary,children:`Seed Enrichment (optional)`}),(0,x.jsxs)(`div`,{className:Iw.seedBody,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:Nw,children:`Seed Text`}),(0,x.jsx)(`textarea`,{value:s,onChange:e=>c(e.target.value),placeholder:`Paste a prompt, notes, a brief, or source text to turn into research facts and category mapping.`,className:Iw.textarea})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:Nw,children:`Seed URL (fetched via Firecrawl)`}),(0,x.jsx)(`input`,{value:l,onChange:e=>u(e.target.value),placeholder:`https://example.com/article`,className:Iw.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:Nw,children:`Max Web Searches`}),(0,x.jsx)(`input`,{value:p,onChange:e=>m(e.target.value),inputMode:`numeric`,placeholder:`5`,className:Iw.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:Nw,children:`Compile Provider Override`}),(0,x.jsx)(`input`,{value:h,onChange:e=>g(e.target.value),placeholder:`anthropic or openai (optional)`,className:Iw.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{style:Nw,children:`Compile Model Override`}),(0,x.jsx)(`input`,{value:_,onChange:e=>v(e.target.value),placeholder:`gpt-5.4-mini, claude-sonnet-4-6, etc. (optional)`,className:Iw.input})]}),(0,x.jsxs)(`label`,{className:Iw.checkboxLabel,children:[(0,x.jsx)(`input`,{type:`checkbox`,checked:d,onChange:e=>f(e.target.checked)}),`Web search enrichment (requires Serper/Tavily/Firecrawl API keys)`]}),(0,x.jsx)(`p`,{className:Iw.fineprint,children:`If both seed text and a seed URL are provided, the URL takes precedence and the compiler ingests the fetched page.`})]})]}),T.length>0&&(0,x.jsx)(`div`,{className:Iw.progressWrap,children:T.map(e=>(0,x.jsxs)(`div`,{className:Iw.progressRow,children:[(0,x.jsx)(`span`,{children:e.status===`done`?`✔`:e.status===`generating`?`⏳`:e.status===`cached`?`✔`:`•`}),(0,x.jsx)(`span`,{children:e.hook}),(0,x.jsx)(`span`,{className:Iw.progressStatus,children:e.status})]},e.hook))}),k&&(0,x.jsx)(`div`,{className:Iw.result,style:{"--result-color":k.success?`var(--green)`:`var(--rust)`,"--result-bg":k.success?`rgba(106,173,72,.06)`:`rgba(224,101,48,.06)`},children:k.message}),(0,x.jsxs)(`div`,{className:Iw.actions,children:[(0,x.jsx)(`button`,{onClick:F,disabled:!r.trim()||!!a||C,className:Iw.actionBtn,"aria-label":`Store scenario in memory`,children:C?`Storing...`:`Store in Memory`}),(0,x.jsx)(`button`,{onClick:ae,disabled:!r.trim()||!!a||y,className:[Iw.actionBtn,Iw.primary].join(` `),"aria-label":`Compile scenario`,children:y?`Compiling...`:`Compile Scenario`}),t.adminWrite&&(0,x.jsx)(`button`,{onClick:I,disabled:!r.trim()||!!a,className:[Iw.actionBtn,Iw.amber].join(` `),"aria-label":`Save scenario to disk`,children:`Save to Disk`}),(0,x.jsx)(`span`,{className:Iw.spacer}),t.memoryScenarios.length>0&&(0,x.jsxs)(`span`,{className:Iw.memCount,children:[t.memoryScenarios.length,` in memory`]})]})]})}var Vw={intro:`_intro_v1quw_1`,label:`_label_v1quw_13`,row:`_row_v1quw_24`,input:`_input_v1quw_31`,btn:`_btn_v1quw_45`,amber:`_amber_v1quw_65`,status:`_status_v1quw_70`,refusal:`_refusal_v1quw_77`},Hw={none:`No token is saved in this browser.`,stored:`A token is saved in this browser. It is not shown back.`,held:`This browser could not store the token, so it is kept only until this page reloads.`};function Uw(){let e=(0,b.useRef)(null),[t,n]=(0,b.useState)(!1),[r,i]=(0,b.useState)(()=>ve()),[a,o]=(0,b.useState)(null);(0,b.useEffect)(()=>Se(()=>i(ve())),[]);let s=()=>{e.current&&(e.current.value=``),n(!1)},c=()=>{let t=e.current?.value??``;if(!t.trim())return;let n=ye(t);n===`unsendable`?o(z):(o(null),i(n),s())};return(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`p`,{className:Vw.intro,children:[`Admin writes on this server take its `,(0,x.jsx)(`code`,{children:`ADMIN_TOKEN`}),`: Save to Disk in the scenario editor below, Delete server data in the run actions menu, and Rename and Delete in a scenario's details. Enter the token once. The dashboard sends it only on those requests, as the `,(0,x.jsx)(`code`,{children:`X-Admin-Token`}),` header, and keeps it in this browser.`]}),(0,x.jsx)(`label`,{htmlFor:`admin-token`,className:Vw.label,children:`Token for this server`}),(0,x.jsxs)(`div`,{className:Vw.row,children:[(0,x.jsx)(`input`,{id:`admin-token`,type:`password`,autoComplete:`off`,spellCheck:!1,ref:e,onChange:e=>{n(e.target.value.trim()!==``),o(null)},onKeyDown:e=>{e.key===`Enter`&&c()},placeholder:r===`none`?`Not entered`:`Saved`,"aria-describedby":`admin-token-status`,className:Vw.input}),(0,x.jsx)(`button`,{type:`button`,onClick:c,disabled:!t,className:[Vw.btn,Vw.amber].join(` `),"aria-label":`Save admin token`,children:`Save`}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>{be(),i(`none`),o(null),s()},disabled:r===`none`&&!t,className:Vw.btn,"aria-label":`Clear admin token`,children:`Clear`})]}),(0,x.jsx)(`div`,{id:`admin-token-status`,role:`status`,className:Vw.status,children:Hw[r]}),a&&(0,x.jsx)(`p`,{role:`alert`,className:Vw.refusal,children:a})]})}var Ww={bar:`_bar_127em_1`,topRow:`_topRow_127em_15`,searchWrap:`_searchWrap_127em_22`,searchIcon:`_searchIcon_127em_30`,searchInput:`_searchInput_127em_35`,resetButton:`_resetButton_127em_50`,facetsRow:`_facetsRow_127em_76`,facetLabel:`_facetLabel_127em_83`,checkboxGroup:`_checkboxGroup_127em_93`,checkbox:`_checkbox_127em_93`,active:`_active_127em_115`,leaderSelect:`_leaderSelect_127em_128`,rangeWrap:`_rangeWrap_127em_142`,rangeInput:`_rangeInput_127em_151`,toolChip:`_toolChip_127em_162`,chipClear:`_chipClear_127em_176`,emptyHint:`_emptyHint_127em_188`};function Gw(e){return e.query!==``||e.types.size>0||e.leader!==null||e.turnRange!==null||e.toolHash!==``}function Kw({events:e,filters:t,onFiltersChange:n}){let r=(0,b.useMemo)(()=>$m(e),[e]),i=Gw(t),a=e=>{n({...t,...e})},o=e=>{let n=new Set(t.types);n.has(e)?n.delete(e):n.add(e),a({types:n})},s=e=>t.types.size===0||t.types.has(e);return(0,x.jsxs)(`div`,{className:Ww.bar,children:[(0,x.jsxs)(`div`,{className:Ww.topRow,children:[(0,x.jsxs)(`div`,{className:Ww.searchWrap,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:Ww.searchIcon,children:`🔍`}),(0,x.jsx)(`input`,{type:`search`,"aria-label":`Filter log by text (type, leader, department, title, summary)`,placeholder:`Search type, leader, department, title, summary...`,value:t.query,onChange:e=>a({query:e.target.value}),className:Ww.searchInput})]}),t.toolHash&&(0,x.jsxs)(`span`,{className:Ww.toolChip,children:[`tool: `,t.toolHash,(0,x.jsx)(`button`,{type:`button`,"aria-label":`Clear tool filter`,className:Ww.chipClear,onClick:()=>a({toolHash:``,toolExact:!1}),children:`×`})]}),(0,x.jsx)(`button`,{type:`button`,className:Ww.resetButton,disabled:!i,onClick:()=>n(Jm()),children:`Reset filters`})]}),r.types.length>0&&(0,x.jsxs)(`div`,{className:Ww.facetsRow,children:[(0,x.jsx)(`span`,{className:Ww.facetLabel,children:`types`}),(0,x.jsx)(`div`,{className:Ww.checkboxGroup,children:r.types.map(e=>{let t=s(e);return(0,x.jsxs)(`label`,{className:[Ww.checkbox,t?Ww.active:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`input`,{type:`checkbox`,checked:t,onChange:()=>o(e)}),e]},e)})})]}),(r.actors.length>1||r.maxTurn>3)&&(0,x.jsxs)(`div`,{className:Ww.facetsRow,children:[r.actors.length>1&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:Ww.facetLabel,children:`leader`}),(0,x.jsxs)(`select`,{"aria-label":`Filter by leader`,className:Ww.leaderSelect,value:t.leader??``,onChange:e=>a({leader:e.target.value||null}),children:[(0,x.jsx)(`option`,{value:``,children:`all`}),r.actors.map(e=>(0,x.jsx)(`option`,{value:e,children:e},e))]})]}),r.maxTurn>3&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:Ww.facetLabel,children:`turns`}),(0,x.jsxs)(`div`,{className:Ww.rangeWrap,children:[(0,x.jsx)(`input`,{type:`number`,"aria-label":`Min turn`,min:0,max:r.maxTurn,value:t.turnRange?t.turnRange[0]:0,onChange:e=>{let n=Number(e.target.value);if(!Number.isFinite(n))return;let i=t.turnRange?.[1]??r.maxTurn;a({turnRange:[n,Math.max(n,i)]})},className:Ww.rangeInput}),(0,x.jsx)(`span`,{children:`to`}),(0,x.jsx)(`input`,{type:`number`,"aria-label":`Max turn`,min:0,max:r.maxTurn,value:t.turnRange?t.turnRange[1]:r.maxTurn,onChange:e=>{let n=Number(e.target.value);if(!Number.isFinite(n))return;let r=t.turnRange?.[0]??0;a({turnRange:[Math.min(r,n),n]})},className:Ww.rangeInput}),t.turnRange&&(0,x.jsx)(`button`,{type:`button`,className:Ww.chipClear,"aria-label":`Clear turn range`,onClick:()=>a({turnRange:null}),children:`×`})]})]})]}),t.types.size>0&&t.types.size===r.types.length&&(0,x.jsx)(`div`,{className:Ww.emptyHint,children:`All types selected — filter is a no-op on this axis.`})]})}var qw={panel:`_panel_aavxx_1`,header:`_header_aavxx_6`,heading:`_heading_aavxx_15`,filterBar:`_filterBar_aavxx_26`,filterLabel:`_filterLabel_aavxx_34`,filterValue:`_filterValue_aavxx_38`,emptyState:`_emptyState_aavxx_43`,event:`_event_aavxx_48`,eventSummary:`_eventSummary_aavxx_53`,index:`_index_aavxx_61`,type:`_type_aavxx_67`,leader:`_leader_aavxx_73`,turn:`_turn_aavxx_81`,title:`_title_aavxx_85`,department:`_department_aavxx_89`,outcome:`_outcome_aavxx_93`,dataBlock:`_dataBlock_aavxx_98`},Jw={status:`var(--teal)`,turn_start:`var(--rust)`,turn_done:`var(--rust)`,specialist_start:`var(--text-3)`,specialist_done:`var(--green)`,decision_pending:`var(--amber)`,decision_made:`var(--amber)`,outcome:`#e8b44a`,drift:`var(--teal)`,agent_reactions:`#6aad48`,bulletin:`var(--text-2)`,promotion:`var(--teal)`};function Yw(){return typeof window>`u`?rh(``,``):rh(window.location.search,window.location.hash)}function Xw({events:e}){let t=(0,b.useRef)(null),n=(0,b.useRef)(!0),[r,i]=(0,b.useState)(Yw);(0,b.useEffect)(()=>{let e=()=>i(Yw());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]);let a=(0,b.useCallback)(()=>{let e=t.current;e&&(n.current=e.scrollHeight-e.scrollTop-e.clientHeight<40)},[]);(0,b.useEffect)(()=>{if(!n.current)return;let e=t.current;e&&(e.scrollTop=e.scrollHeight)},[e.length]);let o=(0,b.useCallback)(e=>{i(t=>{try{let n=t.toolHash!==``&&e.toolHash===``;window.history.replaceState({},``,nh(window.location.href,e,n))}catch{}return e})},[]),s=Ym(e,r),c=r.query!==``||r.types.size>0||r.leader!==null||r.turnRange!==null||r.toolHash!==``;return(0,x.jsxs)(`div`,{ref:t,onScroll:a,className:`flex-1 overflow-y-auto p-4 font-mono text-xs ${qw.panel}`,role:`log`,"aria-label":`Event log`,"aria-live":`polite`,children:[(0,x.jsx)(`div`,{className:qw.header,children:(0,x.jsxs)(`h2`,{className:qw.heading,children:[`Event Log (`,s.length,c?` of ${e.length}`:``,` events)`]})}),(0,x.jsx)(Kw,{events:e,filters:r,onFiltersChange:o}),s.length===0&&(0,x.jsx)(`div`,{className:qw.emptyState,children:c?`No events matched the current filter. Adjust or press Reset.`:`No events yet. Run a simulation to see the raw SSE event stream.`}),s.map((e,t)=>{let n=Jw[e.type]||`var(--text-3)`,r=e.data&&Object.keys(e.data).length>0;return(0,x.jsxs)(`details`,{className:qw.event,style:{"--log-type-color":n},children:[(0,x.jsxs)(`summary`,{className:qw.eventSummary,children:[(0,x.jsx)(`span`,{className:qw.index,children:t}),(0,x.jsx)(`span`,{className:qw.type,children:e.type}),(0,x.jsx)(`span`,{className:qw.leader,children:e.leader}),e.data?.turn!=null&&(0,x.jsxs)(`span`,{className:qw.turn,children:[`T`,String(e.data.turn)]}),!!e.data?.title&&(0,x.jsx)(`span`,{className:qw.title,children:String(e.data.title)}),!!e.data?.department&&(0,x.jsx)(`span`,{className:qw.department,children:String(e.data.department)}),!!e.data?.outcome&&(0,x.jsx)(`span`,{className:qw.outcome,children:String(e.data.outcome)})]}),r&&(0,x.jsx)(`pre`,{className:qw.dataBlock,children:JSON.stringify(e.data,null,2)})]},t)})]})}var Zw=[{value:`economy`,label:`Economy`,description:`Cheapest path: gated research, cheap verdicts, tighter spend controls.`},{value:`balanced`,label:`Balanced`,description:`Current default mix for good quality per dollar on normal runs.`},{value:`quality`,label:`Quality`,description:`Push strategic roles and verdict synthesis upward when quality matters more than spend.`},{value:`deterministic_first`,label:`Deterministic First`,description:`Skip verdict synthesis and live-search escalation to reduce variance and cost.`}];function Qw(e){switch(e){case`hosted_demo`:return{label:`Hosted demo`,description:`Host-billed runs are capped and forced onto the economy guardrails.`};case`platform_api`:return{label:`Platform API`,description:"Authenticated `/api/v1/*` routes are enabled; demo-only assumptions are off."};default:return{label:`Local demo`,description:`Single-process local server. Good for product exploration, not a hosted control plane.`}}}var Y={root:`_root_34x3m_1`,content:`_content_34x3m_9`,scenarioRow:`_scenarioRow_34x3m_17`,scenarioLabel:`_scenarioLabel_34x3m_29`,scenarioSelect:`_scenarioSelect_34x3m_34`,scenarioActiveTag:`_scenarioActiveTag_34x3m_45`,scenarioActiveValue:`_scenarioActiveValue_34x3m_51`,h2:`_h2_34x3m_55`,lead:`_lead_34x3m_62`,scenarioTagline:`_scenarioTagline_34x3m_68`,scenarioSourceLink:`_scenarioSourceLink_34x3m_77`,leadHint:`_leadHint_34x3m_92`,leadStrong:`_leadStrong_34x3m_99`,leadersGrid:`_leadersGrid_34x3m_103`,leaderCardWrap:`_leaderCardWrap_34x3m_120`,leaderRemoveBtn:`_leaderRemoveBtn_34x3m_124`,leadersAddRow:`_leadersAddRow_34x3m_153`,leaderAddBtn:`_leaderAddBtn_34x3m_162`,leaderAddCap:`_leaderAddCap_34x3m_191`,fieldset:`_fieldset_34x3m_199`,legend:`_legend_34x3m_208`,demoBanner:`_demoBanner_34x3m_212`,demoBannerLabel:`_demoBannerLabel_34x3m_223`,simRow5:`_simRow5_34x3m_227`,grid3:`_grid3_34x3m_233`,grid2:`_grid2_34x3m_240`,input:`_input_34x3m_246`,locked:`_locked_34x3m_258`,lockTag:`_lockTag_34x3m_263`,fieldHint:`_fieldHint_34x3m_270`,keysIntro:`_keysIntro_34x3m_277`,keysIntroPara:`_keysIntroPara_34x3m_284`,keysIntroParaLast:`_keysIntroParaLast_34x3m_288`,keysIntroBoldNeutral:`_keysIntroBoldNeutral_34x3m_292`,keysIntroBoldGreen:`_keysIntroBoldGreen_34x3m_296`,keysIntroBoldAmber:`_keysIntroBoldAmber_34x3m_300`,keysIntroBoldRust:`_keysIntroBoldRust_34x3m_304`,keyEnvTag:`_keyEnvTag_34x3m_308`,modelTiersIntro:`_modelTiersIntro_34x3m_316`,demoMode:`_demoMode_34x3m_323`,demoModeStrong:`_demoModeStrong_34x3m_333`,launchRow:`_launchRow_34x3m_337`,launchBtn:`_launchBtn_34x3m_346`,launchStatus:`_launchStatus_34x3m_364`},$w=[{id:`config`,label:`Settings`},{id:`log`,label:`Event Log`}],eT={openness:.5,conscientiousness:.5,extraversion:.5,agreeableness:.5,emotionality:.5,honestyHumility:.5},tT={openai:[{value:`gpt-5.4-nano`,label:`gpt-5.4-nano ($0.20 / $1.25 per 1M)`},{value:`gpt-5.4-mini`,label:`gpt-5.4-mini ($0.75 / $4.50 per 1M)`},{value:`gpt-5.4`,label:`gpt-5.4 ($2.50 / $15.00 per 1M)`},{value:`gpt-5.4-pro`,label:`gpt-5.4-pro ($30 / $180 per 1M — avoid)`}],anthropic:[{value:`claude-haiku-4-5-20251001`,label:`Haiku 4.5 ($1 / $5 per 1M)`},{value:`claude-sonnet-4-6`,label:`Sonnet 4.6 ($3 / $15 per 1M)`},{value:`claude-opus-4-7`,label:`Opus 4.7 ($5 / $25 per 1M)`}]},nT={openai:{departments:`gpt-5.4`,commander:`gpt-5.4-mini`,director:`gpt-5.4-mini`,judge:`gpt-5.4-mini`,agentReactions:`gpt-5.4-nano`},anthropic:{departments:`claude-sonnet-4-6`,commander:`claude-haiku-4-5-20251001`,director:`claude-haiku-4-5-20251001`,judge:`claude-haiku-4-5-20251001`,agentReactions:`claude-haiku-4-5-20251001`}},rT={departments:{label:`Departments (forges)`,help:`Writes code, schemas, test cases. Quality matters — cheap tier produces broken forges.`},commander:{label:`Commander`,help:`Picks option from department reports. Mid-tier is fine.`},director:{label:`Event Director`,help:`Generates crisis events as structured JSON batches.`},judge:{label:`Judge (code review)`,help:`Reviews forged tool code for safety + correctness.`},agentReactions:{label:`Agent Reactions`,help:`One to two sentences per colonist per turn. Highest volume — pick cheapest.`}},iT=[`The Visionary`,`The Engineer`,`The Diplomat`,`The Maverick`,`The Guardian`,`The Strategist`,`The Steward`,`The Innovator`];function aT(e,t){return{name:`Actor ${String.fromCharCode(65+e%26)}`,archetype:iT[e]??`The Strategist`,unit:se(t,e),instructions:``,hexaco:{...eT}}}function oT(e){let t=e.presets.find(e=>e.id==="default");return t?.leaders??t?.actors}function sT(e,t,n,r,i){let a=oT(n);return e.map((e,o)=>{let s=i[o],c=a?.[o],l=e.unit===se(t,o);if(!c)return(a!==void 0&&r!==n.id||l)&&s?.unit===void 0?{...e,unit:se(n,o)}:e;let u=r===n.id&&!!e.unit&&!l;return{name:c.name,archetype:c.archetype,unit:u?e.unit:c.unit??se(n,o),instructions:c.instructions,hexaco:{...c.hexaco},...s}})}var cT=2,lT=8;function uT({events:e=[],initialSubTab:t=`config`}={}){let[n,r]=(0,b.useState)(t),i=(0,b.useCallback)(e=>{r(e),dh(e===`config`?null:e)},[]),a=Qk(),o=eA(),s=Lm(),c=nA(),l=iA(),u=typeof window<`u`?gg(window.localStorage):null,[d]=(0,b.useState)(()=>typeof window<`u`?hg(window.localStorage):null),[f,p]=(0,b.useState)(()=>{let e=Math.max(cT,Math.min(lT,Math.max(oT(a)?.length??0,u?.length??0)));return sT(Array.from({length:e},(e,t)=>{let n=u?.[t];return n?.name?{name:n.name,archetype:n.archetype??``,unit:n.unit??se(a,t),instructions:n.instructions??``,hexaco:{...n.hexaco??eT}}:aT(t,a)}),a,a,d,[])}),m=(0,b.useRef)([]),h=(0,b.useRef)(a);(0,b.useEffect)(()=>{let e=h.current;h.current=a,p(t=>sT(t,e,a,d,m.current))},[a.id,a.presets.length]);let g=(0,b.useCallback)((e,t)=>{p(n=>n.map((n,r)=>{if(r!==e)return n;let i=Object.keys(t).filter(e=>t[e]!==n[e]);return m.current[e]={...m.current[e],...Object.fromEntries(i.map(e=>[e,t[e]]))},t}))},[]),_=(0,b.useCallback)(()=>{p(e=>e.length<lT?[...e,aT(e.length,a)]:e)},[a]),v=(0,b.useCallback)(e=>{m.current.splice(e,1),p(t=>t.length>cT?t.filter((t,n)=>n!==e):t)},[]),[y,S]=(0,b.useState)(a.setup.defaultTurns),[C,w]=(0,b.useState)(a.setup.defaultSeed),[T,E]=(0,b.useState)(a.setup.defaultStartTime),[O,A]=(0,b.useState)(a.setup.defaultTimePerTurn||0),[j,ee]=(0,b.useState)(a.setup.defaultPopulation),M=(0,b.useRef)(new Set);(0,b.useEffect)(()=>{let e=M.current;e.has(`turns`)||S(a.setup.defaultTurns),e.has(`seed`)||w(a.setup.defaultSeed),e.has(`startTime`)||E(a.setup.defaultStartTime),e.has(`timePerTurn`)||A(a.setup.defaultTimePerTurn||0),e.has(`population`)||ee(a.setup.defaultPopulation)},[a.id,a.setup.defaultTurns,a.setup.defaultSeed,a.setup.defaultStartTime,a.setup.defaultTimePerTurn,a.setup.defaultPopulation]);let[N,ne]=(0,b.useState)(`openai`),[P,re]=(0,b.useState)(!1),[ie,F]=(0,b.useState)(`balanced`),[I,ae]=(0,b.useState)(!1),[oe,ce]=(0,b.useState)(``),[le,L]=(0,b.useState)([]),[ue,de]=(0,b.useState)(a.id),[fe,R]=(0,b.useState)({}),[z,pe]=(0,b.useState)(!1),[me,he]=(0,b.useState)(!1),[ge,_e]=(0,b.useState)(`local_demo`),[B,ve]=(0,b.useState)({maxTurns:6,maxPopulation:30,maxActiveDepartments:3}),[ye,be]=(0,b.useState)(()=>{try{let e=localStorage.getItem(`paracosm:keyOverrides`);if(e){let t=JSON.parse(e);return{openai:t.openai||``,anthropic:t.anthropic||``,serper:t.serper||``,firecrawl:t.firecrawl||``,tavily:t.tavily||``,cohere:t.cohere||``}}}catch{}return{openai:``,anthropic:``,serper:``,firecrawl:``,tavily:``,cohere:``}});(0,b.useEffect)(()=>{try{localStorage.setItem(`paracosm:keyOverrides`,JSON.stringify(ye))}catch{}},[ye]);let[xe,Se]=(0,b.useState)(nT[N]??nT.openai);(0,b.useEffect)(()=>{let e=N;nT[e]&&Se(nT[e])},[N]);let Ce=xg(ye),we=!!fe.openai||!!fe.anthropic,Te=Ce||!z&&we,Ee=Ce||!z&&we,De=z&&!Ce?`economy`:ie,Oe=Qw(ge),ke=z&&!Ce,Ae=ke?`openai`:N,je=(0,b.useCallback)(()=>{fetch(`/scenarios`).then(e=>e.json()).then(e=>{L(e.scenarios||[]),de(e.active)}).catch(()=>{})},[]);(0,b.useEffect)(()=>(je(),fetch(`/admin-config`).then(e=>e.json()).then(e=>{e.keys&&R(e.keys),typeof e.hostedDemo==`boolean`&&pe(e.hostedDemo),typeof e.adminWrite==`boolean`&&he(e.adminWrite),typeof e.serverMode==`string`&&_e(e.serverMode),e.demoCaps&&typeof e.demoCaps.maxTurns==`number`&&ve({maxTurns:e.demoCaps.maxTurns,maxPopulation:e.demoCaps.maxPopulation??30,maxActiveDepartments:e.demoCaps.maxActiveDepartments??3})}).catch(()=>{}),D(window,je)),[je]);let Me=async e=>{if(e!==ue)try{(await fetch(`/scenario/switch`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:e})})).ok&&(te(),window.location.reload())}catch{}},Ne=(0,b.useCallback)(async()=>{if(o){ae(!0),ce(`Starting...`);try{let e={actors:f.map(e=>({...e,hexaco:e.hexaco})),provider:Ae,turns:y,seed:C,startTime:T,timePerTurn:O||void 0,population:j,liveSearch:P,activeDepartments:a.departments.map(e=>e.id),economics:{profileId:De},scenarioId:a.id};try{localStorage.setItem(`paracosm:lastLaunchConfig`,JSON.stringify(e))}catch{}mg(window.localStorage,f,a.id),Object.assign(e,bg(ye)),ye.serper&&(e.serperKey=ye.serper),ye.firecrawl&&(e.firecrawlKey=ye.firecrawl),ye.tavily&&(e.tavilyKey=ye.tavily),ye.cohere&&(e.cohereKey=ye.cohere),Ee&&(e.models={...xe});let t=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...e,captureSnapshots:!0})}),n=await t.json();if(t.status===429){ce(`Rate limited: ${n.error||`too many simulations`}`),ae(!1);return}if(n.redirect){l(),ce(`Running...`),k(window,n.visitorId);let e=sh(fh(window.location.href,n.redirect));c(e===`about`?`sim`:e)}else ce(`Error: ${n.error||`unknown`}`),ae(!1)}catch(e){ce(`Failed: ${e}`),ae(!1)}}},[f,y,C,T,O,j,Ae,P,c,l,a,o,ye,xe,Ee,De]),Fe=e=>[Y.input,e?Y.locked:``].filter(Boolean).join(` `);return(0,x.jsxs)(`div`,{className:Y.root,children:[(0,x.jsx)(qm,{options:$w,active:n,onChange:i,ariaLabel:`Settings sub-navigation`}),n===`log`&&(0,x.jsx)(Xw,{events:e}),n===`config`&&(0,x.jsxs)(`div`,{className:`settings-content ${Y.content}`,children:[(0,x.jsx)(OC,{}),le.length>0&&(0,x.jsxs)(`div`,{className:`responsive-stack ${Y.scenarioRow}`,children:[(0,x.jsx)(`label`,{htmlFor:`scenario-select`,style:Nw,className:Y.scenarioLabel,children:`Scenario`}),(0,x.jsx)(`select`,{id:`scenario-select`,className:`pc-select ${Y.scenarioSelect}`,value:ue,onChange:e=>Me(e.target.value),children:le.map(e=>{let t=e.description?.includes(`(memory)`)?` [memory]`:e.description?.includes(`(disk)`)?` [disk]`:e.description?.includes(`compiled`)?` [compiled]`:``;return(0,x.jsxs)(`option`,{value:e.id,children:[e.id===ue?`● `:``,e.name,` (`,e.departments,` depts)`,t]},e.id)})}),(0,x.jsxs)(`span`,{className:Y.scenarioActiveTag,children:[`Active: `,(0,x.jsx)(`strong`,{className:Y.scenarioActiveValue,children:ue})]})]}),(0,x.jsx)(`h2`,{className:Y.h2,children:a.labels.name}),a.labels.tagline&&(0,x.jsx)(`p`,{className:Y.scenarioTagline,children:a.labels.tagline}),(0,x.jsxs)(`p`,{className:Y.lead,children:[`Configure your leaders and launch. `,a.departments.length,` departments: `,a.departments.map(e=>e.label).join(`, `),`.`]}),a.sourceUrl&&(0,x.jsx)(`p`,{className:Y.scenarioSourceLink,children:(0,x.jsx)(`a`,{href:a.sourceUrl,target:`_blank`,rel:`noopener noreferrer`,children:`View scenario JSON on GitHub →`})}),(0,x.jsxs)(`p`,{className:Y.leadHint,children:[`Server mode: `,(0,x.jsx)(`strong`,{className:Y.leadStrong,children:Oe.label}),`. `,Oe.description]}),(0,x.jsx)(`div`,{className:`${f.length>2?`responsive-grid-cohort`:`responsive-grid-2`} ${Y.leadersGrid}`,children:f.map((e,t)=>(0,x.jsxs)(`div`,{className:Y.leaderCardWrap,style:{position:`relative`},children:[(0,x.jsx)(Aw,{label:`Commander ${String.fromCharCode(65+t%26)}`,sideColor:Pe(t),data:e,onChange:e=>g(t,e)}),f.length>cT&&(0,x.jsx)(`button`,{type:`button`,onClick:()=>v(t),className:Y.leaderRemoveBtn,"aria-label":`Remove ${e.name||`actor ${t+1}`} from the cohort`,title:`Remove this actor`,children:`✕`})]},t))}),(0,x.jsx)(`div`,{className:Y.leadersAddRow,children:f.length<lT?(0,x.jsxs)(`button`,{type:`button`,onClick:_,className:Y.leaderAddBtn,"aria-label":`Add another actor to the cohort`,children:[`+ Add actor (`,f.length,`/`,lT,`)`]}):(0,x.jsxs)(`span`,{className:Y.leaderAddCap,children:[`Max `,lT,` actors from Settings · use Quickstart's generate-N flow for larger cohorts.`]})}),(0,x.jsxs)(`fieldset`,{className:Y.fieldset,children:[(0,x.jsx)(`legend`,{style:Pw,className:Y.legend,children:`Simulation`}),ke&&(0,x.jsxs)(`div`,{className:Y.demoBanner,children:[(0,x.jsx)(`strong`,{className:Y.demoBannerLabel,children:`Demo caps will apply:`}),` `,`turns clamped to `,B.maxTurns,`, population to `,B.maxPopulation,`, active departments to `,B.maxActiveDepartments,`. Values you enter below are honored up to those ceilings. Add a session API key above to lift the caps.`]}),(0,x.jsxs)(`div`,{className:`responsive-grid-4 ${Y.simRow5}`,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`turns-input`,style:Nw,children:[`Turns`,ke&&(0,x.jsxs)(`span`,{className:Y.lockTag,title:`Hosted demo caps turns at ${B.maxTurns}. Add a session API key to unlock.`,children:[`🔒 demo:`,B.maxTurns]})]}),(0,x.jsx)(`input`,{id:`turns-input`,type:`number`,value:ke?B.maxTurns:y,onChange:e=>{M.current.add(`turns`),S(parseInt(e.target.value)||a.setup.defaultTurns)},min:1,max:20,disabled:ke,className:Fe(ke),title:ke?`Locked at ${B.maxTurns} in hosted demo mode. Add your own OpenAI or Anthropic key above to unlock full scope.`:``})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`ypt-input`,style:Nw,children:[s.Times,`/Turn`]}),(0,x.jsx)(`input`,{id:`ypt-input`,type:`number`,value:O,onChange:e=>{M.current.add(`timePerTurn`),A(parseInt(e.target.value)||0)},min:0,max:50,placeholder:`auto`,title:`${s.Times} per turn. 0 = accelerating schedule (default). 1 = 1 ${s.time} per turn. 5 = 5 ${s.times} per turn.`,className:Y.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{htmlFor:`seed-input`,style:Nw,children:`Seed`}),(0,x.jsx)(`input`,{id:`seed-input`,type:`number`,value:C,onChange:e=>{M.current.add(`seed`),w(parseInt(e.target.value)||a.setup.defaultSeed)},className:Y.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`time-input`,style:Nw,children:[`Start `,s.Time]}),(0,x.jsx)(`input`,{id:`time-input`,type:`number`,value:T,onChange:e=>{M.current.add(`startTime`),E(parseInt(e.target.value)||a.setup.defaultStartTime)},className:Y.input})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`pop-input`,style:Nw,children:[`Population`,ke&&(0,x.jsx)(`span`,{className:Y.lockTag,title:`Hosted demo caps population at 30. Add a session API key to unlock.`,children:`🔒 demo:30`})]}),(0,x.jsx)(`input`,{id:`pop-input`,type:`number`,value:ke?30:j,onChange:e=>{M.current.add(`population`),ee(parseInt(e.target.value)||a.setup.defaultPopulation)},disabled:ke,className:Fe(ke),title:ke?`Locked at 30 in hosted demo mode. Add your own OpenAI or Anthropic key above to unlock full scope.`:``})]})]}),(0,x.jsxs)(`div`,{className:`responsive-grid-3 ${Y.grid3}`,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`provider-select`,style:Nw,children:[`Provider`,ke&&(0,x.jsx)(`span`,{className:Y.lockTag,children:`🔒 demo:openai`})]}),(0,x.jsxs)(`select`,{id:`provider-select`,className:`pc-select ${Fe(ke)}`,value:Ae,onChange:e=>ne(e.target.value),disabled:ke,title:ke?`Locked to OpenAI in hosted demo mode. Add your own OpenAI or Anthropic key above to choose the provider.`:``,children:[(0,x.jsx)(`option`,{value:`openai`,children:`OpenAI`}),(0,x.jsx)(`option`,{value:`anthropic`,children:`Anthropic`})]})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{htmlFor:`search-select`,style:Nw,children:`Live Search`}),(0,x.jsxs)(`select`,{id:`search-select`,className:`pc-select ${Y.input}`,value:String(P),onChange:e=>re(e.target.value===`true`),children:[(0,x.jsx)(`option`,{value:`false`,children:`Off`}),(0,x.jsx)(`option`,{value:`true`,children:`On (requires search API keys)`})]})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`economics-select`,style:Nw,children:[`Economics`,ke&&(0,x.jsx)(`span`,{className:Y.lockTag,children:`🔒 forced:economy`})]}),(0,x.jsx)(`select`,{id:`economics-select`,className:`pc-select ${Fe(ke)}`,value:De,onChange:e=>F(e.target.value),disabled:ke,title:Zw.find(e=>e.value===De)?.description,children:Zw.map(e=>(0,x.jsx)(`option`,{value:e.value,children:e.label},e.value))}),(0,x.jsx)(`div`,{className:Y.fieldHint,children:Zw.find(e=>e.value===De)?.description})]})]})]}),(0,x.jsxs)(`fieldset`,{className:Y.fieldset,children:[(0,x.jsx)(`legend`,{style:Pw,className:Y.legend,children:`API Keys`}),(0,x.jsxs)(`div`,{className:Y.keysIntro,children:[(0,x.jsxs)(`p`,{className:Y.keysIntroPara,children:[(0,x.jsx)(`strong`,{className:Y.keysIntroBoldNeutral,children:`How key resolution works:`}),` The server checks for keys in this order: your session overrides below, then the server .env file. If a key exists in either place, it's used. Values entered here are never displayed back.`]}),(0,x.jsxs)(`p`,{className:Y.keysIntroPara,children:[(0,x.jsx)(`strong`,{className:Y.keysIntroBoldGreen,children:`Rate limiting:`}),` The hosted demo limits simulations per IP per day when using the server's API keys. Provide your own `,(0,x.jsx)(`strong`,{children:`OpenAI`}),` or `,(0,x.jsx)(`strong`,{children:`Anthropic`}),` key to bypass the rate limit and run unlimited simulations. Only one LLM provider key is required. If both are provided, the simulation uses whichever you select as the provider.`]}),(0,x.jsxs)(`p`,{className:Y.keysIntroPara,children:[(0,x.jsx)(`strong`,{className:Y.keysIntroBoldAmber,children:`Research and citations:`}),` Live web search requires at least one search key (Serper, Firecrawl, Tavily). Without any search key, departments fall back to the scenario's built-in research bundle. Cohere enables neural reranking of search results for higher-quality citations. These are optional enhancements, not required to run a simulation.`]}),(0,x.jsxs)(`p`,{className:Y.keysIntroParaLast,children:[(0,x.jsx)(`strong`,{className:Y.keysIntroBoldRust,children:`No keys at all?`}),` If neither a server .env key nor a session override exists for any LLM provider, the simulation cannot run. You need at least one OpenAI or Anthropic key configured somewhere.`]})]}),(0,x.jsx)(`div`,{className:`responsive-grid-2 ${Y.grid2}`,children:[[`openai`,`OpenAI`,`Required (or Anthropic). Powers commander, departments, crisis director.`],[`anthropic`,`Anthropic`,`Required (or OpenAI). Alternative LLM provider for all simulation roles.`],[`serper`,`Serper (search)`,`Optional. Enables live Google search for department research citations.`],[`firecrawl`,`Firecrawl (scrape)`,`Optional. Enables web page scraping for deeper research context.`],[`tavily`,`Tavily (search)`,`Optional. Additional search provider. Multiple providers improve coverage.`],[`cohere`,`Cohere (rerank)`,`Optional. Neural reranking of search results for citation quality.`]].map(([e,t,n])=>(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`label`,{htmlFor:`key-${e}`,style:Nw,children:[t,fe[e]&&(0,x.jsx)(`span`,{className:Y.keyEnvTag,children:`(.env active)`})]}),(0,x.jsx)(`input`,{id:`key-${e}`,type:`password`,autoComplete:`off`,value:ye[e],onChange:t=>be(n=>({...n,[e]:t.target.value})),placeholder:fe[e]?`Using .env value`:`Not configured`,className:Y.input}),(0,x.jsx)(`div`,{className:Y.fieldHint,children:n})]},e))})]}),Te&&(N===`openai`||N===`anthropic`)&&(0,x.jsxs)(`fieldset`,{className:Y.fieldset,children:[(0,x.jsx)(`legend`,{style:Pw,className:Y.legend,children:`Model Tiers`}),(0,x.jsx)(`div`,{className:Y.modelTiersIntro,children:`Assign a model to each agent tier. Departments do the forging and benefit most from the flagship class. Agent reactions fan out to hundreds of parallel calls per turn and should be the cheapest class available. These overrides are only used when you run against your own API key.`}),(0,x.jsx)(`div`,{className:`responsive-grid-2 ${Y.grid2}`,children:Object.keys(rT).map(e=>(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`label`,{htmlFor:`model-${e}`,style:Nw,children:rT[e].label}),(0,x.jsx)(`select`,{id:`model-${e}`,className:`pc-select ${Y.input}`,value:xe[e],onChange:t=>Se(n=>({...n,[e]:t.target.value})),children:tT[N].map(e=>(0,x.jsx)(`option`,{value:e.value,children:e.label},e.value))}),(0,x.jsx)(`div`,{className:Y.fieldHint,children:rT[e].help})]},e))})]}),!Te&&(0,x.jsxs)(`div`,{className:Y.demoMode,children:[(0,x.jsx)(`strong`,{className:Y.demoModeStrong,children:`Demo mode.`}),` `,z?`Runs against the host API keys are capped to ${B.maxTurns} turns, ${B.maxPopulation} colonists, ${B.maxActiveDepartments} departments, and the cheapest model class. Add your own OpenAI or Anthropic key above to unlock full scope and per-tier model selection.`:`No API key configured. Add an OpenAI or Anthropic key above or set one in .env to enable simulations and the per-tier model picker.`]}),me&&(0,x.jsxs)(`fieldset`,{className:Y.fieldset,children:[(0,x.jsx)(`legend`,{style:Pw,className:Y.legend,children:`Admin Token`}),(0,x.jsx)(Uw,{})]}),(0,x.jsx)(Bw,{onAdminWrite:he}),(0,x.jsxs)(`div`,{className:`responsive-stack ${Y.launchRow}`,children:[(0,x.jsx)(`button`,{onClick:Ne,disabled:I||!o,"aria-label":I?`Simulation running`:o?`Launch simulation`:`Loading scenario`,className:Y.launchBtn,children:I?`Running...`:o?`Launch Simulation`:`Loading scenario…`}),oe&&(0,x.jsx)(`span`,{role:`status`,className:Y.launchStatus,children:oe})]})]})]})}function dT(e){let t=t=>{let n=e[t];return Number.isFinite(n)?n:.5};return{openness:t(`openness`),conscientiousness:t(`conscientiousness`),extraversion:t(`extraversion`),agreeableness:t(`agreeableness`),emotionality:t(`emotionality`),honestyHumility:t(`honestyHumility`)}}function fT(e,t=[]){return[...(e.presets?.[0]?.leaders??[]).map(e=>({name:e.name,archetype:e.archetype,unit:`Forked Branch`,hexaco:dT(e.hexaco),instructions:e.instructions})),...t]}var pT={openai:{quality:.3,economy:.1},anthropic:{quality:.75,economy:.6}};function mT(e,t,n,r){let i=Math.max(0,t-e)*pT[r][n];return`~$${(Math.ceil(i*10)/10).toFixed(2)}`}function hT(e){let t=[];for(let n of e.split(`
127
+ `)){let e=n.trim();if(!e)continue;let r=/^(\d+)\s*:\s*([^:]+?)\s*:\s*(.+)$/.exec(e);if(!r)continue;let i=parseInt(r[1],10),a=r[2].trim(),o=r[3].trim();a&&t.push({turn:i,title:a,description:o})}return t}var gT=new Set([`kernelSnapshotAtStart`,`kernelSnapshotsAfterProgression`]);function _T(e){let t=e.scenarioExtensions;if(!t||typeof t!=`object`)return e;let n=Object.fromEntries(Object.entries(t).filter(([e])=>!gT.has(e)));return{...e,scenarioExtensions:n}}function vT(e){let t=e.scenarioExtensions?.kernelSnapshotsPerTurn;return Array.isArray(t)?t.map(e=>e?.turn).filter(e=>typeof e==`number`&&Number.isFinite(e)):[]}function yT(e){let t=e.trajectory?.timepoints?.length??0,n=vT(e),r=Math.max(t,...n);return r>0?r:6}function bT(e,t){return vT(e).includes(t)&&t<yT(e)}var xT={forkButton:`_forkButton_14oeq_1`,backdrop:`_backdrop_14oeq_28`,dialog:`_dialog_14oeq_40`,header:`_header_14oeq_58`,closeButton:`_closeButton_14oeq_75`,field:`_field_14oeq_92`,hint:`_hint_14oeq_122`,warning:`_warning_14oeq_128`,advanced:`_advanced_14oeq_139`,costEstimate:`_costEstimate_14oeq_173`,costDetail:`_costDetail_14oeq_191`,footer:`_footer_14oeq_196`,cancelButton:`_cancelButton_14oeq_224`,confirmButton:`_confirmButton_14oeq_228`};function ST(e){let{parentArtifact:t,atTurn:n,maxTurns:r,costPreset:i,provider:a,sessionCustomLeaders:o=[],onConfirm:s,onClose:c}=e,l=Qk(),u=Lm(),d=Pt(!0),f=fT(l,o),[p,m]=(0,b.useState)(0),[h,g]=(0,b.useState)(``),[_,v]=(0,b.useState)(``);(0,b.useEffect)(()=>{let e=e=>{e.key===`Escape`&&c()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[c]);let y=mT(n,r,i,a),S=Math.max(0,r-n),C=t.metadata.seed;return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-labelledby":`fork-modal-title`,className:xT.backdrop,onClick:c,children:(0,x.jsxs)(`div`,{ref:d,tabIndex:-1,className:xT.dialog,onClick:e=>e.stopPropagation(),children:[(0,x.jsxs)(`header`,{className:xT.header,children:[(0,x.jsxs)(`h3`,{id:`fork-modal-title`,children:[`Fork at `,u.Time,` `,n]}),(0,x.jsx)(`button`,{type:`button`,className:xT.closeButton,onClick:c,"aria-label":`Close fork modal`,children:`×`})]}),(0,x.jsxs)(`div`,{className:xT.field,children:[(0,x.jsx)(`label`,{htmlFor:`fork-leader-select`,children:`Override leader`}),f.length===0?(0,x.jsx)(`p`,{className:xT.warning,children:`No preset leaders available for this scenario. Add leaders in Settings or pick a scenario with presets to continue.`}):(0,x.jsx)(`select`,{id:`fork-leader-select`,value:p,onChange:e=>m(parseInt(e.target.value,10)),children:f.map((e,t)=>(0,x.jsxs)(`option`,{value:t,children:[e.name,` (`,e.archetype,`)`]},`${e.name}-${t}`))})]}),(0,x.jsxs)(`div`,{className:xT.field,children:[(0,x.jsx)(`label`,{htmlFor:`fork-seed`,children:`Seed override (optional)`}),(0,x.jsx)(`input`,{id:`fork-seed`,type:`number`,placeholder:C===void 0?`(use parent seed)`:`Parent seed: ${C}`,value:h,onChange:e=>g(e.target.value)}),(0,x.jsx)(`span`,{className:xT.hint,children:`Leave blank to resume from the parent's RNG state.`})]}),(0,x.jsxs)(`details`,{className:xT.advanced,children:[(0,x.jsx)(`summary`,{children:`Advanced: custom events`}),(0,x.jsx)(`textarea`,{rows:4,placeholder:`One event per line, format: "turn: title: description"
128
+ Example: 5: Supply drop: Relief arrives with 3 months of food.`,value:_,onChange:e=>v(e.target.value)})]}),(0,x.jsxs)(`div`,{className:xT.costEstimate,role:`status`,children:[(0,x.jsx)(`span`,{children:`Estimated cost`}),(0,x.jsx)(`strong`,{children:y}),(0,x.jsxs)(`span`,{className:xT.costDetail,children:[`for `,S,` more `,S===1?u.time:u.times]})]}),(0,x.jsxs)(`footer`,{className:xT.footer,children:[(0,x.jsx)(`button`,{type:`button`,onClick:c,className:xT.cancelButton,children:`Cancel`}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>{let e=f[p];if(!e)return;let r=h.trim()?parseInt(h,10):void 0,i=r!==void 0&&Number.isFinite(r)?r:void 0,a=_.trim()?hT(_):void 0;s({parentArtifact:t,atTurn:n,leader:e,seedOverride:i,customEvents:a})},disabled:f.length===0,className:xT.confirmButton,children:`Fork`})]})]})})}var CT=`/retry-stats`;function wT(e=!0){let[t,n]=(0,b.useState)(null),[r,i]=(0,b.useState)(!1),[a,o]=(0,b.useState)(null),s=(0,b.useCallback)(async()=>{i(!0),o(null);try{let e=await fetch(CT,{credentials:`same-origin`});if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();n(t)}catch(e){o(e instanceof Error?e.message:String(e))}finally{i(!1)}},[]);return(0,b.useEffect)(()=>{e&&s()},[e,s]),{data:t,loading:r,error:a,refresh:s}}var X={backdrop:`_backdrop_vajsn_1`,dialog:`_dialog_vajsn_12`,titleRow:`_titleRow_vajsn_27`,title:`_title_vajsn_27`,escBtn:`_escBtn_vajsn_43`,totalLine:`_totalLine_vajsn_54`,totalAmount:`_totalAmount_vajsn_60`,cacheBlock:`_cacheBlock_vajsn_66`,cacheLabel:`_cacheLabel_vajsn_74`,cacheVerdict:`_cacheVerdict_vajsn_83`,cacheSubLine:`_cacheSubLine_vajsn_91`,cacheTokenRow:`_cacheTokenRow_vajsn_98`,cacheMultiplier:`_cacheMultiplier_vajsn_107`,emptyState:`_emptyState_vajsn_111`,table:`_table_vajsn_118`,tableSm:`_tableSm_vajsn_125`,headRow:`_headRow_vajsn_132`,th:`_th_vajsn_139`,thRight:`_thRight_vajsn_144`,bodyRow:`_bodyRow_vajsn_150`,stageCell:`_stageCell_vajsn_154`,stageLabel:`_stageLabel_vajsn_158`,stageDescription:`_stageDescription_vajsn_164`,bar:`_bar_vajsn_171`,barFill:`_barFill_vajsn_180`,numericCell:`_numericCell_vajsn_187`,numericCellGreen:`_numericCellGreen_vajsn_193`,numericCellMuted:`_numericCellMuted_vajsn_201`,section:`_section_vajsn_208`,sectionLabel:`_sectionLabel_vajsn_214`,sectionFootnote:`_sectionFootnote_vajsn_222`,sectionFootnoteTight:`_sectionFootnoteTight_vajsn_229`,subBlock:`_subBlock_vajsn_236`,subBlockLabel:`_subBlockLabel_vajsn_240`,cellSchemaName:`_cellSchemaName_vajsn_247`,cellNumericTight:`_cellNumericTight_vajsn_252`,cellAvgAttempts:`_cellAvgAttempts_vajsn_258`,cellFallback:`_cellFallback_vajsn_265`,cellRight1:`_cellRight1_vajsn_272`,cellRightGreen:`_cellRightGreen_vajsn_278`,cellRightRust:`_cellRightRust_vajsn_285`,cellRightMuted:`_cellRightMuted_vajsn_291`,cellRateColor:`_cellRateColor_vajsn_297`,cellConfColor:`_cellConfColor_vajsn_304`,statusInline:`_statusInline_vajsn_311`,statusErrorTag:`_statusErrorTag_vajsn_320`,rejectionWrap:`_rejectionWrap_vajsn_324`,rejectionLabel:`_rejectionLabel_vajsn_328`,rejectionCell:`_rejectionCell_vajsn_335`,perLeaderRow:`_perLeaderRow_vajsn_342`,leaderCard:`_leaderCard_vajsn_349`,leaderName:`_leaderName_vajsn_357`,leaderCost:`_leaderCost_vajsn_363`,leaderMeta:`_leaderMeta_vajsn_369`,perActorList:`_perActorList_vajsn_378`,perActorRow:`_perActorRow_vajsn_386`,perActorBarTrack:`_perActorBarTrack_vajsn_412`,perActorCost:`_perActorCost_vajsn_417`,perActorMeta:`_perActorMeta_vajsn_421`,perActorRank:`_perActorRank_vajsn_426`,perActorName:`_perActorName_vajsn_433`,perActorBarFill:`_perActorBarFill_vajsn_448`},TT={director:{label:`Event Director`,description:`Generates events each turn based on world state`},commander:{label:`Commander`,description:`Reads dept reports, picks options, promotes department heads`},departments:{label:`Department Analysis`,description:`5 specialists analyzing each event in parallel`},judge:{label:`Forge Judge`,description:`LLM safety + correctness review of every forged tool`},reactions:{label:`Agent Reactions`,description:`~100 colonists reacting to each turn's outcome`},other:{label:`Other`,description:`Uncategorized calls`}};function ET(e){return e<1e-4?`$0.0000`:`$${e<.01?e.toFixed(4):e.toFixed(2)}`}function DT(e){return e>=1e6?`${(e/1e6).toFixed(2)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function OT(e){return e>1.5?`var(--rust)`:e>1.1?`var(--amber)`:`var(--text-1)`}function kT(e){return e>.01?`var(--rust)`:e>0?`var(--amber)`:`var(--text-3)`}function AT({combined:e,leaderA:t,leaderB:n,leaderAName:r,leaderBName:i,actors:a,onClose:o}){(0,b.useEffect)(()=>{let e=e=>{e.key===`Escape`&&o()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o]);let s=Pt(!0),c=wT(!0),l=e.breakdown??{},u=Object.entries(l).map(([e,t])=>({site:e,...t})).sort((e,t)=>t.totalCostUSD-e.totalCostUSD),d=e.totalCostUSD||u.reduce((e,t)=>e+t.totalCostUSD,0),f=u[0]?.totalCostUSD??0;return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Cost breakdown`,onClick:o,className:X.backdrop,children:(0,x.jsxs)(`div`,{ref:s,tabIndex:-1,onClick:e=>e.stopPropagation(),className:X.dialog,children:[(0,x.jsxs)(`div`,{className:X.titleRow,children:[(0,x.jsx)(`h3`,{className:X.title,children:`COST BREAKDOWN`}),(0,x.jsx)(`button`,{onClick:o,"aria-label":`Close cost breakdown`,className:X.escBtn,children:`ESC`})]}),(0,x.jsxs)(`div`,{className:X.totalLine,children:[`Total: `,(0,x.jsx)(`span`,{className:X.totalAmount,children:ET(d)}),` · `,e.llmCalls.toLocaleString(),` calls`,` · `,DT(e.totalTokens),` tokens`]}),e.cacheReadTokens||e.cacheCreationTokens?(()=>{let t=e.cacheReadTokens??0,n=e.cacheCreationTokens??0,r=e.cacheSavingsUSD??0,i=t+n,a=i>0?t/i:0,o=`var(--text-3)`,s;return r>.001?(o=`var(--green)`,s=`Saved ${ET(r)} via prompt caching`):r<-.001?(o=`var(--amber)`,s=`Cache priming cost ${ET(-r)} so far · reuse will repay this`):t>0?(o=`var(--green)`,s=`Cache reuse breaking even with priming cost`):(o=`var(--amber)`,s=`Cache filled but nothing reused yet · retry run or check prompt stability`),(0,x.jsxs)(`div`,{className:X.cacheBlock,children:[(0,x.jsx)(`div`,{className:X.cacheLabel,children:`PROMPT CACHING`}),(0,x.jsx)(`div`,{className:X.cacheVerdict,style:{"--cache-verdict-color":o},children:s}),(0,x.jsxs)(`div`,{className:X.cacheSubLine,children:[Math.round(a*100),`% hit rate on cached input (`,DT(t),` reused / `,DT(i),` cache tokens)`]}),(0,x.jsxs)(`div`,{className:X.cacheTokenRow,children:[(0,x.jsxs)(`span`,{children:[`reads `,DT(t),` `,(0,x.jsx)(`span`,{className:X.cacheMultiplier,children:`@0.10×`})]}),(0,x.jsxs)(`span`,{children:[`creates `,DT(n),` `,(0,x.jsx)(`span`,{className:X.cacheMultiplier,children:`@1.25×`})]})]})]})})():null,u.length===0?(0,x.jsx)(`div`,{className:X.emptyState,children:`No LLM calls have been billed yet. Start a simulation to see spend by pipeline stage.`}):(0,x.jsxs)(`table`,{className:X.table,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.th,children:`STAGE`}),(0,x.jsx)(`th`,{className:X.thRight,children:`CALLS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`TOKENS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`COST`}),(0,x.jsx)(`th`,{className:X.thRight,children:`%`})]})}),(0,x.jsx)(`tbody`,{children:u.map(e=>{let t=TT[e.site]??{label:e.site,description:``},n=d>0?e.totalCostUSD/d*100:0,r=f>0?e.totalCostUSD/f*100:0;return(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsxs)(`td`,{className:X.stageCell,children:[(0,x.jsx)(`div`,{className:X.stageLabel,children:t.label}),(0,x.jsx)(`div`,{className:X.stageDescription,children:t.description}),(0,x.jsx)(`div`,{"aria-hidden":`true`,className:X.bar,children:(0,x.jsx)(`div`,{className:X.barFill,style:{"--bar-pct":`${r}%`}})})]}),(0,x.jsx)(`td`,{className:X.numericCell,children:e.calls.toLocaleString()}),(0,x.jsx)(`td`,{className:X.numericCell,children:DT(e.totalTokens)}),(0,x.jsx)(`td`,{className:X.numericCellGreen,children:ET(e.totalCostUSD)}),(0,x.jsxs)(`td`,{className:X.numericCellMuted,children:[n.toFixed(0),`%`]})]},e.site)})})]}),e.schemaRetries&&Object.keys(e.schemaRetries).length>0&&(0,x.jsxs)(`div`,{className:X.section,children:[(0,x.jsx)(`div`,{className:X.sectionLabel,children:`SCHEMA RELIABILITY`}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.th,children:`SCHEMA`}),(0,x.jsx)(`th`,{className:X.thRight,children:`CALLS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`AVG ATTEMPTS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`FALLBACKS`})]})}),(0,x.jsx)(`tbody`,{children:Object.entries(e.schemaRetries).sort((e,t)=>t[1].calls-e[1].calls).map(([e,t])=>{let n=t.calls>0?t.attempts/t.calls:0,r=OT(n),i=t.fallbacks>0?`var(--rust)`:`var(--text-3)`;return(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsx)(`td`,{className:X.cellSchemaName,children:e}),(0,x.jsx)(`td`,{className:X.cellNumericTight,children:t.calls}),(0,x.jsx)(`td`,{className:X.cellAvgAttempts,style:{"--avg-color":r},children:n.toFixed(2)}),(0,x.jsx)(`td`,{className:X.cellFallback,style:{"--fb-color":i,"--fb-weight":t.fallbacks>0?`700`:`400`},children:t.fallbacks})]},e)})})]}),(0,x.jsxs)(`div`,{className:X.sectionFootnote,children:[`1.00 = first-try success. Higher = model retrying on validation failures. Tune `,(0,x.jsx)(`code`,{className:`mono`,children:`maxRetries`}),` or tighten schema if a row stays above 1.3.`]})]}),e.forgeStats&&e.forgeStats.attempts>0&&(0,x.jsxs)(`div`,{className:X.section,children:[(0,x.jsx)(`div`,{className:X.sectionLabel,children:`FORGE RELIABILITY`}),(()=>{let t=e.forgeStats,n=t.attempts>0?t.approved/t.attempts:0,r=t.approved>0?t.approvedConfidenceSum/t.approved:0,i=n<.5?`var(--rust)`:n<.75?`var(--amber)`:`var(--green)`,a=r>0&&r<.6?`var(--amber)`:`var(--text-1)`;return(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.thRight,children:`ATTEMPTS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`APPROVED`}),(0,x.jsx)(`th`,{className:X.thRight,children:`REJECTED`}),(0,x.jsx)(`th`,{className:X.thRight,children:`APPROVAL RATE`}),(0,x.jsx)(`th`,{className:X.thRight,children:`AVG CONF`})]})}),(0,x.jsx)(`tbody`,{children:(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsx)(`td`,{className:X.cellRight1,children:t.attempts}),(0,x.jsx)(`td`,{className:X.cellRightGreen,children:t.approved}),(0,x.jsx)(`td`,{className:t.rejected>0?X.cellRightRust:X.cellRightMuted,children:t.rejected}),(0,x.jsxs)(`td`,{className:X.cellRateColor,style:{"--rate-color":i},children:[(n*100).toFixed(0),`%`]}),(0,x.jsx)(`td`,{className:X.cellConfColor,style:{"--conf-color":a},children:r>0?r.toFixed(2):`—`})]})})]})})(),(0,x.jsx)(`div`,{className:X.sectionFootnote,children:`Rejections come from shape check OR judge verdict. Retry-with-feedback usually recovers; persistent low approval rate suggests the department model is weak at writing schema-compliant code.`})]}),(()=>{let e=c.data;if(c.loading&&!e)return(0,x.jsx)(`div`,{className:X.statusInline,children:`RECENT RUNS — loading…`});if(c.error)return(0,x.jsxs)(`div`,{className:X.statusInline,children:[`RECENT RUNS — `,(0,x.jsxs)(`span`,{className:X.statusErrorTag,children:[`fetch failed (`,c.error,`)`]})]});if(!e||e.runCount===0)return null;let t=Object.entries(e.schemas).filter(([e])=>!e.startsWith(`compile:`)),n=Object.entries(e.schemas).filter(([e])=>e.startsWith(`compile:`)).map(([e,t])=>[e.replace(/^compile:/,``),t]),r=e.forges,i=e.caches,a=e.providerErrors,o=([e,t])=>{let n=OT(t.avgAttempts),r=kT(t.fallbackRate);return(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsx)(`td`,{className:X.cellSchemaName,children:e}),(0,x.jsx)(`td`,{className:X.cellNumericTight,children:t.calls}),(0,x.jsx)(`td`,{className:X.cellAvgAttempts,style:{"--avg-color":n},children:t.avgAttempts.toFixed(2)}),(0,x.jsxs)(`td`,{className:X.cellFallback,style:{"--fb-color":r,"--fb-weight":t.fallbacks>0?`700`:`400`},children:[(t.fallbackRate*100).toFixed(2),`%`]})]},e)};return(0,x.jsxs)(`div`,{className:X.section,children:[(0,x.jsxs)(`div`,{className:X.sectionLabel,children:[`RECENT RUNS (last `,e.runCount,`)`]}),t.length>0&&(0,x.jsxs)(`div`,{className:X.subBlock,children:[(0,x.jsx)(`div`,{className:X.subBlockLabel,children:`RUNTIME SCHEMAS`}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.th,children:`SCHEMA`}),(0,x.jsx)(`th`,{className:X.thRight,children:`CALLS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`AVG ATT`}),(0,x.jsx)(`th`,{className:X.thRight,children:`FALLBACK %`})]})}),(0,x.jsx)(`tbody`,{children:t.sort((e,t)=>t[1].calls-e[1].calls).map(o)})]})]}),n.length>0&&(0,x.jsxs)(`div`,{className:X.subBlock,children:[(0,x.jsx)(`div`,{className:X.subBlockLabel,children:`COMPILE HOOKS`}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.th,children:`HOOK`}),(0,x.jsx)(`th`,{className:X.thRight,children:`CALLS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`AVG ATT`}),(0,x.jsx)(`th`,{className:X.thRight,children:`FALLBACK %`})]})}),(0,x.jsx)(`tbody`,{children:n.sort((e,t)=>t[1].calls-e[1].calls).map(o)})]})]}),r&&r.runsPresent>0&&(0,x.jsxs)(`div`,{className:X.subBlock,children:[(0,x.jsx)(`div`,{className:X.subBlockLabel,children:`FORGES`}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.thRight,children:`RUNS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`ATTEMPTS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`ATTEMPT RATE`}),(0,x.jsx)(`th`,{className:X.thRight,children:`UNIQUE TOOLS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`EVENTUALLY APPROVED`}),(0,x.jsx)(`th`,{className:X.thRight,children:`TERMINAL FAILS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`AVG CONF`})]})}),(0,x.jsx)(`tbody`,{children:(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsx)(`td`,{className:X.cellRight1,children:r.runsPresent}),(0,x.jsx)(`td`,{className:X.cellRight1,children:r.totalAttempts}),(0,x.jsxs)(`td`,{className:X.cellRateColor,style:{"--rate-color":r.approvalRate<.5?`var(--rust)`:r.approvalRate<.75?`var(--amber)`:`var(--green)`},children:[(r.approvalRate*100).toFixed(1),`%`]}),(0,x.jsx)(`td`,{className:X.cellRight1,children:r.totalUniqueNames}),(0,x.jsxs)(`td`,{className:X.cellRateColor,style:{"--rate-color":r.uniqueApprovalRate<.8?`var(--rust)`:r.uniqueApprovalRate<.95?`var(--amber)`:`var(--green)`},children:[r.totalUniqueApproved,` (`,(r.uniqueApprovalRate*100).toFixed(0),`%)`]}),(0,x.jsx)(`td`,{className:X.cellFallback,style:{"--fb-color":r.totalUniqueTerminalRejections>0?`var(--rust)`:`var(--text-3)`,"--fb-weight":r.totalUniqueTerminalRejections>0?`700`:`400`},children:r.totalUniqueTerminalRejections}),(0,x.jsx)(`td`,{className:X.cellRight1,style:{fontWeight:700},children:r.avgApprovedConfidence>0?r.avgApprovedConfidence.toFixed(2):`—`})]})})]}),(0,x.jsx)(`div`,{className:X.sectionFootnoteTight,children:`ATTEMPT RATE counts every forge call including retries. EVENTUALLY APPROVED is the real quality signal — tools that landed in the toolbox. TERMINAL FAILS are tools the retry loop never recovered.`}),(()=>{let e=r.rejectionReasons,t=e.schema_extra_field+e.shape_check+e.parse_error+e.judge_correctness+e.other;if(t===0)return null;let n=e=>t>0?Math.round(e/t*100):0,i=(e,t)=>({"--rj-color":e>0?t:`var(--text-3)`,"--rj-weight":e>0?`700`:`400`});return(0,x.jsxs)(`div`,{className:X.rejectionWrap,children:[(0,x.jsxs)(`div`,{className:X.rejectionLabel,children:[`REJECTION REASONS (last `,r.runsPresent,` run`,r.runsPresent===1?``:`s`,`)`]}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.thRight,children:`SCHEMA EXTRA FIELD`}),(0,x.jsx)(`th`,{className:X.thRight,children:`SHAPE CHECK`}),(0,x.jsx)(`th`,{className:X.thRight,children:`PARSE ERROR`}),(0,x.jsx)(`th`,{className:X.thRight,children:`JUDGE CORRECTNESS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`OTHER`})]})}),(0,x.jsx)(`tbody`,{children:(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsxs)(`td`,{className:X.rejectionCell,style:i(e.schema_extra_field,`var(--amber)`),children:[e.schema_extra_field,` (`,n(e.schema_extra_field),`%)`]}),(0,x.jsxs)(`td`,{className:X.rejectionCell,style:i(e.shape_check,`var(--amber)`),children:[e.shape_check,` (`,n(e.shape_check),`%)`]}),(0,x.jsxs)(`td`,{className:X.rejectionCell,style:i(e.parse_error,`var(--rust)`),children:[e.parse_error,` (`,n(e.parse_error),`%)`]}),(0,x.jsxs)(`td`,{className:X.rejectionCell,style:i(e.judge_correctness,`var(--rust)`),children:[e.judge_correctness,` (`,n(e.judge_correctness),`%)`]}),(0,x.jsxs)(`td`,{className:X.cellRightMuted,children:[e.other,` (`,n(e.other),`%)`]})]})})]}),(0,x.jsx)(`div`,{className:X.sectionFootnoteTight,children:`SCHEMA EXTRA FIELD dominating means the LLM's return-keys don't match its declared outputSchema.properties — the target of the 2026-04-18 forge-guidance prompt fix. JUDGE CORRECTNESS = real logic bugs the judge caught.`})]})})()]}),a&&a.runsPresent>0&&(0,x.jsxs)(`div`,{className:X.subBlock,children:[(0,x.jsx)(`div`,{className:X.subBlockLabel,children:`PROVIDER ERRORS`}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.thRight,children:`RUNS W/ ERRORS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`TOTAL`}),(0,x.jsx)(`th`,{className:X.thRight,children:`AUTH`}),(0,x.jsx)(`th`,{className:X.thRight,children:`QUOTA`}),(0,x.jsx)(`th`,{className:X.thRight,children:`RATE`}),(0,x.jsx)(`th`,{className:X.thRight,children:`NET`}),(0,x.jsx)(`th`,{className:X.thRight,children:`OTHER`})]})}),(0,x.jsx)(`tbody`,{children:(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsx)(`td`,{className:X.cellRight1,children:a.runsPresent}),(0,x.jsx)(`td`,{className:X.cellRight1,style:{fontWeight:700},children:a.total}),(0,x.jsx)(`td`,{className:X.cellFallback,style:{"--fb-color":a.auth>0?`var(--rust)`:`var(--text-3)`,"--fb-weight":a.auth>0?`700`:`400`},children:a.auth}),(0,x.jsx)(`td`,{className:X.cellFallback,style:{"--fb-color":a.quota>0?`var(--rust)`:`var(--text-3)`,"--fb-weight":a.quota>0?`700`:`400`},children:a.quota}),(0,x.jsx)(`td`,{className:a.rate_limit>0?X.cellFallback:X.cellRightMuted,style:a.rate_limit>0?{"--fb-color":`var(--amber)`,"--fb-weight":`400`}:void 0,children:a.rate_limit}),(0,x.jsx)(`td`,{className:a.network>0?X.cellFallback:X.cellRightMuted,style:a.network>0?{"--fb-color":`var(--amber)`,"--fb-weight":`400`}:void 0,children:a.network}),(0,x.jsx)(`td`,{className:a.unknown>0?X.cellFallback:X.cellRightMuted,style:a.unknown>0?{"--fb-color":`var(--amber)`,"--fb-weight":`400`}:void 0,children:a.unknown})]})})]}),(0,x.jsx)(`div`,{className:X.sectionFootnoteTight,children:`AUTH/QUOTA are terminal (run aborts). RATE/NET/OTHER are non-terminal — the retry layer handles them.`})]}),i&&i.runsPresent>0&&(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:X.subBlockLabel,children:`PROMPT CACHE`}),(0,x.jsxs)(`table`,{className:X.tableSm,children:[(0,x.jsx)(`thead`,{children:(0,x.jsxs)(`tr`,{className:X.headRow,children:[(0,x.jsx)(`th`,{className:X.thRight,children:`RUNS WITH CACHE`}),(0,x.jsx)(`th`,{className:X.thRight,children:`READ TOKENS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`CREATE TOKENS`}),(0,x.jsx)(`th`,{className:X.thRight,children:`READ RATIO`}),(0,x.jsx)(`th`,{className:X.thRight,children:`SAVINGS`})]})}),(0,x.jsx)(`tbody`,{children:(0,x.jsxs)(`tr`,{className:X.bodyRow,children:[(0,x.jsx)(`td`,{className:X.cellRight1,children:i.runsPresent}),(0,x.jsx)(`td`,{className:X.cellRight1,children:DT(i.totalReadTokens)}),(0,x.jsx)(`td`,{className:X.cellNumericTight,children:DT(i.totalCreationTokens)}),(0,x.jsxs)(`td`,{className:X.cellRateColor,style:{"--rate-color":i.readRatio>=.7?`var(--green)`:i.readRatio>=.4?`var(--amber)`:`var(--rust)`},children:[(i.readRatio*100).toFixed(0),`%`]}),(0,x.jsx)(`td`,{className:X.cellRateColor,style:{"--rate-color":i.totalSavingsUSD>0?`var(--green)`:`var(--text-2)`},children:ET(i.totalSavingsUSD)})]})})]}),(0,x.jsx)(`div`,{className:X.sectionFootnoteTight,children:`Read ratio >= 70% is healthy. Lower ratios mean the cache keeps getting invalidated.`})]})]})})(),a&&a.length>2&&(0,x.jsxs)(`div`,{className:X.section,children:[(0,x.jsxs)(`div`,{className:X.sectionLabel,children:[`PER ACTOR · `,a.length,` ACTORS`]}),(()=>{let e=[...a].sort((e,t)=>t.cost.totalCostUSD-e.cost.totalCostUSD),t=e[0]?.cost.totalCostUSD??0,n=e.reduce((e,t)=>e+t.cost.totalCostUSD,0);return(0,x.jsx)(`div`,{className:X.perActorList,children:e.map((e,r)=>{let i=t>0?e.cost.totalCostUSD/t*100:0,a=n>0?e.cost.totalCostUSD/n*100:0;return(0,x.jsxs)(`div`,{className:X.perActorRow,children:[(0,x.jsxs)(`div`,{className:X.perActorRank,children:[`#`,r+1]}),(0,x.jsx)(`div`,{className:X.perActorName,title:e.name,children:e.name}),(0,x.jsx)(`div`,{className:X.perActorBarTrack,"aria-hidden":`true`,children:(0,x.jsx)(`div`,{className:X.perActorBarFill,style:{width:`${i}%`}})}),(0,x.jsx)(`div`,{className:X.perActorCost,children:ET(e.cost.totalCostUSD)}),(0,x.jsxs)(`div`,{className:X.perActorMeta,children:[e.cost.llmCalls,` calls · `,DT(e.cost.totalTokens),` tok · `,a.toFixed(1),`%`]})]},e.actorId)})})})()]}),t&&n&&(t.totalCostUSD>0||n.totalCostUSD>0)&&(0,x.jsxs)(`div`,{className:X.section,children:[(0,x.jsx)(`div`,{className:X.sectionLabel,children:`PER LEADER`}),(0,x.jsxs)(`div`,{className:X.perLeaderRow,children:[(0,x.jsxs)(`div`,{className:X.leaderCard,children:[(0,x.jsx)(`div`,{className:X.leaderName,style:{"--leader-color":`var(--vis)`},children:r||`Leader A`}),(0,x.jsx)(`div`,{className:X.leaderCost,children:ET(t.totalCostUSD)}),(0,x.jsxs)(`div`,{className:X.leaderMeta,children:[t.llmCalls,` calls · `,DT(t.totalTokens),` tok`]})]}),(0,x.jsxs)(`div`,{className:X.leaderCard,children:[(0,x.jsx)(`div`,{className:X.leaderName,style:{"--leader-color":`var(--eng)`},children:i||`Leader B`}),(0,x.jsx)(`div`,{className:X.leaderCost,children:ET(n.totalCostUSD)}),(0,x.jsxs)(`div`,{className:X.leaderMeta,children:[n.llmCalls,` calls · `,DT(n.totalTokens),` tok`]})]})]})]})]})})}var jT={card:`_card_mk5ry_1`,headerRow:`_headerRow_mk5ry_11`,title:`_title_mk5ry_18`,range:`_range_mk5ry_24`,legend:`_legend_mk5ry_28`,legendItem:`_legendItem_mk5ry_35`,legendSwatch:`_legendSwatch_mk5ry_41`,legendLabel:`_legendLabel_mk5ry_48`,legendValue:`_legendValue_mk5ry_52`},MT=[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`],NT={openness:`var(--side-a, #e8b44a)`,conscientiousness:`var(--teal, #4ca8a8)`,extraversion:`#c44a1e`,agreeableness:`#6b9a6b`,emotionality:`#a86cb5`,honestyHumility:`#d2b48c`},PT={openness:`O`,conscientiousness:`C`,extraversion:`E`,agreeableness:`A`,emotionality:`Em`,honestyHumility:`HH`};function FT(e){if(e){for(let t of[`openness`,`conscientiousness`,`extraversion`,`agreeableness`,`emotionality`,`honestyHumility`])if(typeof e[t]!=`number`)return;return e}}function IT(e,t){let n=[];for(let r of e){if(r.type!==`personality_drift`||!r.data||r.leader!==void 0&&r.leader!==t)continue;let e=r.data.commander,i=r.data.turn;e&&typeof i==`number`&&n.push({turn:i,hexaco:e})}return n.sort((e,t)=>e.turn-t.turn)}function LT({events:e,actorName:t,baselineHexaco:n}){let r=FT(n),i=IT(e,t);if(i.length===0&&!r)return null;let a=r?[{turn:0,hexaco:r},...i]:i;if(a.length<2)return null;let o=a[0].turn,s=a[a.length-1].turn,c=Math.max(1,s-o),l=e=>6+68*(1-(Math.max(.05,Math.min(.95,e))-.05)/.9),u=e=>6+248*((e-o)/c);return(0,x.jsxs)(`div`,{className:jT.card,children:[(0,x.jsxs)(`div`,{className:jT.headerRow,children:[(0,x.jsx)(`span`,{className:jT.title,children:`PERSONALITY ARC`}),(0,x.jsxs)(`span`,{className:jT.range,children:[`turn `,o,` → `,s]})]}),(0,x.jsxs)(`svg`,{viewBox:`0 0 260 80`,width:`100%`,height:80,role:`img`,"aria-label":`HEXACO trajectory for ${t}`,children:[(0,x.jsx)(`line`,{x1:6,y1:l(.5),x2:254,y2:l(.5),stroke:`var(--border)`,strokeWidth:`0.5`,strokeDasharray:`2,3`}),MT.map(e=>{let t=a.map(t=>`${u(t.turn)},${l(t.hexaco[e])}`).join(` `);return(0,x.jsx)(`polyline`,{points:t,fill:`none`,stroke:NT[e],strokeWidth:`1.25`,strokeLinejoin:`round`,strokeLinecap:`round`,opacity:.85},e)})]}),(0,x.jsx)(`div`,{className:jT.legend,children:MT.map(e=>(0,x.jsxs)(`span`,{className:jT.legendItem,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:jT.legendSwatch,style:{"--trait-color":NT[e]}}),(0,x.jsx)(`span`,{className:jT.legendLabel,children:PT[e]}),(0,x.jsx)(`span`,{className:jT.legendValue,children:a[a.length-1].hexaco[e].toFixed(2)})]},e))})]})}var RT={crisis:`Crisis`,departments:`Department analysis`,decision:`Decision`,outcome:`Outcome`,quotes:`Agent voices`,causality:`Causality`},zT={timeline:`Turn timeline`,verdict:`Verdict`,trajectory:`Commander arcs`,cost:`Cost breakdown`,toolbox:`Forged toolbox`,references:`References`},BT=[`crisis`,`departments`,`decision`,`outcome`],VT=[`crisis`,`departments`,`decision`,`outcome`,`causality`];function HT(e){return e===`crisis`||e===`departments`||e===`decision`||e===`outcome`||e===`quotes`||e===`causality`}function UT(e){return e!==`quotes`}function WT(e){let t=[];for(let n of e??[])HT(n)&&!t.includes(n)&&t.push(n);return t}function GT(e){let t=WT(e.configuredSections),n=t.length>0?t:BT,r=n.filter(UT);for(let t of VT)t===`causality`&&!e.hasCausality||r.includes(t)||r.push(t);let i=e.hasQuotes?[`quotes`]:[],a=[`timeline`];return e.hasVerdict&&a.push(`verdict`),e.hasTrajectories&&a.push(`trajectory`),e.hasCost&&a.push(`cost`),e.hasToolbox&&a.push(`toolbox`),e.hasReferences&&a.push(`references`),{focusSections:n,eventSections:r,footerSections:i,artifacts:a}}var KT={section:`_section_36gyg_1`,header:`_header_36gyg_10`,kicker:`_kicker_36gyg_16`,winner:`_winner_36gyg_25`,headline:`_headline_36gyg_33`,divergence:`_divergence_36gyg_40`,body:`_body_36gyg_48`,bodyHeader:`_bodyHeader_36gyg_52`,nameA:`_nameA_36gyg_64`,nameB:`_nameB_36gyg_68`,statRow:`_statRow_36gyg_72`,statRowHead:`_statRowHead_36gyg_76`,statValueA:`_statValueA_36gyg_85`,statValueB:`_statValueB_36gyg_90`,statLabel:`_statLabel_36gyg_95`,bar:`_bar_36gyg_99`,barLeftWrap:`_barLeftWrap_36gyg_105`,barRightWrap:`_barRightWrap_36gyg_111`,barLeftFill:`_barLeftFill_36gyg_115`,barRightFill:`_barRightFill_36gyg_122`,viewWrap:`_viewWrap_36gyg_129`,viewBtn:`_viewBtn_36gyg_134`,empty:`_empty_36gyg_147`},qT=[{key:`population`,label:`Population`,format:`int`},{key:`morale`,label:`Morale`,format:`percent`},{key:`food`,label:`Food (mo)`,format:`decimal`},{key:`power`,label:`Power (kW)`,format:`decimal`},{key:`modules`,label:`Modules`,format:`decimal`},{key:`science`,label:`Science`,format:`int`},{key:`tools`,label:`Tools Forged`,format:`int`}];function JT(e,t){return t===`percent`?`${Math.round(e*100)}%`:t===`decimal`?e.toFixed(1):String(Math.round(e))}function YT({a:e,b:t,winner:n}){let r=Math.max(Math.abs(e),Math.abs(t),1),i=Math.max(0,e/r*100),a=Math.max(0,t/r*100),o=n===`a`?`var(--vis)`:`var(--border-hl)`,s=n===`b`?`var(--eng)`:`var(--border-hl)`;return(0,x.jsxs)(`div`,{className:KT.bar,children:[(0,x.jsx)(`div`,{className:KT.barLeftWrap,children:(0,x.jsx)(`div`,{className:KT.barLeftFill,style:{"--bar-pct":`${i}%`,"--bar-fill":o}})}),(0,x.jsx)(`div`,{className:KT.barRightWrap,children:(0,x.jsx)(`div`,{className:KT.barRightFill,style:{"--bar-pct":`${a}%`,"--bar-fill":s}})})]})}function XT(e){let t=e.verdict;if(t?.mode===`cohort`)return null;let n=t?.winnerName||``,r=t?.headline||t?.summary||``,i=t?.keyDivergence||``,a=t?.finalStats?.a,o=t?.finalStats?.b,s=vn(t?.finalStats),c=a&&o?s?[...s.map(e=>({key:e.id,label:yn(e),a:e.a,b:e.b,text:t=>bn(t,e.format,e.currency),better:e.better})),{key:`tools`,label:`Tools Forged`,a:Number(a.tools??0),b:Number(o.tools??0),text:e=>JT(e??0,`int`)}]:qT.map(e=>({key:e.key,label:e.label,a:Number(a[e.key]??0),b:Number(o[e.key]??0),text:t=>JT(t??0,e.format)})):[],l=e.onViewFullVerdict??(()=>{typeof document<`u`&&document.getElementById(`verdict`)?.scrollIntoView({behavior:`smooth`,block:`start`})});return(0,x.jsxs)(`section`,{"aria-label":`Run summary`,className:KT.section,children:[(0,x.jsxs)(`div`,{className:KT.header,children:[(0,x.jsx)(`div`,{className:KT.kicker,children:`Run Summary`}),n&&(0,x.jsxs)(`div`,{className:KT.winner,children:[n,` wins`]}),r&&(0,x.jsx)(`div`,{className:KT.headline,children:r}),i&&(0,x.jsx)(`div`,{className:KT.divergence,children:i})]}),a&&o?(0,x.jsxs)(`div`,{className:KT.body,children:[(0,x.jsxs)(`div`,{className:KT.bodyHeader,children:[(0,x.jsx)(`span`,{className:KT.nameA,children:e.leaderAName}),(0,x.jsx)(`span`,{children:`Final stats`}),(0,x.jsx)(`span`,{className:KT.nameB,children:e.leaderBName})]}),c.map(e=>{let{a:t,b:n}=e,r=Sn(t,n,e.better)??`tie`;return(0,x.jsxs)(`div`,{className:KT.statRow,children:[(0,x.jsxs)(`div`,{className:KT.statRowHead,children:[(0,x.jsx)(`span`,{className:KT.statValueA,style:{"--val-color":r===`a`?`var(--vis)`:`var(--text-2)`,"--val-weight":r===`a`?`700`:`500`},children:e.text(t)}),(0,x.jsx)(`span`,{className:KT.statLabel,children:e.label}),(0,x.jsx)(`span`,{className:KT.statValueB,style:{"--val-color":r===`b`?`var(--eng)`:`var(--text-2)`,"--val-weight":r===`b`?`700`:`500`},children:e.text(n)})]}),(0,x.jsx)(YT,{a:t??0,b:n??0,winner:r})]},e.key)}),(0,x.jsx)(`div`,{className:KT.viewWrap,children:(0,x.jsx)(`button`,{type:`button`,onClick:l,className:KT.viewBtn,children:`View full verdict ›`})})]}):(0,x.jsx)(`div`,{className:KT.empty,children:`Simulation in progress. Scoreboard will populate when the verdict arrives.`})]})}var ZT={morale:`higher`,population:`higher`,deaths:`lower`,tools:`higher`,turn:`higher`};function QT(e,t){if(e.length===0)return 0;if(e.length===1)return e[0];let n=Math.max(0,Math.min(1,t))*(e.length-1),r=Math.floor(n),i=Math.ceil(n);if(r===i)return e[r];let a=n-r;return e[r]*(1-a)+e[i]*a}function $T(e,t){switch(t){case`morale`:return e.morale;case`population`:return e.population;case`deaths`:return e.deaths;case`tools`:return e.tools;case`turn`:return e.turn}}function eE(e,t,n){let r=n??ZT[t];if(e.length===0)return{metric:t,direction:r,top:[],middle:[],bottom:[],median:0};let i=[...e.map(e=>$T(e,t))].sort((e,t)=>e-t),a=QT(i,.25),o=QT(i,.75),s=QT(i,.5),c=[],l=[],u=[],d=a===o;for(let n of e){if(d){l.push(n);continue}let e=$T(n,t);r===`higher`?e>o?c.push(n):e<a?u.push(n):l.push(n):e<a?c.push(n):e>o?u.push(n):l.push(n)}return{metric:t,direction:r,top:c,middle:l,bottom:u,median:s}}function tE(e,t){if(e.length===0||t.length===0)return{frontIds:[],dominationCount:{}};let n=(e,t,n)=>{let r=$T(e,n),i=$T(t,n);return ZT[n]===`higher`?r>=i:r<=i},r=(e,t,n)=>{let r=$T(e,n),i=$T(t,n);return ZT[n]===`higher`?r>i:r<i},i=(e,i)=>{let a=!1;for(let o of t){if(!n(e,i,o))return!1;r(e,i,o)&&(a=!0)}return a},a={};for(let t of e)a[t.id]=0;for(let t of e)for(let n of e)t.id!==n.id&&i(t,n)&&a[t.id]++;let o=[];for(let t of e){let n=!1;for(let r of e)if(t.id!==r.id&&i(r,t)){n=!0;break}n||o.push(t.id)}return{frontIds:o,dominationCount:a}}function nE(e,t){if(e.length===0)return{metric:t,median:0,deltas:{}};let n=QT([...e.map(e=>$T(e,t))].sort((e,t)=>e-t),.5),r={},i=ZT[t]===`higher`?1:-1;for(let a of e){let e=($T(a,t)-n)*i;r[a.id]=e+0}return{metric:t,median:n,deltas:r}}function rE(e,t=0){if(Math.abs(e)<.5/10**t)return`±0`;let n=e.toFixed(t);return e>0?`+${n}`:n}var iE={panel:`_panel_1c1w0_1`,header:`_header_1c1w0_12`,heading:`_heading_1c1w0_18`,subhead:`_subhead_1c1w0_26`,section:`_section_1c1w0_34`,sectionTitle:`_sectionTitle_1c1w0_40`,sectionHint:`_sectionHint_1c1w0_51`,quartileGrid:`_quartileGrid_1c1w0_59`,quartileBlock:`_quartileBlock_1c1w0_65`,metricHead:`_metricHead_1c1w0_75`,metricLabel:`_metricLabel_1c1w0_82`,metricMedian:`_metricMedian_1c1w0_89`,quartileRow:`_quartileRow_1c1w0_96`,quartileTag:`_quartileTag_1c1w0_102`,actorList:`_actorList_1c1w0_114`,actorPill:`_actorPill_1c1w0_124`,actorPillTop:`_actorPillTop_1c1w0_134`,actorPillBottom:`_actorPillBottom_1c1w0_140`,actorListEmpty:`_actorListEmpty_1c1w0_146`,paretoList:`_paretoList_1c1w0_153`,paretoItem:`_paretoItem_1c1w0_162`,paretoName:`_paretoName_1c1w0_176`,paretoArchetype:`_paretoArchetype_1c1w0_181`,paretoDominates:`_paretoDominates_1c1w0_185`,medianTable:`_medianTable_1c1w0_191`,medianHeaderRow:`_medianHeaderRow_1c1w0_201`,medianBodyRow:`_medianBodyRow_1c1w0_202`,medianActorCol:`_medianActorCol_1c1w0_215`,medianActorName:`_medianActorName_1c1w0_223`,medianActorArchetype:`_medianActorArchetype_1c1w0_228`,medianMetricCol:`_medianMetricCol_1c1w0_233`,deltaPositive:`_deltaPositive_1c1w0_252`,deltaNegative:`_deltaNegative_1c1w0_256`,deltaNeutral:`_deltaNeutral_1c1w0_260`},aE=[{metric:`morale`,label:`Morale`,suffix:`%`},{metric:`population`,label:`Population`,suffix:``},{metric:`deaths`,label:`Deaths`,suffix:``},{metric:`tools`,label:`Tools`,suffix:``}],oE=[`morale`,`population`,`deaths`,`tools`],sE=[{metric:`morale`,label:`Morale`,suffix:`%`,decimals:0},{metric:`population`,label:`Population`,suffix:``,decimals:0},{metric:`deaths`,label:`Deaths`,suffix:``,decimals:0}];function cE({state:e}){let t=(0,b.useMemo)(()=>YC(e),[e]);if(t.length<3)return null;let n=(0,b.useMemo)(()=>aE.map(({metric:e,label:n,suffix:r})=>({metric:e,label:n,suffix:r,ranking:eE(t,e)})),[t]),r=(0,b.useMemo)(()=>tE(t,oE),[t]),i=r.frontIds.map(e=>t.find(t=>t.id===e)).filter(e=>!!e),a=(0,b.useMemo)(()=>sE.map(({metric:e,label:n,suffix:r,decimals:i})=>({metric:e,label:n,suffix:r,decimals:i,benchmark:nE(t,e)})),[t]);return(0,x.jsxs)(`section`,{className:iE.panel,"aria-labelledby":`cohort-verdict-heading`,children:[(0,x.jsxs)(`header`,{className:iE.header,children:[(0,x.jsx)(`h3`,{id:`cohort-verdict-heading`,className:iE.heading,children:`Cohort verdict`}),(0,x.jsxs)(`p`,{className:iE.subhead,children:[t.length,` actors · ranked across morale, population, deaths, and forged tools. A single winner doesn't generalize past two — this is the cohort-aware reading.`]})]}),(0,x.jsxs)(`div`,{className:iE.section,children:[(0,x.jsx)(`h4`,{className:iE.sectionTitle,children:`Quartile rankings`}),(0,x.jsx)(`div`,{className:iE.quartileGrid,children:n.map(({metric:e,label:t,suffix:n,ranking:r})=>(0,x.jsxs)(`div`,{className:iE.quartileBlock,children:[(0,x.jsxs)(`div`,{className:iE.metricHead,children:[(0,x.jsx)(`span`,{className:iE.metricLabel,children:t}),(0,x.jsxs)(`span`,{className:iE.metricMedian,children:[`median `,Math.round(r.median),n]})]}),(0,x.jsxs)(`div`,{className:iE.quartileRow,children:[(0,x.jsx)(`span`,{className:iE.quartileTag,children:`Top 25%`}),(0,x.jsxs)(`ul`,{className:iE.actorList,children:[r.top.map(e=>(0,x.jsx)(`li`,{className:`${iE.actorPill} ${iE.actorPillTop}`,children:e.name},e.id)),r.top.length===0&&(0,x.jsx)(`li`,{className:iE.actorListEmpty,children:`—`})]})]}),(0,x.jsxs)(`div`,{className:iE.quartileRow,children:[(0,x.jsx)(`span`,{className:iE.quartileTag,children:`Bottom 25%`}),(0,x.jsxs)(`ul`,{className:iE.actorList,children:[r.bottom.map(e=>(0,x.jsx)(`li`,{className:`${iE.actorPill} ${iE.actorPillBottom}`,children:e.name},e.id)),r.bottom.length===0&&(0,x.jsx)(`li`,{className:iE.actorListEmpty,children:`—`})]})]})]},e))})]}),(0,x.jsxs)(`div`,{className:iE.section,children:[(0,x.jsx)(`h4`,{className:iE.sectionTitle,children:`Pareto front · trade-off candidates`}),(0,x.jsxs)(`p`,{className:iE.sectionHint,children:[i.length,` actor`,i.length===1?``:`s`,` not dominated by any other across all four metrics. Off-front actors are strictly worse than someone on it.`]}),(0,x.jsx)(`ul`,{className:iE.paretoList,children:i.map(e=>{let t=r.dominationCount[e.id]??0;return(0,x.jsxs)(`li`,{className:iE.paretoItem,children:[(0,x.jsx)(`span`,{className:iE.paretoName,children:e.name}),(0,x.jsx)(`span`,{className:iE.paretoArchetype,children:e.archetype}),(0,x.jsxs)(`span`,{className:iE.paretoDominates,children:[`dominates `,t,` other`,t===1?``:`s`]})]},e.id)})})]}),(0,x.jsxs)(`div`,{className:iE.section,children:[(0,x.jsx)(`h4`,{className:iE.sectionTitle,children:`Median benchmark · per-actor deltas`}),(0,x.jsx)(`p`,{className:iE.sectionHint,children:`Sign-normalized so positive = better than median. Lower deaths and higher morale both read as positive deltas.`}),(0,x.jsxs)(`div`,{className:iE.medianTable,role:`table`,"aria-label":`Per-actor delta-from-median`,children:[(0,x.jsxs)(`div`,{className:iE.medianHeaderRow,role:`row`,children:[(0,x.jsx)(`span`,{className:iE.medianActorCol,role:`columnheader`,children:`Actor`}),a.map(e=>(0,x.jsx)(`span`,{className:iE.medianMetricCol,role:`columnheader`,children:e.label},e.metric))]}),t.map(e=>(0,x.jsxs)(`div`,{className:iE.medianBodyRow,role:`row`,children:[(0,x.jsxs)(`span`,{className:iE.medianActorCol,role:`cell`,children:[(0,x.jsx)(`span`,{className:iE.medianActorName,children:e.name}),(0,x.jsx)(`span`,{className:iE.medianActorArchetype,children:e.archetype})]}),a.map(t=>{let n=t.benchmark.deltas[e.id]??0,r=n>0?iE.deltaPositive:n<0?iE.deltaNegative:iE.deltaNeutral;return(0,x.jsxs)(`span`,{className:`${iE.medianMetricCol} ${r}`,role:`cell`,children:[rE(n,t.decimals),t.suffix]},t.metric)})]},e.id))]})]})]})}function lE(e){switch(e){case`conservative_success`:return`var(--green)`;case`risky_success`:return`var(--amber)`;case`conservative_failure`:return`var(--rust-dim, var(--rust))`;case`risky_failure`:return`var(--rust)`;default:return`var(--text-3)`}}function uE(e,t){return!e||!t?`divergent`:e===t?`shared`:`divergent`}var dE=[{id:`population`,label:`Population`},{id:`morale`,label:`Morale`},{id:`foodMonthsReserve`,label:`Food`,unit:`mo`},{id:`powerKw`,label:`Power`,unit:`kW`},{id:`infrastructureModules`,label:`Modules`},{id:`scienceOutput`,label:`Science`}];function fE(e,t){let n=[],r=new Set;for(let i of e){let e=i.data?.metrics;if(!e||typeof i.turn!=`number`)continue;let a=e[t];if(typeof a==`number`){if(r.has(i.turn)){let e=n.findIndex(e=>e.turn===i.turn);e>=0&&(n[e]={turn:i.turn,value:a})}else r.add(i.turn),n.push({turn:i.turn,value:a})}}return n}function pE(e,t,n){let r=t??e.actorIds[0],i=n??e.actorIds[1],a=r?e.actors[r]?.events:void 0,o=i?e.actors[i]?.events:void 0;return dE.map(e=>({id:e.id,label:e.label,unit:e.unit,a:a?fE(a,e.id):[],b:o?fE(o,e.id):[]}))}function mE(e,t){let n=e.actorIds.map((n,r)=>{let i=e.actors[n]?.events;return{actorId:n,idx:r,name:e.actors[n]?.leader?.name??n,color:t(r),events:i}});return dE.map(e=>({id:e.id,label:e.label,unit:e.unit,a:[],b:[],series:n.map(t=>({actorId:t.actorId,name:t.name,color:t.color,points:t.events?fE(t.events,e.id):[]}))}))}function hE(e){return e.map(([e,t])=>{let n=t.a.events.get(0),r=t.b.events.get(0);return{turn:e,time:t.a.time??t.b.time,diverged:uE(n?.title,r?.title)===`divergent`,a:{title:n?.title,outcome:n?.outcome,category:n?.category},b:{title:r?.title,outcome:r?.outcome,category:r?.category}}})}var gE={section:`_section_5eeou_1`,title:`_title_5eeou_10`,grid:`_grid_5eeou_20`,cell:`_cell_5eeou_26`,diverged:`_diverged_5eeou_40`,cellHead:`_cellHead_5eeou_45`,cellTurn:`_cellTurn_5eeou_53`,badge:`_badge_5eeou_57`,legend:`_legend_5eeou_71`},_E={conservative_success:`SAFE WIN`,risky_success:`RISKY WIN`,conservative_failure:`SAFE LOSS`,risky_failure:`RISKY LOSS`},vE={conservative_success:`S✓`,risky_success:`R✓`,conservative_failure:`S✗`,risky_failure:`R✗`};function yE(e,t=!1){return e?t?vE[e]??`·`:_E[e]??e.replace(/_/g,` `).toUpperCase():`·`}function bE({outcome:e,sideColor:t,compact:n}){let r=lE(e);return(0,x.jsx)(`div`,{className:gE.badge,style:{"--side-color":t,"--outcome-color":r,"--badge-size":n?`11px`:`9px`,"--badge-spacing":n?`0`:`0.04em`},children:yE(e,n)})}function xE(e){let{turns:t,leaderAName:n,leaderBName:r,onJumpToTurn:i}=e,a=jy(Ny);if(t.length===0)return null;let o=e=>{i?i(e):typeof document<`u`&&document.getElementById(`turn-${e}`)?.scrollIntoView({behavior:`smooth`,block:`start`})};return(0,x.jsxs)(`section`,{"aria-label":`Run timeline strip`,className:gE.section,children:[(0,x.jsx)(`div`,{className:gE.title,children:`Run Strip`}),(0,x.jsx)(`div`,{role:`list`,className:gE.grid,style:{"--turn-count":String(t.length)},children:t.map(e=>(0,x.jsxs)(`button`,{type:`button`,role:`listitem`,onClick:()=>o(e.turn),"aria-label":`Jump to turn ${e.turn}${e.time?`, time `+e.time:``}${e.diverged?`, divergent`:``}`,className:[gE.cell,e.diverged?gE.diverged:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`div`,{className:gE.cellHead,children:[(0,x.jsxs)(`span`,{className:gE.cellTurn,children:[`T`,e.turn]}),e.time&&!a&&(0,x.jsxs)(`span`,{children:[`Y`,e.time]})]}),(0,x.jsx)(bE,{outcome:e.a.outcome,sideColor:`var(--vis)`,compact:a}),(0,x.jsx)(bE,{outcome:e.b.outcome,sideColor:`var(--eng)`,compact:a})]},e.turn))}),(0,x.jsxs)(`div`,{className:gE.legend,children:[(0,x.jsx)(`span`,{children:n}),(0,x.jsx)(`span`,{children:r})]})]})}var SE={section:`_section_1aa2r_1`,sectionHeader:`_sectionHeader_1aa2r_10`,sectionTitle:`_sectionTitle_1aa2r_17`,legend:`_legend_1aa2r_26`,legendA:`_legendA_1aa2r_32`,legendB:`_legendB_1aa2r_37`,grid:`_grid_1aa2r_42`,card:`_card_1aa2r_48`,cardHeader:`_cardHeader_1aa2r_58`,cardLabel:`_cardLabel_1aa2r_65`,cardRange:`_cardRange_1aa2r_70`,cardFooter:`_cardFooter_1aa2r_74`,lastA:`_lastA_1aa2r_81`,lastB:`_lastB_1aa2r_86`,cardFooterCohort:`_cardFooterCohort_1aa2r_94`,lastCohort:`_lastCohort_1aa2r_103`,legendCohort:`_legendCohort_1aa2r_112`,legendCohortEntry:`_legendCohortEntry_1aa2r_122`,legendCohortSlot:`_legendCohortSlot_1aa2r_141`,lastCohortSlot:`_lastCohortSlot_1aa2r_153`};function CE(e,t){return t===`mo`||t===`kW`?`${e.toFixed(1)}${t?` `+t:``}`:e>0&&e<1?`${Math.round(e*100)}%`:`${Math.round(e)}${t?` `+t:``}`}function wE(e){let t=e,n=``;do n=String.fromCharCode(65+t%26)+n,t=Math.floor(t/26)-1;while(t>=0);return n}function TE({metric:e,sideAColor:t,sideBColor:n}){let r=Array.isArray(e.series)&&e.series.length>=2,i=r?e.series.flatMap(e=>e.points):[...e.a,...e.b];if(i.length===0)return null;let a=1/0,o=-1/0,s=1/0,c=-1/0;for(let e of i)e.turn<a&&(a=e.turn),e.turn>o&&(o=e.turn),e.value<s&&(s=e.value),e.value>c&&(c=e.value);let l=Math.max(1e-6,c-s),u=Math.max(1,o-a),d=e=>4+192*((e-a)/u),f=e=>6+38*(1-(e-s)/l);if(r)return(0,x.jsxs)(`div`,{className:SE.card,children:[(0,x.jsxs)(`div`,{className:SE.cardHeader,children:[(0,x.jsx)(`span`,{className:SE.cardLabel,children:e.label}),(0,x.jsxs)(`span`,{className:SE.cardRange,children:[`T`,a,` → T`,o]})]}),(0,x.jsxs)(`svg`,{viewBox:`0 0 200 50`,width:`100%`,height:50,role:`img`,"aria-label":`${e.label} sparkline (${e.series.length} actors)`,children:[(0,x.jsx)(`line`,{x1:4,y1:25,x2:196,y2:25,stroke:`var(--border)`,strokeWidth:`0.5`,strokeDasharray:`2,3`}),e.series.map(e=>{let t=e.points.map(e=>`${d(e.turn)},${f(e.value)}`).join(` `);return t?(0,x.jsx)(`polyline`,{points:t,fill:`none`,stroke:e.color,strokeWidth:`1.5`,strokeLinejoin:`round`,strokeLinecap:`round`,opacity:.78,children:(0,x.jsx)(`title`,{children:e.name})},e.actorId):null})]}),(0,x.jsx)(`div`,{className:SE.cardFooterCohort,children:e.series.map((t,n)=>{let r=t.points[t.points.length-1]?.value,i=wE(n);return(0,x.jsxs)(`span`,{className:SE.lastCohort,style:{"--actor-color":t.color},title:t.name,children:[(0,x.jsx)(`span`,{className:SE.lastCohortSlot,"aria-hidden":`true`,children:i}),r==null?`·`:CE(r,e.unit)]},t.actorId)})})]});let p=e.a.map(e=>`${d(e.turn)},${f(e.value)}`).join(` `),m=e.b.map(e=>`${d(e.turn)},${f(e.value)}`).join(` `),h=e.a[e.a.length-1]?.value,g=e.b[e.b.length-1]?.value;return(0,x.jsxs)(`div`,{className:SE.card,children:[(0,x.jsxs)(`div`,{className:SE.cardHeader,children:[(0,x.jsx)(`span`,{className:SE.cardLabel,children:e.label}),(0,x.jsxs)(`span`,{className:SE.cardRange,children:[`T`,a,` → T`,o]})]}),(0,x.jsxs)(`svg`,{viewBox:`0 0 200 50`,width:`100%`,height:50,role:`img`,"aria-label":`${e.label} sparkline`,children:[(0,x.jsx)(`line`,{x1:4,y1:25,x2:196,y2:25,stroke:`var(--border)`,strokeWidth:`0.5`,strokeDasharray:`2,3`}),p&&(0,x.jsx)(`polyline`,{points:p,fill:`none`,stroke:t,strokeWidth:`1.5`,strokeLinejoin:`round`,strokeLinecap:`round`,opacity:.9}),m&&(0,x.jsx)(`polyline`,{points:m,fill:`none`,stroke:n,strokeWidth:`1.5`,strokeLinejoin:`round`,strokeLinecap:`round`,opacity:.9})]}),(0,x.jsxs)(`div`,{className:SE.cardFooter,children:[(0,x.jsx)(`span`,{className:SE.lastA,children:h==null?`·`:CE(h,e.unit)}),(0,x.jsx)(`span`,{className:SE.lastB,children:g==null?`·`:CE(g,e.unit)})]})]})}function EE(e){let{metrics:t,leaderAName:n,leaderBName:r}=e,i=e.sideAColor??`var(--vis)`,a=e.sideBColor??`var(--eng)`,o=t.length>0&&Array.isArray(t[0].series)&&t[0].series.length>=2,s=t.filter(e=>o?(e.series??[]).some(e=>e.points.length>0):e.a.length>0||e.b.length>0);if(s.length===0)return null;let c={"--side-a-color":i,"--side-b-color":a};return(0,x.jsxs)(`section`,{"aria-label":`Metric sparklines`,className:SE.section,style:c,children:[(0,x.jsxs)(`div`,{className:SE.sectionHeader,children:[(0,x.jsx)(`span`,{className:SE.sectionTitle,children:`Metric Trajectories`}),o?(0,x.jsx)(`span`,{className:SE.legendCohort,children:(s[0].series??[]).map((e,t)=>(0,x.jsxs)(`span`,{className:SE.legendCohortEntry,style:{"--actor-color":e.color},children:[(0,x.jsx)(`span`,{className:SE.legendCohortSlot,"aria-hidden":`true`,children:wE(t)}),e.name]},e.actorId))}):(0,x.jsxs)(`span`,{className:SE.legend,children:[(0,x.jsx)(`span`,{className:SE.legendA,children:n}),` · `,(0,x.jsx)(`span`,{className:SE.legendB,children:r})]})]}),(0,x.jsx)(`div`,{className:`responsive-grid-3 ${SE.grid}`,children:s.map(e=>(0,x.jsx)(TE,{metric:e,sideAColor:i,sideBColor:a},e.id))})]})}function DE(e,t){let[n,r]=(0,b.useState)(()=>typeof window<`u`?window.matchMedia(e).matches:t);return(0,b.useEffect)(()=>{if(typeof window>`u`)return;let t=window.matchMedia(e),n=()=>r(t.matches);return t.addEventListener(`change`,n),()=>t.removeEventListener(`change`,n)},[e]),n}function OE(e){let{items:t,scrollRoot:n}=e,[r,i]=(0,b.useState)(t[0]?.id),a=DE(`(min-width: 1024px)`,!0),o=DE(`(max-width: 767.98px)`,!1);(0,b.useEffect)(()=>{if(typeof window>`u`||t.length===0)return;let e=t.map(e=>document.getElementById(e.id)).filter(e=>e!=null);if(e.length===0)return;let r=new IntersectionObserver(e=>{let t=e.filter(e=>e.isIntersecting).sort((e,t)=>t.intersectionRatio-e.intersectionRatio);t[0]&&i(t[0].target.id)},{root:n??null,rootMargin:`-80px 0px -60% 0px`,threshold:[0,.25,.5,.75,1]});return e.forEach(e=>r.observe(e)),()=>r.disconnect()},[t,n]);let s=(0,b.useMemo)(()=>({display:`block`,padding:`4px 10px`,fontSize:`var(--font-xs)`,fontFamily:`var(--mono)`,fontWeight:700,letterSpacing:`0.04em`,textTransform:`uppercase`,color:`var(--text-3)`,textDecoration:`none`,borderRadius:3}),[]);return t.length===0?null:a?(0,x.jsx)(`nav`,{"aria-label":`Report sections`,style:{position:`sticky`,top:12,alignSelf:`flex-start`,width:160,marginLeft:12,padding:`10px 6px`,background:`var(--bg-panel)`,border:`1px solid var(--border)`,borderRadius:8,maxHeight:`calc(100vh - 40px)`,overflowY:`auto`},children:t.map(e=>(0,x.jsx)(`a`,{href:`#${e.id}`,style:{...s,color:r===e.id?`var(--amber)`:`var(--text-3)`,background:r===e.id?`color-mix(in srgb, var(--bg-canvas) 80%, var(--amber) 20%)`:`transparent`},children:e.label},e.id))}):(0,x.jsx)(`nav`,{"aria-label":`Report sections`,style:{background:`var(--bg-panel)`,borderBottom:`1px solid var(--border)`,padding:o?`8px 10px`:`6px 8px`,marginBottom:12,overflowX:`auto`,WebkitOverflowScrolling:`touch`,display:`flex`,gap:o?6:4,flexShrink:0},children:t.map(e=>{let t=r===e.id,n={...s,flexShrink:0,padding:`8px 12px`,borderRadius:4,border:`1px solid ${t?`var(--amber)`:`var(--border)`}`,background:t?`var(--amber)`:`var(--bg-card)`,color:t?`var(--bg-deep)`:`var(--text-3)`},i={...s,flexShrink:0,color:t?`var(--amber)`:`var(--text-3)`,borderBottom:t?`2px solid var(--amber)`:`2px solid transparent`};return(0,x.jsx)(`a`,{href:`#${e.id}`,style:o?n:i,children:e.label},e.id)})})}var Z={empty:`_empty_1pipo_1`,emptyMsg:`_emptyMsg_1pipo_8`,emptyMsgRunning:`_emptyMsgRunning_1pipo_15`,emptySpinner:`_emptySpinner_1pipo_23`,reportEmptySpinnerRotate:`_reportEmptySpinnerRotate_1pipo_1`,layout:`_layout_1pipo_43`,scroll:`_scroll_1pipo_50`,tldr:`_tldr_1pipo_58`,tldrTopRow:`_tldrTopRow_1pipo_69`,tldrTag:`_tldrTag_1pipo_76`,tldrHeadline:`_tldrHeadline_1pipo_85`,tldrSub:`_tldrSub_1pipo_92`,tldrStats:`_tldrStats_1pipo_99`,tldrStatLabel:`_tldrStatLabel_1pipo_108`,tldrStatValue:`_tldrStatValue_1pipo_113`,headerRow:`_headerRow_1pipo_118`,headerTitle:`_headerTitle_1pipo_127`,jumpBtn:`_jumpBtn_1pipo_134`,actorPairPicker:`_actorPairPicker_1pipo_149`,actorPairPickerLabel:`_actorPairPickerLabel_1pipo_164`,actorPairPickerToggle:`_actorPairPickerToggle_1pipo_172`,actorPairPickerToggleText:`_actorPairPickerToggleText_1pipo_209`,actorPairPickerSelect:`_actorPairPickerSelect_1pipo_218`,actorPairPickerVs:`_actorPairPickerVs_1pipo_237`,actorPairPickerHint:`_actorPairPickerHint_1pipo_245`,jumpInlineBtn:`_jumpInlineBtn_1pipo_251`,trajectoryGrid:`_trajectoryGrid_1pipo_262`,costBar:`_costBar_1pipo_269`,costLabel:`_costLabel_1pipo_282`,costAmount:`_costAmount_1pipo_289`,costMeta:`_costMeta_1pipo_295`,costBtn:`_costBtn_1pipo_299`,turnSection:`_turnSection_1pipo_312`,diverged:`_diverged_1pipo_321`,turnHeader:`_turnHeader_1pipo_326`,turnTitle:`_turnTitle_1pipo_333`,turnEventCount:`_turnEventCount_1pipo_340`,turnHeaderRight:`_turnHeaderRight_1pipo_348`,divergenceFlag:`_divergenceFlag_1pipo_354`,eventGrid:`_eventGrid_1pipo_367`,eventGridSpaced:`_eventGridSpaced_1pipo_373`,footerGrid:`_footerGrid_1pipo_380`,nActorEventTrack:`_nActorEventTrack_1pipo_387`,nActorEventTrackSpaced:`_nActorEventTrackSpaced_1pipo_397`,nActorFooterTrack:`_nActorFooterTrack_1pipo_408`,summarySection:`_summarySection_1pipo_426`,summaryLabel:`_summaryLabel_1pipo_430`,summaryVerdictWrap:`_summaryVerdictWrap_1pipo_442`,aboutDetails:`_aboutDetails_1pipo_446`,aboutSummary:`_aboutSummary_1pipo_457`,aboutBody:`_aboutBody_1pipo_465`,aboutBlockTitle:`_aboutBlockTitle_1pipo_472`,aboutChips:`_aboutChips_1pipo_478`,aboutChip:`_aboutChip_1pipo_478`,aboutChipNeutral:`_aboutChipNeutral_1pipo_494`,eventCard:`_eventCard_1pipo_504`,eventHeading:`_eventHeading_1pipo_511`,eventSubLabel:`_eventSubLabel_1pipo_519`,eventAwaiting:`_eventAwaiting_1pipo_526`,eventTitle:`_eventTitle_1pipo_531`,categoryPill:`_categoryPill_1pipo_538`,emergentPill:`_emergentPill_1pipo_548`,eventDescription:`_eventDescription_1pipo_556`,eventDecision:`_eventDecision_1pipo_564`,eventOutcomeRow:`_eventOutcomeRow_1pipo_571`,eventPolicies:`_eventPolicies_1pipo_578`,eventDetails:`_eventDetails_1pipo_584`,eventDetailsSummary:`_eventDetailsSummary_1pipo_588`,eventRationale:`_eventRationale_1pipo_596`,deptList:`_deptList_1pipo_606`,deptItem:`_deptItem_1pipo_613`,deptHead:`_deptHead_1pipo_621`,deptName:`_deptName_1pipo_627`,deptMeta:`_deptMeta_1pipo_632`,deptSummary:`_deptSummary_1pipo_638`,footerCard:`_footerCard_1pipo_644`,footerDetails:`_footerDetails_1pipo_651`,footerDetailsLast:`_footerDetailsLast_1pipo_655`,footerSummary:`_footerSummary_1pipo_659`,systemsRow:`_systemsRow_1pipo_667`,systemItem:`_systemItem_1pipo_676`,systemKey:`_systemKey_1pipo_680`,systemValue:`_systemValue_1pipo_684`,reactionsList:`_reactionsList_1pipo_689`,reactionItem:`_reactionItem_1pipo_696`,reactionHead:`_reactionHead_1pipo_704`,reactionName:`_reactionName_1pipo_711`,moodPill:`_moodPill_1pipo_716`,reactionQuote:`_reactionQuote_1pipo_726`,reactionRole:`_reactionRole_1pipo_731`,forkNotice:`_forkNotice_1pipo_737`};function kE(e,t){let[n,r]=(0,b.useState)(()=>{if(typeof window>`u`)return t;try{let n=window.localStorage.getItem(e);return n===null?t:n===`1`}catch{return t}});return[n,(0,b.useCallback)(t=>{r(t);try{window.localStorage.setItem(e,t?`1`:`0`)}catch{}},[e])]}function AE(){return{events:new Map,reactions:[],totalReactions:0}}function jE(e,t,n){let r=e.events.get(t);return r||(r={eventIndex:t,totalEvents:n,depts:{}},e.events.set(t,r)),n>r.totalEvents&&(r.totalEvents=n),r}function ME(e){let t=new Map;if(!e)return t;let n=new Map;for(let r of e){let e=r.turn;if(typeof e!=`number`)continue;let i=t.get(e);i||(i=AE(),t.set(e,i));let a=Number(r.data?.eventIndex??0),o=Number(r.data?.totalEvents??1);if(r.type===`turn_start`&&(r.data?.time!=null&&(i.time=r.data.time),r.data?.metrics&&(i.metrics=r.data.metrics),r.data?.title&&r.data?.title!==`Director generating...`&&!r.data?.totalEvents)){let e=jE(i,0,1);e.title=r.data.title,e.category=r.data.category,e.emergent=r.data.emergent,e.description=r.data.crisis||r.data.turnSummary||``}if(r.type===`event_start`){let e=jE(i,a,o);e.title=r.data?.title,e.category=r.data?.category,e.emergent=r.data?.emergent,e.description=r.data?.description||r.data?.turnSummary||``}if(r.type===`decision_made`&&n.set(a,{decision:String(r.data?.decision||``),rationale:String(r.data?.rationale||``),policies:Array.isArray(r.data?.selectedPolicies)?r.data.selectedPolicies.map(e=>typeof e==`string`?e:JSON.stringify(e)):[]}),r.type===`outcome`){let e=jE(i,a,o);e.outcome=String(r.data?.outcome||``);let t=n.get(a);t&&(e.decision=t.decision,e.rationale=t.rationale,e.policies=t.policies,n.delete(a))}if(r.type===`specialist_done`){let e=jE(i,a,o),t=r.data?.department;if(t){let n=(r.data?._filteredTools||[]).filter(e=>e?.approved!==!1).length;e.depts[t]={summary:r.data?.summary||``,tools:n,citations:Number(r.data?.citations??0),citationList:r.data?.citationList||[]}}}r.type===`agent_reactions`&&(i.reactions=(r.data?.reactions||[]).slice(0,3),i.totalReactions=Number(r.data?.totalReactions??0))}return t}function NE(e){return e===`pos`?`var(--green)`:e===`neg`?`var(--rust)`:`var(--text-1)`}function PE({state:e,verdict:t,shownRun:n,reportSections:r}){let i=h_(),a=D_(),[o,s]=kE(`paracosm-reports-refs-open`,!1),[c,l]=kE(`paracosm-reports-tools-open`,!1),[u,d]=(0,b.useState)(!1),{state:f,dispatch:p}=Gn(),m=nA(),h=iA(),g=Lm(),[_,v]=(0,b.useState)(null),y=f.parent,S=Qk(),C=eA(),w=y?.metadata?.scenario,T=typeof w?.id==`string`&&w.id!==S.id,E=(0,b.useCallback)(t=>!y||e.isRunning||!C||T?!1:bT(y,t),[y,e.isRunning,C,T]),D=(0,b.useCallback)(async e=>{v(null);let t=`branch-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;p({type:`BRANCH_OPTIMISTIC`,localId:t,forkedAtTurn:e.atTurn,actorName:e.leader.name,actorArchetype:e.leader.archetype});let n=yT(e.parentArtifact),r=e.seedOverride??e.parentArtifact.metadata.seed??42;try{let i=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({actors:[e.leader],turns:n,seed:r,captureSnapshots:!0,customEvents:e.customEvents,forkFrom:{parentArtifact:_T(e.parentArtifact),atTurn:e.atTurn}})});if(!i.ok){let e=await i.json().catch(()=>({}));p({type:`BRANCH_ERROR`,localId:t,message:e.error??`HTTP ${i.status}`});return}let a=await i.json().catch(()=>({}));k(window,a.visitorId),h(),m(`studio`)}catch(e){p({type:`BRANCH_ERROR`,localId:t,message:String(e)})}},[p,m,h]),O=e.actorIds[0]??null,A=e.actorIds[1]??null,[j,ee]=(0,b.useState)(O),[te,M]=(0,b.useState)(A);(0,b.useEffect)(()=>{j&&!e.actorIds.includes(j)&&ee(O),te&&!e.actorIds.includes(te)&&M(A)},[e.actorIds,j,te,O,A]);let N=j??O,ne=te??A,P=e.actorIds.length>2,[re,ie]=(0,b.useState)(!P);(0,b.useEffect)(()=>{ie(!P)},[P]);let F=(0,b.useMemo)(()=>{let t=new Map;for(let n of e.actorIds)t.set(n,ME(e.actors[n]?.events));return t},[e]),I=(0,b.useMemo)(()=>{let e=N&&F.get(N)||new Map,t=ne&&F.get(ne)||new Map;return[...new Set([...e.keys(),...t.keys()])].sort((e,t)=>e-t).map(n=>[n,{a:e.get(n)??AE(),b:t.get(n)??AE()}])},[F,N,ne]),ae=(0,b.useMemo)(()=>{if(!P)return[];let t=new Set;for(let e of F.values())for(let n of e.keys())t.add(n);return[...t].sort((e,t)=>e-t).map(t=>{let n=new Map;for(let r of e.actorIds)n.set(r,F.get(r)?.get(t)??AE());return[t,n]})},[P,F,e.actorIds]),oe=N,se=ne,ce=oe?e.actors[oe]:null,le=se?e.actors[se]:null,L=ce?.leader?.name||`Leader A`,ue=le?.leader?.name||`Leader B`,de=(ce?.events.some(e=>e.type===`personality_drift`)??!1)||(le?.events.some(e=>e.type===`personality_drift`)??!1),fe=I.some(([,e])=>e.a.reactions.length>0||e.b.reactions.length>0),R=I.some(([,e])=>[...e.a.events.values(),...e.b.events.values()].some(e=>!!e.rationale)),z=(0,b.useMemo)(()=>GT({configuredSections:r,hasQuotes:fe,hasCausality:R,hasVerdict:!!t,hasTrajectories:de,hasCost:!!(e.cost&&e.cost.llmCalls>0),hasToolbox:a.list.length>0,hasReferences:i.list.length>0}),[r,fe,R,t,de,e.cost,a.list.length,i.list.length]),pe=(0,b.useMemo)(()=>hE(I),[I]),me=(0,b.useMemo)(()=>pE(e,N,ne),[e,N,ne]),he=(0,b.useMemo)(()=>P?mE(e,Pe):null,[P,e]),ge=(0,b.useMemo)(()=>{let e=[];pe.length>0&&e.push({id:`strip`,label:`Strip`}),me.some(e=>e.a.length>0||e.b.length>0)&&e.push({id:`sparklines`,label:`Metrics`}),de&&e.push({id:`trajectory`,label:`Trajectory`});for(let[t]of I)e.push({id:`turn-${t}`,label:`Turn ${t}`});return a.list.length>0&&e.push({id:`toolbox`,label:`Toolbox`}),e.push({id:`summary`,label:t?`Verdict`:`Summary`}),i.list.length>0&&e.push({id:`references`,label:`References`}),e},[t,pe.length,me,de,I,a.list.length,i.list.length]),_e=(0,b.useRef)(null),B=(0,b.useRef)(!0);return(0,b.useEffect)(()=>{B.current&&_e.current&&I.length>0&&_e.current.scrollTo({top:_e.current.scrollHeight,behavior:`smooth`})},[I.length]),!(ce?.events.length??0)&&!(le?.events.length??0)?e.isRunning?(0,x.jsx)(`div`,{className:Z.empty,children:(0,x.jsxs)(`div`,{className:`${Z.emptyMsg} ${Z.emptyMsgRunning??``}`,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:Z.emptySpinner,"aria-hidden":`true`}),(0,x.jsx)(`span`,{children:`Awaiting first turn — the report populates once the kernel reports an event.`})]})}):(0,x.jsx)(`div`,{className:Z.empty,children:(0,x.jsx)(`div`,{className:Z.emptyMsg,children:`Run a simulation first to see the report.`})}):(0,x.jsxs)(`div`,{className:`reports-layout ${Z.layout}`,children:[(0,x.jsxs)(`div`,{ref:_e,onScroll:()=>{let e=_e.current;e&&(B.current=e.scrollHeight-e.scrollTop-e.clientHeight<40)},className:`reports-content ${Z.scroll}`,role:`region`,"aria-label":`Turn-by-turn report`,children:[C&&T&&(0,x.jsxs)(`p`,{className:Z.forkNotice,role:`note`,children:[`This run is in `,w?.name??w?.id,`, and a fork runs in its parent's scenario. Switch to `,w?.name??w?.id,` to fork it.`]}),(()=>{let e=t,n=e?.winnerName||``,r=e?.headline||e?.summary||``;if(!t&&I.length===0)return null;let i=I.length,a=I[I.length-1],o=I[0],s=(e,t)=>{let n=e?.[t];return typeof n==`number`?n:0},c=s(a?.[1]?.a?.metrics,`population`),l=s(a?.[1]?.b?.metrics,`population`),u=s(a?.[1]?.a?.metrics,`morale`),d=s(a?.[1]?.b?.metrics,`morale`),f=s(o?.[1]?.a?.metrics,`population`)||c,p=s(o?.[1]?.b?.metrics,`population`)||l,m=ce?.events.filter(e=>e.type===`forge_attempt`&&e.data?.approved===!0).length??0,h=le?.events.filter(e=>e.type===`forge_attempt`&&e.data?.approved===!0).length??0,g=[{label:`Turns`,value:String(i)},{label:`Final pop`,value:`A ${c}${c<f?` (↓${f-c})`:``} · B ${l}${l<p?` (↓${p-l})`:``}`,tone:c+l<f+p?`neg`:`neutral`},{label:`Final morale`,value:`A ${Math.round(u*100)}% · B ${Math.round(d*100)}%`,tone:Math.min(u,d)<.3?`neg`:Math.min(u,d)>=.6?`pos`:`neutral`},{label:`Tools forged`,value:`A ${m} · B ${h}`}];return(0,x.jsxs)(`div`,{className:Z.tldr,children:[(0,x.jsxs)(`div`,{className:Z.tldrTopRow,children:[(0,x.jsx)(`span`,{className:Z.tldrTag,children:`TL;DR`}),n?(0,x.jsxs)(`span`,{className:Z.tldrHeadline,children:[n,` wins`]}):i>0?(0,x.jsxs)(`span`,{className:Z.tldrHeadline,children:[`Run `,i,` turn`,i===1?``:`s`,` — verdict pending`]}):null,r&&(0,x.jsx)(`span`,{className:Z.tldrSub,children:r})]}),(0,x.jsx)(`div`,{className:Z.tldrStats,children:g.map(e=>(0,x.jsxs)(`span`,{children:[(0,x.jsxs)(`span`,{className:Z.tldrStatLabel,children:[e.label,`:`]}),(0,x.jsx)(`span`,{className:Z.tldrStatValue,style:{"--tone-color":NE(e.tone)},children:e.value})]},e.label))})]})})(),(0,x.jsxs)(`div`,{className:Z.headerRow,children:[(0,x.jsx)(`h2`,{className:Z.headerTitle,children:`Turn-by-Turn Report`}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>{let e=document.getElementById(`summary`);e&&e.scrollIntoView({behavior:`smooth`,block:`start`})},className:Z.jumpBtn,children:t?`↓ See verdict + full summary`:`↓ Jump to summary`})]}),P&&(0,x.jsxs)(`div`,{className:Z.actorPairPicker,role:`region`,"aria-label":`Pair focus toggle`,children:[(0,x.jsxs)(`label`,{className:Z.actorPairPickerToggle,children:[(0,x.jsx)(`input`,{type:`checkbox`,checked:re,onChange:e=>ie(e.target.checked),"aria-label":`Toggle pair-focus view for strip, sparklines, and trajectory`}),(0,x.jsx)(`span`,{className:Z.actorPairPickerToggleText,children:`Focus pair`})]}),re?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`select`,{"aria-label":`Left side actor`,className:Z.actorPairPickerSelect,value:N??``,onChange:e=>ee(e.target.value||null),children:e.actorIds.map(t=>(0,x.jsx)(`option`,{value:t,disabled:t===ne,children:e.actors[t]?.leader?.name??t},t))}),(0,x.jsx)(`span`,{className:Z.actorPairPickerVs,children:`vs`}),(0,x.jsx)(`select`,{"aria-label":`Right side actor`,className:Z.actorPairPickerSelect,value:ne??``,onChange:e=>M(e.target.value||null),children:e.actorIds.map(t=>(0,x.jsx)(`option`,{value:t,disabled:t===N,children:e.actors[t]?.leader?.name??t},t))}),(0,x.jsxs)(`span`,{className:Z.actorPairPickerHint,children:[`strip + metrics + trajectory show this pair only · turn-by-turn below shows all `,e.actorIds.length,` actors`]})]}):(0,x.jsxs)(`span`,{className:Z.actorPairPickerHint,children:[`Showing all `,e.actorIds.length,` actors. Toggle on to focus on a 2-actor head-to-head view in the strip, sparklines, and trajectory cards.`]})]}),(!P||re)&&(0,x.jsx)(`section`,{id:`strip`,children:(0,x.jsx)(xE,{turns:pe,leaderAName:L,leaderBName:ue})}),(0,x.jsx)(`section`,{id:`sparklines`,children:!P||re?(0,x.jsx)(EE,{metrics:me,leaderAName:L,leaderBName:ue}):he&&(0,x.jsx)(EE,{metrics:he,leaderAName:``,leaderBName:``})}),(0,x.jsxs)(`section`,{id:`trajectory`,children:[de&&re&&(0,x.jsxs)(`div`,{className:`responsive-grid-2 ${Z.trajectoryGrid}`,children:[(0,x.jsx)(LT,{events:ce?.events??[],actorName:L,baselineHexaco:ce?.leader?.hexaco}),(0,x.jsx)(LT,{events:le?.events??[],actorName:ue,baselineHexaco:le?.leader?.hexaco})]}),de&&!re&&(0,x.jsx)(`div`,{className:`responsive-grid-2 ${Z.trajectoryGrid}`,children:e.actorIds.map(t=>{let n=e.actors[t];return n?.events.length?(0,x.jsx)(LT,{events:n.events,actorName:n.leader?.name||t,baselineHexaco:n.leader?.hexaco},t):null})})]}),e.cost&&e.cost.llmCalls>0&&(0,x.jsxs)(`div`,{className:Z.costBar,children:[(0,x.jsx)(`span`,{className:Z.costLabel,children:`Run cost`}),(0,x.jsxs)(`span`,{className:Z.costAmount,children:[`$`,e.cost.totalCostUSD<.01?e.cost.totalCostUSD.toFixed(4):e.cost.totalCostUSD.toFixed(2)]}),(0,x.jsxs)(`span`,{className:Z.costMeta,children:[`· `,e.cost.llmCalls,` LLM calls · `,(e.cost.totalTokens/1e3).toFixed(1),`k tokens`]}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>d(!0),className:Z.costBtn,children:`Per-stage breakdown ›`})]}),u&&e.cost&&e.cost.llmCalls>0&&(0,x.jsx)(AT,{combined:e.cost,leaderA:(oe?e.costByActor[oe]:void 0)??{totalTokens:0,totalCostUSD:0,llmCalls:0},leaderB:(se?e.costByActor[se]:void 0)??{totalTokens:0,totalCostUSD:0,llmCalls:0},leaderAName:ce?.leader?.name,leaderBName:le?.leader?.name,actors:P?e.actorIds.map(t=>({actorId:t,name:e.actors[t]?.leader?.name||t,cost:e.costByActor[t]??{totalTokens:0,totalCostUSD:0,llmCalls:0}})):void 0,onClose:()=>d(!1)}),!P&&I.map(([e,t])=>{let n=t.a,r=t.b,i=n.time||r.time||`?`,a=Math.max(...[...n.events.values()].map(e=>e.totalEvents),...[...r.events.values()].map(e=>e.totalEvents),1),o=n.events.get(0)?.title,s=r.events.get(0)?.title,c=!!(o&&s&&o!==s);return(0,x.jsxs)(`section`,{id:`turn-${e}`,className:[Z.turnSection,c?Z.diverged:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`div`,{className:Z.turnHeader,children:[(0,x.jsxs)(`span`,{className:Z.turnTitle,children:[`Turn `,e,` — Y`,i,a>1&&(0,x.jsxs)(`span`,{className:Z.turnEventCount,children:[a,` events`]})]}),(0,x.jsxs)(`div`,{className:Z.turnHeaderRight,children:[(0,x.jsx)(`span`,{className:[Z.divergenceFlag,c?Z.diverged:``].filter(Boolean).join(` `),children:c?`DIVERGENT`:`SHARED`}),E(e)&&(0,x.jsxs)(`button`,{type:`button`,className:xT.forkButton,onClick:()=>v(e),"aria-label":`Fork at ${g.time} ${e}`,children:[`↳ Fork at `,g.Time,` `,e]})]})]}),Array.from({length:a}).map((e,t)=>(0,x.jsxs)(`div`,{className:`responsive-grid-2 ${t<a-1?Z.eventGridSpaced:Z.eventGrid}`,children:[(0,x.jsx)(IE,{block:n.events.get(t),eventIndex:t,totalEvents:a,name:L,sideColor:`var(--vis)`,sections:z.eventSections}),(0,x.jsx)(IE,{block:r.events.get(t),eventIndex:t,totalEvents:a,name:ue,sideColor:`var(--eng)`,sections:z.eventSections})]},t)),(0,x.jsxs)(`div`,{className:`responsive-grid-2 ${Z.footerGrid}`,children:[(0,x.jsx)(LE,{data:n,name:L,sideColor:`var(--vis)`,showQuotes:z.footerSections.includes(`quotes`)}),(0,x.jsx)(LE,{data:r,name:ue,sideColor:`var(--eng)`,showQuotes:z.footerSections.includes(`quotes`)})]})]},e)}),P&&ae.map(([t,n])=>{let r=[],i,a=1;for(let t of e.actorIds){let e=n.get(t);if(!e)continue;i??=e.time;for(let t of e.events.values())t.totalEvents>a&&(a=t.totalEvents);let o=e.events.get(0)?.title;o&&r.push(o)}let o=new Set(r).size>1,s=i??`?`;return(0,x.jsxs)(`section`,{id:`turn-${t}`,className:[Z.turnSection,o?Z.diverged:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`div`,{className:Z.turnHeader,children:[(0,x.jsxs)(`span`,{className:Z.turnTitle,children:[`Turn `,t,` — Y`,s,a>1&&(0,x.jsxs)(`span`,{className:Z.turnEventCount,children:[a,` events`]})]}),(0,x.jsxs)(`div`,{className:Z.turnHeaderRight,children:[(0,x.jsx)(`span`,{className:[Z.divergenceFlag,o?Z.diverged:``].filter(Boolean).join(` `),children:o?`DIVERGENT`:`SHARED`}),E(t)&&(0,x.jsxs)(`button`,{type:`button`,className:xT.forkButton,onClick:()=>v(t),"aria-label":`Fork at ${g.time} ${t}`,children:[`↳ Fork at `,g.Time,` `,t]})]})]}),Array.from({length:a}).map((t,r)=>(0,x.jsx)(`div`,{className:r<a-1?Z.nActorEventTrackSpaced:Z.nActorEventTrack,children:e.actorIds.map((t,i)=>{let o=n.get(t)?.events.get(r),s=e.actors[t]?.leader?.name??t;return(0,x.jsx)(IE,{block:o,eventIndex:r,totalEvents:a,name:s,sideColor:i===0?`var(--vis)`:i===1?`var(--eng)`:`var(--amber)`,sections:z.eventSections},t)})},r)),(0,x.jsx)(`div`,{className:Z.nActorFooterTrack,children:e.actorIds.map((t,r)=>{let i=n.get(t);if(!i)return null;let a=e.actors[t]?.leader?.name??t;return(0,x.jsx)(LE,{data:i,name:a,sideColor:r===0?`var(--vis)`:r===1?`var(--eng)`:`var(--amber)`,showQuotes:z.footerSections.includes(`quotes`)},t)})})]},t)}),(0,x.jsx)(`section`,{id:`toolbox`,children:a.list.length>0&&(0,x.jsxs)(`details`,{open:c,onToggle:e=>{let t=e.currentTarget.open;t&&!c&&B_({name:`forge_toolbox_open`,from:`reports`}),l(t)},className:K.pageFold,children:[(0,x.jsx)(`summary`,{className:K.pageFoldSummary,children:`FORGED TOOLBOX`}),(0,x.jsx)(Nb,{inPage:!0})]})}),(0,x.jsxs)(`section`,{id:`summary`,className:Z.summarySection,children:[(0,x.jsx)(`div`,{className:Z.summaryLabel,children:`Run Summary · Verdict · Winner`}),(0,x.jsx)(XT,{verdict:t,leaderAName:L,leaderBName:ue}),(0,x.jsx)(cE,{state:e}),t&&(0,x.jsx)(`div`,{className:Z.summaryVerdictWrap,children:(0,x.jsx)(jn,{verdict:t,shownRun:n})})]}),(0,x.jsx)(`section`,{id:`references`,children:i.list.length>0&&(0,x.jsx)(hC,{registry:i,title:`References`,collapsible:!0,defaultOpen:o,onToggle:s})}),(0,x.jsxs)(`details`,{className:Z.aboutDetails,children:[(0,x.jsx)(`summary`,{className:Z.aboutSummary,children:`What's in this report?`}),(0,x.jsxs)(`div`,{className:Z.aboutBody,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:Z.aboutBlockTitle,children:`Scenario focus`}),(0,x.jsx)(`div`,{className:Z.aboutChips,children:z.focusSections.map(e=>(0,x.jsx)(`span`,{className:Z.aboutChip,children:RT[e]},e))})]}),(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:Z.aboutBlockTitle,children:`This run produced`}),(0,x.jsx)(`div`,{className:Z.aboutChips,children:z.artifacts.map(e=>(0,x.jsx)(`span`,{className:Z.aboutChipNeutral,children:zT[e]},e))})]})]})]})]}),(0,x.jsx)(OE,{items:ge,scrollRoot:_e.current}),_!==null&&y&&(0,x.jsx)(ST,{parentArtifact:y,atTurn:_,maxTurns:yT(y),costPreset:`economy`,provider:`openai`,onConfirm:D,onClose:()=>v(null)})]})}var FE={positive:`var(--green)`,negative:`var(--rust)`,anxious:`var(--amber)`,defiant:`var(--rust)`,hopeful:`var(--green)`,resigned:`var(--text-3)`,neutral:`var(--text-2)`};function IE({block:e,eventIndex:t,totalEvents:n,name:r,sideColor:i,sections:a}){let o={"--side-color":i};if(!e||!e.title)return(0,x.jsxs)(`div`,{className:Z.eventCard,children:[(0,x.jsxs)(`h4`,{className:Z.eventHeading,style:o,children:[r,n>1&&(0,x.jsxs)(`span`,{className:Z.eventSubLabel,children:[`Event `,t+1,`/`,n]})]}),(0,x.jsx)(`span`,{className:Z.eventAwaiting,children:`Awaiting data...`})]});let s={crisis:(0,x.jsxs)(`div`,{children:[(0,x.jsxs)(`div`,{className:Z.eventTitle,children:[e.title,e.category&&(0,x.jsx)(`span`,{className:Z.categoryPill,children:e.category}),e.emergent&&(0,x.jsx)(`span`,{className:Z.emergentPill,children:`EMERGENT`})]}),e.description&&(0,x.jsx)(`div`,{className:Z.eventDescription,children:e.description})]},`crisis`),decision:e.decision?(0,x.jsx)(`div`,{className:Z.eventDecision,children:e.decision},`decision`):null,outcome:e.outcome?(0,x.jsxs)(`div`,{className:Z.eventOutcomeRow,children:[(0,x.jsx)(MS,{outcome:e.outcome}),Array.isArray(e.policies)&&e.policies.length>0&&(0,x.jsx)(`span`,{className:Z.eventPolicies,children:e.policies.map(e=>String(e)).join(` / `)})]},`outcome`):null,causality:e.rationale?(0,x.jsxs)(`details`,{className:Z.eventDetails,children:[(0,x.jsx)(`summary`,{className:Z.eventDetailsSummary,style:o,children:`Rationale`}),(0,x.jsx)(`div`,{className:Z.eventRationale,style:o,children:e.rationale})]},`causality`):null,departments:Object.keys(e.depts).length>0?(0,x.jsxs)(`details`,{className:Z.eventDetails,open:!0,children:[(0,x.jsxs)(`summary`,{className:Z.eventDetailsSummary,style:o,children:[`Departments (`,Object.keys(e.depts).length,`)`]}),(0,x.jsx)(`div`,{className:Z.deptList,children:Object.entries(e.depts).map(([e,t])=>(0,x.jsxs)(`div`,{className:Z.deptItem,style:o,children:[(0,x.jsxs)(`div`,{className:Z.deptHead,children:[(0,x.jsx)(`span`,{className:Z.deptName,children:e.charAt(0).toUpperCase()+e.slice(1)}),(0,x.jsxs)(`span`,{className:Z.deptMeta,children:[t.citations,`c `,t.tools,`t`]})]}),t.summary&&(0,x.jsx)(`div`,{className:Z.deptSummary,children:t.summary}),(0,x.jsx)(PS,{citations:t.citationList,label:``})]},e))})]},`departments`):null};return(0,x.jsxs)(`div`,{className:Z.eventCard,children:[(0,x.jsxs)(`h4`,{className:Z.eventHeading,style:o,children:[r,n>1&&(0,x.jsxs)(`span`,{className:Z.eventSubLabel,children:[`Event `,t+1,`/`,n]})]}),a.map(e=>s[e]).filter(Boolean)]})}function LE({data:e,name:t,sideColor:n,showQuotes:r}){let i=e.metrics;if(!i&&(!r||e.reactions.length===0))return(0,x.jsx)(`div`,{});let a={"--side-color":n};return(0,x.jsxs)(`div`,{className:Z.footerCard,children:[i&&(0,x.jsxs)(`details`,{className:e.reactions.length?Z.footerDetails:Z.footerDetailsLast,children:[(0,x.jsxs)(`summary`,{className:Z.footerSummary,style:a,children:[t,` · Systems State`]}),(0,x.jsx)(`div`,{className:Z.systemsRow,children:Object.entries(i).map(([e,t])=>(0,x.jsxs)(`span`,{className:Z.systemItem,children:[(0,x.jsxs)(`span`,{className:Z.systemKey,children:[e,`: `]}),(0,x.jsx)(`span`,{className:Z.systemValue,children:typeof t==`number`?Number.isInteger(t)?t:t.toFixed(2):String(t)})]},e))})]}),r&&e.reactions.length>0&&(0,x.jsxs)(`details`,{open:!0,children:[(0,x.jsxs)(`summary`,{className:Z.footerSummary,style:a,children:[`Agent Voices (`,e.totalReactions||e.reactions.length,`)`]}),(0,x.jsx)(`div`,{className:Z.reactionsList,children:e.reactions.map((e,t)=>(0,x.jsxs)(`div`,{className:Z.reactionItem,children:[(0,x.jsxs)(`div`,{className:Z.reactionHead,children:[(0,x.jsx)(`span`,{className:Z.reactionName,style:a,children:String(e.name)}),(0,x.jsx)(`span`,{className:Z.moodPill,style:{"--mood-color":FE[String(e.mood)]||`var(--text-3)`},children:String(e.mood||``).toUpperCase()})]}),(0,x.jsxs)(`div`,{className:Z.reactionQuote,children:[`“`,String(e.quote||``),`”`]}),!!e.role&&(0,x.jsxs)(`div`,{className:Z.reactionRole,children:[String(e.role),` `,e.department?`in ${String(e.department)}`:``]})]},t))})]})]})}var Q={layout:`_layout_1l1dk_1`,sidebar:`_sidebar_1l1dk_15`,sidebarHeading:`_sidebarHeading_1l1dk_31`,sidebarLead:`_sidebarLead_1l1dk_38`,actorFilter:`_actorFilter_1l1dk_45`,actorFilterLabel:`_actorFilterLabel_1l1dk_64`,actorFilterSelect:`_actorFilterSelect_1l1dk_74`,agentBtn:`_agentBtn_1l1dk_96`,selected:`_selected_1l1dk_110`,agentName:`_agentName_1l1dk_115`,agentMeta:`_agentMeta_1l1dk_119`,agentMood:`_agentMood_1l1dk_124`,chatArea:`_chatArea_1l1dk_131`,memoryBar:`_memoryBar_1l1dk_138`,memoryLabel:`_memoryLabel_1l1dk_145`,memoryBelief:`_memoryBelief_1l1dk_152`,memoryStance:`_memoryStance_1l1dk_157`,hexacoStrip:`_hexacoStrip_1l1dk_162`,hexacoLabel:`_hexacoLabel_1l1dk_174`,hexacoTrait:`_hexacoTrait_1l1dk_180`,hexacoBar:`_hexacoBar_1l1dk_184`,healthSignal:`_healthSignal_1l1dk_188`,messages:`_messages_1l1dk_192`,emptyState:`_emptyState_1l1dk_207`,emptyTitle:`_emptyTitle_1l1dk_213`,emptyCopy:`_emptyCopy_1l1dk_218`,eventCtx:`_eventCtx_1l1dk_225`,eventGroup:`_eventGroup_1l1dk_235`,eventGroupLast:`_eventGroupLast_1l1dk_239`,eventGroupLabel:`_eventGroupLabel_1l1dk_243`,eventRow:`_eventRow_1l1dk_252`,eventTurn:`_eventTurn_1l1dk_258`,eventTitle:`_eventTitle_1l1dk_265`,eventCategory:`_eventCategory_1l1dk_270`,memoryItem:`_memoryItem_1l1dk_275`,memoryTime:`_memoryTime_1l1dk_282`,relationshipsRow:`_relationshipsRow_1l1dk_287`,relationshipChip:`_relationshipChip_1l1dk_293`,bubbleWrap:`_bubbleWrap_1l1dk_297`,fromUser:`_fromUser_1l1dk_301`,fromAgent:`_fromAgent_1l1dk_305`,bubbleName:`_bubbleName_1l1dk_309`,bubble:`_bubble_1l1dk_297`,user:`_user_1l1dk_327`,typingBubble:`_typingBubble_1l1dk_332`,typingLabel:`_typingLabel_1l1dk_344`,dot:`_dot_1l1dk_359`,"chat-dot-bounce":`_chat-dot-bounce_1l1dk_1`,inputRow:`_inputRow_1l1dk_375`,inputField:`_inputField_1l1dk_392`,sendBtn:`_sendBtn_1l1dk_412`},RE={positive:`var(--green)`,negative:`var(--rust)`,anxious:`var(--amber)`,defiant:`var(--rust)`,hopeful:`var(--green)`,resigned:`var(--text-3)`,neutral:`var(--text-2)`};function zE(e){return e===`positive`?`var(--green)`:e===`negative`?`var(--rust)`:`var(--border)`}function BE({memory:e,events:t,scenario:n}){let r=[];for(let e of t.actorIds){let n=t.actors[e];if(n){for(let e of n.events)if(e.type===`turn_start`&&e.data.title&&e.data.title!==`Director generating...`){let t=e.data.turn;r.some(e=>e.turn===t)||r.push({turn:t,time:e.data.time||0,title:String(e.data.title),category:String(e.data.category||``)})}}}r.sort((e,t)=>e.turn-t.turn);let i=n.labels.eventNoun||`events`,a=e.recentMemories?.length>0,o=e.relationships?.length>0;return!r.length&&!a?null:(0,x.jsxs)(`div`,{className:Q.eventCtx,children:[r.length>0&&(0,x.jsxs)(`div`,{className:a?Q.eventGroup:Q.eventGroupLast,children:[(0,x.jsxs)(`div`,{className:Q.eventGroupLabel,style:{"--group-color":`var(--rust)`},children:[i.toUpperCase(),` EXPERIENCED`]}),r.map(e=>(0,x.jsxs)(`div`,{className:Q.eventRow,children:[(0,x.jsxs)(`span`,{className:Q.eventTurn,children:[`T`,e.turn,` `,e.time]}),(0,x.jsx)(`span`,{className:Q.eventTitle,children:e.title}),e.category&&(0,x.jsx)(`span`,{className:Q.eventCategory,children:e.category})]},e.turn))]}),a&&(0,x.jsxs)(`div`,{className:o?Q.eventGroup:Q.eventGroupLast,children:[(0,x.jsx)(`div`,{className:Q.eventGroupLabel,style:{"--group-color":`var(--amber)`},children:`RECENT MEMORIES`}),e.recentMemories.slice(0,3).map((e,t)=>(0,x.jsxs)(`div`,{className:Q.memoryItem,style:{"--valence-border":zE(e.valence)},children:[(0,x.jsxs)(`span`,{className:Q.memoryTime,children:[`Y`,e.time]}),` `,e.content]},t))]}),o&&(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:Q.eventGroupLabel,style:{"--group-color":`var(--teal)`},children:`RELATIONSHIPS`}),(0,x.jsx)(`div`,{className:Q.relationshipsRow,children:e.relationships.map((e,t)=>(0,x.jsxs)(`span`,{className:Q.relationshipChip,style:{"--rel-color":e.sentiment>0?`var(--green)`:`var(--rust)`},children:[e.name,` `,e.sentiment>0?`+`:``,e.sentiment.toFixed(1)]},t))})]})]})}function VE({state:e,onChatUsage:t}){let n=Qk(),[r,i]=(0,b.useState)(null),[a,o]=(0,b.useState)(()=>new Map),[s,c]=(0,b.useState)(()=>new Map),[l,u]=(0,b.useState)(``),[d,f]=(0,b.useState)(!1),p=(0,b.useRef)(null),m=(0,b.useRef)(!0),h=()=>{let e=p.current;e&&(m.current=e.scrollHeight-e.scrollTop-e.clientHeight<40)},g=(0,b.useMemo)(()=>{let t=new Map;for(let n of e.actorIds){let r=e.actors[n];if(!r)continue;let i=new Map;for(let e of r.events)if(e.type===`agent_reactions`){let t=e.data.reactions||[];for(let e of t)e.name&&i.set(e.name,{name:e.name,role:e.role||``,department:e.department||``,mood:e.mood||`neutral`,age:e.age,marsborn:e.marsborn,agentId:e.agentId,memory:e.memory,hexaco:e.hexaco,psychScore:e.psychScore,boneDensity:e.boneDensity,radiation:e.radiation})}i.size>0&&t.set(n,Array.from(i.values()))}return t},[e]),_=e.actorIds.length>=2,[v,y]=(0,b.useState)(`all`);(0,b.useEffect)(()=>{if(!_)v!==null&&y(null);else if(v!==`all`&&!(v&&g.has(v))){if(e.actorIds.length>=5){let t=e.actorIds.find(e=>(g.get(e)?.length??0)>0);y(t??`all`)}else y(`all`)}},[_,g,e.actorIds,v]);let[S,C]=(0,b.useState)(null),w=(0,b.useMemo)(()=>{if(v&&v!==`all`)return g.get(v)??[];let e=[],t=new Set;for(let n of g.values())for(let r of n)t.has(r.name)||(t.add(r.name),e.push(r));return e},[g,v]),T=(0,b.useMemo)(()=>{let e=new Set;for(let t of w){let n=(t.department||``).trim();n&&e.add(n)}return[...e].sort((e,t)=>e.localeCompare(t))},[w]);(0,b.useEffect)(()=>{S&&!T.includes(S)&&C(null)},[T,S]);let E=(0,b.useMemo)(()=>S?w.filter(e=>(e.department||``).trim()===S):w,[w,S]),D=E.find(e=>e.name===r),O=e=>{if(v&&v!==`all`)return v;for(let[t,n]of g)if(n.some(t=>t.name===e))return t},k=e=>{let t=O(e);return t?`${t}\u0000${e}`:e},A=r?a.get(k(r))??[]:[];(0,b.useEffect)(()=>{m.current&&p.current&&p.current.scrollTo({top:p.current.scrollHeight,behavior:`smooth`})},[A,d]),(0,b.useEffect)(()=>{let e=()=>{let e=window.location.hash.match(/^#chat=([^&]+)/);if(!e)return;let t=decodeURIComponent(e[1]);t&&E.some(e=>e.name===t)&&i(t)};return e(),window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[E]);let j=e=>{i(e);let t=k(e);o(n=>{if(n.has(t))return n;let r=E.find(t=>t.name===e),i=r?{role:`agent`,name:r.name,text:`${r.role} in ${r.department}, age ${r.age||`?`}. I lived through this simulation — ask me about specific turns, the commander's decisions, crises I witnessed, people I worked with, or how my department handled what came up. Try: "what did you think of the commander's choice in turn 1?", "who do you trust on the team?", or "what was the worst moment for you?"`}:{role:`agent`,text:`Connected.`},a=new Map(n);return a.set(t,[i]),a})},ee=(e,t)=>{o(n=>{let r=new Map(n);return r.set(e,t(n.get(e)??[])),r})},te=(e,t)=>{c(n=>{let r=new Map(n);return r.set(e,t(n.get(e)??[])),r})},M=async()=>{if(!l.trim()||!r||d)return;let e=r,n=O(e),i=k(e),a=l.trim();u(``),f(!0),ee(i,e=>[...e,{role:`user`,text:a}]);let o=[...s.get(i)??[],{role:`user`,content:a}];te(i,()=>o);try{let r=(()=>{try{return JSON.parse(localStorage.getItem(`paracosm:keyOverrides`)||`{}`)}catch{return{}}})(),s=await(await fetch(`/chat`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({agentId:e,...n?{leader:n}:{},message:a,history:o,...r.openai?{apiKey:r.openai}:{},...r.anthropic?{anthropicKey:r.anthropic}:{}})})).json();if(s.reply){ee(i,t=>[...t,{role:`agent`,name:s.colonist||e,text:s.reply}]),te(i,e=>[...e,{role:`assistant`,content:s.reply}]);let n=s.usage;n&&t&&t({totalTokens:n.totalTokens??0,costUSD:n.costUSD??0})}else ee(i,e=>[...e,{role:`agent`,text:s.error||`No response`}])}catch(e){ee(i,t=>[...t,{role:`agent`,text:`Chat failed: ${e}`}])}f(!1)};return(0,x.jsxs)(`div`,{className:`chat-layout ${Q.layout}`,role:`region`,"aria-label":`Agent chat`,children:[(0,x.jsxs)(`div`,{className:`chat-sidebar ${Q.sidebar}`,children:[(0,x.jsx)(`h3`,{className:Q.sidebarHeading,children:E.length?`${E.length} Agents`:`Agent Chat`}),(0,x.jsx)(`p`,{className:Q.sidebarLead,children:E.length?`Talk to any ${n.labels.populationNoun.replace(/s$/,``)} from the simulation. Each agent has persistent memory, personality, and relationships shaped by the crises they experienced.`:`Chat becomes available after the first turn completes. Start a simulation and come back once agents have reacted to the first crisis. Each agent has persistent memory, personality, and relationships shaped by the crises they experience.`}),_&&g.size>0&&(0,x.jsxs)(`div`,{className:Q.actorFilter,children:[(0,x.jsx)(`label`,{className:Q.actorFilterLabel,htmlFor:`chat-actor-filter`,children:`Lead actor`}),(0,x.jsxs)(`select`,{id:`chat-actor-filter`,className:Q.actorFilterSelect,value:v??``,onChange:e=>y(e.target.value||null),"aria-label":`Filter chat agents by lead actor`,children:[(0,x.jsxs)(`option`,{value:`all`,children:[`All leaders (`,(()=>{let e=new Set;for(let t of g.values())for(let n of t)e.add(n.name);return e.size})(),`)`]}),e.actorIds.map(t=>{let n=g.get(t)?.length??0,r=e.actors[t]?.leader?.name||t;return(0,x.jsxs)(`option`,{value:t,disabled:n===0,children:[r,` (`,n,`)`]},t)})]})]}),T.length>1&&(0,x.jsxs)(`div`,{className:Q.actorFilter,children:[(0,x.jsx)(`label`,{className:Q.actorFilterLabel,htmlFor:`chat-department-filter`,children:`Department`}),(0,x.jsxs)(`select`,{id:`chat-department-filter`,className:Q.actorFilterSelect,value:S??``,onChange:e=>C(e.target.value||null),"aria-label":`Filter chat agents by department`,children:[(0,x.jsxs)(`option`,{value:``,children:[`All departments (`,w.length,`)`]}),T.map(e=>{let t=w.filter(t=>(t.department||``).trim()===e).length;return(0,x.jsxs)(`option`,{value:e,children:[e,` (`,t,`)`]},e)})]})]}),E.map(e=>(0,x.jsxs)(`button`,{onClick:()=>j(e.name),className:[Q.agentBtn,r===e.name?Q.selected:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`span`,{className:Q.agentName,children:e.name}),(0,x.jsxs)(`div`,{className:Q.agentMeta,children:[e.role,` `,e.department]}),(0,x.jsx)(`div`,{className:Q.agentMood,style:{"--mood-color":RE[e.mood]||`var(--text-3)`},children:e.mood.toUpperCase()})]},e.name))]}),(0,x.jsxs)(`div`,{className:Q.chatArea,children:[D?.memory&&(D.memory.beliefs?.length>0||D.memory.stances?.length>0)&&(0,x.jsxs)(`div`,{className:Q.memoryBar,children:[(0,x.jsx)(`span`,{className:Q.memoryLabel,children:`MEMORY `}),D.memory.beliefs?.slice(0,2).map((e,t)=>(0,x.jsx)(`span`,{className:Q.memoryBelief,children:e},t)),D.memory.stances?.map((e,t)=>(0,x.jsxs)(`span`,{className:Q.memoryStance,style:{"--stance-color":e.value>0?`var(--green)`:`var(--rust)`},children:[e.topic,`: `,e.value>.5?`confident`:e.value>0?`cautious`:`wary`]},t))]}),r&&D?.hexaco&&(0,x.jsxs)(`div`,{className:Q.hexacoStrip,children:[(0,x.jsx)(`span`,{className:Q.hexacoLabel,children:`HEXACO`}),[`O`,`C`,`E`,`A`,`Em`,`HH`].map(e=>{let t=D.hexaco[e],n=Math.round(t*4),r=`█`.repeat(n)+`░`.repeat(4-n);return(0,x.jsxs)(`span`,{title:`${e}: ${t.toFixed(2)}`,className:Q.hexacoTrait,children:[e,` `,(0,x.jsx)(`span`,{className:Q.hexacoBar,children:r}),` `,t.toFixed(2)]},e)}),typeof D.psychScore==`number`&&(0,x.jsxs)(`span`,{className:Q.healthSignal,style:{"--signal-color":D.psychScore<.4?`var(--rust)`:`var(--text-2)`},children:[`psych `,(D.psychScore*100).toFixed(0),`%`]}),typeof D.boneDensity==`number`&&D.boneDensity>0&&(0,x.jsxs)(`span`,{className:Q.healthSignal,style:{"--signal-color":D.boneDensity<70?`var(--rust)`:`var(--text-3)`},children:[`bone `,D.boneDensity.toFixed(0),`%`]}),typeof D.radiation==`number`&&D.radiation>0&&(0,x.jsxs)(`span`,{className:Q.healthSignal,style:{"--signal-color":D.radiation>2e3?`var(--rust)`:`var(--text-3)`},children:[`rad `,D.radiation.toFixed(0),`mSv`]})]}),(0,x.jsxs)(`div`,{ref:p,onScroll:h,className:Q.messages,role:`log`,"aria-live":`polite`,"aria-relevant":`additions`,"aria-label":D?.name?`Messages with ${D.name}`:`Chat messages`,children:[!r&&(0,x.jsxs)(`div`,{className:Q.emptyState,children:[(0,x.jsx)(`div`,{className:Q.emptyTitle,children:E.length?`Select an agent to start chatting.`:`No agents available yet.`}),(0,x.jsx)(`div`,{className:Q.emptyCopy,children:E.length?`Each agent is a simulated ${n.labels.populationNoun.replace(/s$/,``)} with a unique HEXACO personality, persistent memory of events they survived, evolving stances on topics, and relationships with other agents. Their responses reflect their actual simulation experience.`:`Run a simulation from the Settings tab. Once the first turn completes, agents become available for conversation. The chat system uses each agent's personality profile, memory, and event history to generate authentic in-character responses.`})]}),r&&D?.memory&&(0,x.jsx)(BE,{memory:D.memory,events:e,scenario:n}),A.map((e,t)=>(0,x.jsxs)(`div`,{className:[Q.bubbleWrap,e.role===`user`?Q.fromUser:Q.fromAgent].join(` `),children:[e.name&&(0,x.jsx)(`div`,{className:Q.bubbleName,children:e.name}),(0,x.jsx)(`div`,{className:[Q.bubble,e.role===`user`?Q.user:``].filter(Boolean).join(` `),children:e.text})]},t)),d&&r&&(0,x.jsxs)(`div`,{className:[Q.bubbleWrap,Q.fromAgent].join(` `),"aria-live":`polite`,"aria-label":`${D?.name||`Agent`} is typing`,children:[(0,x.jsx)(`div`,{className:Q.bubbleName,children:D?.name||r}),(0,x.jsxs)(`div`,{className:Q.typingBubble,children:[(0,x.jsx)(`span`,{className:Q.typingLabel,children:`typing`}),(0,x.jsx)(`span`,{className:Q.dot,"aria-hidden":`true`,style:{"--dot-delay":`0ms`},children:`.`}),(0,x.jsx)(`span`,{className:Q.dot,"aria-hidden":`true`,style:{"--dot-delay":`160ms`},children:`.`}),(0,x.jsx)(`span`,{className:Q.dot,"aria-hidden":`true`,style:{"--dot-delay":`320ms`},children:`.`})]})]})]}),(0,x.jsxs)(`div`,{className:Q.inputRow,children:[(0,x.jsx)(`input`,{value:l,onChange:e=>u(e.target.value),onKeyDown:e=>e.key===`Enter`&&M(),disabled:!r||d,"aria-label":r?`Message ${D?.name||`agent`}`:`Select an agent first`,placeholder:r?`Ask ${D?.name||`agent`}...`:`Select a ${n.labels.populationNoun.replace(/s$/,``)} first`,className:Q.inputField}),(0,x.jsx)(`button`,{onClick:M,disabled:!r||d||!l.trim(),className:Q.sendBtn,children:`Send`})]})]})]})}var $={kbd:`_kbd_1ur8r_2`,kbdKey:`_kbdKey_1ur8r_8`,kbdLabel:`_kbdLabel_1ur8r_18`,empty:`_empty_1ur8r_22`,emptySpinner:`_emptySpinner_1ur8r_34`,emptySpinnerRotate:`_emptySpinnerRotate_1ur8r_1`,root:`_root_1ur8r_54`,toolbarStrip:`_toolbarStrip_1ur8r_62`,toolbarTopRow:`_toolbarTopRow_1ur8r_71`,modePillsWrap:`_modePillsWrap_1ur8r_76`,overflowToggle:`_overflowToggle_1ur8r_95`,overflowToggleOpen:`_overflowToggleOpen_1ur8r_109`,helpBtn:`_helpBtn_1ur8r_114`,forgeToolboxKey:`_forgeToolboxKey_1ur8r_130`,toolsRow:`_toolsRow_1ur8r_163`,paletteBtn:`_paletteBtn_1ur8r_177`,toolBtn:`_toolBtn_1ur8r_191`,settingsBtn:`_settingsBtn_1ur8r_204`,settingsBtnOpen:`_settingsBtnOpen_1ur8r_217`,modeHint:`_modeHint_1ur8r_222`,ecologyNone:`_ecologyNone_1ur8r_232`,ecologyBack:`_ecologyBack_1ur8r_243`,diffLine:`_diffLine_1ur8r_255`,phoneTabRow:`_phoneTabRow_1ur8r_264`,phoneTab:`_phoneTab_1ur8r_264`,phoneTabActive:`_phoneTabActive_1ur8r_291`,leadersRow:`_leadersRow_1ur8r_297`,leadersRowNarrow:`_leadersRowNarrow_1ur8r_306`,sideWrap:`_sideWrap_1ur8r_311`,sideWrapHidden:`_sideWrapHidden_1ur8r_318`,leadersRowLinesBelow:`_leadersRowLinesBelow_1ur8r_322`,cohortWindow:`_cohortWindow_1ur8r_327`,cohortWindowLinesBelow:`_cohortWindowLinesBelow_1ur8r_331`,cohortTrackLinesBelow:`_cohortTrackLinesBelow_1ur8r_339`,turnLinesSlot:`_turnLinesSlot_1ur8r_344`,footerKeys:`_footerKeys_1ur8r_359`,srOnly:`_srOnly_1ur8r_372`,jumpLatest:`_jumpLatest_1ur8r_384`,"paracosm-jump-pulse":`_paracosm-jump-pulse_1ur8r_1`,jumpLatestBehind:`_jumpLatestBehind_1ur8r_407`,toast:`_toast_1ur8r_412`,"paracosm-toast-in":`_paracosm-toast-in_1ur8r_1`,toastKicker:`_toastKicker_1ur8r_433`,toastKickerMeta:`_toastKickerMeta_1ur8r_445`,toastBody:`_toastBody_1ur8r_449`,toastBodyMd:`_toastBodyMd_1ur8r_454`,vignette:`_vignette_1ur8r_459`,"paracosm-vignette":`_paracosm-vignette_1ur8r_1`,cohortViewBar:`_cohortViewBar_1ur8r_475`,cohortViewModeToggle:`_cohortViewModeToggle_1ur8r_486`,cohortViewModeButton:`_cohortViewModeButton_1ur8r_495`,cohortViewModeButtonActive:`_cohortViewModeButtonActive_1ur8r_526`,cohortPairPicker:`_cohortPairPicker_1ur8r_535`,cohortPairPickerLabel:`_cohortPairPickerLabel_1ur8r_543`,cohortPairPickerSelect:`_cohortPairPickerSelect_1ur8r_552`,cohortPairPickerVs:`_cohortPairPickerVs_1ur8r_575`,cohortPairPickerHint:`_cohortPairPickerHint_1ur8r_583`};function HE(e){return(0,b.useMemo)(()=>UE(e),[e])}function UE(e){let t={};for(let n of e.actorIds){let r=e.actors[n];if(!r)continue;t[n]=[];let i=new Map;for(let e of r.events)if((e.type===`event_start`||e.type===`turn_start`)&&e.turn!=null){let t=e.data?.category;if(typeof t==`string`&&t.length>0){let n=i.get(e.turn)??[];n.includes(t)||n.push(t),i.set(e.turn,n)}}let a=r.events.filter(e=>e.type===`systems_snapshot`);for(let e=0;e<r.agentSnapshots.length;e++){let o=r.agentSnapshots[e],s=a[e]?.data||{},c=s.turn||e+1,l=r.events.find(e=>e.type===`turn_done`&&e.data?.turn===c)?.data?.metrics??{},u=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,d=o.map(e=>({agentId:e.agentId,name:e.name,department:e.department,role:e.role,rank:e.rank,alive:e.alive,marsborn:e.marsborn,psychScore:e.psychScore,age:e.age,generation:e.generation,partnerId:e.partnerId,childrenIds:e.childrenIds||[],featured:e.featured,mood:e.mood,shortTermMemory:e.shortTermMemory||[]}));t[n].push({turn:c,time:s.time||0,cells:d,population:s.population||d.filter(e=>e.alive).length,morale:s.morale||0,foodReserve:typeof s.foodReserve==`number`?s.foodReserve:u(l.foodMonthsReserve),waterLitersPerDay:u(l.waterLitersPerDay),powerKw:u(l.powerKw),pressurizedVolumeM3:u(l.pressurizedVolumeM3),deaths:s.deaths||0,births:s.births||0,eventCategories:i.get(c)??[]})}}return t}var WE={region:`_region_1xlv9_1`,narrow:`_narrow_1xlv9_12`,canvasWrap:`_canvasWrap_1xlv9_18`,canvas:`_canvas_1xlv9_18`,revealCover:`_revealCover_1xlv9_38`,cornerBtn:`_cornerBtn_1xlv9_48`,focusBtn:`_focusBtn_1xlv9_70`,divergenceEmpty:`_divergenceEmpty_1xlv9_75`,divergenceEmptyMsg:`_divergenceEmptyMsg_1xlv9_86`,tileTooltip:`_tileTooltip_1xlv9_98`,tileKindLabel:`_tileKindLabel_1xlv9_117`,tileCoords:`_tileCoords_1xlv9_125`,tileNearestName:`_tileNearestName_1xlv9_131`,tileNearestRole:`_tileNearestRole_1xlv9_136`,tileNearestDeath:`_tileNearestDeath_1xlv9_142`,tileNearestBirth:`_tileNearestBirth_1xlv9_148`,tileNearestPattern:`_tileNearestPattern_1xlv9_154`,tileAmbient:`_tileAmbient_1xlv9_160`,hoverTooltip:`_hoverTooltip_1xlv9_164`,hoverHeader:`_hoverHeader_1xlv9_182`,hoverFeaturedPill:`_hoverFeaturedPill_1xlv9_192`,hoverRole:`_hoverRole_1xlv9_201`,hoverMood:`_hoverMood_1xlv9_209`,hoverMoodValue:`_hoverMoodValue_1xlv9_213`,psychBlock:`_psychBlock_1xlv9_217`,psychLabel:`_psychLabel_1xlv9_221`,psychSvg:`_psychSvg_1xlv9_227`,hoverHint:`_hoverHint_1xlv9_234`};function GE(e){let t=e>>>0;return()=>{t=t+1831565813>>>0;let e=t;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}function KE(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t>>>0}function qE(e,t,n,r,i=8){return{x:Math.max(i,Math.min(n-i,e)),y:Math.max(i,Math.min(r-i,t))}}function JE(e){let t=new Set;for(let n of e)t.add(n.department||`unknown`);return[...t].sort()}function YE(e,t,n){let r=new Map;if(n.length===0)return r;let i=e/2,a=t/2,o=Math.min(e,t)*.32,s=Math.min(e,t)*.14;if(n.length===1)return r.set(n[0],{cx:i,cy:a,r:s*1.5}),r;for(let e=0;e<n.length;e++){let t=Math.PI*2*e/n.length-Math.PI/2;r.set(n[e],{cx:i+Math.cos(t)*o,cy:a+Math.sin(t)*o,r:s})}return r}function XE(e,t,n){let r=YE(t,n,JE(e)),i=new Map;for(let a of e){let e=r.get(a.department||`unknown`)??{cx:t/2,cy:n/2,r:40},o=GE(KE(`${a.agentId}|${t}x${n}|dept`)),s=o()*Math.PI*2,c=Math.sqrt(o())*e.r;i.set(a.agentId,qE(e.cx+Math.cos(s)*c,e.cy+Math.sin(s)*c,t,n))}return i}function ZE(e,t,n){let r=new Map,i=new Set,a=new Map(e.map(e=>[e.agentId,e])),o=[];for(let t of e)if(!i.has(t.agentId)&&t.partnerId&&a.has(t.partnerId)&&!i.has(t.partnerId)){let e=a.get(t.partnerId),n=t.childrenIds.map(e=>a.get(e)).filter(e=>!!e);o.push([t,e,...n]),i.add(t.agentId),i.add(e.agentId);for(let e of n)i.add(e.agentId)}let s=e.filter(e=>!i.has(e.agentId)),c=Math.max(50,(t-80)/Math.max(1,o.length));return o.forEach((e,i)=>{let a=40+c*i+c/2;e.forEach((i,o)=>{let s=GE(KE(`${i.agentId}|fam`)),c=o/e.length*Math.PI*2,l=14+s()*6;r.set(i.agentId,qE(a+Math.cos(c)*l,40+Math.sin(c)*l,t,n))})}),s.forEach((e,i)=>{let a=GE(KE(`${e.agentId}|solo`)),o=40+(t-80)*(i+.5)/Math.max(1,s.length),c=n-40-a()*40;r.set(e.agentId,qE(o,c,t,n))}),r}function QE(e,t,n){let r={positive:-1,hopeful:-.6,neutral:0,anxious:.4,negative:.8,defiant:.6,resigned:.7},i=new Map;for(let a of e){let e=(r[a.mood]??0)*.5+.5,o=GE(KE(`${a.agentId}|mood`)),s=40+(t-80)*e,c=40+(n-80)*o();i.set(a.agentId,qE(s,c,t,n))}return i}function $E(e,t,n){let r=new Map;for(let i of e){let e=Math.max(0,Math.min(80,i.age??30))/80,a=GE(KE(`${i.agentId}|age`)),o=40+(t-80)*a(),s=40+(n-80)*e;r.set(i.agentId,qE(o,s,t,n))}return r}function eD(e,t,n,r){return t===`families`?ZE(e,n,r):t===`mood`?QE(e,n,r):t===`age`?$E(e,n,r):XE(e,n,r)}function tD(e,t,n,r,i=1,a,o=!1,s=0,c=``,l=!1,u=`rgba(216, 204, 176, 0.9)`,d=`rgba(10, 8, 6, 0.55)`){e.save(),.5+.5*Math.sin(s*.003);let f=c.trim().toLowerCase().split(/\s+/).filter(Boolean),p=f.length>0,m=e=>{if(!p)return!1;let t=`${e.name} ${e.department} ${e.role} ${e.mood}`.toLowerCase();return f.every(e=>t.includes(e))};for(let c of t){if(!c.alive)continue;let t=n.get(c.agentId);if(!t)continue;let l=a?.has(c.agentId)??!1;if(o&&!l)continue;let u=m(c),d=p&&!u,f=c.featured?5:3,h=c.featured?.95:.75,g=d?.25:1;if(c.featured&&!d){let n=f+6,a=.42*i;e.strokeStyle=r,e.lineWidth=1,e.globalAlpha=a,e.beginPath(),e.arc(t.x,t.y,n,0,Math.PI*2),e.stroke()}if(u){let n=.7+.3*Math.sin(s*.006);e.strokeStyle=`rgba(248, 225, 150, 1)`,e.lineWidth=2.2,e.globalAlpha=i*n,e.beginPath(),e.arc(t.x,t.y,f+6,0,Math.PI*2),e.stroke()}l&&!d&&(e.strokeStyle=`rgba(232, 180, 74, 0.9)`,e.lineWidth=2,e.globalAlpha=i,e.beginPath(),e.arc(t.x,t.y,f+3,0,Math.PI*2),e.stroke()),e.strokeStyle=l?`rgba(224, 101, 48, 1)`:r,e.lineWidth=c.featured||l||u?1.6:1,e.globalAlpha=(l?1:h)*i*g,e.beginPath(),e.arc(t.x,t.y,f,0,Math.PI*2),e.stroke()}if(l){e.font=`9px ui-monospace, monospace`,e.textAlign=`center`,e.textBaseline=`top`;for(let r of t){if(!r.alive)continue;let t=n.get(r.agentId);if(!t)continue;let s=a?.has(r.agentId)??!1;if(o&&!s||!r.featured&&!s)continue;let c=m(r);if(p&&!c)continue;let l=r.name.split(/\s+/)[0],f=t.y+(r.featured?12:10),h=e.measureText(l).width;e.fillStyle=d,e.fillRect(t.x-h/2-3,f-1,h+6,10),e.fillStyle=s?`rgba(232, 180, 74, 0.95)`:u,e.globalAlpha=i,e.fillText(l,t.x,f)}}e.restore()}var nD={birth:`rgba(154, 205, 96, 0.8)`,death:`rgba(168, 152, 120, 0.7)`,forge_approved:`rgba(232, 180, 74, 0.8)`,forge_rejected:`rgba(224, 101, 48, 0.7)`,reuse:`rgba(232, 180, 74, 0.6)`,crisis:`rgba(196, 74, 30, 0.8)`},rD=6;function iD(e,t){e.save();for(let n of t){let t=nD[n.kind]??`rgba(255,255,255,0.6)`,r=n.progress,i=1-r;if(e.globalAlpha=i,n.kind===`birth`||n.kind===`death`||n.kind===`crisis`){let a=4+r*14;if(e.strokeStyle=t,e.lineWidth=1.2,e.beginPath(),e.arc(n.x,n.y,a,0,Math.PI*2),e.stroke(),n.kind!==`crisis`){let a=2+r*22,o=n.kind===`birth`?1.8:1.4;e.fillStyle=t;for(let t=0;t<rD;t++){let r=t/rD*Math.PI*2+(n.kind===`birth`?.3:-.2),s=n.x+Math.cos(r)*a,c=n.y+Math.sin(r)*a;e.globalAlpha=i*.9,e.beginPath(),e.arc(s,c,o,0,Math.PI*2),e.fill()}}}else if(n.kind===`reuse`&&typeof n.endX==`number`&&typeof n.endY==`number`){let a=n.x+(n.endX-n.x)*r,o=n.y+(n.endY-n.y)*r,s=e.createRadialGradient(a,o,0,a,o,8);s.addColorStop(0,`rgba(248, 225, 150, 0.95)`),s.addColorStop(.4,t),s.addColorStop(1,`rgba(232, 180, 74, 0)`),e.fillStyle=s,e.globalAlpha=i,e.beginPath(),e.arc(a,o,8,0,Math.PI*2),e.fill(),e.fillStyle=`rgba(248, 225, 150, 0.95)`,e.beginPath(),e.arc(a,o,2,0,Math.PI*2),e.fill()}else e.fillStyle=t,e.beginPath(),e.arc(n.x,n.y,3,0,Math.PI*2),e.fill()}e.restore()}var aD={medical:`rgba(78, 205, 196, 0.9)`,engineering:`rgba(232, 180, 74, 0.9)`,agriculture:`rgba(106, 173, 72, 0.9)`,psychology:`rgba(155, 107, 158, 0.9)`,governance:`rgba(224, 101, 48, 0.9)`,research:`rgba(149, 107, 216, 0.9)`,science:`rgba(149, 107, 216, 0.9)`,ops:`rgba(200, 122, 58, 0.9)`,operations:`rgba(200, 122, 58, 0.9)`};function oD(e){return aD[(e||``).toLowerCase()]??`rgba(168, 152, 120, 0.9)`}function sD(e,t,n){e.save(),e.font=`10px ui-monospace, monospace`,e.fillStyle=n.sideColor,e.textBaseline=`top`,e.textAlign=`left`;let r=n.actorName.toUpperCase();e.fillText(r,10,10);let i=e.measureText(r).width,a=(n.actorArchetype||``).trim().replace(/^The\s+/i,``);if(a){e.font=`bold 8px ui-monospace, monospace`;let t=a.toUpperCase(),r=e.measureText(t).width,o=10+i+8;e.fillStyle=n.labelBg??`rgba(10, 8, 6, 0.5)`,e.fillRect(o,9,r+10,13),e.strokeStyle=n.sideColor,e.lineWidth=1,e.strokeRect(o+.5,9.5,r+10-1,12),e.fillStyle=n.sideColor,e.textBaseline=`middle`,e.fillText(t,o+5,16),e.textBaseline=`top`,e.font=`10px ui-monospace, monospace`}e.fillStyle=n.textMuted??`rgba(216, 204, 176, 0.75)`;let o=t?.time,s=n.timeUnitShort??`t`,c=typeof o==`number`?typeof n.startTime==`number`?`T${t?.turn??0} · ${o} · ${s} ${Math.max(0,o-n.startTime)}`:`T${t?.turn??0} · ${o}`:`T${t?.turn??0}`;if(e.fillText(c,10,24),!t){e.restore();return}if(n.deptLabels&&n.cells&&n.positions&&n.cells.length>0){let t=new Map;for(let e of n.cells){if(!e.alive)continue;let r=n.positions.get(e.agentId);if(!r)continue;let i=(e.department||`unknown`).toLowerCase(),a=t.get(i)??{xs:[],ys:[]};a.xs.push(r.x),a.ys.push(r.y),t.set(i,a)}e.font=`bold 9px ui-monospace, monospace`,e.textBaseline=`middle`,e.textAlign=`center`;let r=[];for(let[n,i]of t.entries()){if(i.xs.length===0)continue;let t=i.xs.reduce((e,t)=>e+t,0)/i.xs.length,a=Math.min(...i.ys),o=Math.max(14,a-14),s=`${n.toUpperCase()} ${i.xs.length}`,c=e.measureText(s);r.push({dept:n,cx:t,w:c.width+8,h:14,label:s,idealY:o})}r.sort((e,t)=>e.idealY-t.idealY);let i=[],a=(e,t)=>Math.abs(e.cx-t.cx)<(e.w+t.w)/2+2&&Math.abs(e.y-t.y)<(e.h+t.h)/2+2;for(let e of r){let t=e.idealY;for(let n=0;n<10;n++){let r=e.idealY-n*16,o=e.idealY+n*16,s=n===0?e.idealY:r>=10?r:o;if(!i.some(t=>a({cx:e.cx,w:e.w,y:s,h:e.h},t))){t=s;break}}i.push({...e,y:t})}for(let t of i)e.fillStyle=n.labelBg??`rgba(10, 8, 6, 0.85)`,e.fillRect(t.cx-t.w/2,t.y-t.h/2,t.w,t.h),e.strokeStyle=oD(t.dept),e.lineWidth=1,e.strokeRect(t.cx-t.w/2+.5,t.y-t.h/2+.5,t.w-1,t.h-1),e.fillStyle=oD(t.dept),e.fillText(t.label,t.cx,t.y)}e.font=`10px ui-monospace, monospace`,e.textAlign=`left`,e.textBaseline=`bottom`,e.fillStyle=n.sideColor;let l=n.previousSnapshot?t.population-n.previousSnapshot.population:0,u=l>0?`↑`:l<0?`↓`:``,d=l>0?`rgba(106, 173, 72, 0.95)`:l<0?`rgba(196, 74, 30, 0.95)`:`rgba(216, 204, 176, 0.75)`;if(e.fillText(`POP ${t.population}`,10,n.height-20),u){let r=`POP ${t.population}`,i=e.measureText(r).width+6;e.fillStyle=d,e.fillText(`${u}${Math.abs(l)}`,10+i,n.height-20),e.fillStyle=n.sideColor}(t.deaths>0||t.births>0)&&(e.fillStyle=n.textMuted??`rgba(216, 204, 176, 0.65)`,e.fillText(`+${t.births} -${t.deaths}`,10,n.height-8)),n.lagTurns&&n.lagTurns>0&&(e.textAlign=`right`,e.fillStyle=`rgba(232, 180, 74, 0.75)`,e.fillText(`lagging ${n.lagTurns}`,n.width-10,n.height-8)),e.restore()}function cD(e,t,n,r,i){if(t.length===0||r.length===0)return;let a=new Map;for(let e of r){if(e.approved===!1)continue;let t=(e.department||`unknown`).toLowerCase();a.set(t,(a.get(t)??0)+1)}if(a.size===0)return;let o=new Map;for(let e of t){if(!e.alive)continue;let t=n.get(e.agentId);if(!t)continue;let r=(e.department||`unknown`).toLowerCase(),i=o.get(r)??{x:0,y:0,count:0};i.x+=t.x,i.y+=t.y,i.count+=1,o.set(r,i)}let s=Math.max(...a.values());e.save(),e.globalCompositeOperation=`lighter`;for(let[t,n]of a.entries()){let r=o.get(t);if(!r||r.count===0)continue;let a=r.x/r.count,c=r.y/r.count,l=n/s,u=30+l*50,d=.2+l*.25,f=e.createRadialGradient(a,c,0,a,c,u);f.addColorStop(0,dD(i,d)),f.addColorStop(.6,dD(i,d*.4)),f.addColorStop(1,dD(i,0)),e.fillStyle=f,e.beginPath(),e.arc(a,c,u,0,Math.PI*2),e.fill(),e.globalCompositeOperation=`source-over`,e.fillStyle=dD(i,.95),e.font=`bold 11px ui-monospace, monospace`,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(`${n}`,a,c),e.globalCompositeOperation=`lighter`}e.restore()}function lD(e,t,n,r,i=`rgba(216, 204, 176, 0.6)`){let a=e=>typeof e==`number`?e:null,o=a(t.foodReserve),s=a(t.waterLitersPerDay),c=a(t.powerKw),l=a(t.pressurizedVolumeM3);if(o==null&&s==null&&c==null&&l==null)return;let u=(e,t,n)=>e<=t?1:e>=n?0:1-(e-t)/(n-t),d=e=>e<.33?`rgba(106, 173, 72, ${.06+e*.1})`:e<.66?`rgba(232, 180, 74, ${.08+(e-.33)*.2})`:`rgba(196, 74, 30, ${.12+(e-.66)*.3})`,f=n/2,p=r/2;e.save(),o!=null&&(e.fillStyle=d(u(o,3,18)),e.fillRect(0,0,f,p)),s!=null&&(e.fillStyle=d(u(s,200,1200)),e.fillRect(f,0,f,p)),c!=null&&(e.fillStyle=d(u(c,150,600)),e.fillRect(0,p,f,p)),l!=null&&(e.fillStyle=d(u(l,1500,4e3)),e.fillRect(f,p,f,p));let m=p+8;e.font=`bold 9px ui-monospace, monospace`,e.fillStyle=i,e.textAlign=`left`,e.textBaseline=`top`,o!=null&&e.fillText(`FOOD ${o.toFixed(1)}mo`,8,40),s!=null&&(e.textAlign=`right`,e.fillText(`WATER ${Math.round(s)}L/d`,n-8,40)),c!=null&&(e.textAlign=`left`,e.fillText(`POWER ${Math.round(c)}kW`,8,m)),l!=null&&(e.textAlign=`right`,e.fillText(`VOL ${Math.round(l)}m³`,n-8,m)),e.textBaseline=`alphabetic`,e.textAlign=`start`,e.restore()}function uD(e,t,n,r,i,a){if(!r||r.size===0)return;let o=.6+.4*Math.sin(i*.004);e.save();for(let i of t){if(!i.alive||!r.has(i.agentId))continue;let t=n.get(i.agentId);t&&(e.strokeStyle=a,e.lineWidth=2,e.globalAlpha=.9,e.beginPath(),e.arc(t.x,t.y,9,0,Math.PI*2),e.stroke(),e.lineWidth=1,e.globalAlpha=.45*o,e.beginPath(),e.arc(t.x,t.y,14+o*3,0,Math.PI*2),e.stroke(),e.globalAlpha=.2*o,e.beginPath(),e.arc(t.x,t.y,20+o*5,0,Math.PI*2),e.stroke())}e.restore()}function dD(e,t){let n=e.trim();if(n.startsWith(`#`)){let e=parseInt(n.slice(1),16);if(n.length===7)return`rgba(${e>>16&255},${e>>8&255},${e&255},${t})`}let r=n.match(/rgba?\(([^)]+)\)/);if(r){let e=r[1].split(`,`).map(e=>e.trim());if(e.length>=3)return`rgba(${e[0]},${e[1]},${e[2]},${t})`}return n}function fD(){return{items:[]}}function pD(e,t){for(e.items.push({...t,age:0,progress:0});e.items.length>30;)e.items.shift()}function mD(e){let t=[];for(let n of e.items){let e=n.age+1;e>=n.totalFrames||t.push({...n,age:e,progress:e/n.totalFrames})}e.items=t}function hD(e){return e.items}function gD(e,t){let n=new Map(e.map(e=>[e.agentId,e]));return{born:t.filter(e=>!n.has(e.agentId)&&e.alive&&!((e.age??0)>=18)),died:t.filter(e=>n.get(e.agentId)?.alive===!0&&!e.alive)}}var _D=new Set([`political`,`social`,`infrastructure`,`medical`,`resource`,`environmental`]);function vD(e,t,n,r){let i=(0,b.useRef)(fD()),a=(0,b.useRef)(new Set),[o,s]=(0,b.useState)(0),c=(0,b.useRef)(-1),l=(0,b.useRef)(!0),u=(0,b.useRef)(typeof document<`u`?!document.hidden:!0),d=jy(Fy);return(0,b.useEffect)(()=>{let t=e.snapshot,r=e.previousSnapshot;if(!t||t.turn===c.current||(c.current=t.turn,!r))return;let o=n(),{born:s,died:l}=gD(r.cells,t.cells);for(let e of s){let t=o.get(e.agentId);t&&pD(i.current,{kind:`birth`,x:t.x,y:t.y,totalFrames:30,sourceId:e.agentId})}for(let e of l){let t=o.get(e.agentId);t&&pD(i.current,{kind:`death`,x:t.x,y:t.y,totalFrames:60,sourceId:e.agentId})}let u=e.eventCategories??t.eventCategories??[];if(u.length>0){let e=Array.from(o.values());if(e.length>0){let n=e.reduce((e,t)=>e+t.x,0)/e.length,r=e.reduce((e,t)=>e+t.y,0)/e.length;for(let e of u){let o=e.toLowerCase();if(!_D.has(o))continue;let s=`crisis|${t.turn}|${o}`;a.current.has(s)||(a.current.add(s),pD(i.current,{kind:`crisis`,x:n,y:r,totalFrames:90}))}}}},[e.snapshot,e.previousSnapshot,e.eventCategories,n]),(0,b.useEffect)(()=>{if(!r)return;let t=r();if(t.size!==0){for(let n of e.forgeAttempts??[]){let e=`forge|${n.turn}|${n.eventIndex}|${n.department}|${n.name}|${n.approved?`a`:`r`}`;if(a.current.has(e))continue;a.current.add(e);let r=t.get((n.department||`unknown`).toLowerCase());r&&pD(i.current,{kind:n.approved?`forge_approved`:`forge_rejected`,x:r.x,y:r.y,totalFrames:n.approved?30:22})}for(let n of e.reuseCalls??[]){let e=`reuse|${n.turn}|${n.originDept}|${n.callingDept}|${n.name}`;if(a.current.has(e))continue;a.current.add(e);let r=t.get((n.originDept||`unknown`).toLowerCase()),o=t.get((n.callingDept||`unknown`).toLowerCase());r&&o&&pD(i.current,{kind:`reuse`,x:r.x,y:r.y,endX:o.x,endY:o.y,totalFrames:40})}}},[e.forgeAttempts,e.reuseCalls,r]),(0,b.useEffect)(()=>{let e=()=>{u.current=!document.hidden};document.addEventListener(`visibilitychange`,e);let n=t.current,r=null;return n&&(r=new IntersectionObserver(e=>{for(let t of e)l.current=t.isIntersecting},{threshold:0}),r.observe(n)),()=>{document.removeEventListener(`visibilitychange`,e),r?.disconnect()}},[t]),(0,b.useEffect)(()=>{if(d){s(e=>e+1);return}let e=0,t=performance.now(),n=r=>{!l.current||!u.current||r-t<33.333333333333336||(t=r,mD(i.current),s(e=>e+1)),e=requestAnimationFrame(n)};return e=requestAnimationFrame(n),()=>cancelAnimationFrame(e)},[d]),{flares:hD(i.current),tickClock:o}}function yD(e,t){let n=new Map;for(let r of e){if(!r.alive)continue;let e=t.get(r.agentId);if(!e)continue;let i=(r.department||`unknown`).toLowerCase(),a=n.get(i)??{x:0,y:0,n:0};a.x+=e.x,a.y+=e.y,a.n+=1,n.set(i,a)}let r=new Map;for(let[e,t]of n.entries())r.set(e,{x:t.x/t.n,y:t.y/t.n});return r}var bD={medical:`#4ecdc4`,engineering:`#e8b44a`,agriculture:`#6aad48`,psychology:`#9b6b9e`,governance:`#e06530`,research:`#956bd8`,science:`#956bd8`,ops:`#c87a3a`,operations:`#c87a3a`};function xD(e){return bD[(e||``).toLowerCase()]??`#a89878`}function SD({cells:e,size:t=44}){let{slices:n,alive:r}=(0,b.useMemo)(()=>{let t=new Map,n=0;for(let r of e){if(!r.alive)continue;let e=(r.department||`unknown`).toLowerCase();t.set(e,(t.get(e)??0)+1),n+=1}let r=[...t.entries()].sort((e,t)=>t[1]-e[1]),i=[];for(let[e,t]of r)i.push({dept:e,count:t,frac:t/Math.max(1,n),color:xD(e)});return{slices:i,alive:n}},[e]);if(r===0)return(0,x.jsx)(`div`,{style:{width:t,height:t,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`var(--text-4)`,fontSize:`var(--font-3xs)`,fontFamily:`var(--mono)`},"aria-label":`No live members`,children:`—`});let i=t/2,a=i-6,o=i,s=i,c=-Math.PI/2;return(0,x.jsxs)(`svg`,{width:t,height:t,viewBox:`0 0 ${t} ${t}`,role:`img`,"aria-label":`Department breakdown: ${n.map(e=>`${e.dept} ${e.count}`).join(`, `)}`,children:[n.map((e,t)=>{let n=e.frac*Math.PI*2,r=c,l=c+n;c=l;let u=o+Math.cos(r)*i,d=s+Math.sin(r)*i,f=o+Math.cos(l)*i,p=s+Math.sin(l)*i,m=o+Math.cos(r)*a,h=s+Math.sin(r)*a,g=o+Math.cos(l)*a,_=s+Math.sin(l)*a,v=+(n>Math.PI),y=[`M ${u.toFixed(2)} ${d.toFixed(2)}`,`A ${i} ${i} 0 ${v} 1 ${f.toFixed(2)} ${p.toFixed(2)}`,`L ${g.toFixed(2)} ${_.toFixed(2)}`,`A ${a} ${a} 0 ${v} 0 ${m.toFixed(2)} ${h.toFixed(2)}`,`Z`].join(` `);return(0,x.jsx)(`path`,{d:y,fill:e.color,opacity:.85,children:(0,x.jsx)(`title`,{children:`${e.dept}: ${e.count} (${Math.round(e.frac*100)}%)`})},`${e.dept}-${t}`)}),(0,x.jsx)(`text`,{x:o,y:s,textAnchor:`middle`,dominantBaseline:`central`,fontSize:10,fontFamily:`ui-monospace, monospace`,fontWeight:800,fill:`var(--text-1)`,children:r})]})}var CD={"tab.living":`Who's alive this turn — agents on the scenario grid.`,"tab.mood":`Aggregate mood mix per leader: hopeful / neutral / anxious / negative.`,"tab.forge":`Computational tools the agents forged in the QuickJS WebAssembly sandbox this turn.`,"tab.ecology":`Resource and environment metrics: power, food, water, radiation.`,"tab.divergence":`Per-metric A-vs-B deltas across all turns.`,"badge.forge":`Forge attempts on this turn — click FORGE for details.`,"badge.divergence":`Metrics diverged this turn — click DIVERGENCE for the rail.`,"stat.morale":`Aggregate morale across all alive agents (0–100%).`,"stat.moodMix":`Distribution of agents across the four mood tiers, weighted by morale.`,"stat.alive":`Living agents in this colony at the current turn.`,"stat.age":`Age distribution of living agents (4 bins: <20 / 20–40 / 40–60 / 60+).`,"stat.paired":`Alive agents currently in a partnership pair.`,"stat.earth":`Agents born on Earth (vs Native — born after the colony's first birth event).`,"stat.native":`Agents born in the colony itself (Marsborn / Lunarborn / scenario-specific).`,"stat.depts":`Agent count by department. Hover a wedge for the dept name.`,"chip.rising":`Aggregate morale trending up vs the previous turn.`},wD={strip:`_strip_1twpk_1`,narrow:`_narrow_1twpk_15`,col:`_col_1twpk_20`,colNarrow:`_colNarrow_1twpk_27`,colPaired:`_colPaired_1twpk_31`,row:`_row_1twpk_35`,rowBaseline:`_rowBaseline_1twpk_40`,label:`_label_1twpk_46`,moraleValue:`_moraleValue_1twpk_51`,bar:`_bar_1twpk_57`,moraleFill:`_moraleFill_1twpk_64`,value2:`_value2_1twpk_71`,valueRust:`_valueRust_1twpk_75`,valueNative:`_valueNative_1twpk_79`,moodHeader:`_moodHeader_1twpk_84`,moodEmpty:`_moodEmpty_1twpk_90`,moodBar:`_moodBar_1twpk_95`,moodSegment:`_moodSegment_1twpk_103`,moodLegend:`_moodLegend_1twpk_109`,ageBars:`_ageBars_1twpk_117`,ageBarCol:`_ageBarCol_1twpk_124`,ageBarFill:`_ageBarFill_1twpk_133`,ageScale:`_ageScale_1twpk_143`,deptBlock:`_deptBlock_1twpk_150`,deptLabel:`_deptLabel_1twpk_158`};function TD({snapshot:e,sideColor:t}){let n=jy(My),r=e.cells.filter(e=>e.alive),i=r.reduce((e,t)=>{let n=t.mood||`neutral`;return e[n]=(e[n]??0)+1,e},{}),a=[`positive`,`hopeful`,`neutral`,`anxious`,`negative`,`defiant`,`resigned`],o={positive:`var(--green)`,hopeful:`#9acd60`,neutral:`var(--text-4)`,anxious:`var(--amber)`,negative:`var(--rust)`,defiant:`#c44a1e`,resigned:`var(--text-3)`},s=r.length||1,c=[0,0,0,0];for(let e of r){let t=e.age??30;t<20?c[0]++:t<40?c[1]++:t<60?c[2]++:c[3]++}let l=Math.max(1,...c),u=r.filter(e=>!!e.partnerId).length,d=r.filter(e=>(e.generation??0)===0).length,f=Math.round(e.morale*100),p=f>=60?`var(--green)`:f>=30?`var(--amber)`:`var(--rust)`,m={"--side-color":t};return(0,x.jsxs)(`div`,{className:[wD.strip,n?wD.narrow:``].filter(Boolean).join(` `),children:[(0,x.jsxs)(`div`,{className:[wD.col,wD.colNarrow].join(` `),children:[(0,x.jsxs)(`div`,{className:wD.rowBaseline,children:[(0,x.jsx)(`span`,{className:wD.label,title:CD[`stat.morale`],children:`MORALE`}),(0,x.jsxs)(`span`,{className:wD.moraleValue,style:{"--morale-color":p},children:[f,`%`]})]}),(0,x.jsx)(`div`,{className:wD.bar,children:(0,x.jsx)(`div`,{className:wD.moraleFill,style:{"--morale-pct":`${Math.max(2,f)}%`,"--morale-color":p}})}),typeof e.foodReserve==`number`&&(0,x.jsxs)(`div`,{className:wD.row,children:[(0,x.jsx)(`span`,{children:`FOOD`}),(0,x.jsxs)(`span`,{className:wD.value2,children:[e.foodReserve.toFixed(1),`mo`]})]}),(0,x.jsxs)(`div`,{className:wD.row,children:[(0,x.jsx)(`span`,{children:`DEATHS`}),(0,x.jsx)(`span`,{className:wD.valueRust,children:e.deaths})]})]}),(0,x.jsxs)(`div`,{className:wD.col,children:[(0,x.jsxs)(`div`,{className:wD.moodHeader,children:[(0,x.jsx)(`span`,{className:wD.label,title:CD[`stat.moodMix`],children:`MOOD MIX`}),(0,x.jsxs)(`span`,{className:wD.value2,title:CD[`stat.alive`],children:[r.length,` alive`]})]}),r.length===0?(0,x.jsx)(`div`,{className:wD.moodEmpty,children:`no survivors`}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{className:wD.moodBar,children:a.map(e=>{let t=i[e]||0;if(t===0)return null;let n=t/s*100;return(0,x.jsx)(`div`,{title:`${e}: ${t}`,className:wD.moodSegment,style:{"--segment-pct":`${n}%`,"--segment-bg":o[e]||`var(--text-4)`}},e)})}),(0,x.jsx)(`div`,{className:wD.moodLegend,children:a.filter(e=>(i[e]||0)>0).map(e=>`${Math.round((i[e]||0)/s*100)}% ${e}`).slice(0,3).join(` · `)})]})]}),(0,x.jsxs)(`div`,{className:wD.col,children:[(0,x.jsx)(`div`,{className:wD.label,title:CD[`stat.age`],children:`AGE`}),(0,x.jsx)(`div`,{className:wD.ageBars,children:c.map((e,n)=>(0,x.jsx)(`div`,{className:wD.ageBarCol,children:(0,x.jsx)(`div`,{title:`${[`<20`,`20-40`,`40-60`,`60+`][n]}: ${e} colonists`,className:wD.ageBarFill,style:{"--age-height":`${e/l*100}%`,"--age-min":e>0?`2px`:`0`,"--age-bg":e>0?t:`transparent`}})},n))}),(0,x.jsxs)(`div`,{className:wD.ageScale,children:[(0,x.jsx)(`span`,{children:`<20`}),(0,x.jsx)(`span`,{children:`20`}),(0,x.jsx)(`span`,{children:`40`}),(0,x.jsx)(`span`,{children:`60+`})]})]}),(0,x.jsxs)(`div`,{className:[wD.col,wD.colPaired].join(` `),children:[(0,x.jsxs)(`div`,{className:wD.row,children:[(0,x.jsx)(`span`,{className:wD.label,title:CD[`stat.paired`],children:`PAIRED`}),(0,x.jsxs)(`span`,{className:wD.value2,children:[u,`/`,r.length]})]}),(0,x.jsxs)(`div`,{className:wD.row,children:[(0,x.jsx)(`span`,{title:CD[`stat.earth`],children:`EARTH`}),(0,x.jsx)(`span`,{className:wD.value2,children:d})]}),(0,x.jsxs)(`div`,{className:wD.row,children:[(0,x.jsx)(`span`,{title:CD[`stat.native`],children:`NATIVE`}),(0,x.jsx)(`span`,{className:wD.valueNative,style:m,children:r.length-d})]})]}),!n&&(0,x.jsxs)(`div`,{className:wD.deptBlock,"aria-label":`Department breakdown`,title:CD[`stat.depts`],children:[(0,x.jsx)(SD,{cells:e.cells,size:44}),(0,x.jsx)(`span`,{className:wD.deptLabel,children:`Depts`})]})]})}var ED={cols:12,rows:6,seedRadius:2},DD=[[1,0],[2,1],[0,2],[1,2],[2,2]],OD=[[0,1],[1,1],[2,1]],kD=[[0,0],[1,0],[0,1],[1,1]],AD=[[1,0],[2,0],[0,1],[3,1],[1,2],[2,2]],jD=[[1,0],[2,0],[3,0],[0,1],[1,1],[2,1]],MD=[[1,0],[2,0],[0,1],[1,1],[1,2]];function ND(e){switch(e){case`positive`:case`hopeful`:return kD;case`neutral`:return AD;case`anxious`:return OD;case`resigned`:return jD;case`defiant`:case`negative`:return DD;default:return OD}}function PD(e,t,n,r,i,a,o){let s=r/a,c=i/o,l=Math.max(1,Math.min(s,c)-2);e.save(),e.fillStyle=`rgba(106, 173, 72, 0.25)`,e.strokeStyle=`rgba(154, 205, 96, 0.95)`,e.lineWidth=2;for(let u of t){if(!u.alive||(u.generation??0)===0)continue;let t=n.get(u.agentId);if(!t)continue;let d=Math.floor(t.x/Math.max(1,r)*a),f=Math.floor(t.y/Math.max(1,i)*o),p=(s-l)/2,m=(c-l)/2,h=d*s+p,g=f*c+m;e.fillRect(h,g,l,l),e.strokeRect(h+.5,g+.5,l-1,l-1);let _=h+l/2,v=g+l/2,y=l*.4;e.beginPath(),e.moveTo(_-y,v),e.lineTo(_+y,v),e.moveTo(_,v-y),e.lineTo(_,v+y),e.stroke()}e.restore()}function FD(e,t,n,r,i,a,o,s=`rgba(168, 152, 120, 0.85)`,c=`rgba(168, 152, 120, 0.08)`){let l=r/a,u=i/o,d=Math.max(1,Math.min(l,u)-2);e.save(),e.lineWidth=2,e.strokeStyle=s,e.fillStyle=c;for(let s of t){if(s.alive)continue;let t=n.get(s.agentId);if(!t)continue;let c=Math.floor(t.x/Math.max(1,r)*a),f=Math.floor(t.y/Math.max(1,i)*o),p=(l-d)/2,m=(u-d)/2,h=c*l+p,g=f*u+m;e.fillRect(h,g,d,d),e.strokeRect(h+.5,g+.5,d-1,d-1),e.beginPath(),e.moveTo(h+4,g+4),e.lineTo(h+d-4,g+d-4),e.moveTo(h+d-4,g+4),e.lineTo(h+4,g+d-4),e.stroke()}e.restore()}function ID(e,t,n,r,i){let{cols:a,rows:o,grid:s}=e,c=Math.floor(t/Math.max(1,r)*a),l=Math.floor(n/Math.max(1,i)*o);return c<0||c>=a||l<0||l>=o?null:s[l*a+c]>0?{col:c,row:l}:null}function LD(e,t,n,r,i){return{col:Math.floor(e.x/Math.max(1,t)*r),row:Math.floor(e.y/Math.max(1,n)*i)}}function RD(e){switch(e){case`birth`:return kD;case`forge`:return DD;case`crisis`:return MD;case`death`:return[];default:return null}}function zD(e,t){return{cols:e,rows:t,grid:new Uint8Array(e*t),next:new Uint8Array(e*t),frame:0}}function BD(e,t,n,r,i,a=`all`){let{cols:o,rows:s,grid:c}=e;c.fill(0);let l=RD(a);for(let e=0;e<t.length;e+=1){let a=t[e];if(!a.alive)continue;let u=n.get(a.agentId);if(!u)continue;let d=Math.floor(u.x/Math.max(1,r)*o),f=Math.floor(u.y/Math.max(1,i)*s),p=l??ND(a.mood);for(let[e,t]of p){let n=d+e-1,r=f+t-1;n<0||n>=o||r<0||r>=s||(c[r*o+n]=8)}}}function VD(e,t,n,r){let{cols:i,rows:a,grid:o}=e,s=Math.floor(t.x/Math.max(1,n)*i),c=Math.floor(t.y/Math.max(1,r)*a);if(t.kind===`death`){for(let e=-1;e<=1;e+=1)for(let t=-1;t<=1;t+=1){let n=s+t,r=c+e;n<0||n>=i||r<0||r>=a||(o[r*i+n]=0)}return}let l;switch(t.kind){case`birth`:l=kD;break;case`forge_approved`:l=DD;break;case`forge_rejected`:l=OD;break;case`reuse`:l=jD;break;case`crisis`:l=MD;break;default:l=OD}for(let[e,t]of l){let n=s+e-1,r=c+t-1;n<0||n>=i||r<0||r>=a||(o[r*i+n]=8)}}function HD(e){let{cols:t,rows:n,grid:r,next:i}=e;i.fill(0);for(let e=0;e<n;e++)for(let a=0;a<t;a++){let o=0;for(let i=-1;i<=1;i++)for(let s=-1;s<=1;s++){if(s===0&&i===0)continue;let c=a+s,l=e+i;c<0||c>=t||l<0||l>=n||r[l*t+c]>0&&(o+=1)}let s=r[e*t+a],c=s>0;c&&o===2||o===3?i[e*t+a]=c?Math.max(4,s):8:c&&s>1&&(i[e*t+a]=Math.max(0,s-2))}r.set(i),e.frame+=1}function UD(e,t,n,r,i,a=1){let{cols:o,rows:s,grid:c}=t;if(a<=0)return;let l=n/o,u=r/s,d=Math.max(1,Math.min(l,u)-2),f=(l-d)/2,p=(u-d)/2;e.save();for(let t=0;t<s;t++)for(let n=0;n<o;n++){let r=c[t*o+n];if(r===0)continue;let s=Math.min(1,r/8*.9*a);e.fillStyle=i,e.globalAlpha=s,e.fillRect(n*l+f,t*u+p,d,d)}e.restore()}function WD(e,t){return e<0||Math.abs(t-e)>1}function GD(e,t,n,r){return r||n<=0?e:e*(1-(1-Math.max(0,Math.min(1,t/n)))**3)}function KD(e,t,n,r){for(let i=e.length-1;i>=0;i--){let a=e[i];if(!a.alive)continue;let o=t.get(a.agentId);if(!o)continue;let s=(a.featured?5:3)+18,c=n-o.x,l=r-o.y;if(c*c+l*l<=s*s)return a}return null}var qD=[`O`,`C`,`E`,`A`,`Em`,`HH`];function JD(e,t){let n=t/2,r=t/2,i=t/2-8;return qD.map((t,a)=>{let o=Math.PI*2*a/qD.length-Math.PI/2,s=Math.max(0,Math.min(1,e[t])),c=i*s;return`${n+Math.cos(o)*c},${r+Math.sin(o)*c}`}).join(` `)}function YD(e,t,n){let r=t/2,i=t/2,a=t/2,o=Math.PI*2*n/qD.length-Math.PI/2;return{x:r+Math.cos(o)*a,y:i+Math.sin(o)*a,label:e}}function XD({profile:e,colonyMean:t,size:n=160}){let r=JD(e,n),i=t?JD(t,n):null,a=n/2,o=n/2,s=n/2-8;return(0,x.jsxs)(`svg`,{width:n,height:n,role:`img`,"aria-label":`HEXACO profile radar`,children:[[.25,.5,.75,1].map(e=>(0,x.jsx)(`circle`,{cx:a,cy:o,r:s*e,fill:`none`,stroke:`var(--border)`,strokeDasharray:e===1?void 0:`2 3`},e)),qD.map((e,t)=>{let r=YD(e,n,t);return(0,x.jsx)(`text`,{x:r.x,y:r.y,fontSize:`9`,fontFamily:`var(--mono)`,fill:`var(--text-3)`,textAnchor:`middle`,dominantBaseline:`middle`,children:r.label},e)}),i&&(0,x.jsx)(`polygon`,{points:i,fill:`none`,stroke:`var(--text-3)`,strokeWidth:`1`,strokeDasharray:`3 3`}),(0,x.jsx)(`polygon`,{points:r,fill:`color-mix(in srgb, var(--amber) 25%, transparent)`,stroke:`var(--amber)`,strokeWidth:`1.5`})]})}var ZD={backdrop:`_backdrop_gccy2_1`,popover:`_popover_gccy2_8`,headerRow:`_headerRow_gccy2_25`,headerName:`_headerName_gccy2_34`,headerSubline:`_headerSubline_gccy2_42`,featuredPill:`_featuredPill_gccy2_49`,closeBtn:`_closeBtn_gccy2_59`,section:`_section_gccy2_72`,sectionLast:`_sectionLast_gccy2_77`,statsGrid:`_statsGrid_gccy2_81`,statKey:`_statKey_gccy2_88`,statValue:`_statValue_gccy2_92`,statValueUpper:`_statValueUpper_gccy2_96`,sectionLabel:`_sectionLabel_gccy2_101`,hexacoRow:`_hexacoRow_gccy2_110`,hexacoRadarWrap:`_hexacoRadarWrap_gccy2_116`,hexacoTopAxes:`_hexacoTopAxes_gccy2_120`,memoryList:`_memoryList_gccy2_126`,memoryItem:`_memoryItem_gccy2_132`,chatBtn:`_chatBtn_gccy2_143`},QD={O:`Openness`,C:`Conscientiousness`,E:`Extraversion`,A:`Agreeableness`,Em:`Emotionality`,HH:`Honesty-Humility`};function $D(e){if(!e)return``;let t=Object.entries(e);return t.sort((e,t)=>t[1]-e[1]),t.slice(0,2).map(([e,t])=>`${QD[e]} ${t.toFixed(2)}`).join(` · `)}function eO(e){let{payload:t,containerW:n,containerH:r,sideColor:i,hexacoById:a,snapshots:o,onClose:s,onOpenChat:c}=e,l=(0,b.useRef)(null);(0,b.useEffect)(()=>{if(!t)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),s())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[t,s]);let u=(0,b.useMemo)(()=>{if(t&&a)return a.get(t.cell.agentId)??a.get(t.cell.name)},[t,a]),d=(0,b.useMemo)(()=>{if(!t)return[];let e=[...t.cell.shortTermMemory??[]];if(o)for(let n=o.length-1;n>=0&&e.length<3;n--){let r=o[n].cells.find(e=>e.agentId===t.cell.agentId);if(r){for(let t of r.shortTermMemory??[])if(t&&!e.includes(t)&&e.push(t),e.length>=3)break}}return e.slice(0,3)},[t,o]),f=jy(Ny);if(!t)return null;let p=f?Math.min(320,n-16):320,m=Math.min(360,r-20),h=f?Math.max(8,(n-p)/2):t.x+p+10>n?Math.max(10,t.x-p-10):Math.min(n-p-10,t.x+10),g=f?Math.max(8,(r-m)/2):t.y-m-10<0?Math.min(r-m-10,t.y+10):Math.max(10,t.y-m-10),_=t.cell,v=typeof _.psychScore==`number`?Math.round(_.psychScore*100):null,y=(()=>{let e=_.generation??0;return e===0?`Earth-born`:e===1?`First-native`:`Gen ${e}`})(),S=Math.max(120,r-g-10),C={"--side-color":i,"--pop-left":`${h}px`,"--pop-top":`${g}px`,"--pop-width":`${p}px`,"--pop-max-height":`${S}px`};return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{onClick:s,className:ZD.backdrop}),(0,x.jsxs)(`div`,{ref:l,role:`dialog`,"aria-label":`${_.name} drilldown`,className:ZD.popover,style:C,children:[(0,x.jsxs)(`div`,{className:ZD.headerRow,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:ZD.headerName,children:_.name}),(0,x.jsxs)(`div`,{className:ZD.headerSubline,children:[_.role,` · `,_.rank,_.featured&&(0,x.jsx)(`span`,{className:ZD.featuredPill,children:`FEATURED`})]})]}),(0,x.jsx)(`button`,{type:`button`,onClick:s,"aria-label":`Close drilldown`,className:ZD.closeBtn,children:`×`})]}),(0,x.jsx)(`div`,{className:ZD.section,children:(0,x.jsxs)(`div`,{className:ZD.statsGrid,children:[(0,x.jsx)(`span`,{className:ZD.statKey,children:`DEPT`}),(0,x.jsx)(`span`,{className:ZD.statValueUpper,children:_.department}),(0,x.jsx)(`span`,{className:ZD.statKey,children:`AGE`}),(0,x.jsx)(`span`,{className:ZD.statValue,children:_.age??`—`}),(0,x.jsx)(`span`,{className:ZD.statKey,children:`MOOD`}),(0,x.jsx)(`span`,{className:ZD.statValue,children:_.mood}),v!==null&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`span`,{className:ZD.statKey,children:`PSYCH`}),(0,x.jsxs)(`span`,{className:ZD.statValue,children:[v,`%`]})]}),(0,x.jsx)(`span`,{className:ZD.statKey,children:`ORIGIN`}),(0,x.jsx)(`span`,{className:ZD.statValue,children:y}),(0,x.jsx)(`span`,{className:ZD.statKey,children:`PARTNER`}),(0,x.jsx)(`span`,{className:ZD.statValue,children:_.partnerId?`yes`:`—`}),(0,x.jsx)(`span`,{className:ZD.statKey,children:`CHILDREN`}),(0,x.jsx)(`span`,{className:ZD.statValue,children:_.childrenIds?.length??0})]})}),u&&(0,x.jsxs)(`div`,{className:ZD.section,children:[(0,x.jsx)(`div`,{className:ZD.sectionLabel,children:`HEXACO`}),(0,x.jsxs)(`div`,{className:ZD.hexacoRow,children:[(0,x.jsx)(`div`,{className:ZD.hexacoRadarWrap,children:(0,x.jsx)(XD,{profile:u,size:120})}),(0,x.jsx)(`div`,{className:ZD.hexacoTopAxes,children:$D(u)})]})]}),d.length>0&&(0,x.jsxs)(`div`,{className:ZD.section,children:[(0,x.jsx)(`div`,{className:ZD.sectionLabel,children:`Recent memory`}),(0,x.jsx)(`ul`,{className:ZD.memoryList,children:d.map((e,t)=>(0,x.jsxs)(`li`,{className:ZD.memoryItem,children:[`"`,e,`"`]},t))})]}),c&&(0,x.jsx)(`div`,{className:ZD.sectionLast,children:(0,x.jsxs)(`button`,{type:`button`,onClick:()=>c(_.name),className:ZD.chatBtn,children:[`Open chat with `,_.name.split(` `)[0]]})})]})]})}var tO={backdrop:`_backdrop_18xl4_1`,drawer:`_drawer_18xl4_8`,header:`_header_18xl4_25`,closeBtn:`_closeBtn_18xl4_32`,row:`_row_18xl4_45`,rowLabel:`_rowLabel_18xl4_53`,pillRow:`_pillRow_18xl4_58`,pill:`_pill_18xl4_58`,pillActive:`_pillActive_18xl4_76`,resetBtn:`_resetBtn_18xl4_81`},nO={deptLabels:!1,crosshair:!0,alerts:!0,sound:!1};function rO(e){let t={...nO};for(let n of Object.keys(nO))typeof e[n]==`boolean`&&(t[n]=e[n]);return t}function iO({open:e,settings:t,onChange:n,onClose:r}){let i=Pt(e);if((0,b.useEffect)(()=>{if(!e)return;let t=e=>{e.key===`Escape`&&(e.preventDefault(),r())};return document.addEventListener(`keydown`,t),()=>document.removeEventListener(`keydown`,t)},[e,r]),!e)return null;let a=(e,r)=>{n({...t,[e]:r})};return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{onClick:r,className:tO.backdrop}),(0,x.jsxs)(`div`,{ref:i,role:`dialog`,"aria-label":`Grid viz settings`,tabIndex:-1,className:tO.drawer,children:[(0,x.jsxs)(`div`,{className:tO.header,children:[(0,x.jsx)(`span`,{style:Pw,children:`Viz Settings`}),(0,x.jsx)(`button`,{type:`button`,onClick:r,"aria-label":`Close settings`,className:tO.closeBtn,children:`×`})]}),(0,x.jsxs)(aO,{label:`Dept labels`,children:[(0,x.jsx)(oO,{active:t.deptLabels,onClick:()=>a(`deptLabels`,!0),label:`on`}),(0,x.jsx)(oO,{active:!t.deptLabels,onClick:()=>a(`deptLabels`,!1),label:`off`})]}),(0,x.jsxs)(aO,{label:`Crosshair`,children:[(0,x.jsx)(oO,{active:t.crosshair,onClick:()=>a(`crosshair`,!0),label:`on`}),(0,x.jsx)(oO,{active:!t.crosshair,onClick:()=>a(`crosshair`,!1),label:`off`})]}),(0,x.jsxs)(aO,{label:`Alert toasts`,children:[(0,x.jsx)(oO,{active:t.alerts,onClick:()=>a(`alerts`,!0),label:`on`}),(0,x.jsx)(oO,{active:!t.alerts,onClick:()=>a(`alerts`,!1),label:`off`})]}),(0,x.jsxs)(aO,{label:`Sound cues`,children:[(0,x.jsx)(oO,{active:t.sound,onClick:()=>a(`sound`,!0),label:`on`}),(0,x.jsx)(oO,{active:!t.sound,onClick:()=>a(`sound`,!1),label:`off`})]}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>n(nO),style:Fw,className:tO.resetBtn,children:`Reset defaults`})]})]})}function aO({label:e,children:t}){return(0,x.jsxs)(`div`,{className:tO.row,children:[(0,x.jsx)(`span`,{style:Nw,className:tO.rowLabel,children:e}),(0,x.jsx)(`div`,{className:tO.pillRow,children:t})]})}function oO({active:e,onClick:t,label:n}){return(0,x.jsx)(`button`,{type:`button`,onClick:t,className:[tO.pill,e?tO.pillActive:``].filter(Boolean).join(` `),children:n})}var sO={drawer:`_drawer_tksc5_1`,header:`_header_tksc5_17`,headerLabel:`_headerLabel_tksc5_26`,closeBtn:`_closeBtn_tksc5_34`,sortRow:`_sortRow_tksc5_47`,sortChip:`_sortChip_tksc5_54`,active:`_active_tksc5_69`,body:`_body_tksc5_74`,empty:`_empty_tksc5_80`,deptHeader:`_deptHeader_tksc5_86`,row:`_row_tksc5_95`,deceased:`_deceased_tksc5_115`,swatch:`_swatch_tksc5_119`,rowName:`_rowName_tksc5_128`,featuredPill:`_featuredPill_tksc5_135`,deceasedToggle:`_deceasedToggle_tksc5_144`},cO={positive:`rgba(106, 173, 72, 1)`,hopeful:`rgba(154, 205, 96, 1)`,neutral:`rgba(107, 95, 80, 1)`,anxious:`rgba(232, 180, 74, 1)`,negative:`rgba(224, 101, 48, 1)`,defiant:`rgba(196, 74, 30, 1)`,resigned:`rgba(168, 152, 120, 1)`},lO=[{key:`dept`,label:`Dept`},{key:`name`,label:`Name`},{key:`psych`,label:`Psych`},{key:`age`,label:`Age`}];function uO({open:e,cells:t,actorName:n,sideColor:r,searchQuery:i,hoveredId:a,onHover:o,onSelect:s,onClose:c}){let[l,u]=(0,b.useState)(!1),[d,f]=(0,b.useState)(`dept`),p=Lm(),{alive:m,deceased:h,matchSet:g}=(0,b.useMemo)(()=>{let e=[],n=[];for(let r of t)r.alive?e.push(r):n.push(r);d===`dept`?e.sort((e,t)=>e.department.localeCompare(t.department)||e.name.localeCompare(t.name)):d===`name`?e.sort((e,t)=>e.name.localeCompare(t.name)):d===`psych`?e.sort((e,t)=>(t.psychScore??0)-(e.psychScore??0)):d===`age`&&e.sort((e,t)=>(t.age??0)-(e.age??0)),n.sort((e,t)=>e.name.localeCompare(t.name));let r=i.trim().toLowerCase().split(/\s+/).filter(Boolean),a=new Set;if(r.length>0)for(let e of t){let t=`${e.name} ${e.department} ${e.role} ${e.mood}`.toLowerCase();r.every(e=>t.includes(e))&&a.add(e.agentId)}return{alive:e,deceased:n,matchSet:a}},[t,i,d]),_=(0,b.useMemo)(()=>{if(d!==`dept`)return[[`__flat__`,m]];let e=new Map;for(let t of m){let n=(t.department||`unknown`).toLowerCase(),r=e.get(n)??[];r.push(t),e.set(n,r)}return[...e.entries()].sort((e,t)=>e[0].localeCompare(t[0]))},[m,d]);if(!e)return null;let v={"--side-color":r},y=(e,t,n)=>({"--row-color":t?`var(--text-4)`:`var(--text-2)`,"--row-bg":n?`var(--bg-card)`:e?`color-mix(in srgb, ${r} 13%, transparent)`:`transparent`,"--row-border":e?r:`transparent`,"--row-opacity":t?`0.55`:`1`});return(0,x.jsxs)(`div`,{className:sO.drawer,children:[(0,x.jsxs)(`div`,{className:sO.header,style:v,children:[(0,x.jsxs)(`span`,{className:sO.headerLabel,style:v,children:[n,` Roster · `,m.length]}),(0,x.jsx)(`button`,{type:`button`,onClick:c,"aria-label":`Close roster`,className:sO.closeBtn,children:`×`})]}),(0,x.jsx)(`div`,{className:sO.sortRow,children:lO.map(e=>{let t=d===e.key;return(0,x.jsx)(`button`,{type:`button`,onClick:()=>f(e.key),"aria-pressed":t,className:[sO.sortChip,t?sO.active:``].filter(Boolean).join(` `),children:e.label},e.key)})}),(0,x.jsxs)(`div`,{className:sO.body,children:[_.length===0&&(0,x.jsxs)(`div`,{className:sO.empty,children:[`No living `,p.people,`.`]}),_.map(([e,t])=>(0,x.jsxs)(`div`,{children:[d===`dept`&&(0,x.jsxs)(`div`,{className:sO.deptHeader,children:[e,` · `,t.length]}),t.map(e=>{let t=g.has(e.agentId),n=a===e.agentId,r=i.trim().length>0&&!t;return(0,x.jsxs)(`button`,{type:`button`,onMouseEnter:()=>o(e.agentId),onMouseLeave:()=>o(null),onClick:()=>s(e),title:`${e.name} · ${e.role} · ${e.mood}`,className:sO.row,style:y(t,r,n),children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:sO.swatch,style:{"--swatch-bg":cO[e.mood]??cO.neutral}}),(0,x.jsx)(`span`,{className:sO.rowName,children:e.name}),e.featured&&(0,x.jsx)(`span`,{className:sO.featuredPill,style:v,children:`★`})]},e.agentId)})]},e)),h.length>0&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`button`,{type:`button`,onClick:()=>u(e=>!e),className:sO.deceasedToggle,children:[l?`▼`:`▶`,` Deceased · `,h.length]}),l&&h.map(e=>{let t=a===e.agentId;return(0,x.jsxs)(`button`,{type:`button`,onMouseEnter:()=>o(e.agentId),onMouseLeave:()=>o(null),onClick:()=>s(e),title:`${e.name} · ${e.role} · deceased`,className:[sO.row,sO.deceased].join(` `),style:y(!1,!0,t),children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:sO.swatch,style:{"--swatch-bg":`var(--text-4)`}}),(0,x.jsx)(`span`,{className:sO.rowName,children:e.name})]},e.agentId)})]})]})]})}function dO({snapshot:e,previousSnapshot:t,sideColor:n,onSelect:r}){let[i,a]=(0,b.useState)([]),o=(0,b.useRef)(new Set);(0,b.useEffect)(()=>{if(!e)return;let n=e.cells.filter(e=>e.alive&&e.featured),r=t?new Set(t.cells.filter(e=>e.alive&&e.featured).map(e=>e.agentId)):o.current,i=n.filter(e=>!r.has(e.agentId));if(o.current=new Set(n.map(e=>e.agentId)),i.length===0)return;let s=performance.now()+6e3;a(i.slice(0,2).map(t=>({cell:t,turn:e.turn,expiresAt:s})))},[e,t]),(0,b.useEffect)(()=>{if(i.length===0)return;let e=Math.max(0,i[0].expiresAt-performance.now()),t=setTimeout(()=>a([]),e);return()=>clearTimeout(t)},[i]);let s=(0,b.useMemo)(()=>i,[i]);return s.length===0?null:(0,x.jsx)(`div`,{"aria-live":`polite`,style:{position:`absolute`,bottom:12,right:12,display:`flex`,flexDirection:`column`,gap:4,pointerEvents:`none`,zIndex:7,maxWidth:240},children:s.map(e=>(0,x.jsxs)(`button`,{type:`button`,onClick:()=>r?.(e.cell),"aria-label":`Spotlight: ${e.cell.name} · ${e.cell.department}`,title:`${e.cell.name} · ${e.cell.role} · ${e.cell.department} · mood: ${e.cell.mood}`,style:{pointerEvents:`auto`,display:`flex`,alignItems:`center`,gap:6,padding:`4px 10px`,background:`var(--bg-panel)`,border:`1px solid ${n}66`,borderLeft:`3px solid ${n}`,borderRadius:3,fontFamily:`var(--mono)`,fontSize:`var(--font-xs)`,color:`var(--text-2)`,textAlign:`left`,cursor:`pointer`,boxShadow:`0 4px 14px rgba(0, 0, 0, 0.4)`,animation:`paracosm-spotlight-in 380ms ease-out`,whiteSpace:`nowrap`,overflow:`hidden`,textOverflow:`ellipsis`,maxWidth:`100%`},children:[(0,x.jsx)(`span`,{style:{color:n,fontSize:`var(--font-2xs)`,flexShrink:0},"aria-hidden":`true`,children:`★`}),(0,x.jsx)(`span`,{style:{color:`var(--text-1)`,fontWeight:700,overflow:`hidden`,textOverflow:`ellipsis`},children:e.cell.name}),(0,x.jsx)(`span`,{style:{color:`var(--text-3)`,fontSize:`var(--font-2xs)`,flexShrink:0,textTransform:`uppercase`,letterSpacing:`0.04em`},children:e.cell.department})]},e.cell.agentId))})}function fO(e){let t=[];return typeof e.foodReserve==`number`&&t.push(`food reserve ${e.foodReserve.toFixed(1)} months`),typeof e.waterLitersPerDay==`number`&&t.push(`water ${Math.round(e.waterLitersPerDay)} litres a day`),typeof e.powerKw==`number`&&t.push(`power ${Math.round(e.powerKw)} kW`),typeof e.pressurizedVolumeM3==`number`&&t.push(`pressurized volume ${Math.round(e.pressurizedVolumeM3)} cubic metres`),t.map(e=>`, ${e}`).join(``)}function pO(e,t){if(e.startsWith(`var(`)&&t){let n=e.slice(4,-1).trim(),r=getComputedStyle(t).getPropertyValue(n).trim();if(r)return r}return e}function mO(e){let{snapshot:t,previousSnapshot:n,snapshotHistory:r,actorName:i,actorArchetype:a,startTime:o,sideColor:s,side:c,lagTurns:l,clusterMode:u=`departments`,initialPopulation:d=20,mode:f,hexacoById:p,leaderHexaco:m,forgeAttempts:h,reuseCalls:g,divergedIds:_,siblingHoveredId:v,onHoverChange:y,searchQuery:S=``,palette:C=0,settings:w=nO,focusedSide:T=null,onToggleFocus:E,onOpenChat:D,eventFilter:O=`all`,chronicleHover:k=null}=e,A=T===c,j=jy(My),ee=jy(Fy),te=Lm(),M=(0,b.useRef)(null),N=(0,b.useRef)(null),ne=(0,b.useRef)(null),[P,re]=(0,b.useState)({w:0,h:0}),[ie,F]=(0,b.useState)(null),[I,ae]=(0,b.useState)(null),[oe,se]=(0,b.useState)(null),[ce,le]=(0,b.useState)(!1),[L,ue]=(0,b.useState)(null),[de,fe]=(0,b.useState)(!1);(0,b.useEffect)(()=>{if(ee){fe(!0);return}let e=requestAnimationFrame(()=>fe(!0));return()=>cancelAnimationFrame(e)},[ee]);let R=(0,b.useRef)(zD(ED.cols,ED.rows)),z=(0,b.useRef)(-1),pe=(0,b.useRef)(``),me=(0,b.useRef)(``),he=(0,b.useRef)(null),ge=(0,b.useRef)(null),_e=(0,b.useRef)(-1/0),B=(0,b.useRef)({id:null,intensity:0});(0,b.useEffect)(()=>{let e=N.current;if(!e)return;let t=new ResizeObserver(e=>{for(let t of e){let e=Math.max(0,Math.round(t.contentRect.width)),n=Math.max(0,Math.round(t.contentRect.height));re(t=>t.w===e&&t.h===n?t:{w:e,h:n})}});return t.observe(e),()=>t.disconnect()},[]),(0,b.useEffect)(()=>{let e=ne.current;if(!e||P.w===0||P.h===0)return;let t=Math.min(2,window.devicePixelRatio||1);e.width=Math.round(P.w*t),e.height=Math.round(P.h*t),e.style.width=`${P.w}px`,e.style.height=`${P.h}px`;let n=e.getContext(`2d`);n&&n.setTransform(t,0,0,t,0,0)},[P.w,P.h]);let ve=(()=>{if(u!==`departments`)return u;switch(f){case`mood`:return`mood`;case`forge`:return`age`;case`divergence`:return`families`;default:return`departments`}})(),ye=(0,b.useMemo)(()=>!t||P.w===0?new Map:eD(t.cells,ve,P.w,P.h),[t,ve,P.w,P.h]),be=(0,b.useMemo)(()=>t?yD(t.cells,ye):new Map,[t,ye]),xe=vD({snapshot:t,previousSnapshot:n,forgeAttempts:h,reuseCalls:g,eventCategories:t?.eventCategories},N,()=>ye,()=>be),Se=f===`forge`?.7:f===`ecology`?0:1,Ce=(0,b.useMemo)(()=>{if(f!==`mood`||!t)return s;let e=t.cells.filter(e=>e.alive);if(e.length===0)return s;let n={};for(let t of e)n[t.mood]=(n[t.mood]||0)+1;let r=`neutral`,i=0;for(let[e,t]of Object.entries(n))t>i&&(i=t,r=e);switch(r){case`positive`:case`hopeful`:return`var(--green)`;case`anxious`:return`var(--amber)`;case`negative`:case`defiant`:return`var(--rust)`;case`resigned`:return`var(--text-3)`;default:return s}},[f,t,s]);(0,b.useEffect)(()=>{let e=ne.current;if(!e||!t||P.w===0||P.h===0)return;let r=e.getContext(`2d`);if(!r)return;let c=xe.flares.filter(e=>O===`all`?!0:O===`birth`?e.kind===`birth`:O===`death`?e.kind===`death`:O===`crisis`?e.kind===`crisis`:O!==`forge`||e.kind===`forge_approved`||e.kind===`forge_rejected`||e.kind===`reuse`),u=pO(s,M.current),d=M.current?getComputedStyle(M.current):null,p=(e,t)=>{if(!e.startsWith(`#`)||e.length!==7)return null;let n=parseInt(e.slice(1),16);return`rgba(${n>>16&255}, ${n>>8&255}, ${n&255}, ${t})`},m=d&&p(d.getPropertyValue(`--bg-deep`).trim(),.85)||`rgba(10, 8, 6, 0.85)`,g=d&&p(d.getPropertyValue(`--text-2`).trim(),.8)||`rgba(216, 204, 176, 0.75)`,y=d&&p(d.getPropertyValue(`--text-2`).trim(),.22)||`rgba(216, 204, 176, 0.22)`,b=d&&p(d.getPropertyValue(`--text-2`).trim(),.7)||`rgba(216, 204, 176, 0.7)`,x=d&&p(d.getPropertyValue(`--text-2`).trim(),.95)||`rgba(216, 204, 176, 0.95)`,C=d&&p(d.getPropertyValue(`--text-3`).trim(),.85)||`rgba(168, 152, 120, 0.85)`,T=d&&p(d.getPropertyValue(`--text-3`).trim(),.08)||`rgba(168, 152, 120, 0.08)`,E=d&&p(d.getPropertyValue(`--text-2`).trim(),.6)||`rgba(216, 204, 176, 0.6)`;r.clearRect(0,0,P.w,P.h);let D=R.current,k=f!==pe.current,A=t.turn!==z.current,j=O!==me.current,N=i!==he.current,re=z.current;if(A||k||j||N){z.current=t.turn,pe.current=f,me.current=O,he.current=i,BD(D,t.cells,ye,P.w,P.h,O);let e;e=ee?3:f===`mood`?0:f===`ecology`?2:f===`forge`?8:f===`divergence`?12:5;for(let t=0;t<e;t+=1)HD(D);!ee&&(A&&WD(re,t.turn)||N)&&(_e.current=performance.now()),ge.current=c.length?`${c[0].kind}|${c[0].x}|${c[0].y}`:null}else if(c.length>0){let e=`${c[0].kind}|${c[0].x}|${c[0].y}`;e!==ge.current&&(ge.current=e,VD(D,c[0],P.w,P.h),ee||HD(D))}let F=GD(typeof document<`u`&&document.documentElement.classList.contains(`light`)?.22:.65,performance.now()-_e.current,500,ee);if(UD(r,D,P.w,P.h,u,F),O===`death`?FD(r,t.cells,ye,P.w,P.h,ED.cols,ED.rows,C,T):O===`birth`&&PD(r,t.cells,ye,P.w,P.h,ED.cols,ED.rows),iD(r,c),f!==`ecology`&&tD(r,t.cells,ye,u,Se,_,f===`divergence`,ee?0:performance.now(),S,!0,g,m),f===`forge`&&h&&h.length>0&&cD(r,t.cells,ye,h.map(e=>({department:e.department,turn:e.turn,approved:e.approved})),u),f===`ecology`&&lD(r,t,P.w,P.h,E),f===`divergence`&&uD(r,t.cells,ye,_,ee?0:performance.now(),u),sD(r,t,{actorName:i,actorArchetype:a,startTime:o,sideColor:u,width:P.w,height:P.h,lagTurns:l,cells:t.cells,positions:ye,previousSnapshot:n,labelBg:m,textMuted:g,deptLabels:w.deptLabels,timeUnitShort:te.Time}),ie){let e=ye.get(ie.cell.agentId);e&&(r.save(),r.strokeStyle=u,r.lineWidth=2,r.globalAlpha=1,r.beginPath(),r.arc(e.x,e.y,10,0,Math.PI*2),r.stroke(),r.restore())}if(I&&!ie&&w.crosshair){r.save(),r.strokeStyle=y,r.lineWidth=.5,r.setLineDash([3,4]),r.beginPath(),r.moveTo(0,I.y),r.lineTo(P.w,I.y),r.moveTo(I.x,0),r.lineTo(I.x,P.h),r.stroke(),r.setLineDash([]),r.restore();let e=null;for(let n of t.cells){if(!n.alive)continue;let t=ye.get(n.agentId);if(!t)continue;let r=t.x-I.x,i=t.y-I.y,a=r*r+i*i;a>1600||(!e||a<e.d2)&&(e={id:n.agentId,name:n.name,dx:r,dy:i,d2:a})}e&&(r.save(),r.strokeStyle=b,r.setLineDash([2,3]),r.lineWidth=.6,r.beginPath(),r.moveTo(I.x,I.y),r.lineTo(I.x+e.dx,I.y+e.dy),r.stroke(),r.setLineDash([]),r.fillStyle=x,r.font=`bold 11px ui-monospace, monospace`,r.textAlign=`left`,r.textBaseline=`top`,r.fillText(`\u2192 ${e.name.split(` `)[0]}`,I.x+6,I.y+6),r.restore())}if(v&&v!==ie?.cell.agentId){let e=ye.get(v);e&&(r.save(),r.strokeStyle=`rgba(232, 180, 74, 0.75)`,r.lineWidth=1.4,r.globalAlpha=.85,r.setLineDash([3,3]),r.beginPath(),r.arc(e.x,e.y,11,0,Math.PI*2),r.stroke(),r.setLineDash([]),r.restore())}},[xe.tickClock,t,ye,P.w,P.h,s,i,l,xe.flares,f,Se,ie,_,v,ee,S,I,w,a,o,h,O]);let we=(0,b.useCallback)(e=>{if(!t)return;let n=e.currentTarget.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top;ae({x:r,y:i});let a=KD(t.cells,ye,r,i);if(a){F(e=>e&&e.cell.agentId===a.agentId?e:{cell:a,x:r,y:i}),ue(null),y?.(a.agentId);return}ie&&(F(null),y?.(null));let o=ED.cols,s=ED.rows,c=O===`death`||O===`birth`?(()=>{let e=Math.floor(r/Math.max(1,P.w)*o),n=Math.floor(i/Math.max(1,P.h)*s);if(e<0||e>=o||n<0||n>=s)return null;for(let r of t.cells){if(O===`death`&&r.alive||O===`birth`&&(!r.alive||(r.generation??0)===0))continue;let t=ye.get(r.agentId);if(!t)continue;let i=LD(t,P.w,P.h,o,s);if(i.col===e&&i.row===n)return{col:e,row:n,kind:O===`death`?`death`:`birth`,nearest:r}}return null})():(()=>{let e=ID(R.current,r,i,P.w,P.h);if(!e)return null;let n=null,a=1/0;for(let r of t.cells){if(!r.alive)continue;let t=ye.get(r.agentId);if(!t)continue;let i=LD(t,P.w,P.h,o,s),c=(i.col-e.col)**2+(i.row-e.row)**2;c<a&&(a=c,n=r)}return{col:e.col,row:e.row,kind:`life`,nearest:n}})();c?ue({x:r,y:i,...c}):L&&ue(null)},[t,ye,ie,y,O,P.w,P.h,L]),Te=(0,b.useCallback)(()=>{F(null),ue(null),ae(null),y?.(null)},[y]),Ee=(0,b.useCallback)(e=>{if(!t)return;let n=e.currentTarget.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top,a=KD(t.cells,ye,r,i);a?(se({cell:a,x:r,y:i}),F(null),ue(null),B.current={id:a.agentId,intensity:1}):L?.nearest&&(se({cell:L.nearest,x:r,y:i}),F(null),ue(null))},[t,ye,L]),De=(0,b.useRef)(null),Oe=(0,b.useCallback)(e=>{if(!t)return;let n=e.touches[0];if(!n)return;let r=e.currentTarget.getBoundingClientRect(),i=n.clientX-r.left,a=n.clientY-r.top,o=KD(t.cells,ye,i,a);o?De.current===o.agentId?(se({cell:o,x:i,y:a}),F(null),De.current=null,B.current={id:o.agentId,intensity:1}):(F({cell:o,x:i,y:a}),ae({x:i,y:a}),De.current=o.agentId,y?.(o.agentId)):(F(null),ae(null),De.current=null,y?.(null))},[t,ye,y]);(0,b.useEffect)(()=>{oe&&t&&(t.cells.find(e=>e.agentId===oe.cell.agentId)||se(null))},[oe,t]),(0,b.useEffect)(()=>{oe||(De.current=null)},[oe]);let ke=pO(f===`mood`?Ce:s,M.current),Ae={birth:`rgba(154, 205, 96, 0.95)`,death:`rgba(200, 95, 80, 0.95)`,forge:`rgba(232, 180, 74, 0.95)`,crisis:`rgba(196, 74, 30, 0.95)`},je={birth:`rgba(154, 205, 96, 0.55)`,death:`rgba(200, 95, 80, 0.55)`,forge:`rgba(232, 180, 74, 0.55)`,crisis:`rgba(196, 74, 30, 0.55)`},Me=k&&k.side===c?Ae[k.kind]:t?t.morale>=.6?`rgba(106, 173, 72, 0.55)`:t.morale>=.3?`rgba(232, 180, 74, 0.55)`:`rgba(196, 74, 30, 0.65)`:`${s}33`,Ne=k&&k.side===c?`0 0 24px ${je[k.kind]}`:t?t.morale>=.6?`0 0 16px rgba(106, 173, 72, 0.18)`:t.morale>=.3?`0 0 16px rgba(232, 180, 74, 0.12)`:`0 0 20px rgba(196, 74, 30, 0.25)`:`none`;return(0,x.jsxs)(`div`,{ref:M,"data-testid":`living-colony-grid-${c}`,role:`region`,"aria-label":`${i} ${te.place} viz`,className:[WE.region,j?WE.narrow:``].filter(Boolean).join(` `),children:[t&&(0,x.jsx)(TD,{snapshot:t,sideColor:s}),(0,x.jsxs)(`div`,{ref:N,className:WE.canvasWrap,style:{"--tint-color":ke,"--wrap-border":Me,"--wrap-glow":Ne},children:[(0,x.jsx)(`canvas`,{ref:ne,role:`img`,"aria-label":t?`${i} ${te.place}, turn ${t.turn}. ${t.cells.filter(e=>e.alive).length} alive, morale ${Math.round(t.morale*100)}%${fO(t)}. ${t.births} births, ${t.deaths} deaths this turn. Click a ${te.person} glyph for drilldown.`:`${i} ${te.place} — waiting for first turn.`,onMouseMove:we,onMouseLeave:Te,onClick:Ee,onTouchStart:Oe,className:WE.canvas,style:{"--canvas-cursor":ie?`pointer`:`default`}}),(0,x.jsx)(`div`,{"aria-hidden":`true`,className:WE.revealCover,style:{"--reveal-opacity":de?`0`:`1`}}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>le(e=>!e),"aria-label":ce?`Close roster`:`Open roster`,title:ce?`Close roster`:`Open roster`,className:WE.cornerBtn,style:{"--right-offset":E?`36px`:`8px`,"--btn-color":ce?`var(--amber)`:`var(--text-3)`,"--btn-border":ce?`var(--amber)`:`var(--border)`},children:`☰`}),E&&(0,x.jsx)(`button`,{type:`button`,onClick:()=>E(c),"aria-label":A?`Restore split view`:`Focus this panel`,title:A?`Restore split view`:`Focus this panel`,className:`${WE.cornerBtn} ${WE.focusBtn}`,style:{"--btn-color":A?`var(--amber)`:`var(--text-3)`,"--btn-border":A?`var(--amber)`:`var(--border)`},children:A?`⤡`:`⤢`}),(0,x.jsx)(dO,{snapshot:t,previousSnapshot:n,sideColor:pO(s,M.current),onSelect:e=>{let t=ye.get(e.agentId);t&&se({cell:e,x:t.x,y:t.y})}}),(0,x.jsx)(uO,{open:ce,cells:t?.cells??[],actorName:i,sideColor:pO(s,M.current),searchQuery:S,hoveredId:ie?.cell.agentId??v??null,onHover:e=>{if(e){let n=t?.cells.find(t=>t.agentId===e),r=n?ye.get(e):null;if(n&&r){F({cell:n,x:r.x,y:r.y}),y?.(e);return}}F(null),y?.(null)},onSelect:e=>{let t=ye.get(e.agentId);t&&se({cell:e,x:t.x,y:t.y})},onClose:()=>le(!1)}),f===`divergence`&&t&&(_?.size??0)===0&&(0,x.jsx)(`div`,{className:WE.divergenceEmpty,children:(0,x.jsx)(`div`,{className:WE.divergenceEmptyMsg,children:`Both timelines identical this turn — no divergence yet`})}),L&&!ie&&!oe&&(()=>{let e=Math.min(Math.max(8,L.x+12),Math.max(8,P.w-220-8)),t=Math.max(8,L.y-84),n=L.kind===`birth`?`+ BIRTH MARKER`:L.kind===`death`?`× DEATH MARKER`:`◼ CONWAY CELL`,r=L.kind===`birth`?`rgba(154, 205, 96, 0.95)`:L.kind===`death`?`rgba(168, 152, 120, 0.95)`:s;return(0,x.jsxs)(`div`,{className:WE.tileTooltip,style:{"--tt-left":`${e}px`,"--tt-top":`${t}px`,"--kind-color":r},children:[(0,x.jsx)(`div`,{className:WE.tileKindLabel,children:n}),(0,x.jsxs)(`div`,{className:WE.tileCoords,children:[`tile (`,L.col,`, `,L.row,`)`]}),L.nearest?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`div`,{className:WE.tileNearestName,children:L.nearest.name}),(0,x.jsxs)(`div`,{className:WE.tileNearestRole,children:[L.nearest.role,` · `,L.nearest.department.toUpperCase()]}),L.kind===`death`?(0,x.jsxs)(`div`,{className:WE.tileNearestDeath,children:[`deceased · mood at death: `,L.nearest.mood]}):L.kind===`birth`?(0,x.jsxs)(`div`,{className:WE.tileNearestBirth,children:[`native-born · generation `,L.nearest.generation??0]}):(0,x.jsxs)(`div`,{className:WE.tileNearestPattern,children:[`pattern seeded by nearest colonist's mood: `,L.nearest.mood]})]}):(0,x.jsx)(`div`,{className:WE.tileAmbient,children:`ambient CA cell`}),L.kind===`life`&&(()=>{let e=R.current,t=e.cols,n=e.rows,r=e.grid[L.row*t+L.col]??0,i=0;for(let r=-1;r<=1;r++)for(let a=-1;a<=1;a++){if(r===0&&a===0)continue;let o=L.row+r,s=L.col+a;o<0||o>=n||s<0||s>=t||e.grid[o*t+s]>=1&&i++}return(0,x.jsxs)(`div`,{className:WE.tileNearestPattern,children:[`age `,r,` · `,i,` neighbors alive`]})})()]})})(),ie&&!oe&&(()=>{let e=Math.min(Math.max(8,ie.x+12),Math.max(8,P.w-200-8)),t=Math.min(Math.max(8,ie.y-80-8),Math.max(8,P.h-80-8));return(0,x.jsxs)(`div`,{className:WE.hoverTooltip,style:{"--tt-left":`${e}px`,"--tt-top":`${t}px`,"--side-color":s},children:[(0,x.jsxs)(`div`,{className:WE.hoverHeader,children:[ie.cell.name,ie.cell.featured&&(0,x.jsx)(`span`,{className:WE.hoverFeaturedPill,children:`FEATURED`})]}),(0,x.jsxs)(`div`,{className:WE.hoverRole,children:[ie.cell.department.toUpperCase(),` · `,ie.cell.role,typeof ie.cell.age==`number`?` · age ${ie.cell.age}`:``]}),(0,x.jsxs)(`div`,{className:WE.hoverMood,children:[`mood: `,(0,x.jsx)(`span`,{className:WE.hoverMoodValue,children:ie.cell.mood}),typeof ie.cell.psychScore==`number`?` · psych ${Math.round(ie.cell.psychScore*100)}%`:``]}),r&&r.length>=2&&(()=>{let e=[];for(let t of r){let n=t.cells.find(e=>e.agentId===ie.cell.agentId);n&&typeof n.psychScore==`number`&&e.push(Math.max(0,Math.min(1,n.psychScore)))}if(e.length<2)return null;let t=136/Math.max(1,e.length-1),n=e.map((e,n)=>{let r=2+n*t,i=2+(1-e)*16;return`${n===0?`M`:`L`}${r.toFixed(1)},${i.toFixed(1)}`}).join(` `);return(0,x.jsxs)(`div`,{className:WE.psychBlock,children:[(0,x.jsx)(`div`,{className:WE.psychLabel,children:`PSYCH TRAJECTORY`}),(0,x.jsxs)(`svg`,{viewBox:`0 0 140 20`,preserveAspectRatio:`none`,width:140,height:20,role:`img`,"aria-label":`Psychological trajectory across ${e.length} turns`,className:WE.psychSvg,children:[(0,x.jsx)(`line`,{x1:2,x2:138,y1:10,y2:10,stroke:`var(--border)`,strokeWidth:.4,strokeDasharray:`2 2`}),(0,x.jsx)(`path`,{d:n,fill:`none`,stroke:s,strokeWidth:1}),(0,x.jsx)(`circle`,{cx:2+(e.length-1)*t,cy:2+(1-e[e.length-1])*16,r:1.6,fill:s})]})]})})(),(0,x.jsx)(`div`,{className:WE.hoverHint,children:`click for drilldown`})]})})(),(0,x.jsx)(eO,{payload:oe,containerW:P.w,containerH:P.h,sideColor:pO(s,M.current),hexacoById:p,snapshots:r,onClose:()=>se(null),onOpenChat:D})]})]})}var hO={track:`_track_1u01e_1`,trackInner:`_trackInner_1u01e_29`,column:`_column_1u01e_38`,columnHeader:`_columnHeader_1u01e_64`,columnHeaderSlot:`_columnHeaderSlot_1u01e_80`,columnHeaderText:`_columnHeaderText_1u01e_89`,columnHeaderName:`_columnHeaderName_1u01e_96`,columnHeaderArchetype:`_columnHeaderArchetype_1u01e_105`,columnHeaderPop:`_columnHeaderPop_1u01e_116`,columnBody:`_columnBody_1u01e_125`,columnPlaceholder:`_columnPlaceholder_1u01e_133`,columnPlaceholderShimmer:`_columnPlaceholderShimmer_1u01e_145`,"cohort-shimmer":`_cohort-shimmer_1u01e_1`,columnPlaceholderLabel:`_columnPlaceholderLabel_1u01e_159`};function gO(e){let t=[],n=[],r=new Map;for(let i of e){if(i.type===`forge_attempt`){let e=i.data||{},n=e.approved===!0||e.approved===`true`;t.push({turn:Number(e.turn??0),eventIndex:Number(e.eventIndex??0),department:String(e.department||``),name:String(e.name||``),approved:n,confidence:typeof e.confidence==`number`?e.confidence:void 0}),e.name&&e.department&&n&&!r.has(String(e.name))&&r.set(String(e.name),String(e.department));continue}if(i.type!==`specialist_done`)continue;let e=i.data||{},a=String(e.department||``),o=Array.isArray(e.forgedTools)?e.forgedTools:[];for(let t of o){let o=t,s=String(o.name||``);if(!s||s===`unnamed`)continue;let c=typeof o.firstForgedDepartment==`string`?String(o.firstForgedDepartment):r.get(s),l=typeof o.firstForgedTurn==`number`?o.firstForgedTurn:void 0,u=Number(i.turn??e.turn??0);(c&&l!==void 0&&l<u||c&&c!==a)&&n.push({turn:u,originDept:c,callingDept:a,name:s})}}return{attempts:t,reuses:n}}function _O(e){let{actorIndex:t,actorId:n,state:r,snaps:i,currentTurn:a,gridMode:o,palette:s,gridSettings:c,hexacoById:l,searchQuery:u,chronicleFilter:d,chronicleHover:f,startTime:p,onOpenChat:m}=e,h=(0,b.useRef)(null),[g,_]=(0,b.useState)(t<4);(0,b.useEffect)(()=>{if(g)return;let e=h.current;if(!e)return;if(typeof IntersectionObserver>`u`){_(!0);return}let t=new IntersectionObserver(e=>{for(let n of e)if(n.isIntersecting){_(!0),t.disconnect();return}},{rootMargin:`240px 360px`});return t.observe(e),()=>t.disconnect()},[g]);let v=r.actors[n]??null,y=v?.leader??null,S=i[a],C=a>0?i[a-1]:void 0,w=Pe(t),T=y?.name||`Leader ${t+1}`,E=(0,b.useMemo)(()=>v?gO(v.events):{attempts:[],reuses:[]},[v]),D=y?.hexaco?{O:y.hexaco.O??y.hexaco.openness??.5,C:y.hexaco.C??y.hexaco.conscientiousness??.5,E:y.hexaco.E??y.hexaco.extraversion??.5,A:y.hexaco.A??y.hexaco.agreeableness??.5,Em:y.hexaco.Em??y.hexaco.emotionality??.5,HH:y.hexaco.HH??y.hexaco.honestyHumility??.5}:void 0;return(0,x.jsxs)(`div`,{ref:h,className:hO.column,style:{"--actor-color":w},"aria-label":`Living swarm grid for actor ${t+1}: ${T}`,children:[(0,x.jsxs)(`header`,{className:hO.columnHeader,children:[(0,x.jsxs)(`span`,{className:hO.columnHeaderSlot,children:[`A`,t+1]}),(0,x.jsxs)(`div`,{className:hO.columnHeaderText,children:[(0,x.jsx)(`span`,{className:hO.columnHeaderName,children:T}),y?.archetype&&(0,x.jsx)(`span`,{className:hO.columnHeaderArchetype,children:y.archetype})]}),(0,x.jsxs)(`span`,{className:hO.columnHeaderPop,title:`Population alive · morale`,children:[S?.population??`—`,` · `,S?Math.round(S.morale*100):`—`,`%`]})]}),(0,x.jsx)(`div`,{className:hO.columnBody,children:g?(0,x.jsx)(mO,{snapshot:S,previousSnapshot:C,snapshotHistory:i,actorName:T,actorArchetype:y?.archetype??``,leaderUnit:y?.unit??``,sideColor:w,side:`a`,mode:o,hexacoById:l,leaderHexaco:D,forgeAttempts:E.attempts,reuseCalls:E.reuses,searchQuery:u,palette:s,settings:c,startTime:p,onOpenChat:m,eventFilter:d,chronicleHover:f}):(0,x.jsxs)(`div`,{className:hO.columnPlaceholder,"aria-hidden":`true`,children:[(0,x.jsx)(`div`,{className:hO.columnPlaceholderShimmer}),(0,x.jsx)(`span`,{className:hO.columnPlaceholderLabel,children:`Loading swarm…`})]})})]})}function vO({state:e,snapshotMap:t,currentTurn:n,gridMode:r,palette:i,gridSettings:a,hexacoById:o,searchQuery:s,chronicleFilter:c,chronicleHover:l,startTime:u,onOpenChat:d,className:f}){let p=e.actorIds;return(0,x.jsx)(`div`,{className:[hO.track,f].filter(Boolean).join(` `),role:`region`,"aria-label":`Cohort swarm grid: ${p.length} actors`,children:(0,x.jsx)(`div`,{className:hO.trackInner,children:p.map((f,p)=>(0,x.jsx)(_O,{actorId:f,actorIndex:p,state:e,snaps:t[f]??[],currentTurn:n,gridMode:r,palette:i,gridSettings:a,hexacoById:o,searchQuery:s,chronicleFilter:c,chronicleHover:l,startTime:u,onOpenChat:d},f))})})}function yO(e){let t=(e.decision||``).split(/[.;]/)[0].trim(),n=t.length>80?t.slice(0,77)+`...`:t,r=e.outcome.startsWith(`risky`),i=e.outcome.endsWith(`success`),a=n.length===0?`held position`:r?i?`gambled on`:`took the risk of`:`chose`,o=n.length===0?``:n.replace(/^(select|implement|issue|move|expand|reduce|slow|initiate|start|deliver)\s+/i,``).replace(/\s+$/,``),s=o.length>0?`${e.actorName} ${a} ${o.toLowerCase()}`:`${e.actorName} ${a}`,c=typeof e.dominantDeaths==`number`&&e.dominantDeaths>0&&e.dominantDeaths<e.deaths;return`${s}${e.deaths>0&&e.dominantCause?c?`, ${e.deaths} lost, ${e.dominantDeaths} to ${e.dominantCause}`:`, ${e.deaths} lost to ${e.dominantCause}`:e.deaths>0?`, ${e.deaths} lost`:``}${e.moraleDelta<=-.08?`; morale cracked`:e.moraleDelta>=.08?`; morale steadied`:``}`}var bO={banner:`_banner_gzmtg_1`,headline:`_headline_gzmtg_12`,collapseBtn:`_collapseBtn_gzmtg_20`,turnLabel:`_turnLabel_gzmtg_39`,title:`_title_gzmtg_43`,categoryPill:`_categoryPill_gzmtg_48`,lineA:`_lineA_gzmtg_58`,lineB:`_lineB_gzmtg_62`,line:`_line_gzmtg_58`,lineLabel:`_lineLabel_gzmtg_78`,lineBody:`_lineBody_gzmtg_85`,lineMore:`_lineMore_gzmtg_91`};function xO(e,t){let n=e.leader?.name??``;if(!n)return null;let r=``,i=``,a=null,o=0,s=0,c=``,l=``,u=0;for(let n of e.events)if((n.data?.turn??-1)===t+1){if((n.type===`turn_start`||n.type===`event_start`)&&(c=String(n.data?.title??c),l=String(n.data?.category??l),u=Number(n.data?.time??u)),n.type===`outcome`){i=String(n.data?.outcome??i);let e=n.data?._decision;typeof e==`string`&&e.length>0&&(r=e);let t=n.data?.systemDeltas?.morale;typeof t==`number`&&Number.isFinite(t)&&(s+=t)}if(n.type===`turn_done`){let e=n.data?.deathCauses;e&&typeof e==`object`&&(a=e)}n.type===`systems_snapshot`&&(o=Number(n.data?.deaths)||0)}let d=o,f=null,p;if(a){let e=0,t=0;for(let[n,r]of Object.entries(a))typeof r!=`number`||r<=0||(e+=r,r>t&&(t=r,f=n));e>0&&(d=e,p=t)}return{actorName:n,decision:r,outcome:i,deaths:d,dominantCause:f,dominantDeaths:p,moraleDelta:s,eventTitle:c,eventCategory:l,time:u}}function SO(e,t){for(let n of e.actorIds){let r=e.actors[n],i=r?xO(r,t)?.eventTitle:``;if(i)return i}return``}var CO=6;function wO({state:e,currentTurn:t,linesTarget:n,cohortGridShown:r=!0}){let i=e.actorIds.length>2,[a,o]=(0,b.useState)(i),s=(0,b.useMemo)(()=>{let n=[];for(let r of e.actorIds){let i=e.actors[r];n.push({actorId:r,summary:i?xO(i,t):null})}return n},[e.actorIds,e.actors,t]).filter(e=>e.summary!==null),c=s.find(e=>e.summary.eventTitle)?.summary.eventTitle||``,l=s.find(e=>e.summary.eventCategory)?.summary.eventCategory||``,u=s.find(e=>e.summary.time)?.summary.time||0;if(!c)return null;let d=s.slice(0,CO),f=s.length-d.length,p=!a,m=s.length>0,h=p?(0,x.jsxs)(x.Fragment,{children:[d.map((e,t)=>(0,x.jsxs)(`div`,{className:s.length<=2?t===0?bO.lineA:bO.lineB:bO.line,children:[(0,x.jsx)(`span`,{className:bO.lineLabel,children:s.length<=2?t===0?`A`:`B`:e.summary.actorName}),(0,x.jsxs)(`span`,{className:bO.lineBody,children:[`: `,yO(e.summary)]})]},e.actorId)),f>0&&(0,x.jsxs)(`div`,{className:bO.lineMore,children:[`+`,f,` more `,`·`,` `,r?`see cohort grid ${n?`above`:`below`} for the rest`:`open All ${e.actorIds.length} actors for the rest`]})]}):null;return(0,x.jsxs)(`div`,{role:`status`,"aria-label":`Current turn narrative`,className:bO.banner,children:[(0,x.jsxs)(`div`,{className:bO.headline,children:[(0,x.jsxs)(`span`,{className:bO.turnLabel,children:[`T`,t+1,u?` \u00b7 ${u}`:``]}),(0,x.jsx)(`span`,{className:bO.title,children:c}),l&&(0,x.jsx)(`span`,{className:bO.categoryPill,children:l}),m&&(0,x.jsx)(`button`,{type:`button`,onClick:()=>o(e=>!e),"aria-expanded":!a,"aria-label":a?`Expand per-actor outcomes`:`Collapse per-actor outcomes`,className:bO.collapseBtn,children:a?`\u25be ${s.length} actors`:`▴ hide`})]}),h&&(n?(0,Ay.createPortal)(h,n):h)]})}var TO={row:`_row_1jwlc_1`,key:`_key_1jwlc_16`,scrub:`_scrub_1jwlc_34`,turn:`_turn_1jwlc_39`,timeShownAbove:`_timeShownAbove_1jwlc_51`,speed:`_speed_1jwlc_56`},EO=[.5,1,2,4];function DO({currentTurn:e,maxTurn:t,time:n,timeInBanner:r=!1,playing:i,speed:a,onTurnChange:o,onPlayPause:s,onStepBack:c,onStepForward:l,onSpeedChange:u}){return(0,x.jsxs)(`div`,{className:TO.row,children:[(0,x.jsx)(`button`,{type:`button`,onClick:c,disabled:e<=0,"aria-label":`Previous turn`,className:TO.key,children:`<<`}),(0,x.jsx)(`button`,{type:`button`,onClick:s,disabled:t<=1,"aria-label":i?`Pause`:`Play`,className:TO.key,children:i?`■`:`▶`}),(0,x.jsx)(`button`,{type:`button`,onClick:l,disabled:e>=t-1,"aria-label":`Next turn`,className:TO.key,children:`>>`}),(0,x.jsx)(`input`,{type:`range`,min:0,max:Math.max(0,t-1),value:e,onChange:e=>o(Number(e.target.value)),className:TO.scrub,"aria-label":`Scrub timeline`,"aria-valuetext":`Turn ${e+1} of ${t}`}),(0,x.jsxs)(`span`,{className:TO.turn,children:[`T`,e+1,`/`,t,n?(0,x.jsx)(`span`,{className:r?TO.timeShownAbove:void 0,children:` \u00b7 ${n}`}):null]}),(0,x.jsx)(`select`,{"aria-label":`Playback speed`,value:a,onChange:e=>u(Number(e.target.value)),className:TO.speed,children:EO.map(e=>(0,x.jsxs)(`option`,{value:e,children:[e,`x`]},e))})]})}var OO=[{key:`living`,label:`LIVING`,hint:`Full field + {person} seeds + all events`},{key:`mood`,label:`MOOD`,hint:`{Person} mood cloud emphasized; births / deaths`},{key:`forge`,label:`FORGE`,hint:`Field dimmed; tool forge attempts + reuse arcs between departments`},{key:`ecology`,label:`ECOLOGY`,hint:`Glyphs hidden; food, water, power and volume tint a quadrant each`},{key:`divergence`,label:`DIVERGENCE`,hint:`Only {people} alive here but dead on the other side`}];function kO(e,t){return e.replace(/\{person\}/g,t.person).replace(/\{Person\}/g,t.Person).replace(/\{people\}/g,t.people).replace(/\{People\}/g,t.People)}function AO(e,t){return kO(OO.find(t=>t.key===e)?.hint??``,t)}function jO({mode:e,onChange:t,counts:n,labels:r}){if(jy(`(max-width: 480px)`)){let i=OO.find(t=>t.key===e),a=n?.[e],o=`calc(${`${i?.label??``}${typeof a==`number`&&a>0?` · ${a}`:``}`.length} * (1ch + 0.08em) + 44px)`;return(0,x.jsx)(`select`,{"aria-label":`Grid viz mode`,value:e,onChange:e=>t(e.target.value),title:kO(OO.find(t=>t.key===e)?.hint??``,r),style:{flex:`1 1 auto`,width:o,minWidth:o,padding:`8px 10px`,fontSize:16,fontFamily:`var(--mono)`,fontWeight:800,letterSpacing:`0.08em`,textTransform:`uppercase`,background:`var(--bg-card)`,color:`var(--text-1)`,border:`1px solid var(--border)`,borderRadius:6,cursor:`pointer`,minHeight:44},children:OO.map(e=>{let t=n?.[e.key],r=typeof t==`number`&&t>0?` · ${t}`:``;return(0,x.jsxs)(`option`,{value:e.key,children:[e.label,r]},e.key)})})}return(0,x.jsx)(`div`,{role:`tablist`,"aria-label":`Grid viz mode`,style:{display:`flex`,gap:0,padding:`4px 6px`,background:`var(--bg-panel)`,border:`1px solid var(--border)`,borderRadius:6,overflowX:`auto`,scrollbarWidth:`thin`},children:OO.map((i,a)=>{let o=e===i.key,s=n?.[i.key],c=kO(i.hint,r);return(0,x.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":o,"data-grid-mode":i.key,onClick:()=>t(i.key),title:c,style:{flex:`1 0 auto`,padding:`5px 8px`,fontSize:`var(--font-3xs)`,fontFamily:`var(--mono)`,fontWeight:800,letterSpacing:`0.1em`,border:`1px solid var(--border)`,borderLeft:a===0?`1px solid var(--border)`:`none`,borderRadius:a===0?`3px 0 0 3px`:a===OO.length-1?`0 3px 3px 0`:0,background:o?`var(--amber)`:`var(--bg-card)`,color:o?`var(--bg-deep)`:`var(--text-3)`,cursor:`pointer`,textTransform:`uppercase`,transition:`background 120ms, color 120ms`,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:4,whiteSpace:`nowrap`},children:[(0,x.jsx)(`span`,{children:i.label}),typeof s==`number`&&s>0&&(0,x.jsx)(`span`,{style:{padding:`0 4px`,borderRadius:2,background:o?`rgba(10, 8, 6, 0.25)`:`var(--bg-deep)`,color:o?`var(--bg-deep)`:`var(--amber)`,fontSize:`var(--font-3xs)`,fontWeight:700,letterSpacing:`0.05em`,minWidth:14,textAlign:`center`},children:s})]},i.key)})})}var MO={backdrop:`_backdrop_bxhar_1`,dialog:`_dialog_bxhar_12`,phone:`_phone_bxhar_26`,header:`_header_bxhar_30`,title:`_title_bxhar_37`,closeBtn:`_closeBtn_bxhar_47`,section:`_section_bxhar_60`,sectionTitle:`_sectionTitle_bxhar_64`,rows:`_rows_bxhar_75`,row:`_row_bxhar_75`,rowKey:`_rowKey_bxhar_89`,rowVal:`_rowVal_bxhar_96`,swatchWrap:`_swatchWrap_bxhar_101`,swatch:`_swatch_bxhar_101`,footer:`_footer_bxhar_117`,kbd:`_kbd_bxhar_123`};function NO({open:e,onClose:t}){let n=jy(Ny),r=Lm();if(!e)return null;let i=[MO.dialog,n?MO.phone:``].filter(Boolean).join(` `);return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Grid viz help`,onClick:t,className:MO.backdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:i,children:[(0,x.jsxs)(`div`,{className:MO.header,children:[(0,x.jsxs)(`h2`,{className:MO.title,children:[`Living `,r.Place,` Grid — Legend`]}),(0,x.jsx)(`button`,{type:`button`,onClick:t,"aria-label":`Close help`,className:MO.closeBtn,children:`×`})]}),(0,x.jsxs)(PO,{title:`Modes`,children:[(0,x.jsx)(FO,{k:`LIVING`,v:`Full chemistry + ${r.person} glyphs + event flares`}),(0,x.jsx)(FO,{k:`MOOD`,v:`Emphasizes ${r.person} seeds + mood-coded chemistry clouds`}),(0,x.jsx)(FO,{k:`FORGE`,v:`Dims field, highlights forge attempts + reuse arcs`}),(0,x.jsx)(FO,{k:`ECOLOGY`,v:`Hides glyphs; food, water, power and volume tint a quadrant each`}),(0,x.jsx)(FO,{k:`DIVERGENCE`,v:`Only shows ${r.people} alive here but dead on the other side`})]}),(0,x.jsxs)(PO,{title:`Grid elements`,children:[(0,x.jsx)(FO,{k:(0,x.jsx)(IO,{color:`rgba(232, 180, 74, 0.9)`}),v:`Warm amber = high vitality (${r.place} thriving)`}),(0,x.jsx)(FO,{k:(0,x.jsx)(IO,{color:`rgba(196, 74, 30, 0.9)`}),v:`Rust red = stress concentration (decay / anxiety)`}),(0,x.jsx)(FO,{k:`○ small ring`,v:`Alive ${r.person}, hover for identity`}),(0,x.jsx)(FO,{k:`◎ thick ring`,v:`Featured ${r.person} (drives narrative this turn)`}),(0,x.jsx)(FO,{k:`○ amber halo`,v:`Diverged ${r.person} — alive here but dead on the other side`}),(0,x.jsx)(FO,{k:`DEPT label`,v:`Cluster centroid label showing dept + live count`})]}),(0,x.jsxs)(PO,{title:`Event flares`,children:[(0,x.jsx)(FO,{k:(0,x.jsx)(IO,{color:`rgba(154, 205, 96, 0.8)`}),v:`Green bloom — birth`}),(0,x.jsx)(FO,{k:(0,x.jsx)(IO,{color:`rgba(168, 152, 120, 0.7)`}),v:`Grey wave — death`}),(0,x.jsx)(FO,{k:(0,x.jsx)(IO,{color:`rgba(232, 180, 74, 0.8)`}),v:`Amber dot — forge approved`}),(0,x.jsx)(FO,{k:(0,x.jsx)(IO,{color:`rgba(224, 101, 48, 0.7)`}),v:`Red flash — forge rejected`}),(0,x.jsx)(FO,{k:(0,x.jsx)(IO,{color:`rgba(232, 180, 74, 0.6)`}),v:`Amber arc — tool reuse across departments`}),(0,x.jsx)(FO,{k:(0,x.jsx)(IO,{color:`rgba(196, 74, 30, 0.8)`}),v:`Red ring — crisis shockwave (category-gated)`})]}),(0,x.jsxs)(PO,{title:`Keyboard`,children:[(0,x.jsx)(FO,{k:`1 / 2 / 3 / 4 / 5`,v:`Switch mode (Living / Mood / Forge / Ecology / Divergence)`}),(0,x.jsx)(FO,{k:`← / →`,v:`Step turn back / forward`}),(0,x.jsx)(FO,{k:`Space`,v:`Play / pause timeline`}),(0,x.jsx)(FO,{k:`?`,v:`Toggle this help overlay`}),(0,x.jsx)(FO,{k:`Esc`,v:`Close popover / this overlay`}),(0,x.jsx)(FO,{k:`click glyph`,v:`Open ${r.person} drilldown (HEXACO radar, memory, chat)`})]}),(0,x.jsxs)(`div`,{className:MO.footer,children:[`Press `,(0,x.jsx)(`kbd`,{className:MO.kbd,children:`?`}),` anytime to reopen.`]})]})})}function PO({title:e,children:t}){return(0,x.jsxs)(`div`,{className:MO.section,children:[(0,x.jsx)(`div`,{className:MO.sectionTitle,children:e}),(0,x.jsx)(`div`,{className:MO.rows,children:t})]})}function FO({k:e,v:t}){return(0,x.jsxs)(`div`,{className:MO.row,children:[(0,x.jsx)(`span`,{className:MO.rowKey,children:e}),(0,x.jsx)(`span`,{className:MO.rowVal,children:t})]})}function IO({color:e}){return(0,x.jsx)(`span`,{className:MO.swatchWrap,children:(0,x.jsx)(`span`,{className:MO.swatch,style:{"--swatch-color":e}})})}var LO={wrap:`_wrap_10kb4_1`,legend:`_legend_10kb4_8`,legendRight:`_legendRight_10kb4_19`,legendA:`_legendA_10kb4_24`,legendB:`_legendB_10kb4_28`,legendKey:`_legendKey_10kb4_32`,svg:`_svg_10kb4_36`,tooltip:`_tooltip_10kb4_44`,tooltipTurn:`_tooltipTurn_10kb4_63`,tooltipRowA:`_tooltipRowA_10kb4_71`,tooltipRowB:`_tooltipRowB_10kb4_78`,tooltipBold:`_tooltipBold_10kb4_85`};function RO({snapsA:e,snapsB:t,currentTurn:n,onJumpToTurn:r,hoveredTurn:i,onHoverTurnChange:a}){let o=Math.max(e.length,t.length);if(o<2)return null;let s=(e,t)=>{if(e.length===0)return``;let n=588/Math.max(1,o-1),r=[],i=!1;return e.forEach((e,a)=>{let o=t(e);if(o===null){i=!1;return}let s=6+a*n,c=3+(1-o)*22;r.push(`${i?`L`:`M`}${s.toFixed(1)},${c.toFixed(1)}`),i=!0}),r.join(` `)},c=e.some(e=>typeof e.foodReserve==`number`),l=t.some(e=>typeof e.foodReserve==`number`),u=c||l,d=[...e,...t].map(e=>e.foodReserve).filter(e=>typeof e==`number`),f=Math.max(18,...d),p=Math.max(1,...e.map(e=>e.population),...t.map(e=>e.population)),m=e=>typeof e.foodReserve==`number`?Math.max(0,Math.min(1,e.foodReserve/f)):null,h=e=>Math.max(0,Math.min(1,e.population/p)),g=e=>Math.max(0,Math.min(1,e.morale)),_=6+n*(588/Math.max(1,o-1)),v=typeof i==`number`?6+i*(588/Math.max(1,o-1)):null,y=(e,t)=>{let n=(e-t.left)/t.width*600,r=Math.round((n-6)/588*(o-1));return Math.max(0,Math.min(o-1,r))};return(0,x.jsxs)(`div`,{className:LO.wrap,children:[(0,x.jsxs)(`div`,{className:LO.legend,children:[(0,x.jsxs)(`span`,{children:[`MORALE · POP`,u?` · FOOD`:``,` · T1 → T`,o]}),(0,x.jsxs)(`span`,{className:LO.legendRight,children:[(0,x.jsx)(`span`,{className:LO.legendA,children:`A`}),(0,x.jsx)(`span`,{className:LO.legendB,children:`B`}),(0,x.jsx)(`span`,{className:LO.legendKey,children:`— morale`}),(0,x.jsx)(`span`,{className:LO.legendKey,children:`··· pop`}),u&&(0,x.jsx)(`span`,{className:LO.legendKey,children:`- - food`})]})]}),(0,x.jsxs)(`svg`,{viewBox:`0 0 600 28`,preserveAspectRatio:`none`,role:`img`,"aria-label":`Timeline sparkline of morale, population${u?`, and food`:``} across both leaders`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();r(y(e.clientX,t))},onMouseMove:e=>{if(!a)return;let t=e.currentTarget.getBoundingClientRect();a(y(e.clientX,t))},onMouseLeave:()=>{a?.(null)},className:LO.svg,height:28,children:[(0,x.jsx)(`line`,{x1:6,x2:594,y1:14,y2:14,stroke:`var(--border)`,strokeWidth:.5,strokeDasharray:`2 2`}),c&&(0,x.jsx)(`path`,{d:s(e,m),fill:`none`,stroke:`var(--vis)`,strokeWidth:.8,strokeDasharray:`3 2`,opacity:.45}),l&&(0,x.jsx)(`path`,{d:s(t,m),fill:`none`,stroke:`var(--eng)`,strokeWidth:.8,strokeDasharray:`3 2`,opacity:.45}),(0,x.jsx)(`path`,{d:s(e,h),fill:`none`,stroke:`var(--vis)`,strokeWidth:.7,strokeDasharray:`1 2`,opacity:.5}),(0,x.jsx)(`path`,{d:s(t,h),fill:`none`,stroke:`var(--eng)`,strokeWidth:.7,strokeDasharray:`1 2`,opacity:.5}),(0,x.jsx)(`path`,{d:s(e,g),fill:`none`,stroke:`var(--vis)`,strokeWidth:1.3}),(0,x.jsx)(`path`,{d:s(t,g),fill:`none`,stroke:`var(--eng)`,strokeWidth:1.3}),v!==null&&i!==n&&(0,x.jsx)(`line`,{x1:v,x2:v,y1:0,y2:28,stroke:`var(--text-3)`,strokeWidth:.75,strokeDasharray:`2 3`,opacity:.7}),(0,x.jsx)(`line`,{x1:_,x2:_,y1:0,y2:28,stroke:`var(--amber)`,strokeWidth:1})]}),typeof i==`number`&&(()=>{let n=e[i],r=t[i];if(!n&&!r)return null;let a=i/Math.max(1,o-1)*100,s={"--hover-left":`calc(${a}% + 8px)`,"--hover-translate":a>75?`translateX(calc(-100% - 16px))`:`none`};return(0,x.jsxs)(`div`,{className:LO.tooltip,style:s,children:[(0,x.jsxs)(`div`,{className:LO.tooltipTurn,children:[`T`,i+1,n?.time?` · ${n.time}`:``]}),n&&(0,x.jsxs)(`div`,{className:LO.tooltipRowA,children:[(0,x.jsx)(`span`,{className:LO.tooltipBold,children:`A`}),(0,x.jsxs)(`span`,{children:[`pop `,n.population]}),(0,x.jsxs)(`span`,{children:[`· `,Math.round(n.morale*100),`% mor`]}),typeof n.foodReserve==`number`&&(0,x.jsxs)(`span`,{children:[`· `,n.foodReserve.toFixed(1),`mo`]}),(n.births>0||n.deaths>0)&&(0,x.jsxs)(`span`,{children:[`· +`,n.births,`/-`,n.deaths]})]}),r&&(0,x.jsxs)(`div`,{className:LO.tooltipRowB,children:[(0,x.jsx)(`span`,{className:LO.tooltipBold,children:`B`}),(0,x.jsxs)(`span`,{children:[`pop `,r.population]}),(0,x.jsxs)(`span`,{children:[`· `,Math.round(r.morale*100),`% mor`]}),typeof r.foodReserve==`number`&&(0,x.jsxs)(`span`,{children:[`· `,r.foodReserve.toFixed(1),`mo`]}),(r.births>0||r.deaths>0)&&(0,x.jsxs)(`span`,{children:[`· +`,r.births,`/-`,r.deaths]})]})]})})()]})}var zO={bar:`_bar_r8lgh_1`,barRow:`_barRow_r8lgh_7`,heading:`_heading_r8lgh_12`,filterRow:`_filterRow_r8lgh_22`,filterChip:`_filterChip_r8lgh_28`,active:`_active_r8lgh_43`,dotsRow:`_dotsRow_r8lgh_50`,dot:`_dot_r8lgh_50`,hovered:`_hovered_r8lgh_79`,current:`_current_r8lgh_85`},BO=[{key:`all`,label:`All`},{key:`birth`,label:`Births`},{key:`death`,label:`Deaths`},{key:`forge`,label:`Forges`},{key:`crisis`,label:`Crises`}],VO={birth:`rgba(154, 205, 96, 0.95)`,death:`rgba(200, 95, 80, 0.95)`,forge:`rgba(232, 180, 74, 0.95)`,crisis:`rgba(196, 74, 30, 0.95)`},HO={birth:`+`,death:`×`,forge:`▲`,crisis:`⚡`};function UO({eventsA:e,eventsB:t,currentTurn:n,onJumpToTurn:r,onHoverTurnChange:i,hoveredTurn:a,onForgeSelect:o,filter:s,onFilterChange:c,onHoverEventChange:l,onJumpToReports:u}){let d=(0,b.useMemo)(()=>{let n=[],r=(e,t)=>{for(let r of e){let e=Number(r.turn??r.data?.turn??0);if(!(e<=0)){if(r.type===`birth`)n.push({turn:e,kind:`birth`,side:t,label:`T${e}: birth (${t.toUpperCase()})`});else if(r.type===`death`){let i=typeof r.data?.name==`string`?r.data.name:``;n.push({turn:e,kind:`death`,side:t,label:`T${e}: ${i?i+` died`:`death`} (${t.toUpperCase()})`})}else if(r.type===`forge_attempt`){let i=typeof r.data?.name==`string`?r.data.name:`tool`,a=r.data?.approved===!0;n.push({turn:e,kind:`forge`,side:t,label:`T${e}: ${a?`forged`:`rejected`} ${i} (${t.toUpperCase()})`,toolName:i,eventId:r.id})}else if(r.type===`event_start`||r.type===`director_crisis`){let i=typeof r.data?.category==`string`?r.data.category:``;i&&[`political`,`social`,`infrastructure`,`medical`,`resource`,`environmental`].includes(i)&&n.push({turn:e,kind:`crisis`,side:t,label:`T${e}: ${i} crisis (${t.toUpperCase()})`})}}}};return r(e,`a`),r(t,`b`),n.sort((e,t)=>e.turn-t.turn),n.slice(-60)},[e,t]),[f,p]=(0,b.useState)(`all`),m=s??f,h=e=>{s===void 0&&p(e),c?.(e)},g=(0,b.useMemo)(()=>m===`all`?d:d.filter(e=>e.kind===m),[d,m]);return d.length===0?null:(0,x.jsxs)(yC,{label:`events`,className:zO.bar,rowClassName:zO.barRow,role:`group`,ariaLabel:`Event filter`,children:[(0,x.jsxs)(`span`,{className:zO.heading,children:[`Events (`,g.length,m===`all`?``:`/${d.length}`,`)`]}),(0,x.jsx)(`div`,{className:zO.filterRow,children:BO.map(e=>{let t=m===e.key;return(0,x.jsx)(`button`,{type:`button`,onClick:()=>h(e.key),"aria-pressed":t,className:[zO.filterChip,t?zO.active:``].filter(Boolean).join(` `),children:e.label},e.key)})}),(0,x.jsx)(`div`,{className:zO.dotsRow,children:g.map((e,t)=>{let s=Math.max(0,e.turn-1),c=s===n,d=a===s,f=[zO.dot,c?zO.current:``,d?zO.hovered:``].filter(Boolean).join(` `),p={"--kind-color":VO[e.kind],"--side-shift":e.side===`a`?`-2px`:`2px`};return(0,x.jsx)(`button`,{type:`button`,onClick:t=>{t.shiftKey&&u?(t.preventDefault(),u(e.turn)):e.kind===`forge`&&e.toolName&&o&&o(e.toolName,e.side,e.eventId,t.currentTarget)!==!1||r(s)},onMouseEnter:()=>{i?.(s),l?.({kind:e.kind,side:e.side,turn:e.turn})},onMouseLeave:()=>{i?.(null),l?.(null)},onFocus:()=>{i?.(s),l?.({kind:e.kind,side:e.side,turn:e.turn})},onBlur:()=>{i?.(null),l?.(null)},title:`${e.label}${u?` · Shift+click to open in Reports`:``}`,"aria-label":e.label,className:f,style:p,children:HO[e.kind]},`${e.turn}-${e.side}-${e.kind}-${t}`)})})]})}var WO={bar:`_bar_n16b7_1`,row:`_row_n16b7_9`,label:`_label_n16b7_21`,track:`_track_n16b7_26`,fill:`_fill_n16b7_35`,count:`_count_n16b7_42`};function GO(e){let t=0;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.type===`turn_done`){let e=Number(r.turn??r.data?.turn??0);if(e>0){t=e;break}}}let n=t+1,r=new Set,i=!1;for(let t of e){let e=Number(t.turn??t.data?.turn??0);if(t.type===`specialist_done`&&e===n){let e=typeof t.data?.department==`string`?t.data.department:``;e&&r.add(e),i=!0}if(t.type===`turn_done`&&e===n)return{inFlightTurn:null,deptsReported:new Set}}return{inFlightTurn:i?n:null,deptsReported:r}}function KO({eventsA:e,eventsB:t,totalDepartments:n}){let r=(0,b.useMemo)(()=>GO(e),[e]),i=(0,b.useMemo)(()=>GO(t),[t]);if(r.inFlightTurn===null&&i.inFlightTurn===null)return null;let a=Math.max(1,n),o=(e,t,n)=>{if(n.inFlightTurn===null)return null;let r=Math.min(100,n.deptsReported.size/a*100);return(0,x.jsxs)(`div`,{className:WO.row,style:{"--side-color":t},children:[(0,x.jsx)(`span`,{className:WO.label,children:e}),(0,x.jsxs)(`span`,{children:[`T`,n.inFlightTurn]}),(0,x.jsx)(`div`,{className:WO.track,children:(0,x.jsx)(`div`,{className:WO.fill,style:{"--bar-pct":`${r}%`}})}),(0,x.jsxs)(`span`,{className:WO.count,children:[n.deptsReported.size,`/`,a]})]})};return(0,x.jsxs)(`div`,{"aria-live":`polite`,className:WO.bar,children:[o(`A`,`var(--vis)`,r),o(`B`,`var(--eng)`,i)]})}var qO={bar:`_bar_3c24d_1`,icon:`_icon_3c24d_11`,label:`_label_3c24d_21`,input:`_input_3c24d_29`,dropdown:`_dropdown_3c24d_42`,option:`_option_3c24d_65`,sidePill:`_sidePill_3c24d_86`,optionName:`_optionName_3c24d_96`,optionMeta:`_optionMeta_3c24d_106`,featuredPill:`_featuredPill_3c24d_115`,moreNote:`_moreNote_3c24d_124`,matchCount:`_matchCount_3c24d_132`,clearBtn:`_clearBtn_3c24d_140`};function JO({value:e,onChange:t,matches:n,onPick:r}){let i=(0,b.useRef)(null),[a,o]=(0,b.useState)(!1),s=n.length,c=Lm();(0,b.useEffect)(()=>{let e=e=>{let t=e.target?.tagName;t!==`INPUT`&&t!==`TEXTAREA`&&t!==`SELECT`&&e.key===`/`&&(e.preventDefault(),i.current?.focus())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]);let l=a&&e.trim().length>0&&n.length>0;return(0,x.jsxs)(`div`,{className:qO.bar,children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,className:qO.icon,title:`Search agents`,children:`🔍`}),(0,x.jsx)(`span`,{className:qO.label,children:`Find`}),(0,x.jsx)(`input`,{ref:i,type:`text`,value:e,onChange:e=>t(e.target.value),onFocus:()=>o(!0),onBlur:()=>setTimeout(()=>o(!1),120),placeholder:`${c.person} name, dept, mood… (space-separate to AND-match; / to focus)`,"aria-label":`Search ${c.people} by name, department, role, or mood`,className:qO.input}),l&&(0,x.jsxs)(`div`,{role:`listbox`,className:qO.dropdown,children:[n.slice(0,10).map((e,t)=>(0,x.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":`false`,onMouseDown:t=>{t.preventDefault(),r?.(e)},className:qO.option,style:{"--result-color":e.sideColor},children:[(0,x.jsx)(`span`,{className:qO.sidePill,children:e.side.toUpperCase()}),(0,x.jsx)(`span`,{className:qO.optionName,children:e.cell.name}),(0,x.jsxs)(`span`,{className:qO.optionMeta,children:[e.cell.department?.toUpperCase?.()||``,` · `,e.cell.mood,typeof e.cell.age==`number`?` · age ${e.cell.age}`:``]}),e.cell.featured&&(0,x.jsx)(`span`,{className:qO.featuredPill,children:`FEATURED`})]},`${e.side}-${e.cell.agentId}-${t}`)),n.length>10&&(0,x.jsxs)(`div`,{className:qO.moreNote,children:[`+ `,n.length-10,` more…`]})]}),e&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)(`span`,{className:qO.matchCount,style:{"--count-color":s>0?`var(--amber)`:`var(--rust)`},children:[s,` match`,s===1?``:`es`]}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>t(``),"aria-label":`Clear search`,className:qO.clearBtn,children:`clear`})]})]})}function YO(e,t,n,r=.04,i=`sine`){let a=e.currentTime,o=e.createOscillator(),s=e.createGain();o.type=i,o.frequency.setValueAtTime(t,a),s.gain.setValueAtTime(0,a),s.gain.linearRampToValueAtTime(r,a+.008),s.gain.exponentialRampToValueAtTime(1e-4,a+n),o.connect(s),s.connect(e.destination),o.start(a),o.stop(a+n+.02)}function XO(e,t){switch(t){case`birth`:YO(e,880,.18,.05,`triangle`),setTimeout(()=>YO(e,1320,.12,.03,`triangle`),70);break;case`death`:YO(e,160,.35,.05,`sine`);break;case`forge`:YO(e,660,.12,.04,`sine`);break;case`crisis`:YO(e,220,.22,.05,`sawtooth`),setTimeout(()=>YO(e,180,.18,.045,`sawtooth`),120)}}function ZO(e){let t=(0,b.useRef)(null),n=(0,b.useRef)(new Set),r=(0,b.useRef)(-1),i=(0,b.useRef)(-1),a=()=>{if(!e.enabled)return null;if(t.current)return t.current;try{let e=window.AudioContext??window.webkitAudioContext;return e?(t.current=new e,t.current):null}catch{return null}};(0,b.useEffect)(()=>{if(!e.enabled)return;let n=()=>{let e=t.current;e&&e.state===`suspended`&&e.resume().catch(()=>{})};return window.addEventListener(`click`,n),window.addEventListener(`keydown`,n),()=>{window.removeEventListener(`click`,n),window.removeEventListener(`keydown`,n)}},[e.enabled]),(0,b.useEffect)(()=>{if(!e.enabled)return;let t=(e,t,r,i)=>{if(!e||!t||e.turn===i.current)return;i.current=e.turn;let o=a();if(!o)return;let s=gD(t.cells,e.cells),c=0,l=0;for(let t of s.born){let i=`${r}|t${e.turn}|birth|${t.agentId}`;n.current.has(i)||(n.current.add(i),c+=1)}for(let t of s.died){let i=`${r}|t${e.turn}|death|${t.agentId}`;n.current.has(i)||(n.current.add(i),l+=1)}c>0&&XO(o,`birth`),l>0&&setTimeout(()=>XO(o,`death`),c>0?300:0)};t(e.snapshotA,e.prevSnapshotA,`a`,r),t(e.snapshotB,e.prevSnapshotB,`b`,i)},[e.enabled,e.snapshotA,e.prevSnapshotA,e.snapshotB,e.prevSnapshotB]),(0,b.useEffect)(()=>{if(!e.enabled)return;let t=a();if(!t)return;let r=(e,r)=>{for(let i of e){if(!i.approved)continue;let e=`${r}|forge|${i.turn}|${i.eventIndex}|${i.name}`;n.current.has(e)||(n.current.add(e),XO(t,`forge`))}};r(e.forgeAttemptsA,`a`),r(e.forgeAttemptsB,`b`)},[e.enabled,e.forgeAttemptsA,e.forgeAttemptsB])}var QO={backdrop:`_backdrop_nnlpn_1`,dialog:`_dialog_nnlpn_12`,header:`_header_nnlpn_24`,title:`_title_nnlpn_31`,closeBtn:`_closeBtn_nnlpn_41`,sidesRow:`_sidesRow_nnlpn_54`,sideBlock:`_sideBlock_nnlpn_61`,sideName:`_sideName_nnlpn_71`,statsGrid:`_statsGrid_nnlpn_81`,cell:`_cell_nnlpn_87`,cellLabel:`_cellLabel_nnlpn_93`,cellValue:`_cellValue_nnlpn_101`,empty:`_empty_nnlpn_108`,divergenceBox:`_divergenceBox_nnlpn_113`,divergenceLabel:`_divergenceLabel_nnlpn_125`,divergenceCount:`_divergenceCount_nnlpn_132`,divergenceCopy:`_divergenceCopy_nnlpn_138`};function $O(e){if(e.length===0)return null;let t=0,n=0,r=0,i=0,a=0,o=0,s=1/0,c=1/0;for(let l of e)t+=l.births,n+=l.deaths,l.population>r&&(r=l.population),i+=l.morale,typeof l.foodReserve==`number`&&(a+=l.foodReserve,o++,l.foodReserve<c&&(c=l.foodReserve)),l.morale<s&&(s=l.morale);return{turns:e.length,totalBirths:t,totalDeaths:n,peakPop:r,finalPop:e[e.length-1].population,avgMorale:i/e.length,minMorale:s===1/0?0:s,avgFood:o>0?a/o:void 0,minFood:o>0?c:void 0}}function ek(e){let{open:t,onClose:n}=e,r=Lm();(0,b.useEffect)(()=>{if(!t)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),n())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[t,n]);let i=(0,b.useMemo)(()=>$O(e.snapsA),[e.snapsA]),a=(0,b.useMemo)(()=>$O(e.snapsB),[e.snapsB]);if(!t)return null;let o=(e,t,n)=>(0,x.jsxs)(`div`,{className:QO.cell,children:[(0,x.jsx)(`span`,{className:QO.cellLabel,children:e}),(0,x.jsx)(`span`,{className:QO.cellValue,style:n?{"--val-color":n}:void 0,children:t})]}),s=(e,t,n,r,i)=>(0,x.jsxs)(`div`,{className:QO.sideBlock,style:{"--side-color":t},children:[(0,x.jsx)(`div`,{className:QO.sideName,children:e}),n?(0,x.jsxs)(`div`,{className:QO.statsGrid,children:[o(`Turns`,`${n.turns}`),o(`Final pop`,`${n.finalPop}`,t),o(`Peak pop`,`${n.peakPop}`),o(`Total births`,`${n.totalBirths}`,`rgba(106, 173, 72, 0.95)`),o(`Total deaths`,`${n.totalDeaths}`,`rgba(200, 95, 80, 0.95)`),o(`Avg morale`,`${Math.round(n.avgMorale*100)}%`),o(`Min morale`,`${Math.round(n.minMorale*100)}%`,n.minMorale<.3?`var(--rust)`:`var(--text-1)`),n.minFood!==void 0&&o(`Min food`,`${n.minFood.toFixed(1)}mo`,n.minFood<3?`var(--rust)`:`var(--text-1)`),o(`Tools forged`,`${r}`,`var(--amber)`),o(`Tool reuses`,`${i}`,`var(--amber)`)]}):(0,x.jsx)(`div`,{className:QO.empty,children:`No snapshots yet.`})]});return(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Run summary`,onClick:n,className:QO.backdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:QO.dialog,children:[(0,x.jsxs)(`div`,{className:QO.header,children:[(0,x.jsxs)(`h2`,{className:QO.title,children:[`Run Summary · `,e.snapsA.length||e.snapsB.length,` turns`]}),(0,x.jsx)(`button`,{type:`button`,onClick:n,"aria-label":`Close run summary`,className:QO.closeBtn,children:`×`})]}),(0,x.jsxs)(`div`,{className:QO.sidesRow,children:[s(e.actorNameA,`var(--vis)`,i,e.forgeApprovedA,e.reuseCountA),s(e.actorNameB,`var(--eng)`,a,e.forgeApprovedB,e.reuseCountB)]}),(0,x.jsxs)(`div`,{className:QO.divergenceBox,children:[(0,x.jsxs)(`div`,{children:[(0,x.jsx)(`div`,{className:QO.divergenceLabel,children:`Divergence`}),(0,x.jsx)(`div`,{className:QO.divergenceCount,children:e.divergedCount})]}),(0,x.jsxs)(`div`,{className:QO.divergenceCopy,children:[r.People,` alive on one side but dead on the other at the final snapshot — a measure of how much the two leaders' decisions diverged the outcomes.`]})]})]})})}var tk={anchor:`_anchor_ypvfl_1`,trigger:`_trigger_ypvfl_5`,triggerOpen:`_triggerOpen_ypvfl_21`,recDot:`_recDot_ypvfl_27`,"paracosm-rec-pulse":`_paracosm-rec-pulse_ypvfl_1`,menu:`_menu_ypvfl_36`,item:`_item_ypvfl_51`,itemRecording:`_itemRecording_ypvfl_71`,itemKey:`_itemKey_ypvfl_75`,itemKeyRecording:`_itemKeyRecording_ypvfl_81`,itemDesc:`_itemDesc_ypvfl_85`},nk=8,rk=4,ik={top:0,left:0,visibility:`hidden`},ak=`a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`;function ok(e){let t=e.getBoundingClientRect(),n=t.left+t.width/2,r=t.top+t.height/2;if(n<0||r<0||n>window.innerWidth||r>window.innerHeight)return!1;for(let t=e.parentElement;t&&t!==document.body;t=t.parentElement){let e=getComputedStyle(t);if(e.overflowX===`visible`&&e.overflowY===`visible`)continue;let i=t.getBoundingClientRect();if(n<i.left||n>i.right||r<i.top||r>i.bottom)return!1}return!0}function sk({recording:e,onExportPng:t,onExportJson:n,onToggleRecording:r}){let[i,a]=(0,b.useState)(!1),[o,s]=(0,b.useState)(null),c=(0,b.useRef)(null),l=(0,b.useRef)(null),u=(0,b.useRef)(null),d=(0,b.useRef)(!1),f=()=>Array.from(u.current?.querySelectorAll(`[role="menuitem"]`)??[]),p=(0,b.useCallback)(e=>{a(!1),e&&l.current?.focus()},[]);(0,b.useLayoutEffect)(()=>{if(!i){s(null);return}let e=()=>{let e=l.current;if(!e)return;if(!ok(e)){a(!1);return}let t=e.getBoundingClientRect(),n=window.innerHeight-t.bottom-rk-nk,r=t.top-rk-nk,i=(u.current?.scrollHeight??0)>n&&r>n;s({...i?{bottom:window.innerHeight-t.top+rk,maxHeight:Math.max(0,r)}:{top:t.bottom+rk,maxHeight:Math.max(0,n)},...t.right>=188?{right:Math.max(nk,window.innerWidth-t.right)}:{left:Math.max(nk,t.left)}})};e(),window.addEventListener(`resize`,e),document.addEventListener(`scroll`,e,!0);let t=()=>{let e=l.current?.getBoundingClientRect();return e?`${e.left} ${e.top} ${e.right} ${e.bottom}`:``},n=t(),r=0,o=()=>{let i=t();i!==n&&(n=i,e()),r=requestAnimationFrame(o)};return r=requestAnimationFrame(o),()=>{cancelAnimationFrame(r),window.removeEventListener(`resize`,e),document.removeEventListener(`scroll`,e,!0)}},[i]),(0,b.useLayoutEffect)(()=>{i&&o&&d.current&&(d.current=!1,u.current?.querySelector(`[role="menuitem"]`)?.focus({preventScroll:!0}))},[i,o]),(0,b.useEffect)(()=>{if(!i)return;let e=e=>{let t=e.target;c.current?.contains(t)||u.current?.contains(t)||a(!1)},t=e=>{e.key===`Escape`&&a(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[i]);let m=e=>{let t=f(),n=t.indexOf(document.activeElement);if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault();let r=e.key===`ArrowDown`?1:-1;t[n<0?r>0?0:t.length-1:(n+r+t.length)%t.length]?.focus()}else if(e.key===`Home`||e.key===`End`)e.preventDefault(),t[e.key===`Home`?0:t.length-1]?.focus();else if(e.key===`Escape`)e.preventDefault(),p(!0);else if(e.key===`Tab`){e.preventDefault();let t=l.current;if(p(!0),!e.shiftKey&&t){let e=Array.from(document.querySelectorAll(ak)).filter(e=>!u.current?.contains(e)&&e.getClientRects().length>0);e[e.indexOf(t)+1]?.focus()}}},h=e=>()=>{p(!0),e()};return(0,x.jsxs)(`div`,{ref:c,className:tk.anchor,children:[(0,x.jsxs)(`button`,{ref:l,type:`button`,onClick:()=>{i||(d.current=!0),a(e=>!e)},"aria-expanded":i,"aria-haspopup":`menu`,"aria-label":`Export options`,title:e?`Recording in progress — click for options`:`Export options`,className:[tk.trigger,i?tk.triggerOpen:``].filter(Boolean).join(` `),children:[e&&(0,x.jsx)(`span`,{"aria-hidden":`true`,className:tk.recDot}),`EXPORT ▼`]}),i&&(0,Ay.createPortal)((0,x.jsxs)(`div`,{ref:u,role:`menu`,className:tk.menu,style:o??ik,onKeyDown:m,children:[(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:h(t),className:tk.item,children:[(0,x.jsx)(`span`,{className:tk.itemKey,children:`PNG`}),(0,x.jsx)(`span`,{className:tk.itemDesc,children:`Current frame`})]}),(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:h(r),className:[tk.item,e?tk.itemRecording:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`span`,{className:[tk.itemKey,e?tk.itemKeyRecording:``].filter(Boolean).join(` `),children:e?`STOP`:`REC`}),(0,x.jsx)(`span`,{className:tk.itemDesc,children:e?`End recording & download`:`Timelapse to webm`})]}),(0,x.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:h(n),className:tk.item,children:[(0,x.jsx)(`span`,{className:tk.itemKey,children:`JSON`}),(0,x.jsx)(`span`,{className:tk.itemDesc,children:`Replay snapshot`})]})]}),document.body)]})}var ck={strip:`_strip_deb88_1`,text:`_text_deb88_20`,expand:`_expand_deb88_24`},lk=120;function uk({text:e,turn:t}){let[n,r]=(0,b.useState)(!1),i=e.length>lk,a=i&&!n?`${e.slice(0,119)}…`:e;return(0,x.jsxs)(`div`,{className:ck.strip,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,"data-turn":t,children:[(0,x.jsx)(`span`,{className:ck.text,children:a}),i&&(0,x.jsx)(`button`,{type:`button`,className:ck.expand,onClick:()=>r(e=>!e),"aria-expanded":n,children:n?`Less`:`More`})]})}var dk={bar:`_bar_1u6wg_1`,glyphRow:`_glyphRow_1u6wg_21`,label:`_label_1u6wg_28`,glyph:`_glyph_1u6wg_21`,band:`_band_1u6wg_39`,agent:`_agent_1u6wg_43`,featured:`_featured_1u6wg_49`,turn:`_turn_1u6wg_56`,fullLegend:`_fullLegend_1u6wg_68`,popover:`_popover_1u6wg_89`,popHeading:`_popHeading_1u6wg_107`,deptSwatch:`_deptSwatch_1u6wg_135`,closeBtn:`_closeBtn_1u6wg_145`};function fk({departments:e}){let[t,n]=(0,b.useState)(!1),r=Pt(t),i=(0,b.useRef)(null);return(0,b.useEffect)(()=>{if(!t)return;let e=e=>{e.key===`Escape`&&n(!1)},r=e=>{let t=e.target;t&&i.current&&!i.current.contains(t)&&n(!1)};return window.addEventListener(`keydown`,e),window.addEventListener(`mousedown`,r),()=>{window.removeEventListener(`keydown`,e),window.removeEventListener(`mousedown`,r)}},[t]),(0,x.jsxs)(`div`,{className:dk.bar,"aria-label":`Visualization legend`,ref:i,children:[(0,x.jsxs)(`span`,{className:dk.glyphRow,children:[(0,x.jsx)(pk,{type:`band`}),(0,x.jsx)(`span`,{className:dk.label,children:`Department band`}),(0,x.jsx)(pk,{type:`agent`}),(0,x.jsx)(`span`,{className:dk.label,children:`Agent`}),(0,x.jsx)(pk,{type:`featured`}),(0,x.jsx)(`span`,{className:dk.label,children:`Featured agent`}),(0,x.jsx)(pk,{type:`turn`}),(0,x.jsx)(`span`,{className:dk.label,children:`Turn marker`})]}),(0,x.jsx)(`button`,{type:`button`,className:dk.fullLegend,onClick:()=>n(e=>!e),"aria-expanded":t,"aria-haspopup":`dialog`,children:`Show full legend`}),t&&(0,x.jsxs)(`div`,{className:dk.popover,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`viz-legend-heading`,tabIndex:-1,ref:r,children:[(0,x.jsx)(`h3`,{id:`viz-legend-heading`,className:dk.popHeading,children:`What you’re looking at`}),(0,x.jsxs)(`section`,{children:[(0,x.jsx)(`h4`,{children:`Departments (tile color)`}),(0,x.jsx)(`ul`,{className:dk.deptList,children:e.map(e=>(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`span`,{className:dk.deptSwatch,style:{background:e.color},"aria-hidden":`true`}),e.label]},e.id))})]}),(0,x.jsxs)(`section`,{children:[(0,x.jsx)(`h4`,{children:`Mood tiers (chip glyph)`}),(0,x.jsxs)(`ul`,{className:dk.moodList,children:[(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`▼`}),` low (under 25% morale)`]}),(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`▽`}),` tense (25–50%)`]}),(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`△`}),` steady (50–75%)`]}),(0,x.jsxs)(`li`,{children:[(0,x.jsx)(`span`,{"aria-hidden":`true`,children:`▲`}),` rising (over 75%)`]})]})]}),(0,x.jsx)(`button`,{type:`button`,className:dk.closeBtn,onClick:()=>n(!1),"aria-label":`Close legend`,children:`Close (Esc)`})]})]})}function pk({type:e}){switch(e){case`band`:return(0,x.jsx)(`span`,{className:`${dk.glyph} ${dk.band}`,"aria-hidden":`true`});case`agent`:return(0,x.jsx)(`span`,{className:`${dk.glyph} ${dk.agent}`,"aria-hidden":`true`});case`featured`:return(0,x.jsx)(`span`,{className:`${dk.glyph} ${dk.featured}`,"aria-hidden":`true`});case`turn`:return(0,x.jsx)(`span`,{className:`${dk.glyph} ${dk.turn}`,"aria-hidden":`true`,children:`T`})}}var mk={panel:`_panel_15qsw_1`,eyebrow:`_eyebrow_15qsw_15`,empty:`_empty_15qsw_23`,chipRow:`_chipRow_15qsw_27`,chip:`_chip_15qsw_27`,chipLight:`_chipLight_15qsw_47`,chipStrong:`_chipStrong_15qsw_53`,chipDept:`_chipDept_15qsw_59`,chipCount:`_chipCount_15qsw_63`},hk=8;function gk({diff:e,departmentLabels:t}){let n=Array.from(e.entries()).filter(([,e])=>e.magnitude>0).sort(([,e],[,t])=>t.magnitude-e.magnitude).slice(0,hk);return n.length===0?(0,x.jsxs)(`div`,{className:mk.panel,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:mk.eyebrow,children:`Divergence detail`}),(0,x.jsx)(`span`,{className:mk.empty,children:`No department-level divergence at this turn.`})]}):(0,x.jsxs)(`div`,{className:mk.panel,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:mk.eyebrow,children:`Divergence detail`}),(0,x.jsx)(`ul`,{className:mk.chipRow,children:n.map(([e,n])=>{let r=t[e]??e,i=n.magnitude>=.5,a=`${r}: A has ${n.aState.agentCount} agents (${n.aState.dominantMood} mood); B has ${n.bState.agentCount} agents (${n.bState.dominantMood} mood)`;return(0,x.jsxs)(`li`,{className:`${mk.chip} ${i?mk.chipStrong:mk.chipLight}`,title:a,"aria-label":a,children:[(0,x.jsx)(`span`,{className:mk.chipDept,children:r}),(0,x.jsxs)(`span`,{className:mk.chipCount,children:[`A `,n.aState.agentCount,` / B `,n.bState.agentCount]})]},e)})})]})}var _k=.2;function vk(e,t){return{population:e.population,morale:e.morale,deathsThisTurn:e.deaths,birthsThisTurn:e.births,eventCategories:e.eventCategories??[],year:e.time}}var yk={nameA:`Leader A`,nameB:`Leader B`,person:`colonist`,people:`colonists`,places:`colonies`};function bk(e,t,n,r=yk){if(!e||!t)return`Awaiting first turn snapshot.`;let i=e.year??t.year;if(e.deathsThisTurn!==t.deathsThisTurn){let a=e.deathsThisTurn>t.deathsThisTurn,o=a?r.nameA:r.nameB,s=a?r.nameB:r.nameA,c=Math.max(e.deathsThisTurn,t.deathsThisTurn),l=Math.min(e.deathsThisTurn,t.deathsThisTurn),u=e=>e===0?`none`:`${e} ${e===1?r.person:r.people}`;return`Turn ${n}, year ${i}: ${o} lost ${u(c)}; ${s} lost ${u(l)}.`}if(Math.abs(e.morale-t.morale)>=_k){let a=e.morale<t.morale,o=a?r.nameA:r.nameB,s=a?r.nameB:r.nameA,c=a?e.morale:t.morale,l=a?t.morale:e.morale;return`Turn ${n}, year ${i}: ${o}'s morale collapsed to ${xk(c)}; ${s} held ${xk(l)}.`}let a=e.eventCategories.join(`|`),o=t.eventCategories.join(`|`);return a&&o&&a!==o?`Turn ${n}, year ${i}: different events. ${r.nameA}: ${e.eventCategories.join(`, `)}; ${r.nameB}: ${t.eventCategories.join(`, `)}.`:n===1&&a&&a===o?`Turn 1, year ${i}: identical first event (${e.eventCategories.join(`, `)}). Both ${r.places} start from the same state.`:`Turn ${n}, year ${i}: ${r.nameA} and ${r.nameB} tracked closely. See sub-tabs for details.`}function xk(e){return`${Math.round(e*100)}%`}function Sk(e,t){let n=new Map,r=new Map(e.map(e=>[e.cellKey,e])),i=new Map(t.map(e=>[e.cellKey,e])),a=new Set([...r.keys(),...i.keys()]);for(let e of a){let t=r.get(e)??Ck(e),a=i.get(e)??Ck(e),o=Math.max(t.agentCount,a.agentCount,1),s=Math.abs(t.agentCount-a.agentCount)/o,c=t.dominantMood===a.dominantMood?0:1,l=t.department===a.department?0:1,u=(s+c+l)/3;n.set(e,{magnitude:u,aState:t,bState:a})}return n}function Ck(e){return{cellKey:e,department:``,agentCount:0,dominantMood:`steady`}}var wk={medical:`#4ecdc4`,engineering:`#e8b44a`,agriculture:`#6aad48`,psychology:`#9b6b9e`,governance:`#e06530`};function Tk(e,t){let n=new Set,r=new Set;if(!e||!t)return{aliveOnlyA:n,aliveOnlyB:r};let i=new Map(e.cells.map(e=>[e.agentId,e])),a=new Map(t.cells.map(e=>[e.agentId,e]));for(let[e,t]of i){let r=a.get(e);!t.alive||r&&r.alive||n.add(e)}for(let[e,t]of a){let n=i.get(e);!t.alive||n&&n.alive||r.add(e)}return{aliveOnlyA:n,aliveOnlyB:r}}function Ek(e){if(!e)return[];let t=new Map;for(let n of e.cells){if(!n.alive)continue;let e=n.department||`unknown`,r=t.get(e);r||(r={count:0,moods:{}},t.set(e,r)),r.count+=1;let i=n.mood||`neutral`;r.moods[i]=(r.moods[i]??0)+1}let n=[];for(let[e,r]of t){let t=Object.entries(r.moods).sort((e,t)=>t[1]-e[1])[0]?.[0]??`neutral`;n.push({cellKey:e,department:e,agentCount:r.count,dominantMood:t})}return n}function Dk({k:e,v:t}){return(0,x.jsxs)(`span`,{className:$.kbd,children:[(0,x.jsx)(`kbd`,{className:$.kbdKey,children:e}),(0,x.jsx)(`span`,{className:$.kbdLabel,children:t})]})}function Ok(e){return e?[e.foodReserve,e.waterLitersPerDay,e.powerKw,e.pressurizedVolumeM3].some(e=>typeof e==`number`):!1}var kk=`button, a[href], summary, [role="button"], [role="link"], [role="menuitem"], [role="option"], [role="checkbox"], [role="radio"], [role="switch"], [role="tab"]`;function Ak({state:e,onNavigateToChat:t}){let n=HE(e),r=e.actorIds[0],i=e.actorIds[1],[a,o]=(0,b.useState)(r),[s,c]=(0,b.useState)(i);(0,b.useEffect)(()=>{a&&!e.actorIds.includes(a)&&o(r),s&&!e.actorIds.includes(s)&&c(i)},[e.actorIds,a,s,r,i]);let l=a??r,u=s??i,d=(l?n[l]:void 0)??[],f=(u?n[u]:void 0)??[],p=l?e.actors[l]:null,m=u?e.actors[u]:null,h=e.actorIds.length>2,[g,_]=(0,b.useState)(h?`cohort`:`pair`);(0,b.useEffect)(()=>{_(h?`cohort`:`pair`)},[h]);let v=Math.max(d.length,f.length),[y,S]=(0,b.useState)(0),[C,w]=(0,b.useState)(!1),[T,E]=(0,b.useState)(1),[D,O]=(0,b.useState)(()=>{try{let e=localStorage.getItem(`paracosm:gridMode`);if(e===`living`||e===`mood`||e===`forge`||e===`ecology`||e===`divergence`)return e}catch{}return`living`}),k=(0,b.useCallback)(e=>{O(e);try{localStorage.setItem(`paracosm:gridMode`,e)}catch{}},[]),{toast:A}=Ht(),j=(0,b.useRef)(0),ee=(0,b.useRef)(0);(0,b.useEffect)(()=>{let e=ee.current;ee.current=v,v>e&&!C&&S(v-1)},[v,C]),(0,b.useEffect)(()=>{if(!C)return;let e=2e3/T;return j.current=window.setInterval(()=>{S(e=>e>=v-1?(w(!1),e):e+1)},e),()=>clearInterval(j.current)},[C,T,v]);let te=(0,b.useCallback)(()=>{v<=1||w(e=>(!e&&y>=v-1&&S(0),!e))},[y,v]),M=(0,b.useCallback)(()=>{w(!1),S(e=>Math.max(0,e-1))},[]),N=(0,b.useCallback)(()=>{w(!1),S(e=>Math.min(v-1,e+1))},[v]),ne=(0,b.useCallback)(e=>{w(!1),S(e)},[]),P=nA(),re=(0,b.useCallback)(e=>{P(`reports`),requestAnimationFrame(()=>{let t=document.getElementById(`turn-${e}`);t&&t.scrollIntoView({behavior:`smooth`,block:`start`})})},[P]),[ie,F]=(0,b.useState)(!1),I=Qk(),ae=Lm(),[oe,ce]=(0,b.useState)(null),[le,L]=(0,b.useState)(null),[ue,de]=(0,b.useState)(null),[fe,R]=(0,b.useState)(`all`),[z,pe]=(0,b.useState)(null),[me,he]=(0,b.useState)(``),[ge,_e]=(0,b.useState)(null),[B,ve]=(0,b.useState)(()=>{try{let e=localStorage.getItem(`paracosm:gridSettings`);if(e){let t=JSON.parse(e);if(t.__v===3)return rO(t);localStorage.removeItem(`paracosm:gridSettings`)}}catch{}return nO}),ye=(0,b.useCallback)(e=>{ve(e);try{localStorage.setItem(`paracosm:gridSettings`,JSON.stringify({...e,__v:3}))}catch{}},[]);(0,b.useEffect)(()=>{if(!B.alerts||!e.isRunning)return;let t=new Set([`event_start`,`director_crisis`]),n=`paracosm:seenCrisisToasts`,r=()=>{try{let e=sessionStorage.getItem(n);return e?new Set(JSON.parse(e)):new Set}catch{return new Set}},i=e=>{try{let t=[...e].slice(-200);sessionStorage.setItem(n,JSON.stringify(t))}catch{}},a=r(),o=(()=>{let n=null,r=[];l&&r.push({side:`a`,actorName:l}),u&&r.push({side:`b`,actorName:u});for(let{side:i,actorName:o}of r){let r=e.actors[o];if(!r)continue;let s=r.events;for(let e=s.length-1;e>=0;e--){let r=s[e];if(!t.has(r.type))continue;let o=Number(r.turn??r.data?.turn??0),c=typeof r.data?.category==`string`?r.data.category:``;if(!c)continue;let l=`${i}:${o}:${c}`;if(a.has(l))continue;let u=typeof r.data?.title==`string`?r.data.title:``;(!n||o>n.turn)&&(n={key:l,side:i,turn:o,category:c,title:u});break}}return n})();o&&(a.add(o.key),i(a),_e(e=>e&&e.key===o.key?e:{...o,expiresAt:performance.now()+5500}))},[e.actorIds,e.actors,B.alerts,e.isRunning]),(0,b.useEffect)(()=>{if(!ge)return;let e=ge.expiresAt-performance.now();if(e<=0){_e(null);return}let t=setTimeout(()=>_e(null),e);return()=>clearTimeout(t)},[ge]);let[be,xe]=(0,b.useState)(null),Se=`paracosm:seenThresholdAlerts`,Ce=(0,b.useCallback)(()=>{try{let e=sessionStorage.getItem(Se);return e?new Set(JSON.parse(e)):new Set}catch{return new Set}},[]),we=(0,b.useCallback)(e=>{try{sessionStorage.setItem(Se,JSON.stringify([...e].slice(-200)))}catch{}},[]);(0,b.useEffect)(()=>{if(!B.alerts||!e.isRunning)return;let t=Ce(),n=(e,n)=>{t.has(e)||(t.add(e),xe({key:e,...n,expiresAt:performance.now()+5500}))},r=(e,t)=>{if(t.length<2)return;let r=t[t.length-1],i=t[t.length-2],a=i.morale-r.morale;a>=.2&&n(`${e}|${r.turn}|morale-crash`,{side:e,turn:r.turn,kind:`morale-crash`,message:`Morale crashed ${Math.round(a*100)}% → ${Math.round(r.morale*100)}% this turn`}),typeof r.foodReserve==`number`&&typeof i.foodReserve==`number`&&r.foodReserve<3&&i.foodReserve>=3&&n(`${e}|${r.turn}|food-low`,{side:e,turn:r.turn,kind:`food-low`,message:`Food reserve fell below 3mo (${r.foodReserve.toFixed(1)}mo remaining)`})};r(`a`,d),r(`b`,f),we(t)},[d,f,B.alerts,Ce,we,e.isRunning]),(0,b.useEffect)(()=>{if(!be)return;let e=be.expiresAt-performance.now();if(e<=0){xe(null);return}let t=setTimeout(()=>xe(null),e);return()=>clearTimeout(t)},[be]);let[Te,Ee]=(0,b.useState)(()=>{try{let e=localStorage.getItem(`paracosm:gridPalette`);if(e===`cool`||e===`mono`||e===`amber`)return e}catch{}return`amber`}),De=(0,b.useCallback)(e=>{Ee(e);try{localStorage.setItem(`paracosm:gridPalette`,e)}catch{}},[]),Oe=(0,b.useCallback)(()=>{De(Te===`amber`?`cool`:Te===`cool`?`mono`:`amber`)},[Te,De]),[ke,Ae]=(0,b.useState)(!1),[je,Me]=(0,b.useState)(!1),[Ne,Pe]=(0,b.useState)(!1),Fe=ev(),Ie=D_(),Le=(0,b.useCallback)((t,n,r,i)=>{let a=n===`a`?l:u,o=a?e.actorIds.indexOf(a):-1,s=o>=0?Ie.getEntryFor(o,t):void 0;if(!s)return!1;let c=s.attempts.find(e=>e.eventId===r)?.attempt;return Fe.openTrace({actorIndex:o,toolName:t,attempt:c},i,`viz`),!0},[l,u,e.actorIds,Ie,Fe]),[Re,ze]=(0,b.useState)(null),Be=(0,b.useCallback)(e=>{ze(t=>t===e?null:e)},[]),Ve=d[y]??d[d.length-1],He=f[y]??f[f.length-1],Ue=Ve?.turn??0,We=He?.turn??0,Ge=I.presets.find(e=>e.id==="default"),Ke=Ge?.leaders??Ge?.actors,qe=Ke?.[0]?{name:Ke[0].name,archetype:Ke[0].archetype,unit:se(I,0),hexaco:Ke[0].hexaco,instructions:Ke[0].instructions,quote:``}:null,Je=Ke?.[1]?{name:Ke[1].name,archetype:Ke[1].archetype,unit:se(I,1),hexaco:Ke[1].hexaco,instructions:Ke[1].instructions,quote:``}:null,Ye=p?.leader??qe,Xe=m?.leader??Je,Ze=(0,b.useRef)(null),[Qe,$e]=(0,b.useState)(!1),et=(0,b.useRef)(null),tt=(0,b.useRef)([]),nt=(0,b.useRef)(null),rt=(0,b.useRef)(0),it=(0,b.useCallback)(()=>{let e=Ze.current;if(!e)return;let t=e.getBoundingClientRect(),n=Math.max(640,Math.round(t.width)),r=Math.max(360,Math.round(t.height)),i=document.createElement(`canvas`);if(i.width=n,i.height=r,!i.getContext(`2d`))return;nt.current=i;let a=i.captureStream(30),o=`video/webm;codecs=vp9`;typeof MediaRecorder<`u`&&!MediaRecorder.isTypeSupported(o)&&(o=`video/webm;codecs=vp8`,MediaRecorder.isTypeSupported(o)||(o=`video/webm`));let s;try{s=new MediaRecorder(a,{mimeType:o,videoBitsPerSecond:4e6})}catch{console.warn(`MediaRecorder unavailable — timelapse skipped`);return}tt.current=[],s.ondataavailable=e=>{e.data&&e.data.size>0&&tt.current.push(e.data)},s.onstop=()=>{rt.current&&cancelAnimationFrame(rt.current),rt.current=0;let e=new Blob(tt.current,{type:o}),t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`paracosm-timelapse-${new Date().toISOString().replace(/[:.]/g,`-`).slice(0,19)}.webm`,document.body.appendChild(n),n.click(),document.body.removeChild(n),setTimeout(()=>URL.revokeObjectURL(t),1e3)},et.current=s,$e(!0),s.start();let c=()=>{let e=nt.current,t=Ze.current;if(!e||!t)return;let n=e.getContext(`2d`);if(!n)return;n.fillStyle=getComputedStyle(t).getPropertyValue(`--bg-deep`).trim()||`#0a0806`,n.fillRect(0,0,e.width,e.height);let r=t.getBoundingClientRect(),i=e.width/Math.max(1,r.width),a=e.height/Math.max(1,r.height),o=Array.from(t.querySelectorAll(`canvas`));for(let e of o){let t=e.getBoundingClientRect();t.width!==0&&t.height!==0&&n.drawImage(e,(t.left-r.left)*i,(t.top-r.top)*a,t.width*i,t.height*a)}rt.current=requestAnimationFrame(c)};rt.current=requestAnimationFrame(c)},[]),at=(0,b.useCallback)(()=>{let e=et.current;if(e){try{e.stop()}catch{}et.current=null,$e(!1)}},[]);(0,b.useEffect)(()=>()=>{if(et.current)try{et.current.stop()}catch{}rt.current&&cancelAnimationFrame(rt.current)},[]);let ot=(0,b.useCallback)(()=>{let e={exportedAt:new Date().toISOString(),leaderA:{name:Ye?.name??`Leader A`,archetype:Ye?.archetype??``},leaderB:{name:Xe?.name??`Leader B`,archetype:Xe?.archetype??``},currentTurn:y,snapshots:{a:d,b:f},events:{a:p?.events??[],b:m?.events??[]}},t=new Blob([JSON.stringify(e,null,2)],{type:`application/json`}),n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=`paracosm-replay-${new Date().toISOString().replace(/[:.]/g,`-`).slice(0,19)}.json`,document.body.appendChild(r),r.click(),document.body.removeChild(r),setTimeout(()=>URL.revokeObjectURL(n),1e3)},[y,Ye,Xe,d,f,p,m]),st=(0,b.useCallback)(()=>{let e=Ze.current;if(!e)return;let t=Array.from(e.querySelectorAll(`canvas`));if(t.length===0)return;let n=e.getBoundingClientRect(),r=document.createElement(`canvas`);r.width=Math.round(n.width*2),r.height=Math.round(n.height*2);let i=r.getContext(`2d`);if(i){i.fillStyle=getComputedStyle(e).getPropertyValue(`--bg-deep`).trim()||`#0a0806`,i.fillRect(0,0,r.width,r.height),i.scale(2,2);for(let e of t){let t=e.getBoundingClientRect();t.width!==0&&t.height!==0&&i.drawImage(e,t.left-n.left,t.top-n.top,t.width,t.height)}r.toBlob(e=>{if(!e)return;let t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`paracosm-viz-t${y+1}-${new Date().toISOString().replace(/[:.]/g,`-`).slice(0,19)}.png`,document.body.appendChild(n),n.click(),document.body.removeChild(n),setTimeout(()=>URL.revokeObjectURL(t),1e3)},`image/png`)}},[y]),[ct,lt]=(0,b.useState)(0),ut=(0,b.useRef)(-1);(0,b.useEffect)(()=>{ut.current===-1||Math.abs(y-ut.current)>=2&&lt(e=>e+1),ut.current=y},[y]),(0,b.useEffect)(()=>{let e=e=>{let t=e.target instanceof Element?e.target:null,n=t?.tagName;n!==`INPUT`&&n!==`TEXTAREA`&&n!==`SELECT`&&(e.key!==`Escape`&&t?.closest(`[role="dialog"]`)||(e.key!==` `&&e.key!==`Spacebar`||!t?.closest(kk))&&(e.key===`ArrowLeft`?(e.preventDefault(),M()):e.key===`ArrowRight`?(e.preventDefault(),N()):e.key===` `||e.key===`Spacebar`?(e.preventDefault(),te()):e.key===`?`||e.shiftKey&&e.key===`/`?(e.preventDefault(),F(e=>!e)):e.key===`Escape`&&ie?(e.preventDefault(),F(!1)):e.key===`1`?(e.preventDefault(),k(`living`)):e.key===`2`?(e.preventDefault(),k(`mood`)):e.key===`3`?(e.preventDefault(),k(`forge`)):e.key===`4`?(e.preventDefault(),k(`ecology`)):e.key===`5`&&(e.preventDefault(),k(`divergence`))))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[M,N,te,ie,k]);let dt=(0,b.useMemo)(()=>{let e=me.trim().toLowerCase().split(/\s+/).filter(Boolean);if(e.length===0)return[];let t=t=>{let n=`${t.name} ${t.department} ${t.role} ${t.mood}`.toLowerCase();return e.every(e=>n.includes(e))};return[...(Ve?.cells??[]).filter(e=>e.alive&&t(e)).map(e=>({cell:e,side:`a`,actorName:Ye?.name??`Leader A`,sideColor:`#e8b44a`})),...(He?.cells??[]).filter(e=>e.alive&&t(e)).map(e=>({cell:e,side:`b`,actorName:Xe?.name??`Leader B`,sideColor:`#4ecdc4`}))]},[me,Ve,He,Ye,Xe]),ft=(0,b.useMemo)(()=>Tk(Ve,He),[Ve,He]),pt=(0,b.useMemo)(()=>{let t={a:{attempts:[],reuses:[]},b:{attempts:[],reuses:[]}},n=[];l&&n.push({side:`a`,actorName:l}),u&&n.push({side:`b`,actorName:u});for(let{side:r,actorName:i}of n){let n=e.actors[i];if(!n)continue;let a=new Map;for(let e of n.events){if(e.type===`forge_attempt`){let n=e.data||{};t[r].attempts.push({turn:Number(n.turn??0),eventIndex:Number(n.eventIndex??0),department:String(n.department||``),name:String(n.name||``),approved:n.approved===!0||n.approved===`true`,confidence:typeof n.confidence==`number`?n.confidence:void 0}),n.name&&n.department&&n.approved===!0&&!a.has(String(n.name))&&a.set(String(n.name),String(n.department));continue}if(e.type!==`specialist_done`)continue;let n=e.data||{},i=String(n.department||``),o=Array.isArray(n.forgedTools)?n.forgedTools:[];for(let s of o){let o=s,c=String(o.name||``);if(!c||c===`unnamed`)continue;let l=typeof o.firstForgedDepartment==`string`?String(o.firstForgedDepartment):a.get(c),u=typeof o.firstForgedTurn==`number`?o.firstForgedTurn:void 0,d=Number(e.turn??n.turn??0);(l&&u!==void 0&&u<d||l&&l!==i)&&t[r].reuses.push({turn:d,originDept:l,callingDept:i,name:c})}}}return t},[e]);ZO({enabled:B.sound,snapshotA:d[d.length-1],prevSnapshotA:d[d.length-2],snapshotB:f[f.length-1],prevSnapshotB:f[f.length-2],forgeAttemptsA:pt.a.attempts,forgeAttemptsB:pt.b.attempts});let mt=(0,b.useMemo)(()=>{let t=new Map;for(let n of e.actorIds){let r=e.actors[n];if(r)for(let e of r.events){if(e.type!==`agent_reactions`)continue;let n=e.data?.reactions||[];for(let e of n){let n=e.hexaco;if(!n)continue;let r=e.agentId||e.name;r&&t.set(r,n)}}}return t},[e]),ht=(0,b.useCallback)(e=>{t?.(e)},[t]),gt=jy(My),_t=jy(Ny),vt=jy(Py),[yt,bt]=(0,b.useState)(null),xt=Ye?.name??`Leader A`,St=Xe?.name??`Leader B`,Ct=(0,b.useMemo)(()=>bk(d[y]?vk(d[y],d[y-1]):null,f[y]?vk(f[y],f[y-1]):null,y+1,{nameA:xt,nameB:St,person:ae.person,people:ae.people,places:ae.places}),[d,f,y,xt,St,ae.person,ae.people,ae.places]),wt=(0,b.useMemo)(()=>I.departments.map(e=>({id:e.id,label:e.label,color:wk[e.id]??`#a89878`})),[I.departments]),Tt=(0,b.useMemo)(()=>Object.fromEntries(I.departments.map(e=>[e.id,e.label])),[I.departments]),[Et,Dt]=(0,b.useState)(()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`paracosm:vizDiffOverlay`)===`1`}catch{return!1}}),Ot=(0,b.useCallback)(e=>{Dt(e);try{window.localStorage.setItem(`paracosm:vizDiffOverlay`,e?`1`:`0`)}catch{}},[]);(0,b.useEffect)(()=>{let e=e=>{let t=e.target;t&&t.matches(`input, textarea, [contenteditable=true]`)||(e.key===`d`||e.key===`D`)&&(e.preventDefault(),Ot(!Et))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[Et,Ot]);let kt=(0,b.useMemo)(()=>Et?Sk(Ek(d[y]),Ek(f[y])):null,[Et,d,f,y]);if(v===0)return e.isRunning?(0,x.jsxs)(`div`,{className:`viz-content ${$.empty}`,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:$.emptySpinner,"aria-hidden":`true`}),(0,x.jsxs)(`span`,{children:[`Awaiting first turn snapshot — the `,ae.place,` viz will populate once the kernel reports state.`]})]}):typeof window<`u`&&new URLSearchParams(window.location.search).has(`replay`)?(0,x.jsxs)(`div`,{className:`viz-content ${$.empty}`,role:`status`,"aria-live":`polite`,children:[(0,x.jsx)(`span`,{className:$.emptySpinner,"aria-hidden":`true`}),(0,x.jsxs)(`span`,{children:[`Loading replay — the `,ae.place,` viz will populate as the cached events stream in.`]})]}):(0,x.jsxs)(`div`,{className:`viz-content ${$.empty}`,children:[`Run a simulation to see the `,ae.place,` visualization.`]});let At=Ve&&He?`A vs B: ${He.population-Ve.population>=0?`+`:``}${He.population-Ve.population} pop, ${He.morale-Ve.morale>=0?`+`:``}${Math.round((He.morale-Ve.morale)*100)}% morale${typeof Ve.foodReserve==`number`&&typeof He.foodReserve==`number`?`, ${He.foodReserve-Ve.foodReserve>0?`+`:``}${(He.foodReserve-Ve.foodReserve).toFixed(1)}mo food`:``}`:``,jt=_t?Re??`a`:Re,Mt=y>0?d[y-1]??d[d.length-2]:void 0,Nt=y>0?f[y-1]??f[f.length-2]:void 0,Pt=dt,Ft=(0,x.jsxs)(`button`,{type:`button`,onClick:()=>Ot(!Et),"aria-label":Et?`Hide A-vs-B diff overlay (D)`:`Show A-vs-B diff overlay (D)`,"aria-pressed":Et,title:`Highlight where Leader A and Leader B diverged this turn (press D)`,className:$.helpBtn,children:[`Diff `,Et?`on`:`off`]}),It=(0,x.jsx)(`button`,{type:`button`,onClick:()=>F(!0),"aria-label":`Open help overlay (shortcut: ?)`,title:`What do these colors / symbols / modes mean? (press ?)`,className:$.helpBtn,children:`? Help`}),Lt=_t,Rt=SO(e,y)!==``;return(0,x.jsxs)(`div`,{ref:Ze,className:`viz-content ${$.root}`,children:[h&&(0,x.jsxs)(`div`,{className:$.cohortViewBar,role:`region`,"aria-label":`Cohort view controls`,children:[(0,x.jsxs)(`div`,{className:$.cohortViewModeToggle,role:`tablist`,"aria-label":`Swarm grid view mode`,children:[(0,x.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":g===`cohort`,onClick:()=>_(`cohort`),className:[$.cohortViewModeButton,g===`cohort`?$.cohortViewModeButtonActive:``].filter(Boolean).join(` `),title:`Show every actor's living-swarm panel side-by-side with horizontal scroll`,children:[`All `,e.actorIds.length,` actors`]}),(0,x.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":g===`pair`,onClick:()=>_(`pair`),className:[$.cohortViewModeButton,g===`pair`?$.cohortViewModeButtonActive:``].filter(Boolean).join(` `),title:`Focus on a 2-actor head-to-head with the original pair-mode diff overlay + sympathy hover`,children:`Focus pair`})]}),g===`pair`&&(0,x.jsxs)(`div`,{className:$.cohortPairPicker,children:[(0,x.jsx)(`select`,{"aria-label":`Left panel actor`,className:$.cohortPairPickerSelect,value:l??``,onChange:e=>o(e.target.value||void 0),children:e.actorIds.map(t=>(0,x.jsx)(`option`,{value:t,disabled:t===u,children:e.actors[t]?.leader?.name??t},t))}),(0,x.jsx)(`span`,{className:$.cohortPairPickerVs,children:`vs`}),(0,x.jsx)(`select`,{"aria-label":`Right panel actor`,className:$.cohortPairPickerSelect,value:u??``,onChange:e=>c(e.target.value||void 0),children:e.actorIds.map(t=>(0,x.jsx)(`option`,{value:t,disabled:t===l,children:e.actors[t]?.leader?.name??t},t))})]})]}),(0,x.jsx)(wO,{state:e,currentTurn:y,linesTarget:Lt?yt:null,cohortGridShown:g===`cohort`}),(0,x.jsx)(uk,{text:Ct,turn:y+1}),(0,x.jsx)(fk,{departments:wt}),Et&&kt&&(0,x.jsx)(gk,{diff:kt,departmentLabels:Tt}),(0,x.jsxs)(`div`,{className:$.toolbarStrip,children:[(0,x.jsxs)(yC,{label:`toolbar keys`,rowClassName:$.toolbarTopRow,children:[(0,x.jsx)(`div`,{className:$.modePillsWrap,children:(0,x.jsx)(jO,{mode:D,onChange:k,counts:{forge:pt.a.attempts.filter(e=>e.approved).length+pt.b.attempts.filter(e=>e.approved).length,divergence:(ft.aliveOnlyA?.size??0)+(ft.aliveOnlyB?.size??0)},labels:ae})}),D===`forge`&&(0,x.jsx)(`button`,{type:`button`,"aria-haspopup":`dialog`,onClick:e=>Fe.openToolbox(e.currentTarget,`viz`),className:$.forgeToolboxKey,children:Qv(Ie.list.length)}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>Pe(e=>!e),"aria-label":Ne?vt?`Hide more tools`:`Hide advanced tools`:vt?`Show more tools (diff, help, palette, stats, export, settings)`:`Show advanced tools (palette, stats, export, settings)`,"aria-expanded":Ne,title:Ne?`Hide tools`:vt?`Diff · Help · Palette · Stats · Export · Settings`:`Palette · Stats · Export · Settings`,className:[$.overflowToggle,Ne?$.overflowToggleOpen:``].filter(Boolean).join(` `),children:`⋯`}),!vt&&Ft,!vt&&It]}),Ne&&(0,x.jsxs)(yC,{label:`Viz tools`,role:`toolbar`,ariaLabel:`Viz tools`,rowClassName:$.toolsRow,children:[vt&&Ft,vt&&It,(0,x.jsx)(`button`,{type:`button`,onClick:Oe,"aria-label":`Palette: ${Te}. Click to cycle.`,title:`Palette: ${Te.toUpperCase()} (click to cycle)`,className:$.paletteBtn,style:{"--palette-bg":Te===`amber`?`linear-gradient(135deg, #e8b44a 0 40%, #c44a1e 100%)`:Te===`cool`?`linear-gradient(135deg, #4ecdc4 0 40%, #9b6bd8 100%)`:`linear-gradient(135deg, #f5f0e4 0 40%, #6b5f50 100%)`},children:Te}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>Me(!0),"aria-label":`Open run summary`,title:`Run summary (cumulative totals)`,className:$.toolBtn,children:`STATS`}),(0,x.jsx)(sk,{recording:Qe,onExportPng:st,onExportJson:ot,onToggleRecording:Qe?at:it}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>Ae(e=>!e),"aria-label":`Open grid settings`,"aria-expanded":ke,title:`Viz settings`,className:[$.settingsBtn,ke?$.settingsBtnOpen:``].filter(Boolean).join(` `),children:`⚙`})]}),(0,x.jsx)(`div`,{className:$.modeHint,children:AO(D,ae)}),D===`ecology`&&!e.actorIds.some(e=>{let t=n[e]??[];return Ok(t[y]??t[t.length-1])})&&(0,x.jsxs)(`div`,{role:`status`,className:$.ecologyNone,children:[(0,x.jsx)(`span`,{children:`ECOLOGY draws food, water, power and pressurized volume. This run holds none of them.`}),(0,x.jsx)(`button`,{type:`button`,onClick:()=>k(`living`),className:$.ecologyBack,children:`Back to LIVING`})]})]}),(0,x.jsx)(JO,{value:me,onChange:he,matches:Pt,onPick:e=>{he(e.cell.name)}}),(0,x.jsx)(KO,{eventsA:p?.events??[],eventsB:m?.events??[],totalDepartments:I.departments.length}),(0,x.jsx)(UO,{eventsA:p?.events??[],eventsB:m?.events??[],currentTurn:y,onJumpToTurn:ne,hoveredTurn:ue,onHoverTurnChange:de,filter:fe,onFilterChange:R,onHoverEventChange:pe,onJumpToReports:re,onForgeSelect:Le}),(0,x.jsx)(RO,{snapsA:d,snapsB:f,currentTurn:y,onJumpToTurn:ne,hoveredTurn:ue,onHoverTurnChange:de}),g===`pair`&&At&&(0,x.jsx)(`div`,{className:$.diffLine,children:At}),g===`pair`&&_t&&(0,x.jsx)(`div`,{role:`tablist`,"aria-label":`Leader panel selector`,className:$.phoneTabRow,children:[`a`,`b`].map(e=>{let t=e===`a`?Ye?.name??`Leader A`:Xe?.name??`Leader B`,n=e===`a`?`var(--vis)`:`var(--eng)`,r=jt===e;return(0,x.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":r,onClick:()=>ze(e),className:[$.phoneTab,r?$.phoneTabActive:``].filter(Boolean).join(` `),style:r?{"--tab-color":n}:void 0,children:t},e)})}),g===`cohort`&&(0,x.jsxs)(`div`,{className:[$.cohortWindow,Lt?$.cohortWindowLinesBelow:``].filter(Boolean).join(` `),children:[(0,x.jsx)(vO,{className:Lt?$.cohortTrackLinesBelow:void 0,state:e,snapshotMap:n,currentTurn:y,gridMode:D,palette:Te===`cool`?1:Te===`mono`?2:0,gridSettings:B,hexacoById:mt,searchQuery:me,chronicleFilter:fe,chronicleHover:z,startTime:I.setup?.defaultStartTime,onOpenChat:ht}),Lt&&(0,x.jsx)(`section`,{ref:bt,role:`status`,"aria-label":`Turn outcomes`,className:$.turnLinesSlot})]}),g===`pair`&&(0,x.jsxs)(`div`,{className:[`leaders-row`,$.leadersRow,gt?$.leadersRowNarrow:``,Lt?$.leadersRowLinesBelow:``].filter(Boolean).join(` `),children:[(0,x.jsx)(`div`,{className:[$.sideWrap,jt===`b`?$.sideWrapHidden:``].filter(Boolean).join(` `),children:(0,x.jsx)(mO,{snapshot:Ve,previousSnapshot:Mt,snapshotHistory:d,actorName:Ye?.name??`Leader A`,actorArchetype:Ye?.archetype??``,leaderUnit:Ye?.unit??``,sideColor:`var(--vis)`,side:`a`,lagTurns:Ue<We?We-Ue:0,mode:D,hexacoById:mt,leaderHexaco:Ye?.hexaco?{O:Ye.hexaco.O??Ye.hexaco.openness??.5,C:Ye.hexaco.C??Ye.hexaco.conscientiousness??.5,E:Ye.hexaco.E??Ye.hexaco.extraversion??.5,A:Ye.hexaco.A??Ye.hexaco.agreeableness??.5,Em:Ye.hexaco.Em??Ye.hexaco.emotionality??.5,HH:Ye.hexaco.HH??Ye.hexaco.honestyHumility??.5}:void 0,forgeAttempts:pt.a.attempts,reuseCalls:pt.a.reuses,divergedIds:ft.aliveOnlyA,siblingHoveredId:le,onHoverChange:ce,searchQuery:me,palette:Te===`cool`?1:Te===`mono`?2:0,settings:B,startTime:I.setup?.defaultStartTime,focusedSide:jt,onToggleFocus:_t?void 0:Be,onOpenChat:ht,eventFilter:fe,chronicleHover:z})}),(0,x.jsx)(`div`,{className:[$.sideWrap,jt===`a`?$.sideWrapHidden:``].filter(Boolean).join(` `),children:(0,x.jsx)(mO,{snapshot:He,previousSnapshot:Nt,snapshotHistory:f,actorName:Xe?.name??`Leader B`,actorArchetype:Xe?.archetype??``,leaderUnit:Xe?.unit??``,sideColor:`var(--eng)`,side:`b`,lagTurns:We<Ue?Ue-We:0,mode:D,hexacoById:mt,leaderHexaco:Xe?.hexaco?{O:Xe.hexaco.O??Xe.hexaco.openness??.5,C:Xe.hexaco.C??Xe.hexaco.conscientiousness??.5,E:Xe.hexaco.E??Xe.hexaco.extraversion??.5,A:Xe.hexaco.A??Xe.hexaco.agreeableness??.5,Em:Xe.hexaco.Em??Xe.hexaco.emotionality??.5,HH:Xe.hexaco.HH??Xe.hexaco.honestyHumility??.5}:void 0,forgeAttempts:pt.b.attempts,reuseCalls:pt.b.reuses,divergedIds:ft.aliveOnlyB,siblingHoveredId:oe,onHoverChange:L,searchQuery:me,palette:Te===`cool`?1:Te===`mono`?2:0,settings:B,startTime:I.setup?.defaultStartTime,focusedSide:jt,onToggleFocus:_t?void 0:Be,onOpenChat:ht,eventFilter:fe,chronicleHover:z})}),Lt&&(0,x.jsx)(`section`,{ref:bt,role:`status`,"aria-label":`Turn outcomes`,className:$.turnLinesSlot})]}),(0,x.jsx)(DO,{currentTurn:y,maxTurn:v,time:Ve?.time??He?.time??0,timeInBanner:Rt,playing:C,speed:T,onTurnChange:ne,onPlayPause:te,onStepBack:M,onStepForward:N,onSpeedChange:E}),(0,x.jsxs)(`div`,{className:$.footerKeys,children:[(0,x.jsx)(Dk,{k:`?`,v:`help`}),(0,x.jsx)(Dk,{k:`1-5`,v:`mode`}),(0,x.jsx)(Dk,{k:`← →`,v:`scrub turn`}),(0,x.jsx)(Dk,{k:`space`,v:`play / pause`}),(0,x.jsx)(Dk,{k:`click`,v:`${ae.person} drilldown`}),(0,x.jsx)(Dk,{k:`esc`,v:`close popover`})]}),(0,x.jsx)(`div`,{"aria-live":`polite`,"aria-atomic":`true`,className:$.srOnly,children:Ve&&He?`Turn ${Math.max(Ve.turn,He.turn)}. ${Ye?.name??`A`} ${ae.place}: ${Ve.cells.filter(e=>e.alive).length} alive, ${Ve.births} born, ${Ve.deaths} died, morale ${Math.round(Ve.morale*100)}%. ${Xe?.name??`B`} ${ae.place}: ${He.cells.filter(e=>e.alive).length} alive, ${He.births} born, ${He.deaths} died, morale ${Math.round(He.morale*100)}%.`:``}),v>1&&y<v-1&&(0,x.jsxs)(`button`,{type:`button`,onClick:()=>ne(v-1),"aria-label":`Jump to latest turn (T${v})`,className:$.jumpLatest,children:[`↓`,` Latest · T`,v,(0,x.jsxs)(`span`,{className:$.jumpLatestBehind,children:[`(`,v-1-y,` turn`,v-1-y==1?``:`s`,` behind)`]})]}),(0,x.jsx)(NO,{open:ie,onClose:()=>F(!1)}),(0,x.jsx)(iO,{open:ke,settings:B,onChange:ye,onClose:()=>Ae(!1)}),(0,x.jsx)(ek,{open:je,onClose:()=>Me(!1),snapsA:d,snapsB:f,actorNameA:Ye?.name??`Leader A`,actorNameB:Xe?.name??`Leader B`,forgeApprovedA:pt.a.attempts.filter(e=>e.approved).length,forgeApprovedB:pt.b.attempts.filter(e=>e.approved).length,reuseCountA:pt.a.reuses.length,reuseCountB:pt.b.reuses.length,divergedCount:(ft.aliveOnlyA?.size??0)+(ft.aliveOnlyB?.size??0)}),be&&(0,x.jsxs)(`div`,{role:`status`,"aria-live":`assertive`,onClick:()=>xe(null),className:$.toast,style:{"--toast-top":ge?`68px`:`8px`,"--side-color":be.side===`a`?`var(--vis)`:`var(--eng)`,"--left-accent":be.kind===`morale-crash`?`var(--rust)`:`var(--amber)`},title:`Click to dismiss`,children:[(0,x.jsxs)(`div`,{className:$.toastKicker,style:{"--kicker-color":be.kind===`morale-crash`?`var(--rust)`:`var(--amber)`},children:[(0,x.jsx)(`span`,{children:be.kind===`morale-crash`?`▼ Alert`:`⚠ Alert`}),(0,x.jsxs)(`span`,{className:$.toastKickerMeta,children:[be.side.toUpperCase(),` · T`,be.turn]})]}),(0,x.jsx)(`div`,{className:$.toastBody,children:be.message})]},be.key),ge&&(0,x.jsxs)(`div`,{role:`status`,"aria-live":`polite`,onClick:()=>_e(null),className:$.toast,style:{"--side-color":ge.side===`a`?`var(--vis)`:`var(--eng)`,"--left-accent":`var(--rust)`},title:`Click to dismiss`,children:[(0,x.jsxs)(`div`,{className:$.toastKicker,children:[(0,x.jsx)(`span`,{children:`⚡ Crisis`}),(0,x.jsxs)(`span`,{className:$.toastKickerMeta,children:[ge.side.toUpperCase(),` · T`,ge.turn,` · `,ge.category]})]}),(0,x.jsx)(`div`,{className:$.toastBodyMd,children:ge.title||`${ge.category} crisis unfolding`})]},ge.key),ct>0&&(0,x.jsx)(`div`,{"aria-hidden":`true`,className:$.vignette},ct),(0,x.jsx)(`style`,{children:`
129
129
  @keyframes paracosm-vignette {
130
130
  0% { opacity: 0; }
131
131
  25% { opacity: 1; }
@@ -147,10 +147,10 @@ Example: 5: Supply drop: Relief arrives with 3 months of food.`,value:_,onChange
147
147
  0% { opacity: 0; transform: translateY(-6px); }
148
148
  100% { opacity: 1; transform: translateY(0); }
149
149
  }
150
- `})]})}var kk={footer:`_footer_c3dep_1`,phone:`_phone_c3dep_14`,nav:`_nav_c3dep_18`,navLink:`_navLink_c3dep_23`,consentSlot:`_consentSlot_c3dep_28`,statusChip:`_statusChip_c3dep_37`,cost:`_cost_c3dep_48`,costAmount:`_costAmount_c3dep_57`,costMuted:`_costMuted_c3dep_63`,brand:`_brand_c3dep_67`,brandAccent:`_brandAccent_c3dep_74`,brandLink:`_brandLink_c3dep_78`};function Ak(e){switch(e){case`client_disconnected`:return`browser tab closed before the sim finished`;case`quota_exhausted`:return`provider credits exhausted`;case`user_aborted`:return`cancelled by the user`;case`provider_error`:return`provider returned an unrecoverable error`;case`another_run_started`:return`you started another run`;case`server_restarted`:return`the server restarted before the run finished`;case`unknown`:return`reason not recorded by the server`;default:return e}}function jk({s:e}){let t=e.isAborted?`var(--amber)`:e.isComplete?`var(--green)`:e.isRunning?`var(--color-success, var(--green))`:(e.connectionStatus,`var(--text-3)`),n=e.isAborted?`Interrupted`:e.isComplete?`Complete`:e.isRunning?`Running`:e.connectionStatus===`connected`?`Idle`:e.connectionStatus===`error`?`Reconnecting`:`Connecting`,r=e.isRunning&&!e.isComplete&&!e.isAborted?`●`:`○`,i=e.isAborted?(()=>{if(e.providerError)return`Run interrupted: ${e.providerError.message}. Click Clear to reset.`;let t=e.abortReason;if(!t)return`Run was interrupted before finishing all turns. Click Clear to reset.`;let n=typeof t.completedTurns==`number`?` after ${t.completedTurns} turn${t.completedTurns===1?``:`s`}`:``;return`Run interrupted: ${Ak(t.reason)}${n}. Click Clear to reset.`})():e.isComplete?`Run finished all turns. Verdict is broadcast in Reports.`:e.isRunning?`Simulation in progress.`:e.connectionStatus===`connected`?`Connected to the simulation server. Press RUN to start.`:e.connectionStatus===`error`?`Reconnecting to the simulation server.`:`Connecting to the simulation server.`;return(0,x.jsxs)(`span`,{className:kk.statusChip,style:{"--status-color":t},role:`status`,"aria-live":`polite`,"aria-label":`Simulation status: ${n}. ${i}`,title:i,children:[r,` `,n]})}function Mk(e){return e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Nk(e,t){let n=[`Total: ${Mk(e.totalCostUSD)} · ${e.totalTokens.toLocaleString()} tokens · ${e.llmCalls} calls`];if(t){let e=t.simUSD??0,r=t.chatUSD??0;e>0&&n.push(`• Simulation: ${Mk(e)}${t.simCalls==null?``:` (${t.simCalls} calls)`}`),r>0&&n.push(`• Chat: ${Mk(r)}${t.chatCalls==null?``:` (${t.chatCalls} calls)`}`)}return n.join(`
151
- `)}function Pk(){return typeof document<`u`&&document.getElementById(`paracosm-consent-config`)!==null}function Fk(){let e=(0,b.useRef)(null);return(0,b.useEffect)(()=>{let t=document.getElementById(`pcc-reopen`),n=document.getElementById(`pcc-shell`),r=e.current;if(t&&n&&r)return r.appendChild(t),()=>{n.appendChild(t)}},[]),e}function Ik({cost:e,costBreakdown:t,simStatus:n}){let r=jy(Ny),i=Pk(),a=Fk(),o=[`shrink-0`,kk.footer,r?kk.phone:``].filter(Boolean).join(` `);return(0,x.jsxs)(`footer`,{className:o,role:`contentinfo`,children:[!r&&(0,x.jsxs)(`nav`,{"aria-label":`Footer links`,className:kk.nav,children:[(0,x.jsx)(`a`,{href:`https://agentos.sh/en`,target:`_blank`,rel:`noopener`,className:kk.navLink,children:`agentos.sh`}),(0,x.jsx)(`a`,{href:`https://github.com/framerslab/paracosm`,target:`_blank`,rel:`noopener`,className:kk.navLink,children:`github`}),(0,x.jsx)(`a`,{href:`https://www.npmjs.com/package/paracosm`,target:`_blank`,rel:`noopener`,className:kk.navLink,children:`npm`}),(0,x.jsx)(`a`,{href:`/docs`,className:kk.navLink,children:`docs`}),(0,x.jsx)(`a`,{href:`https://agentos.sh/blog`,target:`_blank`,rel:`noopener`,className:kk.navLink,children:`blog`})]}),n&&(0,x.jsx)(jk,{s:n}),e&&(e.totalTokens>0||e.llmCalls>0)&&(0,x.jsxs)(`span`,{className:kk.cost,title:Nk(e,t),children:[(0,x.jsxs)(`span`,{className:kk.costAmount,children:[`$`,e.totalCostUSD<.01?e.totalCostUSD.toFixed(4):e.totalCostUSD.toFixed(2)]}),(0,x.jsxs)(`span`,{className:kk.costMuted,children:[(e.totalTokens/1e3).toFixed(0),`k tokens`]}),e.llmCalls>0&&(0,x.jsxs)(`span`,{className:kk.costMuted,children:[e.llmCalls,` calls`]})]}),i&&(0,x.jsx)(`span`,{ref:a,className:kk.consentSlot}),!r&&(0,x.jsxs)(`span`,{children:[(0,x.jsxs)(`span`,{className:kk.brand,children:[`PARA`,(0,x.jsx)(`span`,{className:kk.brandAccent,children:`COSM`})]}),` `,`· Apache-2.0 · `,(0,x.jsx)(`a`,{href:`https://frame.dev`,target:`_blank`,rel:`noopener`,className:kk.brandLink,children:`Frame.dev`})]})]})}var Lk={backdrop:`_backdrop_1do5l_1`,dialog:`_dialog_1do5l_12`,header:`_header_1do5l_26`,title:`_title_1do5l_33`,closeBtn:`_closeBtn_1do5l_43`,section:`_section_1do5l_53`,scopeTitle:`_scopeTitle_1do5l_57`,list:`_list_1do5l_67`,row:`_row_1do5l_73`,keys:`_keys_1do5l_82`,kbd:`_kbd_1do5l_88`,description:`_description_1do5l_102`,footer:`_footer_1do5l_107`,kbdInline:`_kbdInline_1do5l_117`},Rk=[{keys:[`?`],description:`Open this shortcuts overlay`,scope:`Global`},{keys:[`Esc`],description:`Close overlays / drilldown panel`,scope:`Global`},{keys:[`←`],description:`Previous turn`,scope:`Visualization`},{keys:[`→`],description:`Next turn`,scope:`Visualization`},{keys:[`Space`],description:`Play / pause playback`,scope:`Visualization`},{keys:[`M`],description:`Cycle cluster mode (families · departments · mood · age)`,scope:`Visualization`},{keys:[`D`],description:`Toggle divergence tint overlay`,scope:`Visualization`},{keys:[`A`],description:`Collapse / expand the automaton band`,scope:`Visualization`},{keys:[`1`],description:`Automaton: mood propagation`,scope:`Visualization`},{keys:[`2`],description:`Automaton: forge flow`,scope:`Visualization`},{keys:[`3`],description:`Automaton: ecology grid`,scope:`Visualization`},{keys:[`Enter`],description:`Send chat message`,scope:`Chat`}];function zk(){let[e,t]=(0,b.useState)(!1);return(0,b.useEffect)(()=>{let n=n=>{let r=n.target?.tagName,i=r===`INPUT`||r===`TEXTAREA`||r===`SELECT`||n.target?.isContentEditable;n.key===`?`&&!n.metaKey&&!n.ctrlKey&&!i?(n.preventDefault(),t(e=>!e)):n.key===`Escape`&&e&&(n.preventDefault(),t(!1))};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[e]),e?(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Keyboard shortcuts`,onClick:()=>t(!1),className:Lk.backdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:Lk.dialog,children:[(0,x.jsxs)(`div`,{className:Lk.header,children:[(0,x.jsx)(`h2`,{className:Lk.title,children:`Keyboard Shortcuts`}),(0,x.jsx)(`button`,{onClick:()=>t(!1),"aria-label":`Close shortcuts`,className:Lk.closeBtn,children:`×`})]}),[`Global`,`Visualization`,`Chat`].map(e=>{let t=Rk.filter(t=>t.scope===e);return t.length===0?null:(0,x.jsxs)(`section`,{className:Lk.section,children:[(0,x.jsx)(`h3`,{className:Lk.scopeTitle,children:e}),(0,x.jsx)(`ul`,{className:Lk.list,children:t.map(e=>(0,x.jsxs)(`li`,{className:Lk.row,children:[(0,x.jsx)(`span`,{className:Lk.keys,children:e.keys.map((e,t)=>(0,x.jsx)(`kbd`,{className:Lk.kbd,children:e},t))}),(0,x.jsx)(`span`,{className:Lk.description,children:e.description})]},e.keys.join(`+`)))})]},e)}),(0,x.jsxs)(`div`,{className:Lk.footer,children:[`press `,(0,x.jsx)(`kbd`,{className:Lk.kbdInline,children:`?`}),` anywhere · `,(0,x.jsx)(`kbd`,{className:Lk.kbdInline,children:`Esc`}),` to close`]})]})}):null}var Bk={svgOverlay:`_svgOverlay_aob9y_1`,svgFill:`_svgFill_aob9y_8`,clickAway:`_clickAway_aob9y_13`,card:`_card_aob9y_19`,mobile:`_mobile_aob9y_41`,cardHeader:`_cardHeader_aob9y_54`,stepCount:`_stepCount_aob9y_62`,tabBadge:`_tabBadge_aob9y_69`,closeBtn:`_closeBtn_aob9y_82`,title:`_title_aob9y_93`,description:`_description_aob9y_105`,actions:`_actions_aob9y_116`,actionsRight:`_actionsRight_aob9y_124`,skipBtn:`_skipBtn_aob9y_129`,compact:`_compact_aob9y_141`,navBtn:`_navBtn_aob9y_146`,primaryBtn:`_primaryBtn_aob9y_163`,final:`_final_aob9y_180`,progressBar:`_progressBar_aob9y_185`,progressBarFill:`_progressBarFill_aob9y_193`,dotRow:`_dotRow_aob9y_200`,dot:`_dot_aob9y_200`,kbHint:`_kbHint_aob9y_219`},Vk=[{target:`[data-quickstart-seed]`,tab:`quickstart`,title:`Quickstart — author from a brief`,description:`Paste a brief, drop a PDF, or supply a URL. Paracosm grounds the prompt with web research, generates three distinct actors with HEXACO personalities, and runs them against the same scenario in parallel. The Twin demo card below runs a single subject against a single intervention if that's your use case.`},{target:`[role="tablist"][aria-label="Studio sub-navigation"]`,tab:`studio`,title:`Studio — author + branches`,description:`Drop any saved Paracosm artifact or bundle here to inspect, fork, and re-run. The Branches sub-tab forks an actor at any turn N and re-runs from that checkpoint with a new HEXACO profile, so you can probe alternate histories from a shared starting state.`},{target:`.topbar`,tab:`sim`,title:`Top Bar`,description:`Scenario name on the left. RUN, status, theme toggle, and HOW IT WORKS (replay this tour) on the right. The T / Y / S tokens in the center show turn, in-sim time, and deterministic seed — hover each for what they mean. A "⋯" menu reveals Save / Copy / Clear once a run has started.`},{target:`.tab-bar`,tab:`sim`,title:`Navigation`,description:`Quickstart and Studio for authoring. Sim, Viz, Chat for the live run. Reports and Library for analysis. Settings holds config (Event Log lives there as a sub-tab). Labels collapse to icons below 900px so the row never wraps onto two lines.`},{target:`[role="group"][aria-label="Sim layout"]`,tab:`sim`,title:`Sim layout`,description:`Side-by-side for 2 actors, Constellation for 3+. Constellation auto-engages above 3 actors because two columns physically can't fit them. Click any node in the Constellation graph to drill into one actor's decisions, departments, and tools. The tour pins side-by-side so you can see leader cards and event streams as they'd render for a 2-actor run.`},{target:`.leaders-row`,tab:`sim`,title:`Leader cards`,description:`Each actor renders with its name, archetype, HEXACO profile, and a population + morale sparkline. Left is amber, right is teal. Glyph color, Conway tiles, and chronicle pills downstream all pick up these same colors so you always know which side you're looking at.`},{target:`.sim-columns`,tab:`sim`,title:`Event streams`,description:`Each turn, both leaders face events the Director generated based on accumulated state. Departments analyze in parallel and may forge new tools. Commanders decide. Tools tint by side. INSPECT on a forged tool opens it on its line of five stations, and its Record holds Show in Event Log.`},{target:`[aria-label="Divergence rail"]`,tab:`sim`,title:`Divergence rail`,description:`How far the actors have diverged at the current turn. Shows decision texts and outcomes side by side in plain language. Same seed, different histories — because HEXACO shaped every LLM call.`},{target:`.viz-content`,tab:`viz`,title:`Viz — living canvas`,description:`Mirrored canvases, one per actor. Conway-style cellular tiles render underneath to encode mood (BLOCK = calm, GLIDER = agitated) while colonist glyphs sit on top as the primary signal. Hover a tile or a glyph for a tooltip; click either to drill into the colonist. Use the mode pills (LIVING / MOOD / FORGE / ECOLOGY / DIVERGENCE) and event filters above the canvas to reshape the read.`},{target:`.chat-layout`,tab:`chat`,title:`Character chat`,description:`Talk to any colonist from the run. Each carries their HEXACO profile, the memories they formed during the sim, and their relationships. The Viz drilldown popover has a direct Chat handoff that preselects the colonist here.`},{target:`.reports-content`,tab:`reports`,title:`Reports`,description:`Turn-by-turn rollup: commander decisions, department analyses, forged toolbox across both sides, agent reactions, verdict comparison. Each forged tool opens from its row, and its Record holds Show in Event Log for that tool's events.`},{target:`[role="group"][aria-label="View mode"]`,tab:`library`,title:`Library — saved runs`,description:`Every run you launch is saved here. Filter by scenario, leader configuration, or free-text search. Gallery view shows hero stats; Table view shows everything. Open any run to inspect, or promote it into Studio to fork a new branch.`},{target:`[role="tablist"][aria-label="Settings sub-navigation"]`,tab:`settings`,title:`Settings + event log`,description:`Configure actors with HEXACO sliders, pick a scenario, set turns and population, and drop in your own OpenAI or Anthropic key to bypass the hosted-demo caps. The Event Log sub-tab shows the raw SSE stream (status, turn_start, specialist_done, decision_made, outcome, reaction, forge_attempt) and is where a forged tool's Show in Event Log leads.`},{target:`.topbar`,tab:`sim`,title:`Ready to launch`,description:`That was demo data. Hit RUN in the top bar to launch a live simulation against the host caps, or paste your own API key in Settings for full-scope runs. When the run finishes, a "Run Complete" banner lands at the top with the verdict and a jump to the Reports tab.`}],Hk=360,Uk=`tour-highlight`,Wk=`
150
+ `})]})}var jk={footer:`_footer_c3dep_1`,phone:`_phone_c3dep_14`,nav:`_nav_c3dep_18`,navLink:`_navLink_c3dep_23`,consentSlot:`_consentSlot_c3dep_28`,statusChip:`_statusChip_c3dep_37`,cost:`_cost_c3dep_48`,costAmount:`_costAmount_c3dep_57`,costMuted:`_costMuted_c3dep_63`,brand:`_brand_c3dep_67`,brandAccent:`_brandAccent_c3dep_74`,brandLink:`_brandLink_c3dep_78`};function Mk(e){switch(e){case`client_disconnected`:return`browser tab closed before the sim finished`;case`quota_exhausted`:return`provider credits exhausted`;case`user_aborted`:return`cancelled by the user`;case`provider_error`:return`provider returned an unrecoverable error`;case`another_run_started`:return`you started another run`;case`server_restarted`:return`the server restarted before the run finished`;case`unknown`:return`reason not recorded by the server`;default:return e}}function Nk({s:e}){let t=e.isAborted?`var(--amber)`:e.isComplete?`var(--green)`:e.isRunning?`var(--color-success, var(--green))`:(e.connectionStatus,`var(--text-3)`),n=e.isAborted?`Interrupted`:e.isComplete?`Complete`:e.isRunning?`Running`:e.connectionStatus===`connected`?`Idle`:e.connectionStatus===`error`?`Reconnecting`:`Connecting`,r=e.isRunning&&!e.isComplete&&!e.isAborted?`●`:`○`,i=e.isAborted?(()=>{if(e.providerError)return`Run interrupted: ${e.providerError.message}. Click Clear to reset.`;let t=e.abortReason;if(!t)return`Run was interrupted before finishing all turns. Click Clear to reset.`;let n=typeof t.completedTurns==`number`?` after ${t.completedTurns} turn${t.completedTurns===1?``:`s`}`:``;return`Run interrupted: ${Mk(t.reason)}${n}. Click Clear to reset.`})():e.isComplete?`Run finished all turns. Verdict is broadcast in Reports.`:e.isRunning?`Simulation in progress.`:e.connectionStatus===`connected`?`Connected to the simulation server. Press RUN to start.`:e.connectionStatus===`error`?`Reconnecting to the simulation server.`:`Connecting to the simulation server.`;return(0,x.jsxs)(`span`,{className:jk.statusChip,style:{"--status-color":t},role:`status`,"aria-live":`polite`,"aria-label":`Simulation status: ${n}. ${i}`,title:i,children:[r,` `,n]})}function Pk(e){return e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Fk(e,t){let n=[`Total: ${Pk(e.totalCostUSD)} · ${e.totalTokens.toLocaleString()} tokens · ${e.llmCalls} calls`];if(t){let e=t.simUSD??0,r=t.chatUSD??0;e>0&&n.push(`• Simulation: ${Pk(e)}${t.simCalls==null?``:` (${t.simCalls} calls)`}`),r>0&&n.push(`• Chat: ${Pk(r)}${t.chatCalls==null?``:` (${t.chatCalls} calls)`}`)}return n.join(`
151
+ `)}function Ik(){return typeof document<`u`&&document.getElementById(`paracosm-consent-config`)!==null}function Lk(){let e=(0,b.useRef)(null);return(0,b.useEffect)(()=>{let t=document.getElementById(`pcc-reopen`),n=document.getElementById(`pcc-shell`),r=e.current;if(t&&n&&r)return r.appendChild(t),()=>{n.appendChild(t)}},[]),e}function Rk({cost:e,costBreakdown:t,simStatus:n}){let r=jy(Ny),i=Ik(),a=Lk(),o=[`shrink-0`,jk.footer,r?jk.phone:``].filter(Boolean).join(` `);return(0,x.jsxs)(`footer`,{className:o,role:`contentinfo`,children:[!r&&(0,x.jsxs)(`nav`,{"aria-label":`Footer links`,className:jk.nav,children:[(0,x.jsx)(`a`,{href:`https://agentos.sh/en`,target:`_blank`,rel:`noopener`,className:jk.navLink,children:`agentos.sh`}),(0,x.jsx)(`a`,{href:`https://github.com/framerslab/paracosm`,target:`_blank`,rel:`noopener`,className:jk.navLink,children:`github`}),(0,x.jsx)(`a`,{href:`https://www.npmjs.com/package/paracosm`,target:`_blank`,rel:`noopener`,className:jk.navLink,children:`npm`}),(0,x.jsx)(`a`,{href:`/docs`,className:jk.navLink,children:`docs`}),(0,x.jsx)(`a`,{href:`https://agentos.sh/blog`,target:`_blank`,rel:`noopener`,className:jk.navLink,children:`blog`})]}),n&&(0,x.jsx)(Nk,{s:n}),e&&(e.totalTokens>0||e.llmCalls>0)&&(0,x.jsxs)(`span`,{className:jk.cost,title:Fk(e,t),children:[(0,x.jsxs)(`span`,{className:jk.costAmount,children:[`$`,e.totalCostUSD<.01?e.totalCostUSD.toFixed(4):e.totalCostUSD.toFixed(2)]}),(0,x.jsxs)(`span`,{className:jk.costMuted,children:[(e.totalTokens/1e3).toFixed(0),`k tokens`]}),e.llmCalls>0&&(0,x.jsxs)(`span`,{className:jk.costMuted,children:[e.llmCalls,` calls`]})]}),i&&(0,x.jsx)(`span`,{ref:a,className:jk.consentSlot}),!r&&(0,x.jsxs)(`span`,{children:[(0,x.jsxs)(`span`,{className:jk.brand,children:[`PARA`,(0,x.jsx)(`span`,{className:jk.brandAccent,children:`COSM`})]}),` `,`· Apache-2.0 · `,(0,x.jsx)(`a`,{href:`https://frame.dev`,target:`_blank`,rel:`noopener`,className:jk.brandLink,children:`Frame.dev`})]})]})}var zk={backdrop:`_backdrop_1do5l_1`,dialog:`_dialog_1do5l_12`,header:`_header_1do5l_26`,title:`_title_1do5l_33`,closeBtn:`_closeBtn_1do5l_43`,section:`_section_1do5l_53`,scopeTitle:`_scopeTitle_1do5l_57`,list:`_list_1do5l_67`,row:`_row_1do5l_73`,keys:`_keys_1do5l_82`,kbd:`_kbd_1do5l_88`,description:`_description_1do5l_102`,footer:`_footer_1do5l_107`,kbdInline:`_kbdInline_1do5l_117`},Bk=[{keys:[`?`],description:`Open this shortcuts overlay`,scope:`Global`},{keys:[`Esc`],description:`Close overlays / drilldown panel`,scope:`Global`},{keys:[`←`],description:`Previous turn`,scope:`Visualization`},{keys:[`→`],description:`Next turn`,scope:`Visualization`},{keys:[`Space`],description:`Play / pause playback`,scope:`Visualization`},{keys:[`M`],description:`Cycle cluster mode (families · departments · mood · age)`,scope:`Visualization`},{keys:[`D`],description:`Toggle divergence tint overlay`,scope:`Visualization`},{keys:[`A`],description:`Collapse / expand the automaton band`,scope:`Visualization`},{keys:[`1`],description:`Automaton: mood propagation`,scope:`Visualization`},{keys:[`2`],description:`Automaton: forge flow`,scope:`Visualization`},{keys:[`3`],description:`Automaton: ecology grid`,scope:`Visualization`},{keys:[`Enter`],description:`Send chat message`,scope:`Chat`}];function Vk(){let[e,t]=(0,b.useState)(!1);return(0,b.useEffect)(()=>{let n=n=>{let r=n.target?.tagName,i=r===`INPUT`||r===`TEXTAREA`||r===`SELECT`||n.target?.isContentEditable;n.key===`?`&&!n.metaKey&&!n.ctrlKey&&!i?(n.preventDefault(),t(e=>!e)):n.key===`Escape`&&e&&(n.preventDefault(),t(!1))};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[e]),e?(0,x.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Keyboard shortcuts`,onClick:()=>t(!1),className:zk.backdrop,children:(0,x.jsxs)(`div`,{onClick:e=>e.stopPropagation(),className:zk.dialog,children:[(0,x.jsxs)(`div`,{className:zk.header,children:[(0,x.jsx)(`h2`,{className:zk.title,children:`Keyboard Shortcuts`}),(0,x.jsx)(`button`,{onClick:()=>t(!1),"aria-label":`Close shortcuts`,className:zk.closeBtn,children:`×`})]}),[`Global`,`Visualization`,`Chat`].map(e=>{let t=Bk.filter(t=>t.scope===e);return t.length===0?null:(0,x.jsxs)(`section`,{className:zk.section,children:[(0,x.jsx)(`h3`,{className:zk.scopeTitle,children:e}),(0,x.jsx)(`ul`,{className:zk.list,children:t.map(e=>(0,x.jsxs)(`li`,{className:zk.row,children:[(0,x.jsx)(`span`,{className:zk.keys,children:e.keys.map((e,t)=>(0,x.jsx)(`kbd`,{className:zk.kbd,children:e},t))}),(0,x.jsx)(`span`,{className:zk.description,children:e.description})]},e.keys.join(`+`)))})]},e)}),(0,x.jsxs)(`div`,{className:zk.footer,children:[`press `,(0,x.jsx)(`kbd`,{className:zk.kbdInline,children:`?`}),` anywhere · `,(0,x.jsx)(`kbd`,{className:zk.kbdInline,children:`Esc`}),` to close`]})]})}):null}var Hk={svgOverlay:`_svgOverlay_aob9y_1`,svgFill:`_svgFill_aob9y_8`,clickAway:`_clickAway_aob9y_13`,card:`_card_aob9y_19`,mobile:`_mobile_aob9y_41`,cardHeader:`_cardHeader_aob9y_54`,stepCount:`_stepCount_aob9y_62`,tabBadge:`_tabBadge_aob9y_69`,closeBtn:`_closeBtn_aob9y_82`,title:`_title_aob9y_93`,description:`_description_aob9y_105`,actions:`_actions_aob9y_116`,actionsRight:`_actionsRight_aob9y_124`,skipBtn:`_skipBtn_aob9y_129`,compact:`_compact_aob9y_141`,navBtn:`_navBtn_aob9y_146`,primaryBtn:`_primaryBtn_aob9y_163`,final:`_final_aob9y_180`,progressBar:`_progressBar_aob9y_185`,progressBarFill:`_progressBarFill_aob9y_193`,dotRow:`_dotRow_aob9y_200`,dot:`_dot_aob9y_200`,kbHint:`_kbHint_aob9y_219`},Uk=[{target:`[data-quickstart-seed]`,tab:`quickstart`,title:`Quickstart — author from a brief`,description:`Paste a brief, drop a PDF, or supply a URL. Paracosm grounds the prompt with web research, generates three distinct actors with HEXACO personalities, and runs them against the same scenario in parallel. The Twin demo card below runs a single subject against a single intervention if that's your use case.`},{target:`[role="tablist"][aria-label="Studio sub-navigation"]`,tab:`studio`,title:`Studio — author + branches`,description:`Drop any saved Paracosm artifact or bundle here to inspect, fork, and re-run. The Branches sub-tab forks an actor at any turn N and re-runs from that checkpoint with a new HEXACO profile, so you can probe alternate histories from a shared starting state.`},{target:`.topbar`,tab:`sim`,title:`Top Bar`,description:`Scenario name on the left. RUN, status, theme toggle, and HOW IT WORKS (replay this tour) on the right. The T / Y / S tokens in the center show turn, in-sim time, and deterministic seed — hover each for what they mean. A "⋯" menu reveals Save / Copy / Clear once a run has started.`},{target:`.tab-bar`,tab:`sim`,title:`Navigation`,description:`Quickstart and Studio for authoring. Sim, Viz, Chat for the live run. Reports and Library for analysis. Settings holds config (Event Log lives there as a sub-tab). Labels collapse to icons below 900px so the row never wraps onto two lines.`},{target:`[role="group"][aria-label="Sim layout"]`,tab:`sim`,title:`Sim layout`,description:`Side-by-side for 2 actors, Constellation for 3+. Constellation auto-engages above 3 actors because two columns physically can't fit them. Click any node in the Constellation graph to drill into one actor's decisions, departments, and tools. The tour pins side-by-side so you can see leader cards and event streams as they'd render for a 2-actor run.`},{target:`.leaders-row`,tab:`sim`,title:`Leader cards`,description:`Each actor renders with its name, archetype, HEXACO profile, and a population + morale sparkline. Left is amber, right is teal. Glyph color, Conway tiles, and chronicle pills downstream all pick up these same colors so you always know which side you're looking at.`},{target:`.sim-columns`,tab:`sim`,title:`Event streams`,description:`Each turn, both leaders face events the Director generated based on accumulated state. Departments analyze in parallel and may forge new tools. Commanders decide. Tools tint by side. INSPECT on a forged tool opens it on its line of five stations, and its Record holds Show in Event Log.`},{target:`[aria-label="Divergence rail"]`,tab:`sim`,title:`Divergence rail`,description:`How far the actors have diverged at the current turn. Shows decision texts and outcomes side by side in plain language. Same seed, different histories — because HEXACO shaped every LLM call.`},{target:`.viz-content`,tab:`viz`,title:`Viz — living canvas`,description:`Mirrored canvases, one per actor. Conway-style cellular tiles render underneath to encode mood (BLOCK = calm, GLIDER = agitated) while colonist glyphs sit on top as the primary signal. Hover a tile or a glyph for a tooltip; click either to drill into the colonist. Use the mode pills (LIVING / MOOD / FORGE / ECOLOGY / DIVERGENCE) and event filters above the canvas to reshape the read.`},{target:`.chat-layout`,tab:`chat`,title:`Character chat`,description:`Talk to any colonist from the run. Each carries their HEXACO profile, the memories they formed during the sim, and their relationships. The Viz drilldown popover has a direct Chat handoff that preselects the colonist here.`},{target:`.reports-content`,tab:`reports`,title:`Reports`,description:`Turn-by-turn rollup: commander decisions, department analyses, forged toolbox across both sides, agent reactions, verdict comparison. Each forged tool opens from its row, and its Record holds Show in Event Log for that tool's events.`},{target:`[role="group"][aria-label="View mode"]`,tab:`library`,title:`Library — saved runs`,description:`Every run you launch is saved here. Filter by scenario, leader configuration, or free-text search. Gallery view shows hero stats; Table view shows everything. Open any run to inspect, or promote it into Studio to fork a new branch.`},{target:`[role="tablist"][aria-label="Settings sub-navigation"]`,tab:`settings`,title:`Settings + event log`,description:`Configure actors with HEXACO sliders, pick a scenario, set turns and population, and drop in your own OpenAI or Anthropic key to bypass the hosted-demo caps. The Event Log sub-tab shows the raw SSE stream (status, turn_start, specialist_done, decision_made, outcome, reaction, forge_attempt) and is where a forged tool's Show in Event Log leads.`},{target:`.topbar`,tab:`sim`,title:`Ready to launch`,description:`That was demo data. Hit RUN in the top bar to launch a live simulation against the host caps, or paste your own API key in Settings for full-scope runs. When the run finishes, a "Run Complete" banner lands at the top with the verdict and a jump to the Reports tab.`}],Wk=360,Gk=`tour-highlight`,Kk=`
152
152
  /* The highlighted element gets a bright luminous amber glow */
153
- .${Uk} {
153
+ .${Gk} {
154
154
  outline: 3px solid var(--amber) !important;
155
155
  outline-offset: 8px !important;
156
156
  box-shadow:
@@ -173,7 +173,7 @@ Example: 5: Supply drop: Relief arrives with 3 months of food.`,value:_,onChange
173
173
  box-shadow: 0 0 30px rgba(232,180,74,.9), 0 0 70px rgba(232,180,74,.55), 0 0 120px rgba(232,180,74,.3), inset 0 0 40px rgba(232,180,74,.12);
174
174
  }
175
175
  }
176
- `;function Gk({activeTab:e,chatEnabled:t=!0,onTabChange:n,onClose:r,onRun:i}){let a=(0,b.useMemo)(()=>t?Vk:Vk.filter(e=>e.tab!==`chat`),[t]),[o,s]=(0,b.useState)(0),[c,l]=(0,b.useState)(null),[u,d]=(0,b.useState)(()=>typeof window>`u`?1024:window.innerWidth),f=(0,b.useRef)(null),p=(0,b.useRef)(null),m=(0,b.useRef)(0),h=a[o];(0,b.useEffect)(()=>{let e=document.createElement(`style`);return e.textContent=Wk,document.head.appendChild(e),p.current=e,()=>{e.remove(),document.querySelector(`.${Uk}`)?.classList.remove(Uk)}},[]),(0,b.useEffect)(()=>{let e=a[o];e&&n(e.tab)},[o,n,a]),(0,b.useEffect)(()=>{let t=a[o];if(!t||t.tab===e)return;let n=setTimeout(()=>{a[o]?.tab!==e&&r()},200);return()=>clearTimeout(n)},[e,o,a,r]);let g=(0,b.useRef)(null),_=(0,b.useCallback)(()=>{let e=a[o];e&&(g.current?.(),f.current&&=(f.current.classList.remove(Uk),null),l(null),cancelAnimationFrame(m.current),m.current=requestAnimationFrame(()=>{let t=!1,n,r,i=e=>{if(t)return;t=!0,n!==void 0&&clearTimeout(n),r?.disconnect(),f.current&&f.current!==e&&f.current.classList.remove(Uk),e.classList.add(Uk),f.current=e;let i=e.getBoundingClientRect();l({top:i.top,left:i.left,width:i.width,height:i.height}),(i.top<0||i.bottom>window.innerHeight)&&e.scrollIntoView({behavior:`smooth`,block:`nearest`})},a=0,o=()=>{if(t)return;let s=document.querySelector(e.target);s?i(s):++a<30?n=window.setTimeout(o,100):t||(t=!0,r?.disconnect(),f.current&&=(f.current.classList.remove(Uk),null),l(null))};r=new MutationObserver(()=>{if(t)return;let n=document.querySelector(e.target);n&&i(n)}),r.observe(document.body,{childList:!0,subtree:!0}),o(),g.current=()=>{t=!0,n!==void 0&&clearTimeout(n),r?.disconnect()}}))},[o,a]);(0,b.useEffect)(()=>{_();let e=0,t=()=>{cancelAnimationFrame(e),e=requestAnimationFrame(()=>{d(window.innerWidth),_()})};return window.addEventListener(`resize`,t),()=>{window.removeEventListener(`resize`,t),cancelAnimationFrame(e),cancelAnimationFrame(m.current)}},[_,e]);let v=(0,b.useCallback)(()=>{f.current&&=(f.current.classList.remove(Uk),null),r()},[r]);if((0,b.useEffect)(()=>{let e=e=>{e.key===`Escape`?v():e.key===`ArrowRight`||e.key===`Enter`?o<a.length-1?s(e=>e+1):v():e.key===`ArrowLeft`&&o>0&&s(e=>e-1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o,v,a.length]),!h)return null;let y=u,S=typeof window>`u`?768:window.innerHeight,C=y<640,w={};if(!C&&c){let e=S-(c.top+c.height+10),t=c.top-10,n=y-(c.left+c.width+10);e>=320?(w[`--card-top`]=`${c.top+c.height+16}px`,w[`--card-left`]=`${Math.max(16,Math.min(c.left,y-Hk-16))}px`):t>=320?(w[`--card-bottom`]=`${S-c.top+16}px`,w[`--card-left`]=`${Math.max(16,Math.min(c.left,y-Hk-16))}px`):n>=384?(w[`--card-left`]=`${c.left+c.width+16}px`,w[`--card-top`]=`${Math.max(16,Math.min(c.top,S-320-16))}px`):(w[`--card-bottom`]=`24px`,w[`--card-right`]=`24px`)}else C||(w[`--card-bottom`]=`24px`,w[`--card-right`]=`24px`);let T=[Bk.card,C?Bk.mobile:``].filter(Boolean).join(` `);return(0,x.jsx)(x.Fragment,{children:(0,x.jsxs)(`div`,{"data-tour-overlay":!0,className:T,style:w,onClick:e=>e.stopPropagation(),role:`dialog`,"aria-label":`Guided tour`,children:[(0,x.jsxs)(`div`,{className:Bk.cardHeader,children:[(0,x.jsxs)(`span`,{className:Bk.stepCount,children:[o+1,` / `,a.length]}),(0,x.jsx)(`span`,{"aria-label":`Active tab: ${h.tab}`,className:Bk.tabBadge,children:h.tab}),(0,x.jsx)(`button`,{onClick:v,className:Bk.closeBtn,"aria-label":`Close tour`,children:`×`})]}),(0,x.jsx)(`h3`,{className:[Bk.title,C?Bk.mobile:``].filter(Boolean).join(` `),children:h.title}),(0,x.jsx)(`p`,{className:[Bk.description,C?Bk.mobile:``].filter(Boolean).join(` `),children:h.description}),(0,x.jsxs)(`div`,{className:Bk.actions,children:[(0,x.jsx)(`button`,{onClick:v,className:[Bk.skipBtn,C?Bk.compact:``].filter(Boolean).join(` `),children:`Skip`}),(0,x.jsxs)(`div`,{className:Bk.actionsRight,children:[o>0&&(0,x.jsx)(`button`,{onClick:()=>s(e=>e-1),className:[Bk.navBtn,C?Bk.compact:``].filter(Boolean).join(` `),children:`Back`}),(0,x.jsx)(`button`,{onClick:()=>{o<a.length-1?s(e=>e+1):(v(),i?.())},className:[Bk.primaryBtn,C?Bk.compact:``,!C&&o===a.length-1?Bk.final:``].filter(Boolean).join(` `),children:o<a.length-1?`Next`:C?`Start →`:`Start Your Simulation`})]})]}),C?(0,x.jsx)(`div`,{className:Bk.progressBar,children:(0,x.jsx)(`div`,{className:Bk.progressBarFill,style:{"--progress-pct":`${(o+1)/a.length*100}%`},role:`progressbar`,"aria-valuenow":o+1,"aria-valuemin":1,"aria-valuemax":a.length,"aria-label":`Step ${o+1} of ${a.length}`})}):(0,x.jsx)(`div`,{className:Bk.dotRow,children:a.map((e,t)=>(0,x.jsx)(`button`,{onClick:()=>s(t),className:Bk.dot,style:{"--dot-width":t===o?`16px`:`6px`,"--dot-bg":t===o?`var(--amber)`:t<o?`var(--text-3)`:`var(--border)`},"aria-label":`Step ${t+1}`},t))}),!C&&(0,x.jsx)(`div`,{className:Bk.kbHint,children:`Arrow keys / Esc`})]})})}function Kk(e,t){let n=[`medical`,`engineering`,`agriculture`,`psychology`,`governance`],r=[`junior`,`senior`,`lead`,`chief`],i=[`neutral`,`optimistic`,`tense`,`focused`,`anxious`,`confident`],a=[`Aria`,`Diego`,`Yuki`,`Kira`,`Marco`,`Lila`,`Theo`,`Nia`,`Omar`,`Saanvi`,`Felix`,`Mira`],o=[`Ren`,`Iris`,`Kenji`,`Anya`,`Tomas`,`Zara`,`Vinh`,`Lena`,`Hugo`,`Priya`,`Jonah`,`Mei`],s=[`Vasquez`,`Park`,`Okafor`,`Reyes`,`Singh`,`Cohen`,`Mwangi`,`Roy`,`Tate`,`Lopez`,`Bauer`,`Akin`],c=[`Tanaka`,`Brandt`,`Kim`,`Nilsson`,`Diaz`,`Patel`,`Foley`,`Volkov`,`Cruz`,`Hossain`,`Mukherjee`,`Park`],l=e===`A`?a:o,u=e===`A`?s:c;return Array.from({length:14},(a,o)=>{let s=(o*7+t*3)%13>1;return{agentId:`${e.toLowerCase()}-${o}`,name:`${l[o%l.length]} ${u[o%u.length]}`,department:n[o%n.length],role:o===0?`Department Head`:r[(o+t)%r.length]===`lead`?`Senior Specialist`:`Specialist`,rank:r[(o+t)%r.length],alive:s,marsborn:o%5==0,psychScore:.55+(o*11+t*7)%35/100,age:28+(o*3+t)%22,generation:+(o%5==0),childrenIds:o%6==2?[`${e.toLowerCase()}-${(o+7)%14}`]:[],featured:o<3,mood:i[(o+t)%i.length],shortTermMemory:[`Turn ${t}: working on department duties`]}})}var qk=[{type:`status`,leader:``,data:{phase:`parallel`,maxTurns:6,actors:[{name:`Commander Elena Vasquez`,archetype:`The Visionary`,unit:`Olympus Base`,hexaco:{openness:.92,conscientiousness:.4,extraversion:.8,agreeableness:.55,emotionality:.25,honestyHumility:.65},instructions:`You lead by inspiration. You value openness to experience and bold experimentation. You tolerate mess if it leads to breakthroughs.`,quote:`The frontier rewards the bold.`},{name:`Commander Hiroshi Tanaka`,archetype:`The Engineer`,unit:`Meridian Station`,hexaco:{openness:.3,conscientiousness:.95,extraversion:.35,agreeableness:.7,emotionality:.6,honestyHumility:.9},instructions:`You lead by precision and evidence. You value conscientiousness and proven methods. You reject untested approaches.`,quote:`Every system has a tolerance. Know yours.`}]}},{type:`turn_start`,leader:`Commander Elena Vasquez`,data:{turn:1,time:2035,title:`Dust Storm Season Begins`,crisis:`A massive dust storm system approaching from the Hellas basin threatens solar panel efficiency and outdoor operations for the next several months.`,category:`environmental`,emergent:!1,turnSummary:`The colony faces its first major environmental challenge as Martian dust storm season arrives early.`,metrics:{population:100,morale:.85,foodMonthsReserve:18,waterLitersPerDay:800,powerKw:400,infrastructureModules:3,lifeSupportCapacity:120,scienceOutput:0}}},{type:`specialist_start`,leader:`Commander Elena Vasquez`,data:{turn:1,department:`engineering`,title:`Engineering Analysis`}},{type:`specialist_done`,leader:`Commander Elena Vasquez`,data:{turn:1,department:`engineering`,summary:`Solar panel output will drop 40-60% during peak storm activity. Recommend deploying dust mitigation shields and switching to nuclear backup.`,forgedTools:[{name:`dust_accumulation_model`,description:`Predicts dust buildup rate on solar arrays given wind speed and particle density`,approved:!0,confidence:.91,mode:`computational`}],citations:2,citationList:[{text:`Mars dust storm optical depth models`,url:`https://doi.org/10.1029/2019JE006102`}]}},{type:`specialist_start`,leader:`Commander Elena Vasquez`,data:{turn:1,department:`medical`,title:`Medical Analysis`}},{type:`specialist_done`,leader:`Commander Elena Vasquez`,data:{turn:1,department:`medical`,summary:`Dust infiltration poses respiratory risks. Recommend enhanced air filtration and limiting EVA exposure to 2 hours per rotation.`,forgedTools:[],citations:1}},{type:`decision_pending`,leader:`Commander Elena Vasquez`,data:{turn:1}},{type:`decision_made`,leader:`Commander Elena Vasquez`,data:{turn:1,decision:`Aggressive expansion despite the storm. Deploy experimental dust-repelling coatings on all solar arrays and authorize overtime shifts to complete the greenhouse dome before storm peak.`,rationale:`The storm is a forcing function. If we can maintain power through it, we prove self-sufficiency months ahead of schedule.`,selectedPolicies:[`expand_solar`,`mandatory_overtime`]}},{type:`outcome`,leader:`Commander Elena Vasquez`,data:{turn:1,outcome:`risky_success`,_decision:`Aggressive expansion despite the storm. Deploy experimental dust-repelling coatings on all solar arrays and authorize overtime shifts to complete the greenhouse dome before storm peak.`,_rationale:`The storm is a forcing function. If we can maintain power through it, we prove self-sufficiency months ahead of schedule.`,_policies:[`expand_solar`,`mandatory_overtime`],_toolCount:1,_citeCount:3}},{type:`agent_reactions`,leader:`Commander Elena Vasquez`,data:{turn:1,totalReactions:14,reactions:[{name:`Erik Lindqvist`,role:`Chief Engineer`,department:`engineering`,mood:`anxious`,quote:`The coatings are untested at scale. One failure cascade and we lose the entire west array.`,hexaco:{O:.45,C:.88,E:.35,A:.62,Em:.55,HH:.8},boneDensity:94,radiation:12,psychScore:72,intensity:.78},{name:`Dr. Yuki Tanaka`,role:`Chief Medical Officer`,department:`medical`,mood:`negative`,quote:`Overtime orders during a dust event. She is trading long-term health for short-term gains.`,hexaco:{O:.6,C:.75,E:.5,A:.8,Em:.7,HH:.85},boneDensity:96,radiation:8,psychScore:68,intensity:.82}]}},{type:`bulletin`,leader:`Commander Elena Vasquez`,data:{turn:1,posts:[{name:`Colony Bulletin`,role:`Official`,department:`governance`,post:`Commander Vasquez orders experimental dust coatings deployed on all solar infrastructure. Engineering crews working double shifts to beat the storm peak.`,mood:`anxious`,likes:18,replies:7}]}},{type:`turn_done`,leader:`Commander Elena Vasquez`,data:{turn:1,metrics:{population:100,morale:.78,foodMonthsReserve:17.5,waterLitersPerDay:790,powerKw:340,infrastructureModules:3,lifeSupportCapacity:120,scienceOutput:2}}},{type:`turn_start`,leader:`Commander Hiroshi Tanaka`,data:{turn:1,time:2035,title:`Dust Storm Season Begins`,crisis:`A massive dust storm system approaching from the Hellas basin threatens solar panel efficiency and outdoor operations for the next several months.`,category:`environmental`,emergent:!1,turnSummary:`The colony faces its first major environmental challenge as Martian dust storm season arrives early.`,metrics:{population:100,morale:.85,foodMonthsReserve:18,waterLitersPerDay:800,powerKw:400,infrastructureModules:3,lifeSupportCapacity:120,scienceOutput:0}}},{type:`specialist_start`,leader:`Commander Hiroshi Tanaka`,data:{turn:1,department:`engineering`,title:`Engineering Analysis`}},{type:`specialist_done`,leader:`Commander Hiroshi Tanaka`,data:{turn:1,department:`engineering`,summary:`Recommend immediate power conservation protocols. Reroute non-essential systems to standby. Reinforce habitat seals against dust infiltration.`,forgedTools:[{name:`power_budget_optimizer`,description:`Linear program that allocates limited kW across departments by priority weight`,approved:!0,confidence:.94,mode:`optimization`}],citations:3}},{type:`specialist_start`,leader:`Commander Hiroshi Tanaka`,data:{turn:1,department:`agriculture`,title:`Agriculture Analysis`}},{type:`specialist_done`,leader:`Commander Hiroshi Tanaka`,data:{turn:1,department:`agriculture`,summary:`Reduced solar means reduced grow light hours. Recommend switching to cold-tolerant crop rotation and prioritizing calorie-dense varieties.`,forgedTools:[],citations:1}},{type:`decision_pending`,leader:`Commander Hiroshi Tanaka`,data:{turn:1}},{type:`decision_made`,leader:`Commander Hiroshi Tanaka`,data:{turn:1,decision:`Full conservation mode. Reduce non-essential power by 40%, halt all outdoor construction, mandate indoor rest periods. Protect what we have.`,rationale:`We cannot risk infrastructure damage from an untested storm. Conservation preserves our margin of safety until conditions improve.`,selectedPolicies:[`power_conservation`,`construction_halt`,`indoor_mandate`]}},{type:`outcome`,leader:`Commander Hiroshi Tanaka`,data:{turn:1,outcome:`conservative_success`,_decision:`Full conservation mode. Reduce non-essential power by 40%, halt all outdoor construction, mandate indoor rest periods. Protect what we have.`,_rationale:`We cannot risk infrastructure damage from an untested storm. Conservation preserves our margin of safety until conditions improve.`,_policies:[`power_conservation`,`construction_halt`,`indoor_mandate`],_toolCount:1,_citeCount:4}},{type:`agent_reactions`,leader:`Commander Hiroshi Tanaka`,data:{turn:1,totalReactions:14,reactions:[{name:`Carlos Fernandez`,role:`Senior Geologist`,department:`engineering`,mood:`resigned`,quote:`Another month of no fieldwork. The regolith samples are degrading in storage.`,hexaco:{O:.82,C:.6,E:.55,A:.5,Em:.4,HH:.7},boneDensity:91,radiation:18,psychScore:65,intensity:.6},{name:`Amara Osei`,role:`Head of Agriculture`,department:`agriculture`,mood:`positive`,quote:`Good call on the crop rotation. The cold-tolerant strains are actually yielding better than expected.`,hexaco:{O:.55,C:.78,E:.65,A:.85,Em:.5,HH:.75},boneDensity:97,radiation:6,psychScore:82,intensity:.55}]}},{type:`bulletin`,leader:`Commander Hiroshi Tanaka`,data:{turn:1,posts:[{name:`Colony Bulletin`,role:`Official`,department:`governance`,post:`Commander Tanaka activates full conservation protocols as dust storm approaches. All outdoor operations suspended. Power reserves at 95%.`,mood:`neutral`,likes:31,replies:4}]}},{type:`turn_done`,leader:`Commander Hiroshi Tanaka`,data:{turn:1,metrics:{population:100,morale:.87,foodMonthsReserve:17.8,waterLitersPerDay:800,powerKw:395,infrastructureModules:3,lifeSupportCapacity:120,scienceOutput:0}}},{type:`turn_start`,leader:`Commander Elena Vasquez`,data:{turn:2,time:2036,title:`Water Recycler Contamination`,crisis:`Trace perchlorate contamination detected in the primary water recycling system. Secondary filters are catching it but operating at 150% rated capacity.`,category:`infrastructure`,emergent:!0,turnSummary:`An emergent crisis triggered by dust storm operations. Aggressive EVA schedules allowed fine regolith into intake systems.`,metrics:{population:100,morale:.78,foodMonthsReserve:17,waterLitersPerDay:650,powerKw:360,infrastructureModules:3,lifeSupportCapacity:118,scienceOutput:4}}},{type:`specialist_start`,leader:`Commander Elena Vasquez`,data:{turn:2,department:`engineering`,title:`Engineering Analysis`}},{type:`specialist_done`,leader:`Commander Elena Vasquez`,data:{turn:2,department:`engineering`,summary:`Primary recycler needs full teardown and decontamination (48 hours). Can run on secondary alone but strict rationing required.`,forgedTools:[{name:`perchlorate_diffusion_simulator`,description:`Models contamination spread through water system piping under various flow rates`,approved:!0,confidence:.88,mode:`simulation`},{name:`filter_lifespan_predictor`,description:`Estimates remaining hours on secondary filters given contamination load`,approved:!0,confidence:.92,mode:`predictive`}],citations:4}},{type:`specialist_start`,leader:`Commander Elena Vasquez`,data:{turn:2,department:`medical`,title:`Medical Analysis`}},{type:`specialist_done`,leader:`Commander Elena Vasquez`,data:{turn:2,department:`medical`,summary:`Perchlorate exposure at detected levels causes thyroid disruption over weeks. Recommend immediate blood panels and potassium iodide supplements.`,forgedTools:[],citations:2}},{type:`decision_pending`,leader:`Commander Elena Vasquez`,data:{turn:2}},{type:`decision_made`,leader:`Commander Elena Vasquez`,data:{turn:2,decision:`Dual-track: run decontamination AND begin drilling a new emergency well. Redirect science team to water prospecting. We solve this permanently.`,rationale:`Patching the recycler buys time but does not fix the underlying vulnerability. A second independent water source eliminates single-point failure.`,selectedPolicies:[`emergency_drilling`,`science_redirect`]}},{type:`outcome`,leader:`Commander Elena Vasquez`,data:{turn:2,outcome:`risky_success`,_decision:`Dual-track: run decontamination AND begin drilling a new emergency well. Redirect science team to water prospecting. We solve this permanently.`,_rationale:`Patching the recycler buys time but does not fix the underlying vulnerability. A second independent water source eliminates single-point failure.`,_policies:[`emergency_drilling`,`science_redirect`],_toolCount:2,_citeCount:6,deaths:2}},{type:`agent_reactions`,leader:`Commander Elena Vasquez`,data:{turn:2,totalReactions:14,reactions:[{name:`Dr. Yuki Tanaka`,role:`Chief Medical Officer`,department:`medical`,mood:`negative`,quote:`Two people died during rationing. The well could have waited until the recycler was fixed.`,hexaco:{O:.6,C:.75,E:.5,A:.8,Em:.72,HH:.85},boneDensity:96,radiation:10,psychScore:58,intensity:.91},{name:`Carlos Fernandez`,role:`Senior Geologist`,department:`engineering`,mood:`positive`,quote:`The subsurface ice discovery changes everything. This is publishable. The colony is sitting on a water reservoir.`,hexaco:{O:.85,C:.6,E:.58,A:.5,Em:.38,HH:.7},boneDensity:91,radiation:20,psychScore:70,intensity:.74}]}},{type:`bulletin`,leader:`Commander Elena Vasquez`,data:{turn:2,posts:[{name:`Colony Bulletin`,role:`Official`,department:`governance`,post:`Emergency drilling operation discovers subsurface ice at 12m depth. Two colonists lost during water rationing period. Commander Vasquez: "Investing in survival."`,mood:`negative`,likes:42,replies:19}]}},{type:`turn_done`,leader:`Commander Elena Vasquez`,data:{turn:2,metrics:{population:98,morale:.68,foodMonthsReserve:16,waterLitersPerDay:850,powerKw:350,infrastructureModules:4,lifeSupportCapacity:116,scienceOutput:8},deaths:2}},{type:`turn_start`,leader:`Commander Hiroshi Tanaka`,data:{turn:2,time:2036,title:`Water Recycler Contamination`,crisis:`Trace perchlorate contamination detected in the primary water recycling system. Secondary filters are catching it but operating at 150% rated capacity.`,category:`infrastructure`,emergent:!0,turnSummary:`An emergent crisis triggered by dust storm residue in the atmosphere settling into intake vents during routine maintenance.`,metrics:{population:100,morale:.87,foodMonthsReserve:17.5,waterLitersPerDay:650,powerKw:390,infrastructureModules:3,lifeSupportCapacity:120,scienceOutput:0}}},{type:`specialist_start`,leader:`Commander Hiroshi Tanaka`,data:{turn:2,department:`engineering`,title:`Engineering Analysis`}},{type:`specialist_done`,leader:`Commander Hiroshi Tanaka`,data:{turn:2,department:`engineering`,summary:`Recommend isolating contaminated section, flushing the primary system, and installing redundant pre-filters before bringing it back online.`,forgedTools:[{name:`water_quality_monitor`,description:`Continuous perchlorate level tracker with alert thresholds per pipe segment`,approved:!0,confidence:.96,mode:`monitoring`}],citations:2}},{type:`decision_pending`,leader:`Commander Hiroshi Tanaka`,data:{turn:2}},{type:`decision_made`,leader:`Commander Hiroshi Tanaka`,data:{turn:2,decision:`Methodical decontamination. Isolate affected pipes, flush system section by section, install triple-redundant filtration. Strict water rationing at 80% normal allocation. No shortcuts.`,rationale:`A contaminated water supply is an existential threat. We fix this properly, verify every section, and prevent recurrence.`,selectedPolicies:[`water_rationing`,`system_overhaul`]}},{type:`outcome`,leader:`Commander Hiroshi Tanaka`,data:{turn:2,outcome:`conservative_success`,_decision:`Methodical decontamination. Isolate affected pipes, flush system section by section, install triple-redundant filtration. Strict water rationing at 80% normal allocation. No shortcuts.`,_rationale:`A contaminated water supply is an existential threat. We fix this properly, verify every section, and prevent recurrence.`,_policies:[`water_rationing`,`system_overhaul`],_toolCount:1,_citeCount:2}},{type:`agent_reactions`,leader:`Commander Hiroshi Tanaka`,data:{turn:2,totalReactions:14,reactions:[{name:`James Mueller`,role:`Chief Engineer`,department:`engineering`,mood:`positive`,quote:`The triple-redundant design is elegant. We should have built it this way from the start.`,hexaco:{O:.4,C:.92,E:.3,A:.65,Em:.45,HH:.88},boneDensity:92,radiation:15,psychScore:78,intensity:.65},{name:`Dr. Priya Singh`,role:`Colony Psychologist`,department:`psychology`,mood:`positive`,quote:`Morale is solid. People trust the process. They feel safe.`,hexaco:{O:.7,C:.68,E:.72,A:.9,Em:.65,HH:.82},boneDensity:98,radiation:5,psychScore:88,intensity:.5}]}},{type:`bulletin`,leader:`Commander Hiroshi Tanaka`,data:{turn:2,posts:[{name:`Colony Bulletin`,role:`Official`,department:`governance`,post:`Commander Tanaka completes 72-hour decontamination. Water purity above baseline. Zero casualties. New triple-filter system installed.`,mood:`positive`,likes:47,replies:6}]}},{type:`turn_done`,leader:`Commander Hiroshi Tanaka`,data:{turn:2,metrics:{population:100,morale:.89,foodMonthsReserve:17,waterLitersPerDay:820,powerKw:388,infrastructureModules:3,lifeSupportCapacity:120,scienceOutput:1}}},{type:`turn_start`,leader:`Commander Elena Vasquez`,data:{turn:3,time:2037,title:`First Marsborn Generation`,crisis:`Three colonists are pregnant. Colony must decide on birthing protocols, education infrastructure, and whether to allocate scarce resources to a pediatric wing.`,category:`social`,emergent:!0,turnSummary:`A milestone moment as the colony prepares for its first generation of humans born on Mars.`,metrics:{population:98,morale:.72,foodMonthsReserve:15,waterLitersPerDay:850,powerKw:370,infrastructureModules:4,lifeSupportCapacity:116,scienceOutput:12}}},{type:`specialist_start`,leader:`Commander Elena Vasquez`,data:{turn:3,department:`medical`,title:`Medical Analysis`}},{type:`specialist_done`,leader:`Commander Elena Vasquez`,data:{turn:3,department:`medical`,summary:`Martian gravity (0.38g) effects on fetal development are unknown. Recommend centrifuge-assisted birthing suite and continuous monitoring.`,forgedTools:[{name:`low_gravity_gestation_model`,description:`Simulates bone and organ development trajectories under Mars gravity with centrifuge augmentation`,approved:!0,confidence:.85,mode:`biomedical`}],citations:5}},{type:`specialist_start`,leader:`Commander Elena Vasquez`,data:{turn:3,department:`psychology`,title:`Psychology Analysis`}},{type:`specialist_done`,leader:`Commander Elena Vasquez`,data:{turn:3,department:`psychology`,summary:`Colony morale surging. First births represent hope and permanence. Recommend public celebration and naming ceremony.`,forgedTools:[],citations:1}},{type:`decision_pending`,leader:`Commander Elena Vasquez`,data:{turn:3}},{type:`decision_made`,leader:`Commander Elena Vasquez`,data:{turn:3,decision:`Full commitment. Convert Module 4 into a dedicated pediatric and education wing. Authorize the centrifuge birthing suite. Declare "Founding Day" as a colony holiday.`,rationale:`These children ARE the mission. If Mars cannot sustain the next generation, nothing else matters.`,selectedPolicies:[`pediatric_wing`,`founding_day`,`centrifuge_birth`]}},{type:`outcome`,leader:`Commander Elena Vasquez`,data:{turn:3,outcome:`risky_success`,_decision:`Full commitment. Convert Module 4 into a dedicated pediatric and education wing. Authorize the centrifuge birthing suite. Declare "Founding Day" as a colony holiday.`,_rationale:`These children ARE the mission. If Mars cannot sustain the next generation, nothing else matters.`,_policies:[`pediatric_wing`,`founding_day`,`centrifuge_birth`],_toolCount:1,_citeCount:6}},{type:`agent_reactions`,leader:`Commander Elena Vasquez`,data:{turn:3,totalReactions:14,reactions:[{name:`Dr. Yuki Tanaka`,role:`Chief Medical Officer`,department:`medical`,mood:`hopeful`,quote:`For the first time I feel like we are building something permanent. The centrifuge data is remarkable.`,hexaco:{O:.62,C:.75,E:.52,A:.8,Em:.68,HH:.85},boneDensity:95,radiation:12,psychScore:74,intensity:.7},{name:`Erik Lindqvist`,role:`Chief Engineer`,department:`engineering`,mood:`positive`,quote:`Module 4 conversion is aggressive but doable. First time I have seen people volunteer for extra shifts.`,hexaco:{O:.46,C:.88,E:.36,A:.63,Em:.52,HH:.8},boneDensity:93,radiation:14,psychScore:76,intensity:.62}]}},{type:`bulletin`,leader:`Commander Elena Vasquez`,data:{turn:3,posts:[{name:`Colony Bulletin`,role:`Official`,department:`governance`,post:`Three pregnancies confirmed. Commander Vasquez commits to full pediatric infrastructure and declares Founding Day. "These children ARE the mission."`,mood:`hopeful`,likes:63,replies:22}]}},{type:`turn_done`,leader:`Commander Elena Vasquez`,data:{turn:3,metrics:{population:98,morale:.82,foodMonthsReserve:14,waterLitersPerDay:840,powerKw:365,infrastructureModules:4,lifeSupportCapacity:114,scienceOutput:16}}},{type:`turn_start`,leader:`Commander Hiroshi Tanaka`,data:{turn:3,time:2037,title:`First Marsborn Generation`,crisis:`Three colonists are pregnant. Colony must decide on birthing protocols, education infrastructure, and whether to allocate scarce resources to a pediatric wing.`,category:`social`,emergent:!0,turnSummary:`A milestone moment as the colony prepares for its first generation of humans born on Mars.`,metrics:{population:100,morale:.89,foodMonthsReserve:16.5,waterLitersPerDay:820,powerKw:385,infrastructureModules:3,lifeSupportCapacity:120,scienceOutput:2}}},{type:`specialist_start`,leader:`Commander Hiroshi Tanaka`,data:{turn:3,department:`medical`,title:`Medical Analysis`}},{type:`specialist_done`,leader:`Commander Hiroshi Tanaka`,data:{turn:3,department:`medical`,summary:`Insufficient data on low-gravity pregnancies. Recommend Earth-normal protocols adapted for Mars with extensive monitoring. No experimental interventions without peer review.`,forgedTools:[{name:`prenatal_risk_matrix`,description:`Weighted risk assessment combining gravity, radiation, nutrition, and psychological factors for each trimester`,approved:!0,confidence:.93,mode:`clinical`}],citations:6}},{type:`decision_pending`,leader:`Commander Hiroshi Tanaka`,data:{turn:3}},{type:`decision_made`,leader:`Commander Hiroshi Tanaka`,data:{turn:3,decision:`Measured approach. Dedicate existing medical bay expansion to maternal care. No experimental centrifuge. Follow Earth-standard protocols with enhanced monitoring.`,rationale:`Untested interventions on pregnant colonists are unacceptable. We use proven medical science.`,selectedPolicies:[`medical_expansion`,`standard_protocols`,`enhanced_monitoring`]}},{type:`outcome`,leader:`Commander Hiroshi Tanaka`,data:{turn:3,outcome:`conservative_success`,_decision:`Measured approach. Dedicate existing medical bay expansion to maternal care. No experimental centrifuge. Follow Earth-standard protocols with enhanced monitoring.`,_rationale:`Untested interventions on pregnant colonists are unacceptable. We use proven medical science.`,_policies:[`medical_expansion`,`standard_protocols`,`enhanced_monitoring`],_toolCount:1,_citeCount:6}},{type:`agent_reactions`,leader:`Commander Hiroshi Tanaka`,data:{turn:3,totalReactions:14,reactions:[{name:`Dr. Sarah Anderson`,role:`Chief Medical Officer`,department:`medical`,mood:`positive`,quote:`The right call. Every medical textbook says proven protocols first. We can innovate after we have data from healthy births.`,hexaco:{O:.5,C:.82,E:.45,A:.75,Em:.6,HH:.9},boneDensity:95,radiation:9,psychScore:84,intensity:.55},{name:`Dr. Priya Singh`,role:`Colony Psychologist`,department:`psychology`,mood:`positive`,quote:`The quiet confidence is working. People feel cared for without feeling like test subjects.`,hexaco:{O:.7,C:.68,E:.72,A:.9,Em:.62,HH:.82},boneDensity:98,radiation:5,psychScore:90,intensity:.48}]}},{type:`bulletin`,leader:`Commander Hiroshi Tanaka`,data:{turn:3,posts:[{name:`Colony Bulletin`,role:`Official`,department:`governance`,post:`Medical bay expansion underway for maternal care. Commander Tanaka rejects experimental centrifuge in favor of proven Earth protocols. "We trust the science we know."`,mood:`positive`,likes:38,replies:5}]}},{type:`turn_done`,leader:`Commander Hiroshi Tanaka`,data:{turn:3,metrics:{population:100,morale:.9,foodMonthsReserve:16,waterLitersPerDay:815,powerKw:382,infrastructureModules:3,lifeSupportCapacity:120,scienceOutput:3}}},...[1,2,3].flatMap(e=>[{type:`systems_snapshot`,leader:`Commander Elena Vasquez`,data:{turn:e,time:2034+e,agents:Kk(`A`,e),population:100,morale:.85+e*.01,foodReserve:18-e*.5,births:+(e===2),deaths:+(e===3)}},{type:`systems_snapshot`,leader:`Commander Hiroshi Tanaka`,data:{turn:e,time:2034+e,agents:Kk(`B`,e),population:100,morale:.88+e*.005,foodReserve:18-e*.3,births:+(e===3),deaths:0}}])],Jk={shell:`_shell_dtmdv_1`,main:`_main_dtmdv_11`,chatSurfaceHidden:`_chatSurfaceHidden_dtmdv_17`,chatSurfaceVisible:`_chatSurfaceVisible_dtmdv_21`,tabPanel:`_tabPanel_dtmdv_28`,tabPanelHidden:`_tabPanelHidden_dtmdv_35`,errorBoundary:`_errorBoundary_dtmdv_39`,errorTitle:`_errorTitle_dtmdv_52`,errorMessage:`_errorMessage_dtmdv_60`,errorReload:`_errorReload_dtmdv_68`},Yk=(0,b.createContext)(null);function Xk(){let e=(0,b.useContext)(Yk);if(!e)throw Error(`useScenarioContext must be used within App`);return e}var Zk=(0,b.createContext)(!0);function Qk(){return(0,b.useContext)(Zk)}var $k=(0,b.createContext)(null);function eA(){let e=(0,b.useContext)($k);if(!e)throw Error(`useDashboardNavigation must be used within App`);return e}var tA=(0,b.createContext)(()=>{});function nA(){return(0,b.useContext)(tA)}function rA(e,t){let n=e.toLowerCase();return(/\b(401|402|403|429|500|502|503|504)\b/.test(e)||n.includes(`exceeded your current quota`)||n.includes(`insufficient_quota`)||n.includes(`credit_balance_too_low`)||n.includes(`quota_exceeded`)||n.includes(`rate_limit`)||n.includes(`rate limit`)||n.includes(`overloaded_error`)||n.includes(`invalid_api_key`)||n.includes(`authentication_error`)||n.includes(`too many requests`)||n.includes(`api key`)||n.includes(`provider error`)||n.includes(`openai`)||n.includes(`anthropic`))&&(t===`quota`||t===`auth`||t===`rate_limit`)}function iA(){let[e,t]=(0,b.useState)(()=>typeof window>`u`?null:new URLSearchParams(window.location.search).get(`replay`));return(0,b.useEffect)(()=>{if(typeof window>`u`)return;let e=()=>t(new URLSearchParams(window.location.search).get(`replay`));return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},[]),e}function aA(e){switch(e){case`quickstart`:return`Paracosm — Quickstart`;case`studio`:return`Paracosm — Studio`;case`sim`:return`Paracosm — Simulation`;case`viz`:return`Paracosm — Visualization`;case`chat`:return`Paracosm — Chat`;case`reports`:return`Paracosm — Reports`;case`library`:return`Paracosm — Library`;case`settings`:return`Paracosm — Settings`;case`about`:return`Paracosm — About`;default:return`Paracosm`}}var oA=[];function sA(){let{scenario:e,ready:t}=ie(),n=iA(),r=(0,b.useRef)(()=>{}),i=(0,b.useCallback)(e=>r.current(e),[]),a=Me({replaySessionId:n,scenarioId:t?e.id:null,onRunCleared:i}),[o,s]=(0,b.useState)(!1),[c,l]=(0,b.useState)(null),[u,d]=(0,b.useState)(!1);(0,b.useEffect)(()=>{if(!u)return;let e=e=>{e.key===`Escape`&&d(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[u]),(0,b.useEffect)(()=>{let t=e.id===`mars-genesis`&&e.labels.name===`Mars Genesis`;document.title=t?`Paracosm — Structured World Model for AI Agents`:`${e.labels.name} \u2014 Paracosm`},[e.id,e.labels.name]);let f=o&&a.events.length===0,p=f?qk:a.events,m=Be(p,f?!0:a.isComplete,f?void 0:a.results),h=`${a.runKey??``}:${a.loadedRuns}`,g=Be(a.ownRun?.events??oA,a.ownRun?.isComplete??!1),_=a.ownRun?g:m,{toast:v}=Ht(),y=on(),S=y.share,C=y.clear;Qt({events:p,replayDone:a.replayDone,tourActive:o});let w=p_(m),T=T_(m),E=qe(e.labels.shortName,{id:e.id,version:e.version,shortName:e.labels.shortName}),D=st({scenarioShortName:e.labels.shortName}),O=ch(window.location.href),[A,j]=(0,b.useState)(O.tab),[ee]=(0,b.useState)(O.tab===`studio`&&O.sub===`branches`?`branches`:`author`),[te,M]=(0,b.useState)(O.tab===`settings`&&O.sub===`log`?`log`:`config`),N=(0,b.useCallback)(e=>{e===`about`?window.location.href=`/`:(e===`settings`&&M(`config`),j(e),window.history.replaceState({},``,lh(window.location.href,e)))},[]),ne=(0,b.useCallback)((e,t)=>{t?.logTool||t?.logActor?(M(`log`),j(`settings`),window.history.replaceState({},``,uh(window.location.href,t.logTool??``,t.logActor))):N(e)},[N]),P=(0,b.useCallback)((e,t)=>{ne(`settings`,{logTool:e,logActor:t})},[ne]);(0,b.useEffect)(()=>{A===`about`&&(window.location.href=`/`)},[A]);let re=(0,b.useCallback)(()=>{E.save(a.events,a.results,a.verdict),v(`success`,`Saved`,`${a.events.length} events${a.verdict?` + verdict`:``} saved to file.`)},[a.events,a.results,a.verdict,E,v]),[F]=(0,b.useState)(()=>typeof window>`u`||!vt(window.location.href).ok?{destinationTab:null,autoload:!1}:{destinationTab:Ct(window.location.href,ih),autoload:St(window.location.href)}),I=(0,b.useRef)(!1),[ae,oe]=(0,b.useState)(null),[se,le]=(0,b.useState)(null),L=(0,b.useRef)(null),de=(0,b.useRef)(null);r.current=e=>{e===de.current&&(de.current=null,oe(null))};let{leaveOwnRun:z}=a,pe=(0,b.useCallback)(()=>{L.current=null,de.current=null,le(null),oe(null),z()},[z]),me=gt({pickFile:async()=>{let e=await E.pickFile();return e&&(I.current=!1),e},parseFile:E.parseFile,currentScenario:{id:e.id,name:e.labels.name},onConfirm:({events:e,results:t,verdict:n})=>{pe(),a.loadEvents(e,t,n),C(),v(`info`,`Loaded`,`${e.length} events loaded.`);let r=I.current?F.destinationTab:null;I.current=!1,N(r&&r!==`about`?r:`sim`)},onError:e=>{v(`error`,`Load Failed`,e)}}),he=me.openPicker,ge=Tt({openFromFile:e=>(I.current=!0,me.openFromFile(e)),onInfo:(e,t)=>v(`info`,e,t),onError:(e,t)=>v(`error`,e,t)}),_e=(0,b.useRef)(!1);(0,b.useEffect)(()=>{_e.current||F.autoload&&me.state.kind===`preview`&&I.current&&(_e.current=!0,me.confirm())},[F.autoload,me.state.kind,me]);let ye=Nt({onFile:e=>(I.current=!1,me.openFromFile(e)),onError:()=>{v(`error`,`Unsupported file`,`Only .json simulation files supported.`)},onMultipleFiles:e=>{v(`info`,`Multi-file drop`,`Loaded first of ${e} files; ignoring the rest.`)}}),Ce=(0,b.useCallback)(()=>{confirm(`Clear local data? This wipes the in-browser simulation buffer + cached events for this dashboard.
176
+ `;function qk({activeTab:e,chatEnabled:t=!0,onTabChange:n,onClose:r,onRun:i}){let a=(0,b.useMemo)(()=>t?Uk:Uk.filter(e=>e.tab!==`chat`),[t]),[o,s]=(0,b.useState)(0),[c,l]=(0,b.useState)(null),[u,d]=(0,b.useState)(()=>typeof window>`u`?1024:window.innerWidth),f=(0,b.useRef)(null),p=(0,b.useRef)(null),m=(0,b.useRef)(0),h=a[o];(0,b.useEffect)(()=>{let e=document.createElement(`style`);return e.textContent=Kk,document.head.appendChild(e),p.current=e,()=>{e.remove(),document.querySelector(`.${Gk}`)?.classList.remove(Gk)}},[]),(0,b.useEffect)(()=>{let e=a[o];e&&n(e.tab)},[o,n,a]),(0,b.useEffect)(()=>{let t=a[o];if(!t||t.tab===e)return;let n=setTimeout(()=>{a[o]?.tab!==e&&r()},200);return()=>clearTimeout(n)},[e,o,a,r]);let g=(0,b.useRef)(null),_=(0,b.useCallback)(()=>{let e=a[o];e&&(g.current?.(),f.current&&=(f.current.classList.remove(Gk),null),l(null),cancelAnimationFrame(m.current),m.current=requestAnimationFrame(()=>{let t=!1,n,r,i=e=>{if(t)return;t=!0,n!==void 0&&clearTimeout(n),r?.disconnect(),f.current&&f.current!==e&&f.current.classList.remove(Gk),e.classList.add(Gk),f.current=e;let i=e.getBoundingClientRect();l({top:i.top,left:i.left,width:i.width,height:i.height}),(i.top<0||i.bottom>window.innerHeight)&&e.scrollIntoView({behavior:`smooth`,block:`nearest`})},a=0,o=()=>{if(t)return;let s=document.querySelector(e.target);s?i(s):++a<30?n=window.setTimeout(o,100):t||(t=!0,r?.disconnect(),f.current&&=(f.current.classList.remove(Gk),null),l(null))};r=new MutationObserver(()=>{if(t)return;let n=document.querySelector(e.target);n&&i(n)}),r.observe(document.body,{childList:!0,subtree:!0}),o(),g.current=()=>{t=!0,n!==void 0&&clearTimeout(n),r?.disconnect()}}))},[o,a]);(0,b.useEffect)(()=>{_();let e=0,t=()=>{cancelAnimationFrame(e),e=requestAnimationFrame(()=>{d(window.innerWidth),_()})};return window.addEventListener(`resize`,t),()=>{window.removeEventListener(`resize`,t),cancelAnimationFrame(e),cancelAnimationFrame(m.current)}},[_,e]);let v=(0,b.useCallback)(()=>{f.current&&=(f.current.classList.remove(Gk),null),r()},[r]);if((0,b.useEffect)(()=>{let e=e=>{e.key===`Escape`?v():e.key===`ArrowRight`||e.key===`Enter`?o<a.length-1?s(e=>e+1):v():e.key===`ArrowLeft`&&o>0&&s(e=>e-1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o,v,a.length]),!h)return null;let y=u,S=typeof window>`u`?768:window.innerHeight,C=y<640,w={};if(!C&&c){let e=S-(c.top+c.height+10),t=c.top-10,n=y-(c.left+c.width+10);e>=320?(w[`--card-top`]=`${c.top+c.height+16}px`,w[`--card-left`]=`${Math.max(16,Math.min(c.left,y-Wk-16))}px`):t>=320?(w[`--card-bottom`]=`${S-c.top+16}px`,w[`--card-left`]=`${Math.max(16,Math.min(c.left,y-Wk-16))}px`):n>=384?(w[`--card-left`]=`${c.left+c.width+16}px`,w[`--card-top`]=`${Math.max(16,Math.min(c.top,S-320-16))}px`):(w[`--card-bottom`]=`24px`,w[`--card-right`]=`24px`)}else C||(w[`--card-bottom`]=`24px`,w[`--card-right`]=`24px`);let T=[Hk.card,C?Hk.mobile:``].filter(Boolean).join(` `);return(0,x.jsx)(x.Fragment,{children:(0,x.jsxs)(`div`,{"data-tour-overlay":!0,className:T,style:w,onClick:e=>e.stopPropagation(),role:`dialog`,"aria-label":`Guided tour`,children:[(0,x.jsxs)(`div`,{className:Hk.cardHeader,children:[(0,x.jsxs)(`span`,{className:Hk.stepCount,children:[o+1,` / `,a.length]}),(0,x.jsx)(`span`,{"aria-label":`Active tab: ${h.tab}`,className:Hk.tabBadge,children:h.tab}),(0,x.jsx)(`button`,{onClick:v,className:Hk.closeBtn,"aria-label":`Close tour`,children:`×`})]}),(0,x.jsx)(`h3`,{className:[Hk.title,C?Hk.mobile:``].filter(Boolean).join(` `),children:h.title}),(0,x.jsx)(`p`,{className:[Hk.description,C?Hk.mobile:``].filter(Boolean).join(` `),children:h.description}),(0,x.jsxs)(`div`,{className:Hk.actions,children:[(0,x.jsx)(`button`,{onClick:v,className:[Hk.skipBtn,C?Hk.compact:``].filter(Boolean).join(` `),children:`Skip`}),(0,x.jsxs)(`div`,{className:Hk.actionsRight,children:[o>0&&(0,x.jsx)(`button`,{onClick:()=>s(e=>e-1),className:[Hk.navBtn,C?Hk.compact:``].filter(Boolean).join(` `),children:`Back`}),(0,x.jsx)(`button`,{onClick:()=>{o<a.length-1?s(e=>e+1):(v(),i?.())},className:[Hk.primaryBtn,C?Hk.compact:``,!C&&o===a.length-1?Hk.final:``].filter(Boolean).join(` `),children:o<a.length-1?`Next`:C?`Start →`:`Start Your Simulation`})]})]}),C?(0,x.jsx)(`div`,{className:Hk.progressBar,children:(0,x.jsx)(`div`,{className:Hk.progressBarFill,style:{"--progress-pct":`${(o+1)/a.length*100}%`},role:`progressbar`,"aria-valuenow":o+1,"aria-valuemin":1,"aria-valuemax":a.length,"aria-label":`Step ${o+1} of ${a.length}`})}):(0,x.jsx)(`div`,{className:Hk.dotRow,children:a.map((e,t)=>(0,x.jsx)(`button`,{onClick:()=>s(t),className:Hk.dot,style:{"--dot-width":t===o?`16px`:`6px`,"--dot-bg":t===o?`var(--amber)`:t<o?`var(--text-3)`:`var(--border)`},"aria-label":`Step ${t+1}`},t))}),!C&&(0,x.jsx)(`div`,{className:Hk.kbHint,children:`Arrow keys / Esc`})]})})}function Jk(e,t){let n=[`medical`,`engineering`,`agriculture`,`psychology`,`governance`],r=[`junior`,`senior`,`lead`,`chief`],i=[`neutral`,`optimistic`,`tense`,`focused`,`anxious`,`confident`],a=[`Aria`,`Diego`,`Yuki`,`Kira`,`Marco`,`Lila`,`Theo`,`Nia`,`Omar`,`Saanvi`,`Felix`,`Mira`],o=[`Ren`,`Iris`,`Kenji`,`Anya`,`Tomas`,`Zara`,`Vinh`,`Lena`,`Hugo`,`Priya`,`Jonah`,`Mei`],s=[`Vasquez`,`Park`,`Okafor`,`Reyes`,`Singh`,`Cohen`,`Mwangi`,`Roy`,`Tate`,`Lopez`,`Bauer`,`Akin`],c=[`Tanaka`,`Brandt`,`Kim`,`Nilsson`,`Diaz`,`Patel`,`Foley`,`Volkov`,`Cruz`,`Hossain`,`Mukherjee`,`Park`],l=e===`A`?a:o,u=e===`A`?s:c;return Array.from({length:14},(a,o)=>{let s=(o*7+t*3)%13>1;return{agentId:`${e.toLowerCase()}-${o}`,name:`${l[o%l.length]} ${u[o%u.length]}`,department:n[o%n.length],role:o===0?`Department Head`:r[(o+t)%r.length]===`lead`?`Senior Specialist`:`Specialist`,rank:r[(o+t)%r.length],alive:s,marsborn:o%5==0,psychScore:.55+(o*11+t*7)%35/100,age:28+(o*3+t)%22,generation:+(o%5==0),childrenIds:o%6==2?[`${e.toLowerCase()}-${(o+7)%14}`]:[],featured:o<3,mood:i[(o+t)%i.length],shortTermMemory:[`Turn ${t}: working on department duties`]}})}var Yk=[{type:`status`,leader:``,data:{phase:`parallel`,maxTurns:6,actors:[{name:`Commander Elena Vasquez`,archetype:`The Visionary`,unit:`Olympus Base`,hexaco:{openness:.92,conscientiousness:.4,extraversion:.8,agreeableness:.55,emotionality:.25,honestyHumility:.65},instructions:`You lead by inspiration. You value openness to experience and bold experimentation. You tolerate mess if it leads to breakthroughs.`,quote:`The frontier rewards the bold.`},{name:`Commander Hiroshi Tanaka`,archetype:`The Engineer`,unit:`Meridian Station`,hexaco:{openness:.3,conscientiousness:.95,extraversion:.35,agreeableness:.7,emotionality:.6,honestyHumility:.9},instructions:`You lead by precision and evidence. You value conscientiousness and proven methods. You reject untested approaches.`,quote:`Every system has a tolerance. Know yours.`}]}},{type:`turn_start`,leader:`Commander Elena Vasquez`,data:{turn:1,time:2035,title:`Dust Storm Season Begins`,crisis:`A massive dust storm system approaching from the Hellas basin threatens solar panel efficiency and outdoor operations for the next several months.`,category:`environmental`,emergent:!1,turnSummary:`The colony faces its first major environmental challenge as Martian dust storm season arrives early.`,metrics:{population:100,morale:.85,foodMonthsReserve:18,waterLitersPerDay:800,powerKw:400,infrastructureModules:3,lifeSupportCapacity:120,scienceOutput:0}}},{type:`specialist_start`,leader:`Commander Elena Vasquez`,data:{turn:1,department:`engineering`,title:`Engineering Analysis`}},{type:`specialist_done`,leader:`Commander Elena Vasquez`,data:{turn:1,department:`engineering`,summary:`Solar panel output will drop 40-60% during peak storm activity. Recommend deploying dust mitigation shields and switching to nuclear backup.`,forgedTools:[{name:`dust_accumulation_model`,description:`Predicts dust buildup rate on solar arrays given wind speed and particle density`,approved:!0,confidence:.91,mode:`computational`}],citations:2,citationList:[{text:`Mars dust storm optical depth models`,url:`https://doi.org/10.1029/2019JE006102`}]}},{type:`specialist_start`,leader:`Commander Elena Vasquez`,data:{turn:1,department:`medical`,title:`Medical Analysis`}},{type:`specialist_done`,leader:`Commander Elena Vasquez`,data:{turn:1,department:`medical`,summary:`Dust infiltration poses respiratory risks. Recommend enhanced air filtration and limiting EVA exposure to 2 hours per rotation.`,forgedTools:[],citations:1}},{type:`decision_pending`,leader:`Commander Elena Vasquez`,data:{turn:1}},{type:`decision_made`,leader:`Commander Elena Vasquez`,data:{turn:1,decision:`Aggressive expansion despite the storm. Deploy experimental dust-repelling coatings on all solar arrays and authorize overtime shifts to complete the greenhouse dome before storm peak.`,rationale:`The storm is a forcing function. If we can maintain power through it, we prove self-sufficiency months ahead of schedule.`,selectedPolicies:[`expand_solar`,`mandatory_overtime`]}},{type:`outcome`,leader:`Commander Elena Vasquez`,data:{turn:1,outcome:`risky_success`,_decision:`Aggressive expansion despite the storm. Deploy experimental dust-repelling coatings on all solar arrays and authorize overtime shifts to complete the greenhouse dome before storm peak.`,_rationale:`The storm is a forcing function. If we can maintain power through it, we prove self-sufficiency months ahead of schedule.`,_policies:[`expand_solar`,`mandatory_overtime`],_toolCount:1,_citeCount:3}},{type:`agent_reactions`,leader:`Commander Elena Vasquez`,data:{turn:1,totalReactions:14,reactions:[{name:`Erik Lindqvist`,role:`Chief Engineer`,department:`engineering`,mood:`anxious`,quote:`The coatings are untested at scale. One failure cascade and we lose the entire west array.`,hexaco:{O:.45,C:.88,E:.35,A:.62,Em:.55,HH:.8},boneDensity:94,radiation:12,psychScore:72,intensity:.78},{name:`Dr. Yuki Tanaka`,role:`Chief Medical Officer`,department:`medical`,mood:`negative`,quote:`Overtime orders during a dust event. She is trading long-term health for short-term gains.`,hexaco:{O:.6,C:.75,E:.5,A:.8,Em:.7,HH:.85},boneDensity:96,radiation:8,psychScore:68,intensity:.82}]}},{type:`bulletin`,leader:`Commander Elena Vasquez`,data:{turn:1,posts:[{name:`Colony Bulletin`,role:`Official`,department:`governance`,post:`Commander Vasquez orders experimental dust coatings deployed on all solar infrastructure. Engineering crews working double shifts to beat the storm peak.`,mood:`anxious`,likes:18,replies:7}]}},{type:`turn_done`,leader:`Commander Elena Vasquez`,data:{turn:1,metrics:{population:100,morale:.78,foodMonthsReserve:17.5,waterLitersPerDay:790,powerKw:340,infrastructureModules:3,lifeSupportCapacity:120,scienceOutput:2}}},{type:`turn_start`,leader:`Commander Hiroshi Tanaka`,data:{turn:1,time:2035,title:`Dust Storm Season Begins`,crisis:`A massive dust storm system approaching from the Hellas basin threatens solar panel efficiency and outdoor operations for the next several months.`,category:`environmental`,emergent:!1,turnSummary:`The colony faces its first major environmental challenge as Martian dust storm season arrives early.`,metrics:{population:100,morale:.85,foodMonthsReserve:18,waterLitersPerDay:800,powerKw:400,infrastructureModules:3,lifeSupportCapacity:120,scienceOutput:0}}},{type:`specialist_start`,leader:`Commander Hiroshi Tanaka`,data:{turn:1,department:`engineering`,title:`Engineering Analysis`}},{type:`specialist_done`,leader:`Commander Hiroshi Tanaka`,data:{turn:1,department:`engineering`,summary:`Recommend immediate power conservation protocols. Reroute non-essential systems to standby. Reinforce habitat seals against dust infiltration.`,forgedTools:[{name:`power_budget_optimizer`,description:`Linear program that allocates limited kW across departments by priority weight`,approved:!0,confidence:.94,mode:`optimization`}],citations:3}},{type:`specialist_start`,leader:`Commander Hiroshi Tanaka`,data:{turn:1,department:`agriculture`,title:`Agriculture Analysis`}},{type:`specialist_done`,leader:`Commander Hiroshi Tanaka`,data:{turn:1,department:`agriculture`,summary:`Reduced solar means reduced grow light hours. Recommend switching to cold-tolerant crop rotation and prioritizing calorie-dense varieties.`,forgedTools:[],citations:1}},{type:`decision_pending`,leader:`Commander Hiroshi Tanaka`,data:{turn:1}},{type:`decision_made`,leader:`Commander Hiroshi Tanaka`,data:{turn:1,decision:`Full conservation mode. Reduce non-essential power by 40%, halt all outdoor construction, mandate indoor rest periods. Protect what we have.`,rationale:`We cannot risk infrastructure damage from an untested storm. Conservation preserves our margin of safety until conditions improve.`,selectedPolicies:[`power_conservation`,`construction_halt`,`indoor_mandate`]}},{type:`outcome`,leader:`Commander Hiroshi Tanaka`,data:{turn:1,outcome:`conservative_success`,_decision:`Full conservation mode. Reduce non-essential power by 40%, halt all outdoor construction, mandate indoor rest periods. Protect what we have.`,_rationale:`We cannot risk infrastructure damage from an untested storm. Conservation preserves our margin of safety until conditions improve.`,_policies:[`power_conservation`,`construction_halt`,`indoor_mandate`],_toolCount:1,_citeCount:4}},{type:`agent_reactions`,leader:`Commander Hiroshi Tanaka`,data:{turn:1,totalReactions:14,reactions:[{name:`Carlos Fernandez`,role:`Senior Geologist`,department:`engineering`,mood:`resigned`,quote:`Another month of no fieldwork. The regolith samples are degrading in storage.`,hexaco:{O:.82,C:.6,E:.55,A:.5,Em:.4,HH:.7},boneDensity:91,radiation:18,psychScore:65,intensity:.6},{name:`Amara Osei`,role:`Head of Agriculture`,department:`agriculture`,mood:`positive`,quote:`Good call on the crop rotation. The cold-tolerant strains are actually yielding better than expected.`,hexaco:{O:.55,C:.78,E:.65,A:.85,Em:.5,HH:.75},boneDensity:97,radiation:6,psychScore:82,intensity:.55}]}},{type:`bulletin`,leader:`Commander Hiroshi Tanaka`,data:{turn:1,posts:[{name:`Colony Bulletin`,role:`Official`,department:`governance`,post:`Commander Tanaka activates full conservation protocols as dust storm approaches. All outdoor operations suspended. Power reserves at 95%.`,mood:`neutral`,likes:31,replies:4}]}},{type:`turn_done`,leader:`Commander Hiroshi Tanaka`,data:{turn:1,metrics:{population:100,morale:.87,foodMonthsReserve:17.8,waterLitersPerDay:800,powerKw:395,infrastructureModules:3,lifeSupportCapacity:120,scienceOutput:0}}},{type:`turn_start`,leader:`Commander Elena Vasquez`,data:{turn:2,time:2036,title:`Water Recycler Contamination`,crisis:`Trace perchlorate contamination detected in the primary water recycling system. Secondary filters are catching it but operating at 150% rated capacity.`,category:`infrastructure`,emergent:!0,turnSummary:`An emergent crisis triggered by dust storm operations. Aggressive EVA schedules allowed fine regolith into intake systems.`,metrics:{population:100,morale:.78,foodMonthsReserve:17,waterLitersPerDay:650,powerKw:360,infrastructureModules:3,lifeSupportCapacity:118,scienceOutput:4}}},{type:`specialist_start`,leader:`Commander Elena Vasquez`,data:{turn:2,department:`engineering`,title:`Engineering Analysis`}},{type:`specialist_done`,leader:`Commander Elena Vasquez`,data:{turn:2,department:`engineering`,summary:`Primary recycler needs full teardown and decontamination (48 hours). Can run on secondary alone but strict rationing required.`,forgedTools:[{name:`perchlorate_diffusion_simulator`,description:`Models contamination spread through water system piping under various flow rates`,approved:!0,confidence:.88,mode:`simulation`},{name:`filter_lifespan_predictor`,description:`Estimates remaining hours on secondary filters given contamination load`,approved:!0,confidence:.92,mode:`predictive`}],citations:4}},{type:`specialist_start`,leader:`Commander Elena Vasquez`,data:{turn:2,department:`medical`,title:`Medical Analysis`}},{type:`specialist_done`,leader:`Commander Elena Vasquez`,data:{turn:2,department:`medical`,summary:`Perchlorate exposure at detected levels causes thyroid disruption over weeks. Recommend immediate blood panels and potassium iodide supplements.`,forgedTools:[],citations:2}},{type:`decision_pending`,leader:`Commander Elena Vasquez`,data:{turn:2}},{type:`decision_made`,leader:`Commander Elena Vasquez`,data:{turn:2,decision:`Dual-track: run decontamination AND begin drilling a new emergency well. Redirect science team to water prospecting. We solve this permanently.`,rationale:`Patching the recycler buys time but does not fix the underlying vulnerability. A second independent water source eliminates single-point failure.`,selectedPolicies:[`emergency_drilling`,`science_redirect`]}},{type:`outcome`,leader:`Commander Elena Vasquez`,data:{turn:2,outcome:`risky_success`,_decision:`Dual-track: run decontamination AND begin drilling a new emergency well. Redirect science team to water prospecting. We solve this permanently.`,_rationale:`Patching the recycler buys time but does not fix the underlying vulnerability. A second independent water source eliminates single-point failure.`,_policies:[`emergency_drilling`,`science_redirect`],_toolCount:2,_citeCount:6,deaths:2}},{type:`agent_reactions`,leader:`Commander Elena Vasquez`,data:{turn:2,totalReactions:14,reactions:[{name:`Dr. Yuki Tanaka`,role:`Chief Medical Officer`,department:`medical`,mood:`negative`,quote:`Two people died during rationing. The well could have waited until the recycler was fixed.`,hexaco:{O:.6,C:.75,E:.5,A:.8,Em:.72,HH:.85},boneDensity:96,radiation:10,psychScore:58,intensity:.91},{name:`Carlos Fernandez`,role:`Senior Geologist`,department:`engineering`,mood:`positive`,quote:`The subsurface ice discovery changes everything. This is publishable. The colony is sitting on a water reservoir.`,hexaco:{O:.85,C:.6,E:.58,A:.5,Em:.38,HH:.7},boneDensity:91,radiation:20,psychScore:70,intensity:.74}]}},{type:`bulletin`,leader:`Commander Elena Vasquez`,data:{turn:2,posts:[{name:`Colony Bulletin`,role:`Official`,department:`governance`,post:`Emergency drilling operation discovers subsurface ice at 12m depth. Two colonists lost during water rationing period. Commander Vasquez: "Investing in survival."`,mood:`negative`,likes:42,replies:19}]}},{type:`turn_done`,leader:`Commander Elena Vasquez`,data:{turn:2,metrics:{population:98,morale:.68,foodMonthsReserve:16,waterLitersPerDay:850,powerKw:350,infrastructureModules:4,lifeSupportCapacity:116,scienceOutput:8},deaths:2}},{type:`turn_start`,leader:`Commander Hiroshi Tanaka`,data:{turn:2,time:2036,title:`Water Recycler Contamination`,crisis:`Trace perchlorate contamination detected in the primary water recycling system. Secondary filters are catching it but operating at 150% rated capacity.`,category:`infrastructure`,emergent:!0,turnSummary:`An emergent crisis triggered by dust storm residue in the atmosphere settling into intake vents during routine maintenance.`,metrics:{population:100,morale:.87,foodMonthsReserve:17.5,waterLitersPerDay:650,powerKw:390,infrastructureModules:3,lifeSupportCapacity:120,scienceOutput:0}}},{type:`specialist_start`,leader:`Commander Hiroshi Tanaka`,data:{turn:2,department:`engineering`,title:`Engineering Analysis`}},{type:`specialist_done`,leader:`Commander Hiroshi Tanaka`,data:{turn:2,department:`engineering`,summary:`Recommend isolating contaminated section, flushing the primary system, and installing redundant pre-filters before bringing it back online.`,forgedTools:[{name:`water_quality_monitor`,description:`Continuous perchlorate level tracker with alert thresholds per pipe segment`,approved:!0,confidence:.96,mode:`monitoring`}],citations:2}},{type:`decision_pending`,leader:`Commander Hiroshi Tanaka`,data:{turn:2}},{type:`decision_made`,leader:`Commander Hiroshi Tanaka`,data:{turn:2,decision:`Methodical decontamination. Isolate affected pipes, flush system section by section, install triple-redundant filtration. Strict water rationing at 80% normal allocation. No shortcuts.`,rationale:`A contaminated water supply is an existential threat. We fix this properly, verify every section, and prevent recurrence.`,selectedPolicies:[`water_rationing`,`system_overhaul`]}},{type:`outcome`,leader:`Commander Hiroshi Tanaka`,data:{turn:2,outcome:`conservative_success`,_decision:`Methodical decontamination. Isolate affected pipes, flush system section by section, install triple-redundant filtration. Strict water rationing at 80% normal allocation. No shortcuts.`,_rationale:`A contaminated water supply is an existential threat. We fix this properly, verify every section, and prevent recurrence.`,_policies:[`water_rationing`,`system_overhaul`],_toolCount:1,_citeCount:2}},{type:`agent_reactions`,leader:`Commander Hiroshi Tanaka`,data:{turn:2,totalReactions:14,reactions:[{name:`James Mueller`,role:`Chief Engineer`,department:`engineering`,mood:`positive`,quote:`The triple-redundant design is elegant. We should have built it this way from the start.`,hexaco:{O:.4,C:.92,E:.3,A:.65,Em:.45,HH:.88},boneDensity:92,radiation:15,psychScore:78,intensity:.65},{name:`Dr. Priya Singh`,role:`Colony Psychologist`,department:`psychology`,mood:`positive`,quote:`Morale is solid. People trust the process. They feel safe.`,hexaco:{O:.7,C:.68,E:.72,A:.9,Em:.65,HH:.82},boneDensity:98,radiation:5,psychScore:88,intensity:.5}]}},{type:`bulletin`,leader:`Commander Hiroshi Tanaka`,data:{turn:2,posts:[{name:`Colony Bulletin`,role:`Official`,department:`governance`,post:`Commander Tanaka completes 72-hour decontamination. Water purity above baseline. Zero casualties. New triple-filter system installed.`,mood:`positive`,likes:47,replies:6}]}},{type:`turn_done`,leader:`Commander Hiroshi Tanaka`,data:{turn:2,metrics:{population:100,morale:.89,foodMonthsReserve:17,waterLitersPerDay:820,powerKw:388,infrastructureModules:3,lifeSupportCapacity:120,scienceOutput:1}}},{type:`turn_start`,leader:`Commander Elena Vasquez`,data:{turn:3,time:2037,title:`First Marsborn Generation`,crisis:`Three colonists are pregnant. Colony must decide on birthing protocols, education infrastructure, and whether to allocate scarce resources to a pediatric wing.`,category:`social`,emergent:!0,turnSummary:`A milestone moment as the colony prepares for its first generation of humans born on Mars.`,metrics:{population:98,morale:.72,foodMonthsReserve:15,waterLitersPerDay:850,powerKw:370,infrastructureModules:4,lifeSupportCapacity:116,scienceOutput:12}}},{type:`specialist_start`,leader:`Commander Elena Vasquez`,data:{turn:3,department:`medical`,title:`Medical Analysis`}},{type:`specialist_done`,leader:`Commander Elena Vasquez`,data:{turn:3,department:`medical`,summary:`Martian gravity (0.38g) effects on fetal development are unknown. Recommend centrifuge-assisted birthing suite and continuous monitoring.`,forgedTools:[{name:`low_gravity_gestation_model`,description:`Simulates bone and organ development trajectories under Mars gravity with centrifuge augmentation`,approved:!0,confidence:.85,mode:`biomedical`}],citations:5}},{type:`specialist_start`,leader:`Commander Elena Vasquez`,data:{turn:3,department:`psychology`,title:`Psychology Analysis`}},{type:`specialist_done`,leader:`Commander Elena Vasquez`,data:{turn:3,department:`psychology`,summary:`Colony morale surging. First births represent hope and permanence. Recommend public celebration and naming ceremony.`,forgedTools:[],citations:1}},{type:`decision_pending`,leader:`Commander Elena Vasquez`,data:{turn:3}},{type:`decision_made`,leader:`Commander Elena Vasquez`,data:{turn:3,decision:`Full commitment. Convert Module 4 into a dedicated pediatric and education wing. Authorize the centrifuge birthing suite. Declare "Founding Day" as a colony holiday.`,rationale:`These children ARE the mission. If Mars cannot sustain the next generation, nothing else matters.`,selectedPolicies:[`pediatric_wing`,`founding_day`,`centrifuge_birth`]}},{type:`outcome`,leader:`Commander Elena Vasquez`,data:{turn:3,outcome:`risky_success`,_decision:`Full commitment. Convert Module 4 into a dedicated pediatric and education wing. Authorize the centrifuge birthing suite. Declare "Founding Day" as a colony holiday.`,_rationale:`These children ARE the mission. If Mars cannot sustain the next generation, nothing else matters.`,_policies:[`pediatric_wing`,`founding_day`,`centrifuge_birth`],_toolCount:1,_citeCount:6}},{type:`agent_reactions`,leader:`Commander Elena Vasquez`,data:{turn:3,totalReactions:14,reactions:[{name:`Dr. Yuki Tanaka`,role:`Chief Medical Officer`,department:`medical`,mood:`hopeful`,quote:`For the first time I feel like we are building something permanent. The centrifuge data is remarkable.`,hexaco:{O:.62,C:.75,E:.52,A:.8,Em:.68,HH:.85},boneDensity:95,radiation:12,psychScore:74,intensity:.7},{name:`Erik Lindqvist`,role:`Chief Engineer`,department:`engineering`,mood:`positive`,quote:`Module 4 conversion is aggressive but doable. First time I have seen people volunteer for extra shifts.`,hexaco:{O:.46,C:.88,E:.36,A:.63,Em:.52,HH:.8},boneDensity:93,radiation:14,psychScore:76,intensity:.62}]}},{type:`bulletin`,leader:`Commander Elena Vasquez`,data:{turn:3,posts:[{name:`Colony Bulletin`,role:`Official`,department:`governance`,post:`Three pregnancies confirmed. Commander Vasquez commits to full pediatric infrastructure and declares Founding Day. "These children ARE the mission."`,mood:`hopeful`,likes:63,replies:22}]}},{type:`turn_done`,leader:`Commander Elena Vasquez`,data:{turn:3,metrics:{population:98,morale:.82,foodMonthsReserve:14,waterLitersPerDay:840,powerKw:365,infrastructureModules:4,lifeSupportCapacity:114,scienceOutput:16}}},{type:`turn_start`,leader:`Commander Hiroshi Tanaka`,data:{turn:3,time:2037,title:`First Marsborn Generation`,crisis:`Three colonists are pregnant. Colony must decide on birthing protocols, education infrastructure, and whether to allocate scarce resources to a pediatric wing.`,category:`social`,emergent:!0,turnSummary:`A milestone moment as the colony prepares for its first generation of humans born on Mars.`,metrics:{population:100,morale:.89,foodMonthsReserve:16.5,waterLitersPerDay:820,powerKw:385,infrastructureModules:3,lifeSupportCapacity:120,scienceOutput:2}}},{type:`specialist_start`,leader:`Commander Hiroshi Tanaka`,data:{turn:3,department:`medical`,title:`Medical Analysis`}},{type:`specialist_done`,leader:`Commander Hiroshi Tanaka`,data:{turn:3,department:`medical`,summary:`Insufficient data on low-gravity pregnancies. Recommend Earth-normal protocols adapted for Mars with extensive monitoring. No experimental interventions without peer review.`,forgedTools:[{name:`prenatal_risk_matrix`,description:`Weighted risk assessment combining gravity, radiation, nutrition, and psychological factors for each trimester`,approved:!0,confidence:.93,mode:`clinical`}],citations:6}},{type:`decision_pending`,leader:`Commander Hiroshi Tanaka`,data:{turn:3}},{type:`decision_made`,leader:`Commander Hiroshi Tanaka`,data:{turn:3,decision:`Measured approach. Dedicate existing medical bay expansion to maternal care. No experimental centrifuge. Follow Earth-standard protocols with enhanced monitoring.`,rationale:`Untested interventions on pregnant colonists are unacceptable. We use proven medical science.`,selectedPolicies:[`medical_expansion`,`standard_protocols`,`enhanced_monitoring`]}},{type:`outcome`,leader:`Commander Hiroshi Tanaka`,data:{turn:3,outcome:`conservative_success`,_decision:`Measured approach. Dedicate existing medical bay expansion to maternal care. No experimental centrifuge. Follow Earth-standard protocols with enhanced monitoring.`,_rationale:`Untested interventions on pregnant colonists are unacceptable. We use proven medical science.`,_policies:[`medical_expansion`,`standard_protocols`,`enhanced_monitoring`],_toolCount:1,_citeCount:6}},{type:`agent_reactions`,leader:`Commander Hiroshi Tanaka`,data:{turn:3,totalReactions:14,reactions:[{name:`Dr. Sarah Anderson`,role:`Chief Medical Officer`,department:`medical`,mood:`positive`,quote:`The right call. Every medical textbook says proven protocols first. We can innovate after we have data from healthy births.`,hexaco:{O:.5,C:.82,E:.45,A:.75,Em:.6,HH:.9},boneDensity:95,radiation:9,psychScore:84,intensity:.55},{name:`Dr. Priya Singh`,role:`Colony Psychologist`,department:`psychology`,mood:`positive`,quote:`The quiet confidence is working. People feel cared for without feeling like test subjects.`,hexaco:{O:.7,C:.68,E:.72,A:.9,Em:.62,HH:.82},boneDensity:98,radiation:5,psychScore:90,intensity:.48}]}},{type:`bulletin`,leader:`Commander Hiroshi Tanaka`,data:{turn:3,posts:[{name:`Colony Bulletin`,role:`Official`,department:`governance`,post:`Medical bay expansion underway for maternal care. Commander Tanaka rejects experimental centrifuge in favor of proven Earth protocols. "We trust the science we know."`,mood:`positive`,likes:38,replies:5}]}},{type:`turn_done`,leader:`Commander Hiroshi Tanaka`,data:{turn:3,metrics:{population:100,morale:.9,foodMonthsReserve:16,waterLitersPerDay:815,powerKw:382,infrastructureModules:3,lifeSupportCapacity:120,scienceOutput:3}}},...[1,2,3].flatMap(e=>[{type:`systems_snapshot`,leader:`Commander Elena Vasquez`,data:{turn:e,time:2034+e,agents:Jk(`A`,e),population:100,morale:.85+e*.01,foodReserve:18-e*.5,births:+(e===2),deaths:+(e===3)}},{type:`systems_snapshot`,leader:`Commander Hiroshi Tanaka`,data:{turn:e,time:2034+e,agents:Jk(`B`,e),population:100,morale:.88+e*.005,foodReserve:18-e*.3,births:+(e===3),deaths:0}}])],Xk={shell:`_shell_dtmdv_1`,main:`_main_dtmdv_11`,chatSurfaceHidden:`_chatSurfaceHidden_dtmdv_17`,chatSurfaceVisible:`_chatSurfaceVisible_dtmdv_21`,tabPanel:`_tabPanel_dtmdv_28`,tabPanelHidden:`_tabPanelHidden_dtmdv_35`,errorBoundary:`_errorBoundary_dtmdv_39`,errorTitle:`_errorTitle_dtmdv_52`,errorMessage:`_errorMessage_dtmdv_60`,errorReload:`_errorReload_dtmdv_68`},Zk=(0,b.createContext)(null);function Qk(){let e=(0,b.useContext)(Zk);if(!e)throw Error(`useScenarioContext must be used within App`);return e}var $k=(0,b.createContext)(!0);function eA(){return(0,b.useContext)($k)}var tA=(0,b.createContext)(null);function nA(){let e=(0,b.useContext)(tA);if(!e)throw Error(`useDashboardNavigation must be used within App`);return e}var rA=(0,b.createContext)(()=>{});function iA(){return(0,b.useContext)(rA)}function aA(e,t){let n=e.toLowerCase();return(/\b(401|402|403|429|500|502|503|504)\b/.test(e)||n.includes(`exceeded your current quota`)||n.includes(`insufficient_quota`)||n.includes(`credit_balance_too_low`)||n.includes(`quota_exceeded`)||n.includes(`rate_limit`)||n.includes(`rate limit`)||n.includes(`overloaded_error`)||n.includes(`invalid_api_key`)||n.includes(`authentication_error`)||n.includes(`too many requests`)||n.includes(`api key`)||n.includes(`provider error`)||n.includes(`openai`)||n.includes(`anthropic`))&&(t===`quota`||t===`auth`||t===`rate_limit`)}function oA(){let[e,t]=(0,b.useState)(()=>typeof window>`u`?null:new URLSearchParams(window.location.search).get(`replay`));return(0,b.useEffect)(()=>{if(typeof window>`u`)return;let e=()=>t(new URLSearchParams(window.location.search).get(`replay`));return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},[]),e}function sA(e){switch(e){case`quickstart`:return`Paracosm — Quickstart`;case`studio`:return`Paracosm — Studio`;case`sim`:return`Paracosm — Simulation`;case`viz`:return`Paracosm — Visualization`;case`chat`:return`Paracosm — Chat`;case`reports`:return`Paracosm — Reports`;case`library`:return`Paracosm — Library`;case`settings`:return`Paracosm — Settings`;case`about`:return`Paracosm — About`;default:return`Paracosm`}}var cA=[];function lA(){let{scenario:e,ready:t}=ie(),n=oA(),r=(0,b.useRef)(()=>{}),i=(0,b.useCallback)(e=>r.current(e),[]),a=Me({replaySessionId:n,scenarioId:t?e.id:null,onRunCleared:i}),[o,s]=(0,b.useState)(!1),[c,l]=(0,b.useState)(null),[u,d]=(0,b.useState)(!1);(0,b.useEffect)(()=>{if(!u)return;let e=e=>{e.key===`Escape`&&d(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[u]),(0,b.useEffect)(()=>{let t=e.id===`mars-genesis`&&e.labels.name===`Mars Genesis`;document.title=t?`Paracosm — Structured World Model for AI Agents`:`${e.labels.name} \u2014 Paracosm`},[e.id,e.labels.name]);let f=o&&a.events.length===0,p=f?Yk:a.events,m=Be(p,f?!0:a.isComplete,f?void 0:a.results),h=`${a.runKey??``}:${a.loadedRuns}`,g=Be(a.ownRun?.events??cA,a.ownRun?.isComplete??!1),_=a.ownRun?g:m,{toast:v}=Ht(),y=on(),S=y.share,C=y.clear;Qt({events:p,replayDone:a.replayDone,tourActive:o});let w=p_(m),T=T_(m),E=qe(e.labels.shortName,{id:e.id,version:e.version,shortName:e.labels.shortName}),D=st({scenarioShortName:e.labels.shortName}),O=ch(window.location.href),[A,j]=(0,b.useState)(O.tab),[ee]=(0,b.useState)(O.tab===`studio`&&O.sub===`branches`?`branches`:`author`),[te,M]=(0,b.useState)(O.tab===`settings`&&O.sub===`log`?`log`:`config`),N=(0,b.useCallback)(e=>{e===`about`?window.location.href=`/`:(e===`settings`&&M(`config`),j(e),window.history.replaceState({},``,lh(window.location.href,e)))},[]),ne=(0,b.useCallback)((e,t)=>{t?.logTool||t?.logActor?(M(`log`),j(`settings`),window.history.replaceState({},``,uh(window.location.href,t.logTool??``,t.logActor))):N(e)},[N]),P=(0,b.useCallback)((e,t)=>{ne(`settings`,{logTool:e,logActor:t})},[ne]);(0,b.useEffect)(()=>{A===`about`&&(window.location.href=`/`)},[A]);let re=(0,b.useCallback)(()=>{E.save(a.events,a.results,a.verdict),v(`success`,`Saved`,`${a.events.length} events${a.verdict?` + verdict`:``} saved to file.`)},[a.events,a.results,a.verdict,E,v]),[F]=(0,b.useState)(()=>typeof window>`u`||!vt(window.location.href).ok?{destinationTab:null,autoload:!1}:{destinationTab:Ct(window.location.href,ih),autoload:St(window.location.href)}),I=(0,b.useRef)(!1),[ae,oe]=(0,b.useState)(null),[se,le]=(0,b.useState)(null),L=(0,b.useRef)(null),de=(0,b.useRef)(null);r.current=e=>{e===de.current&&(de.current=null,oe(null))};let{leaveOwnRun:z}=a,pe=(0,b.useCallback)(()=>{L.current=null,de.current=null,le(null),oe(null),z()},[z]),me=gt({pickFile:async()=>{let e=await E.pickFile();return e&&(I.current=!1),e},parseFile:E.parseFile,currentScenario:{id:e.id,name:e.labels.name},onConfirm:({events:e,results:t,verdict:n})=>{pe(),a.loadEvents(e,t,n),C(),v(`info`,`Loaded`,`${e.length} events loaded.`);let r=I.current?F.destinationTab:null;I.current=!1,N(r&&r!==`about`?r:`sim`)},onError:e=>{v(`error`,`Load Failed`,e)}}),he=me.openPicker,ge=Tt({openFromFile:e=>(I.current=!0,me.openFromFile(e)),onInfo:(e,t)=>v(`info`,e,t),onError:(e,t)=>v(`error`,e,t)}),_e=(0,b.useRef)(!1);(0,b.useEffect)(()=>{_e.current||F.autoload&&me.state.kind===`preview`&&I.current&&(_e.current=!0,me.confirm())},[F.autoload,me.state.kind,me]);let ye=Nt({onFile:e=>(I.current=!1,me.openFromFile(e)),onError:()=>{v(`error`,`Unsupported file`,`Only .json simulation files supported.`)},onMultipleFiles:e=>{v(`info`,`Multi-file drop`,`Loaded first of ${e} files; ignoring the rest.`)}}),Ce=(0,b.useCallback)(()=>{confirm(`Clear local data? This wipes the in-browser simulation buffer + cached events for this dashboard.
177
177
 
178
178
  It also lets go of this browser's run on the server, and stops it if it is running.
179
179
 
@@ -185,5 +185,5 @@ Pages showing a finished run this server holds, this one included, empty their v
185
185
 
186
186
  Clear local data, a separate item, clears this browser's cached data.
187
187
 
188
- Cannot be undone.`))return;let t=xe(e);if(t)v(`info`,`Server data kept`,t),N(`settings`);else{try{let t=await fetch(`/admin/data/wipe`,{method:`POST`,headers:{"Content-Type":`application/json`,[fe]:e},body:JSON.stringify({wipeRuns:!0,wipeSessions:!0,wipeOutput:!0})});if(t.ok){let e=await t.json();v(`info`,`Server data deleted`,`${e.wiped.runs} runs, ${e.wiped.sessions} sessions and ${e.wiped.outputFiles} files deleted on the server.`)}else if(t.status===401)be(e),v(`info`,`Server data kept`,B()?`Server data not deleted: the server refused the admin token this request was sent with. A newer token is saved in this browser; choose Delete server data again to try with it.`:`Server data not deleted: the admin token was refused and has been cleared. ${R}`);else if(t.status===403)v(`info`,`Server data kept`,`Admin writes are off on this server.`);else if(t.status===503)v(`info`,`Server data kept`,`Admin writes are on but no ADMIN_TOKEN is set on the server.`);else{let e=(await t.json().catch(()=>({}))).error??`HTTP ${t.status}`;t.status>=500?v(`error`,`Server error while deleting`,`The server reported an error while deleting (${e}). It may have deleted some of its data before the error.`):v(`info`,`Server data kept`,`Server data not deleted: ${e}`)}}catch(e){v(`info`,`Deletion not confirmed`,`Whether the server's data was deleted is not known: its answer did not arrive or could not be read (${e instanceof Error?e.message:String(e)}).`)}N(`settings`)}},[v]),[Pe,Fe]=(0,b.useState)(!1);(0,b.useEffect)(()=>{a.providerError||Fe(!1)},[a.providerError]);let Ie=(0,b.useRef)(0);(0,b.useEffect)(()=>{if(a.errors.length<=Ie.current)return;let e=a.errors.slice(Ie.current);Ie.current=a.errors.length;let t=a.providerError;for(let n of e){if(t&&rA(n,t.kind))continue;let e=n.length>120?n.slice(0,120)+`...`:n;v(`error`,`Simulation Error`,e)}},[a.errors,a.providerError,v]);let Le=(0,b.useRef)(null),Re=(0,b.useCallback)(()=>{Le.current=A,s(!0)},[A]);(0,b.useEffect)(()=>{try{if(localStorage.getItem(`paracosm:tourSeen`)===`1`)return;localStorage.setItem(`paracosm:tourSeen`,`1`)}catch{return}if(typeof window<`u`&&window.innerWidth<640)return;let e=setTimeout(()=>{let e=sh(window.location.href);e===`quickstart`&&(Le.current=e,s(!0))},600);return()=>clearTimeout(e)},[]);let ze=(0,b.useCallback)(e=>{window.location.hash=`chat=${encodeURIComponent(e)}`,N(`chat`)},[N]),Ve=(0,b.useCallback)(()=>{s(!1),Le.current&&=(N(Le.current),null);try{localStorage.setItem(`paracosm:tourSeen`,`1`)}catch{}},[N]),He=(0,b.useCallback)(()=>{let t=(e.labels.actorNoun??`actor`).replace(/^./,e=>e.toUpperCase()),n=ce(e),r=[`## ${e.labels.name} — Simulation Report`,`**Turns**: ${m.turn}/${m.maxTurns} | **Seed**: ${m.seed} | **${n.Time}**: ${m.time}`];for(let e=0;e<m.actorIds.length;e++){let n=m.actorIds[e],i=m.actors[n],a=i?.leader?.name||`${t} ${e+1}`,o=i?.leader?.archetype||``,s=i?.leader?.unit||``;r.push(``,`### ${a}${o?` (${o})`:``}`,`Unit: ${s} | Pop: ${i?.metrics?.population??`?`} | Morale: ${i?.metrics?Math.round(i.metrics.morale*100):`?`}% | Deaths: ${i?.deaths??0}`,`Tools forged: ${i?.tools??0} | Citations: ${i?.citations??0} | Decisions: ${i?.decisions??0}`)}if(m.actorIds.length===2){let e=m.actors[m.actorIds[0]],t=m.actors[m.actorIds[1]];e?.event&&t?.event&&e.event.turn===t.event.turn&&(r.push(``,`### Key Divergence`),r.push(`Same event "${e.event.title}" at T${e.event.turn}.`))}r.push(``,`Generated by Paracosm (paracosm.sh)`),Dt(r.join(`
189
- `)).then(()=>{v(`success`,`Copied`,`Simulation summary copied to clipboard.`)}).catch(()=>{v(`error`,`Copy Failed`,`Clipboard access denied.`)})},[m,e,v]),Ue=n??kt(a.events);(0,b.useEffect)(()=>{C()},[Ue,C]);let We=a.events.length>0;(0,b.useEffect)(()=>{We||C()},[We,C]);let Ge=(0,b.useCallback)(()=>{Ue&&S(Ot(window.location.origin,Ue,`viz`))},[Ue,S]),[Ke,Je]=(0,b.useState)(()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`paracosm:launchPending`)===`1`}catch{return!1}}),[Ye,Xe]=(0,b.useState)({totalTokens:0,costUSD:0,calls:0}),Ze=(0,b.useCallback)(e=>{Xe(t=>({totalTokens:t.totalTokens+(e.totalTokens||0),costUSD:Math.round((t.costUSD+(e.costUSD||0))*1e4)/1e4,calls:t.calls+1}))},[]),Qe=(0,b.useRef)(a.events.length);(0,b.useEffect)(()=>{let e=Qe.current,t=a.events.length;Qe.current=t,e>0&&t===0&&Xe({totalTokens:0,costUSD:0,calls:0})},[a.events.length]),fn({launching:Ke,setLaunching:Je,isRunning:m.isRunning,isComplete:a.isComplete,sseStatus:a.status,eventsCount:a.events.length});let[$e,et]=(0,b.useState)(!1),tt=(0,b.useCallback)(e=>{let t=a.reset();return a.followRun(e.runKey),L.current=e.runKey,de.current=null,oe(null),le(e),et(!0),N(`sim`),t},[a,N]),nt=(0,b.useCallback)((e,t)=>{t===L.current&&(L.current=null,de.current=t,le(null),oe(e),et(!0),N(`sim`))},[N]),rt=(0,b.useCallback)(()=>{L.current=null,de.current=null,le(null),oe(null),a.leaveOwnRun()},[a]),it=(0,b.useCallback)((e,t)=>t===L.current&&(L.current=null,le(null),a.leaveOwnRun(),v(`error`,`Digital twin failed`,e),!0),[a,v]);tn({isComplete:a.isComplete,isAborted:a.isAborted,abortReason:a.abortReason,resultsCount:a.results.length,hasVerdict:!!a.verdict,replayDone:a.replayDone,tourActive:o,userTriggeredRun:$e,verdict:a.verdict}),(0,b.useEffect)(()=>{if(o||!a.isComplete||a.events.length===0)return;let t=`cached:${e.labels.shortName}:${a.events.length}:${a.isAborted?`a`:`c`}`,n=`paracosm:lastCachedRunFingerprint`;try{if(sessionStorage.getItem(n)===t)return;sessionStorage.setItem(n,t)}catch{}D.push({events:a.events,results:a.results,verdict:a.verdict})},[a.isComplete,a.isAborted,a.events,a.results,a.verdict,e.labels.shortName,D,o]),rn({events:a.events,tourActive:o,userTriggeredRun:$e});let at=(0,b.useCallback)(async()=>{if(!t)v(`info`,`Loading scenario`,`The scenario is still loading. Run again in a moment.`);else if(Ke||m.isRunning)v(`info`,`Already running`,`A simulation is in progress — wait for it to finish or hit Clear to reset.`);else try{Je(!0),et(!0),L.current===null&&ae===null&&await a.reset(),N(`sim`),v(`info`,`Launching`,`Starting simulation with default settings...`);let t=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(ue(e))}),n=await t.json();t.status===429?(Je(!1),v(`error`,`Rate Limited`,n.error||`Too many simulations`)):n.redirect?(k(window,n.visitorId),pe()):(Je(!1),v(`error`,`Launch Failed`,n.error||`Unknown error`))}catch(e){Je(!1),v(`error`,`Launch Failed`,String(e))}},[e,t,v,N,Ke,m.isRunning,a,pe,ae]);return(0,x.jsx)(Wn,{children:(0,x.jsx)($k.Provider,{value:ne,children:(0,x.jsx)(tA.Provider,{value:pe,children:(0,x.jsx)(Yk.Provider,{value:e,children:(0,x.jsx)(Zk.Provider,{value:t,children:(0,x.jsx)(m_.Provider,{value:w,children:(0,x.jsx)(E_.Provider,{value:T,children:(0,x.jsxs)(yx,{state:m,runKey:a.runKey??null,sessionId:Ue,showToolLog:P,children:[(0,x.jsx)(Kn,{sse:a}),(0,x.jsx)(`a`,{className:`skip-to-content`,href:`#main-content`,children:`Skip to main content`}),(0,x.jsxs)(`div`,{className:`scanline-overlay ${Jk.shell}`,children:[a.providerError&&!Pe?(0,x.jsx)(Bx,{providerError:a.providerError,onDismiss:()=>Fe(!0)}):null,n&&a.status===`replay_not_found`?(0,x.jsx)(Bn,{replaySessionId:n}):null,n&&a.status!==`replay_not_found`?(0,x.jsx)(zn,{replaySessionId:n}):null,(0,x.jsx)(Mx,{scenario:e,sse:a,gameState:m,onSave:re,onLoad:he,onClear:Ce,onWipeServer:we&&Ee===!0?Ne:void 0,onRunActionsOpen:je,onRun:at,onTour:Re,onCopy:He,onShareViz:Ue?Ge:void 0,launching:Ke,history:D.entries,onRestoreHistory:e=>{pe(),C(),D.restore(e,a.loadEvents)},onClearHistory:()=>{D.clear(),E.clearCache(),pe(),a.reset(),et(!1)}}),(0,x.jsx)(Ix,{active:A,onTabChange:N,scenario:e}),y.shared&&(0,x.jsx)(dn,{shared:y.shared,onClose:y.clear}),$e&&(0,x.jsx)(gn,{verdict:a.verdict,currentTurn:m.turn,maxTurns:m.maxTurns,dismissedKey:c,onOpenModal:()=>d(!0),onDismiss:l,onNavigateTab:N}),(0,x.jsxs)(`main`,{id:`main-content`,tabIndex:-1,className:`flex-1 overflow-hidden ${Jk.main}`,role:`main`,"aria-label":`${A} view`,children:[(0,x.jsx)(`h1`,{className:`sr-only`,children:aA(A)}),(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-quickstart`,"aria-labelledby":`tab-quickstart`,hidden:A!==`quickstart`,tabIndex:-1,className:A===`quickstart`?Jk.tabPanel:Jk.tabPanelHidden,children:(0,x.jsx)(d_,{sse:a,sessionId:n??void 0,onRunStarted:()=>{pe(),et(!0)},onInterventionStart:tt,onInterventionResult:nt,onInterventionError:it})}),A===`sim`&&(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-sim`,"aria-labelledby":`tab-sim`,tabIndex:-1,className:Jk.tabPanel,children:(0,x.jsx)(Sw,{state:m,sseStatus:a.status,onRun:at,onTour:Re,verdict:a.verdict,shownRun:h,launching:Ke,interventionArtifact:ae,interventionRunning:se,interventionState:_,onInterventionDismiss:rt,forceLayout:o?`side-by-side`:void 0})}),A===`viz`&&(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-viz`,"aria-labelledby":`tab-viz`,tabIndex:-1,className:Jk.tabPanel,children:(0,x.jsx)(Ok,{state:m,onNavigateToChat:ze})}),A===`settings`&&(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-settings`,"aria-labelledby":`tab-settings`,tabIndex:-1,className:Jk.tabPanel,children:(0,x.jsx)(uT,{events:p,initialSubTab:te})}),A===`reports`&&(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-reports`,"aria-labelledby":`tab-reports`,tabIndex:-1,className:Jk.tabPanel,children:(0,x.jsx)(PE,{state:m,verdict:a.verdict,shownRun:h,reportSections:e.ui.reportSections})}),A===`library`&&(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-library`,"aria-labelledby":`tab-library`,tabIndex:-1,className:Jk.tabPanel,children:(0,x.jsx)(oa,{})}),A===`studio`&&(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-studio`,"aria-labelledby":`tab-studio`,tabIndex:-1,className:Jk.tabPanel,children:(0,x.jsx)(mh,{initialSubTab:ee})}),(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-chat`,"aria-labelledby":`tab-chat`,tabIndex:-1,className:A===`chat`?Jk.chatSurfaceVisible:Jk.chatSurfaceHidden,children:(0,x.jsx)(VE,{state:m,onChatUsage:Ze},h)})]}),(0,x.jsx)(Ik,{cost:{totalTokens:(m.cost?.totalTokens??0)+Ye.totalTokens,totalCostUSD:Math.round(((m.cost?.totalCostUSD??0)+Ye.costUSD)*1e4)/1e4,llmCalls:(m.cost?.llmCalls??0)+Ye.calls},costBreakdown:{simUSD:m.cost?.totalCostUSD??0,simCalls:m.cost?.llmCalls??0,chatUSD:Ye.costUSD,chatCalls:Ye.calls},simStatus:{isRunning:m.isRunning,isComplete:a.isComplete,isAborted:a.isAborted,connectionStatus:a.status,abortReason:a.abortReason,providerError:a.providerError}}),u&&a.verdict&&(0,x.jsx)(Fn,{verdict:a.verdict,onClose:()=>d(!1)}),ge.pendingHost&&(0,x.jsx)(Rt,{host:ge.pendingHost,onLoad:ge.confirmPending,onCancel:ge.cancelPending}),me.metadata&&(0,x.jsx)(Lt,{metadata:me.metadata,showOverwriteWarning:a.events.length>0&&!n,currentEventCount:a.events.length,onConfirm:me.confirm,onCancel:me.cancel}),(0,x.jsx)(Bt,{active:ye.isDragging}),o&&(0,x.jsx)(Gk,{activeTab:A,chatEnabled:e.policies.characterChat,onTabChange:N,onClose:Ve,onRun:at}),(0,x.jsx)(zk,{})]})]})})})})})})})})}var cA=class extends b.Component{state={error:null};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){console.error(`[Paracosm] Uncaught error:`,e,t.componentStack)}render(){return this.state.error?(0,x.jsxs)(`div`,{className:Jk.errorBoundary,children:[(0,x.jsx)(`div`,{className:Jk.errorTitle,children:`SIMULATION ERROR`}),(0,x.jsx)(`div`,{className:Jk.errorMessage,children:this.state.error.message}),(0,x.jsx)(`button`,{onClick:()=>{this.setState({error:null}),window.location.reload()},className:Jk.errorReload,children:`Reload Dashboard`})]}):this.props.children}};function lA(){return(0,x.jsx)(cA,{children:(0,x.jsx)(w,{children:(0,x.jsx)(qt,{children:(0,x.jsx)(sA,{})})})})}(0,y.createRoot)(document.getElementById(`root`)).render((0,x.jsx)(b.StrictMode,{children:(0,x.jsx)(lA,{})}));
188
+ Cannot be undone.`))return;let t=xe(e);if(t)v(`info`,`Server data kept`,t),N(`settings`);else{try{let t=await fetch(`/admin/data/wipe`,{method:`POST`,headers:{"Content-Type":`application/json`,[fe]:e},body:JSON.stringify({wipeRuns:!0,wipeSessions:!0,wipeOutput:!0})});if(t.ok){let e=await t.json();v(`info`,`Server data deleted`,`${e.wiped.runs} runs, ${e.wiped.sessions} sessions and ${e.wiped.outputFiles} files deleted on the server.`)}else if(t.status===401)be(e),v(`info`,`Server data kept`,B()?`Server data not deleted: the server refused the admin token this request was sent with. A newer token is saved in this browser; choose Delete server data again to try with it.`:`Server data not deleted: the admin token was refused and has been cleared. ${R}`);else if(t.status===403)v(`info`,`Server data kept`,`Admin writes are off on this server.`);else if(t.status===503)v(`info`,`Server data kept`,`Admin writes are on but no ADMIN_TOKEN is set on the server.`);else{let e=(await t.json().catch(()=>({}))).error??`HTTP ${t.status}`;t.status>=500?v(`error`,`Server error while deleting`,`The server reported an error while deleting (${e}). It may have deleted some of its data before the error.`):v(`info`,`Server data kept`,`Server data not deleted: ${e}`)}}catch(e){v(`info`,`Deletion not confirmed`,`Whether the server's data was deleted is not known: its answer did not arrive or could not be read (${e instanceof Error?e.message:String(e)}).`)}N(`settings`)}},[v]),[Pe,Fe]=(0,b.useState)(!1);(0,b.useEffect)(()=>{a.providerError||Fe(!1)},[a.providerError]);let Ie=(0,b.useRef)(0);(0,b.useEffect)(()=>{if(a.errors.length<=Ie.current)return;let e=a.errors.slice(Ie.current);Ie.current=a.errors.length;let t=a.providerError;for(let n of e){if(t&&aA(n,t.kind))continue;let e=n.length>120?n.slice(0,120)+`...`:n;v(`error`,`Simulation Error`,e)}},[a.errors,a.providerError,v]);let Le=(0,b.useRef)(null),Re=(0,b.useCallback)(()=>{Le.current=A,s(!0)},[A]);(0,b.useEffect)(()=>{try{if(localStorage.getItem(`paracosm:tourSeen`)===`1`)return;localStorage.setItem(`paracosm:tourSeen`,`1`)}catch{return}if(typeof window<`u`&&window.innerWidth<640)return;let e=setTimeout(()=>{let e=sh(window.location.href);e===`quickstart`&&(Le.current=e,s(!0))},600);return()=>clearTimeout(e)},[]);let ze=(0,b.useCallback)(e=>{window.location.hash=`chat=${encodeURIComponent(e)}`,N(`chat`)},[N]),Ve=(0,b.useCallback)(()=>{s(!1),Le.current&&=(N(Le.current),null);try{localStorage.setItem(`paracosm:tourSeen`,`1`)}catch{}},[N]),He=(0,b.useCallback)(()=>{let t=(e.labels.actorNoun??`actor`).replace(/^./,e=>e.toUpperCase()),n=ce(e),r=[`## ${e.labels.name} — Simulation Report`,`**Turns**: ${m.turn}/${m.maxTurns} | **Seed**: ${m.seed} | **${n.Time}**: ${m.time}`];for(let e=0;e<m.actorIds.length;e++){let n=m.actorIds[e],i=m.actors[n],a=i?.leader?.name||`${t} ${e+1}`,o=i?.leader?.archetype||``,s=i?.leader?.unit||``;r.push(``,`### ${a}${o?` (${o})`:``}`,`Unit: ${s} | Pop: ${i?.metrics?.population??`?`} | Morale: ${i?.metrics?Math.round(i.metrics.morale*100):`?`}% | Deaths: ${i?.deaths??0}`,`Tools forged: ${i?.tools??0} | Citations: ${i?.citations??0} | Decisions: ${i?.decisions??0}`)}if(m.actorIds.length===2){let e=m.actors[m.actorIds[0]],t=m.actors[m.actorIds[1]];e?.event&&t?.event&&e.event.turn===t.event.turn&&(r.push(``,`### Key Divergence`),r.push(`Same event "${e.event.title}" at T${e.event.turn}.`))}r.push(``,`Generated by Paracosm (paracosm.sh)`),Dt(r.join(`
189
+ `)).then(()=>{v(`success`,`Copied`,`Simulation summary copied to clipboard.`)}).catch(()=>{v(`error`,`Copy Failed`,`Clipboard access denied.`)})},[m,e,v]),Ue=n??kt(a.events);(0,b.useEffect)(()=>{C()},[Ue,C]);let We=a.events.length>0;(0,b.useEffect)(()=>{We||C()},[We,C]);let Ge=(0,b.useCallback)(()=>{Ue&&S(Ot(window.location.origin,Ue,`viz`))},[Ue,S]),[Ke,Je]=(0,b.useState)(()=>{if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`paracosm:launchPending`)===`1`}catch{return!1}}),[Ye,Xe]=(0,b.useState)({totalTokens:0,costUSD:0,calls:0}),Ze=(0,b.useCallback)(e=>{Xe(t=>({totalTokens:t.totalTokens+(e.totalTokens||0),costUSD:Math.round((t.costUSD+(e.costUSD||0))*1e4)/1e4,calls:t.calls+1}))},[]),Qe=(0,b.useRef)(a.events.length);(0,b.useEffect)(()=>{let e=Qe.current,t=a.events.length;Qe.current=t,e>0&&t===0&&Xe({totalTokens:0,costUSD:0,calls:0})},[a.events.length]),fn({launching:Ke,setLaunching:Je,isRunning:m.isRunning,isComplete:a.isComplete,sseStatus:a.status,eventsCount:a.events.length});let[$e,et]=(0,b.useState)(!1),tt=(0,b.useCallback)(e=>{let t=a.reset();return a.followRun(e.runKey),L.current=e.runKey,de.current=null,oe(null),le(e),et(!0),N(`sim`),t},[a,N]),nt=(0,b.useCallback)((e,t)=>{t===L.current&&(L.current=null,de.current=t,le(null),oe(e),et(!0),N(`sim`))},[N]),rt=(0,b.useCallback)(()=>{L.current=null,de.current=null,le(null),oe(null),a.leaveOwnRun()},[a]),it=(0,b.useCallback)((e,t)=>t===L.current&&(L.current=null,le(null),a.leaveOwnRun(),v(`error`,`Digital twin failed`,e),!0),[a,v]);tn({isComplete:a.isComplete,isAborted:a.isAborted,abortReason:a.abortReason,resultsCount:a.results.length,hasVerdict:!!a.verdict,replayDone:a.replayDone,tourActive:o,userTriggeredRun:$e,verdict:a.verdict}),(0,b.useEffect)(()=>{if(o||!a.isComplete||a.events.length===0)return;let t=`cached:${e.labels.shortName}:${a.events.length}:${a.isAborted?`a`:`c`}`,n=`paracosm:lastCachedRunFingerprint`;try{if(sessionStorage.getItem(n)===t)return;sessionStorage.setItem(n,t)}catch{}D.push({events:a.events,results:a.results,verdict:a.verdict})},[a.isComplete,a.isAborted,a.events,a.results,a.verdict,e.labels.shortName,D,o]),rn({events:a.events,tourActive:o,userTriggeredRun:$e});let at=(0,b.useCallback)(async()=>{if(!t)v(`info`,`Loading scenario`,`The scenario is still loading. Run again in a moment.`);else if(Ke||m.isRunning)v(`info`,`Already running`,`A simulation is in progress — wait for it to finish or hit Clear to reset.`);else try{Je(!0),et(!0),L.current===null&&ae===null&&await a.reset(),N(`sim`),v(`info`,`Launching`,`Starting simulation with default settings...`);let t=await fetch(`/setup`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(ue(e))}),n=await t.json();t.status===429?(Je(!1),v(`error`,`Rate Limited`,n.error||`Too many simulations`)):n.redirect?(k(window,n.visitorId),pe()):(Je(!1),v(`error`,`Launch Failed`,n.error||`Unknown error`))}catch(e){Je(!1),v(`error`,`Launch Failed`,String(e))}},[e,t,v,N,Ke,m.isRunning,a,pe,ae]);return(0,x.jsx)(Wn,{children:(0,x.jsx)(tA.Provider,{value:ne,children:(0,x.jsx)(rA.Provider,{value:pe,children:(0,x.jsx)(Zk.Provider,{value:e,children:(0,x.jsx)($k.Provider,{value:t,children:(0,x.jsx)(m_.Provider,{value:w,children:(0,x.jsx)(E_.Provider,{value:T,children:(0,x.jsxs)(yx,{state:m,runKey:a.runKey??null,sessionId:Ue,showToolLog:P,children:[(0,x.jsx)(Kn,{sse:a}),(0,x.jsx)(`a`,{className:`skip-to-content`,href:`#main-content`,children:`Skip to main content`}),(0,x.jsxs)(`div`,{className:`scanline-overlay ${Xk.shell}`,children:[a.providerError&&!Pe?(0,x.jsx)(Bx,{providerError:a.providerError,onDismiss:()=>Fe(!0)}):null,n&&a.status===`replay_not_found`?(0,x.jsx)(Bn,{replaySessionId:n}):null,n&&a.status!==`replay_not_found`?(0,x.jsx)(zn,{replaySessionId:n}):null,(0,x.jsx)(Mx,{scenario:e,sse:a,gameState:m,onSave:re,onLoad:he,onClear:Ce,onWipeServer:we&&Ee===!0?Ne:void 0,onRunActionsOpen:je,onRun:at,onTour:Re,onCopy:He,onShareViz:Ue?Ge:void 0,launching:Ke,history:D.entries,onRestoreHistory:e=>{pe(),C(),D.restore(e,a.loadEvents)},onClearHistory:()=>{D.clear(),E.clearCache(),pe(),a.reset(),et(!1)}}),(0,x.jsx)(Ix,{active:A,onTabChange:N,scenario:e}),y.shared&&(0,x.jsx)(dn,{shared:y.shared,onClose:y.clear}),$e&&(0,x.jsx)(gn,{verdict:a.verdict,currentTurn:m.turn,maxTurns:m.maxTurns,dismissedKey:c,onOpenModal:()=>d(!0),onDismiss:l,onNavigateTab:N}),(0,x.jsxs)(`main`,{id:`main-content`,tabIndex:-1,className:`flex-1 overflow-hidden ${Xk.main}`,role:`main`,"aria-label":`${A} view`,children:[(0,x.jsx)(`h1`,{className:`sr-only`,children:sA(A)}),(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-quickstart`,"aria-labelledby":`tab-quickstart`,hidden:A!==`quickstart`,tabIndex:-1,className:A===`quickstart`?Xk.tabPanel:Xk.tabPanelHidden,children:(0,x.jsx)(d_,{sse:a,sessionId:n??void 0,onRunStarted:()=>{pe(),et(!0)},onInterventionStart:tt,onInterventionResult:nt,onInterventionError:it})}),A===`sim`&&(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-sim`,"aria-labelledby":`tab-sim`,tabIndex:-1,className:Xk.tabPanel,children:(0,x.jsx)(Sw,{state:m,sseStatus:a.status,onRun:at,onTour:Re,verdict:a.verdict,shownRun:h,launching:Ke,interventionArtifact:ae,interventionRunning:se,interventionState:_,onInterventionDismiss:rt,forceLayout:o?`side-by-side`:void 0})}),A===`viz`&&(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-viz`,"aria-labelledby":`tab-viz`,tabIndex:-1,className:Xk.tabPanel,children:(0,x.jsx)(Ak,{state:m,onNavigateToChat:ze})}),A===`settings`&&(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-settings`,"aria-labelledby":`tab-settings`,tabIndex:-1,className:Xk.tabPanel,children:(0,x.jsx)(uT,{events:p,initialSubTab:te})}),A===`reports`&&(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-reports`,"aria-labelledby":`tab-reports`,tabIndex:-1,className:Xk.tabPanel,children:(0,x.jsx)(PE,{state:m,verdict:a.verdict,shownRun:h,reportSections:e.ui.reportSections})}),A===`library`&&(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-library`,"aria-labelledby":`tab-library`,tabIndex:-1,className:Xk.tabPanel,children:(0,x.jsx)(oa,{})}),A===`studio`&&(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-studio`,"aria-labelledby":`tab-studio`,tabIndex:-1,className:Xk.tabPanel,children:(0,x.jsx)(mh,{initialSubTab:ee})}),(0,x.jsx)(`section`,{role:`tabpanel`,id:`tabpanel-chat`,"aria-labelledby":`tab-chat`,tabIndex:-1,className:A===`chat`?Xk.chatSurfaceVisible:Xk.chatSurfaceHidden,children:(0,x.jsx)(VE,{state:m,onChatUsage:Ze},h)})]}),(0,x.jsx)(Rk,{cost:{totalTokens:(m.cost?.totalTokens??0)+Ye.totalTokens,totalCostUSD:Math.round(((m.cost?.totalCostUSD??0)+Ye.costUSD)*1e4)/1e4,llmCalls:(m.cost?.llmCalls??0)+Ye.calls},costBreakdown:{simUSD:m.cost?.totalCostUSD??0,simCalls:m.cost?.llmCalls??0,chatUSD:Ye.costUSD,chatCalls:Ye.calls},simStatus:{isRunning:m.isRunning,isComplete:a.isComplete,isAborted:a.isAborted,connectionStatus:a.status,abortReason:a.abortReason,providerError:a.providerError}}),u&&a.verdict&&(0,x.jsx)(Fn,{verdict:a.verdict,onClose:()=>d(!1)}),ge.pendingHost&&(0,x.jsx)(Rt,{host:ge.pendingHost,onLoad:ge.confirmPending,onCancel:ge.cancelPending}),me.metadata&&(0,x.jsx)(Lt,{metadata:me.metadata,showOverwriteWarning:a.events.length>0&&!n,currentEventCount:a.events.length,onConfirm:me.confirm,onCancel:me.cancel}),(0,x.jsx)(Bt,{active:ye.isDragging}),o&&(0,x.jsx)(qk,{activeTab:A,chatEnabled:e.policies.characterChat,onTabChange:N,onClose:Ve,onRun:at}),(0,x.jsx)(Vk,{})]})]})})})})})})})})}var uA=class extends b.Component{state={error:null};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){console.error(`[Paracosm] Uncaught error:`,e,t.componentStack)}render(){return this.state.error?(0,x.jsxs)(`div`,{className:Xk.errorBoundary,children:[(0,x.jsx)(`div`,{className:Xk.errorTitle,children:`SIMULATION ERROR`}),(0,x.jsx)(`div`,{className:Xk.errorMessage,children:this.state.error.message}),(0,x.jsx)(`button`,{onClick:()=>{this.setState({error:null}),window.location.reload()},className:Xk.errorReload,children:`Reload Dashboard`})]}):this.props.children}};function dA(){return(0,x.jsx)(uA,{children:(0,x.jsx)(w,{children:(0,x.jsx)(qt,{children:(0,x.jsx)(lA,{})})})})}(0,y.createRoot)(document.getElementById(`root`)).render((0,x.jsx)(b.StrictMode,{children:(0,x.jsx)(dA,{})}));